]> git.codecow.com Git - nano25519.git/commitdiff
Update documentation and agent file.
authorChris Duncan <chris@codecow.com>
Sat, 17 Oct 2026 23:57:38 +0000 (16:57 -0700)
committerChris Duncan <chris@codecow.com>
Sat, 17 Oct 2026 23:57:38 +0000 (16:57 -0700)
AGENTS.md
README.md
src/lib/bytes.ts
src/lib/wasm.ts

index c5b7969b085e292f154be7c83fac5cc181ac6dc4..2966db26f286ab5702a7035bcee40530cd479286 100644 (file)
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -80,14 +80,15 @@ would silently accept a mismatched keypair.
 npm run build         # clean + compile (asc --debug) + esbuild
 npm run build:prod    # clean + compile + esbuild (minified)
 npm run compile       # generate blake2b.ts, then asc + tsc only, no bundle
-npm test              # build, then all six suites below
-npm run test:prod     # build:prod, then the same six suites; also prepublishOnly
+npm test              # build, then all seven suites below
+npm run test:prod     # build:prod, then the same seven suites; also prepublishOnly
 npm run test:le       # test/node.mjs, the public API
 npm run test:be       # the same, forced down the big-endian marshalling path
 npm run test:frozen   # the same, under --frozen-intrinsics
 npm run test:mutants  # guard mutation tests, see Testing
 npm run test:module   # residue, input scrubbing and result polarity below the host
 npm run test:arithmetic  # field, scalar and group internals against a BigInt reference
