--- /dev/null
+//! SPDX-FileCopyrightText: 2026 Chris Duncan <chris@codecow.com>
+//! SPDX-License-Identifier: GPL-3.0-or-later
+
+/**
+ * Tests that the host leaves no copy of a private key anywhere in the process
+ * once a call returns and the caller has cleared its own bytes.
+ *
+ * `test:module` diffs wasm memory, which host code never touches. The host's
+ * JavaScript leaked the key in two ways of its own, found on 2026-10-17, and
+ * a V8 heap snapshot shows neither, because it only holds objects still
+ * reachable after a collection:
+ *
+ * - V8 keeps a typed array of 64 bytes or less inside its own heap, and the
+ * first read of its `buffer` moves the bytes out and abandons the originals
+ * unzeroed. `words()` read it on the host's key buffer while it held a key.
+ * `allocate()` now backs every buffer with an `ArrayBuffer`, which V8 never
+ * keeps in its heap.
+ * - Unoptimized code boxes a number that is not a small integer as a separate
+ * heap object, so packing the key as 32-bit words left every word behind.
+ * `setInputPrv` now takes sixteen 16-bit halves, which are always small.
+ *
+ * So each case runs in a child process that scrubs its key and waits, while
+ * this process reads the child's whole address space through `/proc/<pid>/mem`
+ * and searches it for the 32 key bytes, and for each 32-bit word of the key as
+ * an IEEE double, signed and unsigned. Every word of the key has its top bit
+ * set, so none of them can be a small integer. The caller's key is a view over
+ * an `ArrayBuffer`, as the README advises, so any copy found is the package's.
+ *
+ * Positive controls prove the search can fire: a child that reads `buffer` on
+ * a copy of the key held in the heap, a child that boxes a word of the key,
+ * and two host builds with a leak seeded back in, one without the
+ * `fill(privateKey, 0)` in `derive()` and one packing the key through
+ * `words()` again, must each be seen. A child that never touches the key must
+ * show nothing, so the patterns do not occur by chance.
+ *
+ * Linux only, and this process must be allowed to read its child's memory,
+ * which `kernel.yama.ptrace_scope` 0 or 1 permits. Elsewhere the suite reports
+ * SKIP and passes nothing.
+ */
+
+import { spawn } from 'node:child_process'
+import { closeSync, openSync, readFileSync, readSync } from 'node:fs'
+import { copyFile, cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { availableParallelism } from 'node:os'
+import { build } from 'esbuild'
+
+const root = new URL('../', import.meta.url)
+const work = new URL('build/heap/', root)
+
+/** Byte `i` of the key; positions 3, 7, … 31 set the top bit of every word. */
+const keyByte = (i) => ((i * 37 + 11) & 255) | (i % 4 === 3 ? 0x80 : 0)
+
+/**
+ * The child. It builds the key byte by byte in an `ArrayBuffer`, so it never
+ * holds a word of it, runs one operation, clears its own copies the way the
+ * README tells callers to, and waits to be read.
+ */
+const CHILD = `
+const [dist, op] = process.argv.slice(2)
+const { derive, sign } = await import(dist)
+const keyByte = ${keyByte.toString()}
+const prv = new Uint8Array(new ArrayBuffer(32))
+for (let i = 0; i < 32; i++) prv[i] = keyByte(i)
+const hex = Array.from(prv, (b) => b.toString(16).padStart(2, '0')).join('')
+const pub = new Uint8Array(new ArrayBuffer(32))
+const sig = new Uint8Array(new ArrayBuffer(64))
+const msg = new Uint8Array(new ArrayBuffer(32)).fill(0x11)
+switch (op) {
+ case 'none': break
+ case 'heap copy': { const copy = new Uint8Array(32); copy.set(prv); copy.buffer; copy.fill(0); break }
+ case 'boxed word': { let w = new Uint32Array(prv.buffer)[0]; w = 0; break }
+ case 'derive': derive(prv, pub); break
+ case 'derive from hex': derive(hex, pub); break
+ case 'sign': derive(prv, pub); sign(msg, prv, pub, sig); break
+ case 'sign from hex': derive(hex, pub); sign(msg, hex, pub, sig); break
+ // pub is never derived here, so it is all zeros and sign refuses it
+ case 'failed sign': try { sign(msg, prv, pub, sig) } catch { } break
+ default: throw new Error('unknown operation ' + op)
+}
+prv.fill(0)
+process.stdout.write('ready\\n')
+setInterval(() => { }, 1 << 30)
+`
+
+/** Seeded leaks; `from` must occur once inside `fn`. */
+const NO_SCRUB = [{ file: 'src/lib/derive.ts', fn: 'derive', from: '\t\tfill(privateKey, 0)\n', to: '' }]
+const WORD_PACKING = [{
+ file: 'src/lib/wasm.ts',
+ fn: 'setInputPrv',
+ from: 'function setInputPrv (b: Bytes): void {\n',
+ to: 'function setInputPrv (b: Bytes): void {\n\tconst w = words(b)\n\treturn exports.setInputPrv(' + Array.from({ length: 8 }, (_, i) => `w[${i}] & 0xffff, w[${i}] >>> 16`).join(', ') + ')\n'
+}]
+
+/** Copies the host sources beside the built wasm, applies the edits, and bundles. */
+async function host (name, edits) {
+ const dir = new URL(`${name}/`, work)
+ await mkdir(new URL('build/', dir), { recursive: true })
+ await cp(new URL('src/', root), new URL('src/', dir), { recursive: true })
+ await copyFile(new URL('build/nano25519.wasm', root), new URL('build/nano25519.wasm', dir))
+ for (const edit of edits) {
+ const path = new URL(edit.file, dir)
+ const source = await readFile(path, 'utf8')
+ const start = source.indexOf(`function ${edit.fn} (`)
+ const end = source.indexOf('\n}\n', start)
+ const body = source.slice(start, end)
+ if (start < 0 || end < 0 || body.split(edit.from).length !== 2) {
+ throw new Error(`control no longer applies: "${edit.from.trim()}" must occur once in ${edit.fn}()`)
+ }
+ await writeFile(path, source.slice(0, start) + body.replace(edit.from, edit.to) + source.slice(end))
+ }
+ const outfile = new URL('dist/index.js', dir).pathname
+ await build({ bundle: true, format: 'esm', platform: 'node', target: 'node22', loader: { '.wasm': 'binary' }, entryPoints: [new URL('src/index.ts', dir).pathname], outfile, logLevel: 'silent' })
+ return outfile
+}
+
+const key = Uint8Array.from({ length: 32 }, (_, i) => keyByte(i))
+const words = Array.from({ length: 8 }, (_, w) => new DataView(key.buffer).getUint32(4 * w, true))
+const double = (v) => { const b = Buffer.alloc(8); b.writeDoubleLE(v); return b }
+/** `[name, bytes]` for the key and each word of it as a double, unsigned and signed. */
+const NEEDLES = [['key', Buffer.from(key)], ...words.flatMap((v, w) => [[`word ${w}`, double(v)], [`word ${w}`, double(v | 0)]])]
+const CHUNK = 1 << 24
+
+/**
+ * Runs `op` in a child against the bundle at `dist`, then searches every
+ * writable mapping of the child's memory, where anything the child computed
+ * must live. Returns the number of distinct addresses of each needle found.
+ * @returns {Promise<Record<string, number>>}
+ */
+async function scan (dist, op) {
+ const child = spawn(process.execPath, [new URL('child.mjs', work).pathname, dist, op], { stdio: ['ignore', 'pipe', 'pipe'] })
+ let stderr = ''
+ child.stderr.on('data', (d) => { stderr += d })
+ const ready = await new Promise((resolve) => {
+ child.stdout.once('data', () => resolve(true))
+ child.once('exit', () => resolve(false))
+ })
+ if (!ready) throw new Error(`child for "${op}" exited: ${stderr.trim().split('\n').at(-1)}`)
+ /** @type {Map<string, Set<number>>} */
+ const hits = new Map()
+ const buf = Buffer.alloc(CHUNK)
+ const fd = openSync(`/proc/${child.pid}/mem`, 'r')
+ try {
+ for (const line of readFileSync(`/proc/${child.pid}/maps`, 'utf8').trim().split('\n')) {
+ const [range, perms] = line.split(/\s+/)
+ if (!perms.startsWith('rw')) continue
+ const [lo, hi] = range.split('-').map((h) => parseInt(h, 16))
+ // overlap reads by a needle's length so none is split across two of them
+ for (let at = lo; at < hi; at += CHUNK - 32) {
+ let n = 0
+ try { n = readSync(fd, buf, 0, Math.min(CHUNK, hi - at), at) } catch { break }
+ const read = buf.subarray(0, n)
+ for (const [name, needle] of NEEDLES) {
+ for (let p = read.indexOf(needle); p >= 0; p = read.indexOf(needle, p + 1)) {
+ if (!hits.has(name)) hits.set(name, new Set())
+ hits.get(name)?.add(at + p)
+ }
+ }
+ if (at + n >= hi) break
+ }
+ }
+ } finally {
+ closeSync(fd)
+ child.kill()
+ }
+ return Object.fromEntries([...hits].map(([name, at]) => [name, at.size]))
+}
+
+/**
+ * Runs `scan()` in a process of its own, this file run with `--scan`, so that
+ * several searches run at once; each is one thread of `indexOf` over hundreds
+ * of megabytes.
+ * @returns {Promise<Record<string, number>>}
+ */
+function scanner (dist, op) {
+ return new Promise((resolve, reject) => {
+ const proc = spawn(process.execPath, [new URL(import.meta.url).pathname, '--scan', dist, op], { stdio: ['ignore', 'pipe', 'pipe'] })
+ let out = ''
+ let err = ''
+ proc.stdout.on('data', (d) => { out += d })
+ proc.stderr.on('data', (d) => { err += d })
+ proc.once('exit', (code) => {
+ try {
+ if (code !== 0) throw new Error(err.trim().split('\n').find((l) => l.startsWith('Error')) ?? `scanner exited ${code}`)
+ resolve(JSON.parse(out))
+ } catch (e) {
+ reject(e)
+ }
+ })
+ })
+}
+
+/** Runs `fn` over `items` with at most `limit` in flight, keeping order. */
+async function pool (items, limit, fn) {
+ const results = []
+ let next = 0
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
+ while (next < items.length) {
+ const i = next++
+ results[i] = await fn(items[i], i)
+ }
+ }))
+ return results
+}
+
+let passes = 0
+let failures = 0
+function check (name, test, detail = '') {
+ console.log(`${test ? '\x1b[32mPASS' : '\x1b[31mFAIL'}\x1b[0m: ${name}${!test && detail ? ` (${detail})` : ''}`)
+ passes += +test
+ failures += +!test
+}
+
+async function main () {
+ const started = performance.now()
+ let scans = 0
+ if (process.platform !== 'linux') {
+ console.log(`\x1b[33mSKIP\x1b[0m: reading a child's memory needs /proc, which ${process.platform} does not have`)
+ return
+ }
+ await rm(work, { recursive: true, force: true })
+ try {
+ await mkdir(work, { recursive: true })
+ await writeFile(new URL('child.mjs', work), CHILD)
+ const dist = new URL('dist/index.js', root).pathname
+ const [noScrub, wordPacking] = await Promise.all([
+ host('no-scrub', NO_SCRUB).catch((err) => err),
+ host('word-packing', WORD_PACKING).catch((err) => err),
+ ])
+ const hasKey = (h) => h.key > 0
+ const hasWords = (h) => Object.keys(h).some((name) => name.startsWith('word '))
+ const none = (h) => Object.keys(h).length === 0
+
+ /** @type {[string, unknown, string, (h: Record<string, number>) => boolean][]} */
+ const cases = [
+ // positive controls: the search sees a stale heap copy and a boxed word,
+ // and sees each leak the host once had when it is seeded back in
+ ['search finds the key left in the heap by reading buffer on a copy of it', dist, 'heap copy', hasKey],
+ ['search finds a word of the key boxed as a number', dist, 'boxed word', hasWords],
+ ['search finds the key left by a derive() without fill(privateKey, 0)', noScrub, 'derive', hasKey],
+ ['search finds the words left by packing the key through words()', wordPacking, 'derive', hasWords],
+ // the patterns do not occur by chance
+ ['no copy of the key or its words in a child that never uses it', dist, 'none', none],
+ ]
+ for (const op of ['derive', 'derive from hex', 'sign', 'sign from hex', 'failed sign']) {
+ cases.push([`no copy of the key or its words after ${op}`, dist, op, none])
+ }
+ scans = cases.length
+ const results = await pool(cases, Math.max(1, availableParallelism() - 1), ([, bundle, op]) => typeof bundle !== 'string'
+ ? Promise.resolve(String(bundle?.message ?? bundle))
+ : scanner(bundle, op).catch((err) => String(err?.message ?? err)))
+ cases.forEach(([name, , , test], i) => {
+ const r = results[i]
+ // a child that cannot be read is a failed check, not a crash
+ if (typeof r === 'string') return check(name, false, r)
+ check(name, test(r), Object.entries(r).map(([k, n]) => `${k} ×${n}`).join(', ') || 'nothing found')
+ })
+ } finally {
+ await rm(work, { recursive: true, force: true })
+ console.log(`${passes} \x1b[32mPASSED\x1b[0m`)
+ console.log(`${failures} \x1b[31mFAILED\x1b[0m`)
+ console.log(`2 builds and ${scans} scans in ${((performance.now() - started) / 1000).toFixed(1)} s`)
+ }
+}
+
+if (process.argv[2] === '--scan') {
+ process.stdout.write(JSON.stringify(await scan(process.argv[3], process.argv[4])))
+} else {
+ await main()
+ process.exitCode = failures > 0 ? 1 : 0
+}
passes += +test
failures += +!test
+// sign() refuses a public key that does not match the one it derives, which is
+// a "return false unless equal" comparison like equalbytes, so corrupt it the
+// same two ways: every bit of every byte, and 0x80 at every pair of bytes, the
+// delta that cancels in an accumulator built with ^= or +=. The check above
+// changes byte 0 only, and a comparison that skipped bytes 1 to 31 passed it.
+{
+ const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub } = NANO_ORG_VECTOR
+ const wrong = pub.slice()
+ /** @type {string[]} */
+ const accepted = []
+ const refused = () => {
+ const r = attempt(() => sign(hash, prv, wrong))
+ wrong.set(pub)
+ return r === 'threw Invalid public key'
+ }
+ for (let i = 0; i < constants.KEY_BYTELENGTH; i++) {
+ for (let bit = 0; bit < 8; bit++) {
+ wrong[i] ^= 1 << bit
+ if (!refused()) accepted.push(`byte ${i} ^ 0x${(1 << bit).toString(16)}`)
+ }
+ for (let j = i + 1; j < constants.KEY_BYTELENGTH; j++) {
+ wrong[i] ^= 0x80
+ wrong[j] ^= 0x80
+ if (!refused()) accepted.push(`bytes ${i} and ${j} ^ 0x80`)
+ }
+ }
+ // the sweep only asserts refusals, so assert the baseline too or it dies quietly
+ const baseline = attempt(() => sign(hash, prv, pub))
+ test = typeof baseline === 'string' && baseline === NANO_ORG_VECTOR.signature.toLowerCase() && accepted.length === 0
+ check(`sign refuses a public key that differs from the derived one in any bit or pair of bytes${test ? '' : ` (baseline ${baseline}; accepted ${accepted.length}, first ${JSON.stringify(accepted.slice(0, 4))})`}`, test)
+ passes += +test
+ failures += +!test
+}
+
// Check verification of live cemented block from small-order public key
result = attempt(() => verify(PROBLEM_VECTOR.signature, PROBLEM_VECTOR.blockHash, PROBLEM_VECTOR.publicKey))
test = result === false
}
// Prototype methods and accessors patched after the module loaded, the
-// static functions the host captures, and the Uint8Array and Uint32Array
-// globals replaced after it loaded, must not change results. Every primitive
-// runs under every patch. derive never touches the message buffer, so a
-// derive-only loop stayed green while sign and verify were signing whatever
-// a patched %TypedArray%.prototype.buffer or DataView getUint32 handed them.
+// static functions the host captures, and the Uint8Array, Uint32Array and
+// ArrayBuffer globals replaced after it loaded, must not change results. Every
+// primitive runs under every patch. derive never touches the message buffer,
+// so a derive-only loop stayed green while sign and verify were signing
+// whatever a patched %TypedArray%.prototype.buffer or DataView getUint32
+// handed them.
// The message is 65 bytes so it crosses as two whole chunks plus a one-byte
// tail, exercising both marshalling paths. sign takes it as bytes and verify
// as hex, so both of the copies normalize() allocates are made under every
return () => { Object.freeze = real }
}]
]
-// The typed array constructors are captured at load because key bytes pass
-// through both: a replaced Uint32Array would be handed the private key's buffer
-// by the word packing. Global bindings stay writable under frozen intrinsics
-// and SES lockdown, so these run under test:frozen too.
+// The typed array constructors and ArrayBuffer are captured at load. The word
+// packing builds a Uint32Array over every message, public key and signature,
+// so a replaced one could change what is signed or verified, and allocate()
+// builds every buffer from the other two. The private key no longer passes
+// through a Uint32Array at all: it crosses as 16-bit halves read byte by byte.
+// Global bindings stay writable under frozen intrinsics and SES lockdown, so
+// these run under test:frozen too.
/** @type {[string, (() => () => void)][]} */
const replacements = [
['globalThis.Uint8Array', () => {
globalThis.Uint32Array = () => { throw new Error('patched') }
return () => { globalThis.Uint32Array = real }
}],
+ // allocate() backs every buffer with an ArrayBuffer, so V8 never holds a key
+ // in its own heap, and captures the constructor like the two above
+ ['globalThis.ArrayBuffer', () => {
+ const real = globalThis.ArrayBuffer
+ //@ts-expect-error
+ globalThis.ArrayBuffer = () => { throw new Error('patched') }
+ return () => { globalThis.ArrayBuffer = real }
+ }],
]
/** @type {[string, () => boolean][]} */
const patchedPrimitives = [