+npm run test:heap     # no copy of a private key left anywhere in the process (Linux)
 npm run profile       # build, then the suite under --cpu-prof into prof/
 npm run clean         # rm -rf {build,dist}
 ```
@@ -108,7 +109,7 @@ every compile. Edit the generator, not its output.
 | `src/index.ts` | Public API and its overloads: `derive`, `sign`, `verify`, `verify_blocks` |
 | `src/lib/wasm.ts` | Instantiates the module and checks the error-code contract; exports `constants`, `Mutex`, and the mutex-gated `setInput()` and `getOutput()` |
 | `src/lib/errors.ts` | Error classes, the host's error-code table, and the `env.abort` handler that turns codes into messages |
-| `src/lib/bytes.ts` | Prototype methods, accessors, the typed array constructors and `String.fromCharCode` captured at load, the helpers built on them, `normalize()`, and hex encoding and constant-time decoding. Imports only `errors.ts`, which imports nothing |
+| `src/lib/bytes.ts` | Prototype methods, accessors, the `ArrayBuffer` and typed array constructors and `String.fromCharCode` captured at load, the helpers built on them, `normalize()`, and hex encoding and constant-time decoding. Imports only `errors.ts`, which imports nothing |
 | `src/lib/{derive,sign,verify}.ts` | Host-side marshalling, one file per primitive. `verify.ts` captures the static functions `verify_blocks` uses |
 | `src/assembly/index.ts` | Wasm entry points, static I/O buffers, the byte setters and getters, and exported constant globals |
 | `src/assembly/crypto_{derive,sign,verify}.ts` | RFC 8032-shaped primitives over BLAKE2b |
@@ -126,6 +127,7 @@ every compile. Edit the generator, not its output.
 | `test/mutants.mjs` | Mutation tests for the start-function guards |
 | `test/module.mjs` | Drives the compiled module directly: secret residue by memory diff, input buffers scrubbed on every path, and `OUTPUT_VERIFY` polarity |
 | `test/arithmetic.mjs` | Differential tests of the internals over a probe build, against `test/reference.mjs` |
+| `test/heap.mjs` | Runs each primitive in a child process and searches that process's memory for the private key and its words |
 | `test/reference.mjs` | Independent BigInt Ed25519-BLAKE2b, both verification rules; tests only |
 | `test/vectors/python_ed25519_blake2b.ts` | The bulk vector set, split out to stop crashing the IDE |
 | `test/vectors/torsion.ts` | The nano.org signature with `R` offset by each small-order point, and with `R` at the identity |
@@ -135,14 +137,26 @@ every compile. Edit the generator, not its output.
 
 Only integers cross the boundary, and the module's memory is neither imported
 nor exported, so the host never holds a view of it. The host packs inputs into
-little-endian 32-bit words and writes them into fixed static buffers with
+little-endian integers and writes them into fixed static buffers with
 `setInputMsg(index, …)`, `setInputPrv`, `setInputPub` and `setInputSig`, calls an
 export that takes only a length or a count, and reads results back a byte at a
 time with `getOutputDeriveByte`, `getOutputSignByte` and `getOutputVerifyByte`.
 `setInputMsg` and the getters check their index first and raise
-`ERROR_INDEX_OUT_OF_RANGE`; the other setters always write their whole buffer. `src/lib/wasm.ts` reads the byte-length globals once
-at module load and re-exports them. Big-endian hosts take a byte-shifting path
-instead of the word view; `test/big-endian.mjs` forces it.
+`ERROR_INDEX_OUT_OF_RANGE`; the other setters always write their whole buffer.
+`src/lib/wasm.ts` reads the byte-length globals once at module load and
+re-exports them.
+
+The message, public key and signature cross as 32-bit words: on little-endian
+hosts through a `Uint32Array` view, and on big-endian hosts by shifting bytes,
+a path `test/big-endian.mjs` forces. **The private key crosses as sixteen
+16-bit halves, built from its bytes by shifts, on every host.** V8 boxes a
+number outside its small-integer range as a separate heap object whenever the
+code is not yet optimized, which is every process's first calls, and nothing
+can clear that object: words of 2³¹ or more on Node, 2³⁰ or more in Chromium.
+Packed as 32-bit words, every such word of the key was left behind; a 16-bit
+value is small on every engine. `setInputPrv` masks each parameter to 16 bits,
+so a caller passing more cannot bleed into the next half. Do not "optimise" the
+key back onto the word view; `test:heap` fails if anything does.
 
 | Buffer | Purpose |
 | --- | --- |
@@ -252,12 +266,14 @@ a bound `Function.prototype.call`: the `%TypedArray%.prototype` getters, `set`
 and `fill`, the `ArrayBuffer.prototype.byteLength` getter, and
 `String.prototype.charCodeAt`. Code that patches a prototype after the package
 loads therefore cannot change what is validated, copied, scrubbed or decoded.
-The `Uint8Array` and `Uint32Array` constructors are captured there too, because
-key bytes pass through both: `words()` builds a `Uint32Array` over the private
-key's own buffer, so a global replaced after load was handed every key, and it
-still would be under `--frozen-intrinsics` and SES `lockdown()`, which freeze
-intrinsics but leave global bindings writable. Allocate with `allocate()`,
-never `new Uint8Array`, on a call path. `verify.ts` captures `Array.isArray`,
+The `ArrayBuffer`, `Uint8Array` and `Uint32Array` constructors are captured
+there too. `allocate()` builds every buffer, the private key's included, from
+the first two, and `words()` builds a `Uint32Array` over every message, public
+key and signature, so a global replaced after load could see or change them,
+and still could under `--frozen-intrinsics` and SES `lockdown()`, which freeze
+intrinsics but leave global bindings writable. Before the private key moved to
+16-bit halves, `words()` handed a replaced `Uint32Array` every key. Allocate
+with `allocate()`, never `new Uint8Array`, on a call path. `verify.ts` captures `Array.isArray`,
 `Object.create`, `Object.defineProperty` and `Object.freeze`, which build
 `verify_blocks`'s result: replacing `Object.defineProperty` after load once
 made a forged block read `true`. `bytes.ts` captures `String.fromCharCode`,
@@ -275,9 +291,9 @@ unloadable in a locked-down realm. Node tames some assignments that would trip
 over a frozen prototype, such as an `Error` subclass assigning its own
 `prototype.name`, so the run catches writes to built-ins themselves, not every
 assignment a stricter lockdown might refuse. SES itself is not part of the
-suite; `test/node.mjs` passed after `lockdown()` from `ses` 2.3.0 on 2026-10-16,
-6220 / 0, with the same patches skipped as under frozen intrinsics. That was the
-suite as of `e9ddef1`; it has not been re-run under SES since.
+suite; `test/node.mjs` passed after `lockdown()` from `ses` 2.3.0 on 2026-10-17,
+6228 / 0, with the same patches skipped as under frozen intrinsics and the
+three global replacements run. Re-run it by hand after changing the suite.
 
 **Results are defined, never assigned.** `verify_blocks` defines each element
 of its `boolean[]` with the captured `Object.defineProperty` and a descriptor
@@ -300,10 +316,37 @@ and the error never names the character. A `NIBBLE[char]` lookup measured
 fixed-vs-random |t| 5.5–8.6 against a null control ≤ 0.56. The arithmetic
 decoder read 0.36–1.39 over four runs on 2026-10-16, against a random-vs-random
 null of 0.21–1.29, all under the 4.5 alarm. Byte keys move only through
-`copy()`, `fill()` and the word packing in `wasm.ts`. Keep anything a private key passes through free of secret-dependent
-branches, indexing and lookups. A hex string cannot be scrubbed, because
-JavaScript strings are immutable; a caller who cares passes bytes and clears
-them.
+`copy()`, `fill()` and the 16-bit packing in `setInputPrv`. Keep anything a
+private key passes through free of secret-dependent branches, indexing and
+lookups. A hex string cannot be scrubbed, because JavaScript strings are
+immutable; a caller who cares passes bytes and clears them.
+
+**No copy of a key outlives a call in the JavaScript heap either.** Clearing
+the host's own buffers in `finally` is not enough, because V8 makes copies
+the host never sees. Until 2026-10-17 a cold `derive` left the whole key in a
+host buffer, and every large word of it boxed, after the caller had cleared its
+own bytes:
+
+- V8 keeps a typed array of 64 bytes or less inside its own heap. The first
+  read of its `buffer` moves the bytes out and abandons the originals unzeroed,
+  so `fill()` clears only the new copy. `words()` read it on the host's key
+  buffer while that held the first key of the process. `allocate()` now builds
+  every buffer over an `ArrayBuffer`, which V8 never keeps in its heap.
+- Unoptimized code, which is every process's first calls, boxes a number
+  outside the small-integer range as a heap object. Reading the key as 32-bit
+  words left every word of 2³¹ or more behind, and eight words are the key,
+  given 40,320 orders to try. `setInputPrv` now takes 16-bit halves.
+
+`isBytes()` still reads `buffer` on the caller's own array, which it must, to
+refuse shared memory, so a key passed as a `new Uint8Array(32)` leaves the
+caller's original bytes behind. Nothing short of skipping that check avoids it;
+the README tells callers to pass keys as a view over an `ArrayBuffer`.
+
+A heap snapshot cannot see any of this, even with numeric values exposed: it
+holds only objects still reachable after a collection, and residue is garbage
+by definition. `test:heap` runs each primitive in a child process and searches
+the child's memory from outside. It runs on Linux with Node; Chromium boxes
+from 2³⁰ rather than 2³¹, which the halves also cover, but no browser is tested.
 
 ## Wasm error reporting
 
@@ -586,13 +629,13 @@ show up on the clock; only the point arithmetic does.
 
 ## Testing
 
-`npm test` builds, then runs six suites: `test/node.mjs` little-endian,
-big-endian and under `--frozen-intrinsics`, then `test:mutants`, `test:module`
-and `test:arithmetic`. Current state is **6362, 6362, 6222, 17, 12 and 47
-passing, 0 failing**; the frozen run skips the 140 checks under prototype and
-static patches, since frozen intrinsics cannot be patched, but keeps the 10
-under global replacements. There
-is no expected failure — if anything fails, it is a regression. `test:all`
+`npm test` builds, then runs seven suites: `test/node.mjs` little-endian,
+big-endian and under `--frozen-intrinsics`, then `test:mutants`, `test:module`,
+`test:arithmetic` and `test:heap`. Current state is **6368, 6368, 6228, 17, 12,
+47 and 10 passing, 0 failing**; the frozen run skips the 140 checks under
+prototype and static patches, since frozen intrinsics cannot be patched, but
+keeps the 15 under global replacements. `test:heap` reports SKIP and passes
+nothing off Linux. There is no expected failure — if anything fails, it is a regression. `test:all`
 chains them with `&&`, so the first red suite stops the rest; run them one by
 one when chasing more than one failure. Every suite sets `process.exitCode`
 rather than calling `process.exit()`, which could cut off output still draining
@@ -841,11 +884,11 @@ uncaptured is caught. The `verify_blocks` case verifies a valid and a forged
 block and requires own elements and a frozen array, because a patch that
 answers `true` for everything passes a valid-only batch. `verify` takes its message as hex and
 `sign` as bytes, so both copies `normalize()` allocates are made under every
-patch. After those patches, `globalThis.Uint8Array` and
-`globalThis.Uint32Array` are replaced with constructors that throw, and every
-primitive runs again. `test:frozen` skips the prototype and static patches, since
-frozen intrinsics cannot be patched, but runs the two replacements, since
-frozen intrinsics leave global bindings writable.
+patch. After those patches, `globalThis.ArrayBuffer`, `globalThis.Uint8Array`
+and `globalThis.Uint32Array` are replaced with constructors that throw, and
+every primitive runs again. `test:frozen` skips the prototype and static
+patches, since frozen intrinsics cannot be patched, but runs the three
+replacements, since frozen intrinsics leave global bindings writable.
 
 Errors raised while the mutex is held — invalid input to `derive`, `sign` and
 `verify`, a bad block or key in `verify_blocks`, a throwing block getter, and a
@@ -854,6 +897,12 @@ outer call completes. Hex input is checked against all 256 byte values in lower,
 upper and mixed case, and 15 invalid characters at every position of a private
 key, including code units above `0xff` whose low byte is a valid digit.
 
+`sign` derives the public key and refuses one that does not match, which is a
+"return false unless equal" comparison like `equalbytes`, so it is corrupted
+the same two ways: every bit of every byte, and `0x80` at all 496 pairs of
+bytes. Until 2026-10-17 only byte 0 was ever changed, and a comparison that
+skipped byte 31, or bytes 1 to 31, passed every suite.
+
 ### Below the API: `test:module` and `test:arithmetic`
 
 `test:module` builds probes with memory exported and checks three things the
@@ -878,6 +927,27 @@ reproduces. Its controls drop `ge_p3_0(r)`, recompute `T` as `X·Y`, and, in one
 probe, drop both canonicity checks and the malformed-point term from each of
 the two small-order predicates; each of the six must be seen.
 
+### Beside the API: `test:heap`
+
+`test:heap` checks that no copy of a private key is left anywhere in the
+process, the JavaScript heap included, once a call returns and the caller has
+cleared its own bytes (see **Host-side invariants**). Each of `derive` and
+`sign`, from bytes and from hex, and a `sign` refused for a mismatched key, runs
+in a child process that clears its key and waits, while a scanner reads every
+writable mapping of the child through `/proc/<pid>/mem` and searches it for
+the 32 key bytes and for each 32-bit word of the key as a double, signed and
+unsigned. Every word of the test key has its top bit set, so none can be a
+small integer, and the caller's key is a view over an `ArrayBuffer`, so every
+copy found is the package's. Scanners run in parallel, about 13 s in all.
+
+Its controls: a child that reads `buffer` on a heap copy of the key, and one
+that boxes a word of it, must each be seen; so must two host builds bundled
+with esbuild beside the built wasm, one without `fill(privateKey, 0)` in
+`derive()` and one packing the key through `words()` again; and a child that
+never uses the key must show nothing. **Do not run it under the big-endian
+preload:** that changes V8's heap enough that even the first control's copy is
+gone by the time the scan reads it, so a clean result there means nothing.
+
 ## Style
 
 - Tabs for indentation, no semicolons, single quotes.
index 3c459784bfc4f4dbdac4e9cc05cac0f851fed7f5..fa2ed2dd74689be2265d6dbd8f51154a1349816f 100644 (file)
--- a/README.md
+++ b/README.md
@@ -71,6 +71,31 @@ string. To receive bytes instead, pass a preallocated output buffer as an
 additional optional argument; the result bytes are written into it directly, and
 the return value is `undefined` instead of a string.
 
+### Clearing private keys
+
+To be able to clear a private key after use, pass it as bytes viewed over an
+`ArrayBuffer`, and clear it with `fill(0)`, as the examples below do:
+
+```javascript
+// `usersPrivateKeyBuffer` is an ArrayBuffer holding the 32-byte private key, so
+// `prv` is a view of it, not a copy
+const prv = new Uint8Array(usersPrivateKeyBuffer);
+
+const pub = nano25519.derive(prv);
+// clean up
+prv.fill(0);
+```
+
+A small array created with `new Uint8Array(32)` or `Uint8Array.from()` is
+stored inside the JavaScript engine's own heap in V8 (Chromium and NodeJS). The
+first time anything reads its `buffer`, as `nano25519` does to reject shared
+memory, V8 moves the bytes out and leaves the originals behind, where
+`prv.fill(0)` cannot reach them. A view over an `ArrayBuffer` never moves, so
+`fill(0)` clears its only copy. Pass `new Uint8Array()` the `ArrayBuffer`
+itself: given another typed array, it copies it into a new, small array. A
+hexadecimal string cannot be cleared at all, since JavaScript strings are
+immutable.
+
 ### Derive (bytes)
 
 ```javascript
@@ -243,14 +268,20 @@ the API functions.
 
 ## Security
 
-Arguments are validated and copied before use. Prototype methods, `Uint8Array`
-and `Uint32Array` constructors, and `Object`, `Array` and `String` functions are
-captured on load, so patching or replacing them afterwards cannot alter results
-or expose a key. `nano25519` does **not** defend against code that runs before
-it loads. [HardenedJavaScript](https://hardenedjs.org/) `lockdown()` and the
-NodeJS `--frozen-intrinsics` flag prevent patching of built-ins, but they leave
-global variables writable, so code must run in its own compartment or realm to
-truly avoid conflicts.
+Arguments are validated and copied before use. Prototype methods, the
+`ArrayBuffer`, `Uint8Array` and `Uint32Array` constructors, and `Object`,
+`Array` and `String` functions are captured on load, so patching or replacing
+them afterwards cannot alter results or expose a key. `nano25519` does **not**
+defend against code that runs before it loads.
+[HardenedJavaScript](https://hardenedjs.org/) `lockdown()` and the NodeJS
+`--frozen-intrinsics` flag prevent patching of built-ins, but they leave global
+variables writable, so code must run in its own compartment or realm to truly
+avoid conflicts.
+
+`nano25519` clears every buffer it copies a private key into before a call
+returns. On NodeJS, the tests check that no copy remains, either in WebAssembly
+memory or anywhere else in the process, when the key is passed as bytes over an
+`ArrayBuffer` (see [Clearing private keys](#clearing-private-keys)).
 
 While effort has been applied to secure this code base, it has not been audited
 by a third-party, so it provides no guarantee of security, fitness, or accuracy.
@@ -281,6 +312,9 @@ Tests are available in the source repository under `test/`.
   is left in its memory and that every input buffer is cleared.
 - `arithmetic.mjs` compares the field, scalar and group arithmetic against
   `reference.mjs`, an independent implementation used only by the tests.
+- `heap.mjs` runs each operation in a child process and searches that
+  process's memory, on Linux, to check that no copy of a private key is left
+  anywhere once the call returns and the caller clears its own bytes.
 - `vectors.mjs` is generated by `esbuild` using the files found in
   `test/vectors`.
 - `index.html` is a web interface to test browser execution and compare
index 5be3e6c013761c1c4a8ddefd7d22c532155d4f8f..961576565e6e11d4001f0b7d771c78be42766808 100644 (file)
@@ -12,7 +12,8 @@ import { Nano25519RangeError, Nano25519TypeError, } from './errors'
  * read internal slots, which a caller's subclass cannot override, so use these
  * helpers on every typed array instead of its own properties, and use
  * `allocate(byteLength)` instead of `new Uint8Array(byteLength)` and
- * `words(buffer)` instead of `new Uint32Array(buffer)`.
+ * `words(buffer)` instead of `new Uint32Array(buffer)`. The `ArrayBuffer`
+ * constructor is captured too, because `allocate()` builds on it.
  */
 
 /** Type aliases for legibility. */
@@ -56,7 +57,15 @@ function isArrayBuffer (a: unknown): a is ArrayBuffer {
        return false
 }
 
-/** Captured version of `new Uint8Array(length)` with argument type-checking. */
+/**
+ * Captured version of `new Uint8Array(length)` with argument type-checking.
+ *
+ * Always over an `ArrayBuffer`: V8 keeps a `new Uint8Array(length)` of 64
+ * bytes or less inside its own heap, and the first read of its `buffer` moves
+ * the bytes out and leaves the originals behind, unzeroed, where `fill()` can
+ * never reach them. A key written into such a buffer outlives every scrub.
+ * `test:heap` searches the process for exactly that.
+ */
 export function allocate (byteLength: number): Bytes {
        const length = byteLength
        if (typeof length !== 'number') {
index d38b4de3b6097d9a60954be27b64d6ddbab5ab9b..1f18eee8b463db30033df1eb7d9213772f2abaa2 100644 (file)
@@ -174,8 +174,12 @@ function setInputMsg (message: Bytes): void {
  * separately on the heap and can remain after zeroing the key, while reading
  * bytes produces small integers that never get their own heap objects and are
  * generally indistinguishable from other unrelated bytes. Values are built as
- * 16-bit words so that they do not get stored on the heap by the JIT engine as
- * it does with about half of 32-bit words.
+ * 16-bit words because V8 boxes any number outside its small-integer range as
+ * a separate heap object whenever the code is not yet optimized, which is the
+ * first calls of every process: unsigned words of 2³¹ or more on 64-bit Node,
+ * and of 2³⁰ or more in Chromium, so at least half of all 32-bit words. Packed
+ * as 32-bit words, each such word of the key was left in memory. A 16-bit
+ * value is small everywhere. `test:heap` checks this.
  */
 function setInputPrv (b: Bytes): void {
        exports.setInputPrv(