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 five suites below
-npm run test:prod # build:prod, then the same five suites; also prepublishOnly
+npm test # build, then all six suites below
+npm run test:prod # build:prod, then the same six 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
| `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/primordials.ts` | Trust root: built-ins captured at load, plus `normalize()`. Imports nothing, by design |
+| `src/lib/bytes.ts` | Prototype methods and accessors 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 |
| `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 |
## Host-side invariants
-Four properties the host now enforces rather than assumes. All four were
+Properties the host enforces rather than assumes. Most of them were
conventions that held only while every caller behaved.
**A mutex guards the shared buffers, and `Mutex.lock()` goes *outside* the
property is what makes the strict comparison redundant, so `test:module` asserts
it directly. Keep both.
-**Results are defined, never assigned.** `verify_blocks` builds its `boolean[]`
-with `slot()` from `primordials.ts`: `Object.defineProperty` with a descriptor
-from `Object.create(null)`, both captured at load. Assignment, `push` and `fill`
-all store through the prototype chain when the index is not yet the array's own,
-so a getter and setter added to `Array.prototype` after load swallowed every
-result and answered `true` for a forged block, with a correct `length` under
-`push`. The descriptor needs no prototype of its own, or a `get` added to
-`Object.prototype` makes it read as an accessor and the call throws. The
-hardening list in `test/node.mjs` patches both.
+**A caller's objects are read through their internal slots.** A caller can
+pass a `Uint8Array` subclass that lies through `length`, `byteLength`,
+`Symbol.toStringTag` or `Symbol.species`, or that overrides `set`.
+`src/lib/bytes.ts` reads type, backing buffer and length with the getters on
+`%TypedArray%.prototype` and `ArrayBuffer.prototype`, and moves bytes with
+`%TypedArray%.prototype.set` called on the object rather than looked up through
+it, so none of the caller's code runs and none of its answers are believed.
+Use `isBytes()`, `byteLength()`, `copy()` and `fill()` on every typed array,
+the caller's and the package's own alike, because they are also the captures
+below.
+
+**Prototype methods are captured at load; global constructors and static
+functions are not.** Every prototype method and accessor the host calls on a
+call path is taken from its prototype once, when `bytes.ts` is evaluated, and
+called through 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.
+Global constructors and static functions such as `Uint8Array`, `Uint32Array`,
+`Array.isArray`, `Object.create` and `Object.defineProperty` are looked up at
+call time. Replacing them is out of scope, as is anything that runs before the
+package loads: such code shares the caller's realm and can take the key wherever
+the caller handles it. An application that needs its realm intact should freeze
+it, with SES `lockdown()` or Node's `--frozen-intrinsics`, before loading this
+package. A new prototype method or accessor on a call path must be captured in
+`bytes.ts` and added to the patch list in `test/node.mjs`; a new global or
+static function need not be.
+
+`test:frozen` runs the suite under `--frozen-intrinsics`, so the package must
+never write to a built-in, at load or later: a polyfill would make it
+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 tested.
+
+**Results are defined, never assigned.** `verify_blocks` defines each element
+of its `boolean[]` with `Object.defineProperty` and a descriptor from
+`Object.create(null)`. Assignment, `push` and `fill` all store through the
+prototype chain when the index is not yet the array's own, so a getter and
+setter added to `Array.prototype` after load swallowed every result and
+answered `true` for a forged block, with a correct `length` under `push`. The
+descriptor needs no prototype of its own, or a `get` added to
+`Object.prototype` makes it read as an accessor and the call throws. The patch
+list in `test/node.mjs` patches both. The array is then frozen and returned as
+`readonly boolean[]`: assigning a result, `push`, `pop`, `sort` and truncating
+`length` all throw in strict mode and fail silently otherwise, while reads,
+`map` and `slice` work. Nothing in the suite asserts the freeze.
+
+**Host code that carries a secret is constant time.** A hex private key is
+decoded in `hexToBytes` by arithmetic on each character code, with no table
+lookup and no early exit: validity accumulates and is checked once at the end,
+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.80–2.23 over four runs on 2026-10-15, against a random-vs-random
+null of 1.18–3.49, 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.
## Wasm error reporting
## Testing
-`npm test` builds, then runs five suites: `test/node.mjs` little- and
-big-endian, then `test:mutants`, `test:module` and `test:arithmetic`. Current
-state is **6288, 6288, 17, 12 and 36 passing, 0 failing**. There is no expected
+`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 **6300, 6300, 6205, 17, 12 and 36
+passing, 0 failing**; the frozen run skips the 95 patch-list checks, since its
+prototypes cannot be patched. 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
reproducing the nano.org signature checks the generator. Before they existed,
`verify()` rejected every order-8 offset (see **Gotchas**) and nothing noticed.
-### Hardening, re-entrancy and hex input
-
-The patch list at the end of `test/node.mjs` replaces built-ins after load and
-runs every primitive under every patch: `Function.prototype.call`, typed-array
-and array methods and accessors, index accessors on `Array.prototype`, and
-`get`, `set` and `Symbol.iterator` on `Object.prototype`. The `verify_blocks`
-case verifies a valid and a forged block and requires own elements, because a
-patch that answers `true` for everything passes a valid-only batch. Errors
-raised while the mutex is held — invalid input to `verify`, a bad block or key
-in `verify_blocks`, a throwing block getter, and a wasm abort from `sign` — must
-each release it, and a getter that calls back in must be refused while the
+### Hostile arguments, patched prototypes, re-entrancy and hex input
+
+A `Uint8Array` subclass that lies through `Symbol.species`, `length`,
+`byteLength` and `Symbol.toStringTag`, and overrides `set`, is passed as every
+byte argument of every primitive and as both output buffers. Each call must
+return what plain bytes return, and the subclass's code must never run. Views
+over a `SharedArrayBuffer`, a bare `SharedArrayBuffer`, a `Uint16Array` and an
+output buffer that lies about its `byteLength` must each be rejected.
+
+The patch list at the end of `test/node.mjs` replaces 19 prototype methods and
+accessors after load and runs every primitive under every patch, `derive` once
+from bytes and once from hex: `Function.prototype.call`,
+`String.prototype.charCodeAt`, typed-array and array methods and accessors,
+index accessors on `Array.prototype`, and `get`, `set` and `Symbol.iterator` on
+`Object.prototype`. Some patch methods the host never calls, such as `slice`,
+`padStart` and `DataView.prototype.getUint32`, so that starting to call one
+uncaptured is caught. The `verify_blocks` case verifies a valid and a forged
+block and requires own elements, because a patch that answers `true` for
+everything passes a valid-only batch. Global constructors and static functions
+are not patched (see **Host-side invariants**). `test:frozen` skips the list,
+since frozen prototypes cannot be patched.
+
+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
+wasm abort from `sign` — must each release it, and a getter that calls back in must be refused while the
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.
| `MAX_VERIFY_BLOCKS_BYTELENGTH` | 6144 | Signatures and hashes of a full batch |
| `MAX_MESSAGE_BYTELENGTH` | 65536 | Largest message `sign()`/`verify()` accept |
+## Security
+
+Arguments are validated and copied before use, and prototype methods are
+captured on load, so monkey patching them afterwards cannot alter results.
+However, it does **not** defend against code that runs before it nor any code
+that replaces global objects like `Uint8Array`; that kind of conflict is not
+preventable, so if that is a concern,
+[HardenedJavaScript](https://hardenedjs.org/) and/or the NodeJS
+`--frozen-intrinsics` flag should be used.
+
+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.
+
## Notes
The tweetnacl-js implementation was originally selected as the basis for
- `node.mjs` is a test for NodeJS to check result validity. It runs a
derive-sign-verify sequence for public test vectors obtained from the
python-ed25519-blake2b library.
-- `big-endian.mjs` runs the NodeJS test again but prepatches the primordial
- `Words` class to emulate toggled endianness.
+- `big-endian.mjs` runs the NodeJS test again but replaces the global
+ `Uint32Array` before loading the package to emulate toggled endianness.
- `vectors.mjs` is generated by `esbuild` using the files found in
`test/vectors`.
- `mutants.mjs` builds copies of the module with known defects and checks that
the self-tests built into the module refuse to load every one of them.
Tests are run with a debug build using `npm t` and a production build with
-`npm run test:prod`. Mutation tests are run with `npm run test:mutants`.
+`npm run test:prod`. Mutation tests are run with `npm run test:mutants`, and the
+NodeJS test under frozen built-ins with `npm run test:frozen`.
## Building
"prepublishOnly": "npm run test:prod",
"profile": "npm run build && node --cpu-prof --cpu-prof-interval 50 --cpu-prof-dir prof test/node.mjs",
"test": "npm run build && npm run test:all",
- "test:all": "npm run test:le && npm run test:be && npm run test:mutants && npm run test:module && npm run test:arithmetic",
+ "test:all": "npm run test:le && npm run test:be && npm run test:frozen && npm run test:mutants && npm run test:module && npm run test:arithmetic",
"test:arithmetic": "node ./test/arithmetic.mjs",
"test:be": "node --import ./test/big-endian.mjs ./test/node.mjs",
+ "test:frozen": "node --frozen-intrinsics ./test/node.mjs",
"test:le": "node ./test/node.mjs",
"test:module": "node ./test/module.mjs",
"test:mutants": "node ./test/mutants.mjs",
*
* The package probes byte order once, at load, by writing `1` into a
* `Uint32Array` and reading its first byte. This swaps the global constructor
- * before the package captures it, so that one probe sees the big-endian layout
+ * before the package loads, so that one probe sees the big-endian layout
* and every other construction passes straight through to the real one.
*
* Forcing the path here is a faithful test of it, not an approximation: the
}
// An error raised while the mutex is held must release it. derive() and sign()
-// validate their inputs, and verify_blocks() its block count, before taking the
-// lock, so those throws never reach the finally that unlocks; these do.
+// check their output buffers, and verify_blocks() its block count, before taking
+// the lock, so those throws never reach the finally that unlocks; these do.
{
const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR
/** @type {[string, () => unknown][]} */
const inside = [
+ ['derive, invalid private key', () => derive('zz'.repeat(32))],
+ ['sign, invalid message', () => sign('zz', prv, pub)],
['verify, invalid message', () => verify(sig, 'zz', pub)],
['verify, invalid public key', () => verify(sig, hash, new Uint8Array(31))],
['verify_blocks, invalid public key', () => verify_blocks(new Uint8Array(31), [{ hash, signature: sig }])],
// Check bulk verification of Nano blocks
try {
- result = verify_blocks(NANO_ORG_VECTOR.publicKeyBytes, [{ hash: NANO_ORG_VECTOR.blockHashBytes, signature: NANO_ORG_VECTOR.signatureBytes }])[0]
+ result = verify_blocks(NANO_ORG_VECTOR.publicKeyBytes, [{ hash: NANO_ORG_VECTOR.blockHashBytes, signature: NANO_ORG_VECTOR.signatureBytes }])
} catch (err) {
console.log(err)
result = false
}
-test = result === true
+test = result[0] === true && Object.isFrozen(result)
check(`verify_blocks single hash bytes ${NANO_ORG_VECTOR.blockHash} with signature bytes ${NANO_ORG_VECTOR.signature}`, test)
passes += +test
failures += +!test
failures += +!test
// An output buffer that lies about its size must be caught by this library's own
-// validation, not by a RangeError escaping from the copy. isBytes() reads
-// internal slots, but the byteLength compared against it is a plain property
-// read, which a subclass can override.
+// validation, not by a RangeError escaping from the copy, so the byteLength
+// compared against the expected size must come from the internal slot, as
+// isBytes() does, never from a property a subclass can override.
try {
class SpoofedOutput extends Uint8Array {
get byteLength () { return 32 }
passes += +test
failures += +!test
-// Hardening: a hostile Uint8Array subclass must not reach input handling.
-// It lies through Symbol.species, length, byteLength and Symbol.toStringTag;
+// A hostile Uint8Array subclass must not reach input handling. It lies through
+// Symbol.species, length, byteLength and Symbol.toStringTag, and overrides set;
// none of those may be consulted, and none of its code may run inside a call.
-let speciesRan = 0
-class HostileBytes extends Uint8Array {
- static get [Symbol.species] () {
- speciesRan++
+// Every byte argument of every primitive is passed as one, plus the output
+// buffers, and each call must return what it returns for plain bytes.
+{
+ const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR
+ let ran = 0
+ class HostileBytes extends Uint8Array {
+ static get [Symbol.species] () {
+ ran++
+ //@ts-expect-error
+ return function (...args) { return new Uint8Array(...args) }
+ }
+ get length () { ran++; return 4 }
+ get byteLength () { ran++; return 4 }
+ //@ts-expect-error
+ get [Symbol.toStringTag] () { ran++; return 'Err' }
//@ts-expect-error
- return function (...args) { return new Uint8Array(...args) }
+ set () { ran++ }
+ }
+ /** @param {Uint8Array} b */
+ const hostile = (b) => new HostileBytes(b)
+ const derived = new HostileBytes(constants.KEY_BYTELENGTH)
+ const signed = new HostileBytes(constants.SIGNATURE_BYTELENGTH)
+ /** @type {[string, () => unknown, unknown][]} */
+ const cases = [
+ ['derive', () => derive(hostile(prv)), NANO_ORG_VECTOR.publicKey.toLowerCase()],
+ ['derive, output buffer', () => { derive(prv, derived); return [...derived] }, [...pub]],
+ ['sign', () => sign(hostile(hash), hostile(prv), hostile(pub)), NANO_ORG_VECTOR.signature.toLowerCase()],
+ ['sign, output buffer', () => { sign(hash, prv, pub, signed); return [...signed] }, [...sig]],
+ ['verify', () => verify(hostile(sig), hostile(hash), hostile(pub)), true],
+ ['verify_blocks', () => verify_blocks(hostile(pub), [{ hash: hostile(hash), signature: hostile(sig) }])[0], true],
+ ]
+ for (const [name, f, expected] of cases) {
+ ran = 0
+ result = attempt(f)
+ test = JSON.stringify(result) === JSON.stringify(expected) && ran === 0
+ check(`${name} ignores a hostile Uint8Array subclass${test ? '' : ` (returned ${JSON.stringify(result)}, ran its code ${ran} times)`}`, test)
+ passes += +test
+ failures += +!test
}
- get length () { return 4 }
- get byteLength () { return 4 }
- //@ts-expect-error
- get [Symbol.toStringTag] () { return 'Err' }
}
-speciesRan = 0
-//@ts-expect-error
-result = attempt(() => derive(new HostileBytes(NANO_ORG_VECTOR.privateKeyBytes)))
-test = result === NANO_ORG_VECTOR.publicKey.toLowerCase() && speciesRan === 0
-check(`derive ignores a hostile Uint8Array subclass`, test)
-passes += +test
-failures += +!test
-// Hardening: builtins patched after the module loaded must not change results.
-// Every primitive runs under every patch. derive never touches the message
+// Prototype methods and accessors patched after the module loaded must not
+// change results. Global constructors and static functions are resolved at call
+// time and are not tested here. 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
Uint8Array.prototype.fill = () => { throw new Error('patched') }
return () => { Uint8Array.prototype.fill = real }
}],
+ // the only prototype method the hex decoder calls, on a private key
+ ['String.prototype.charCodeAt', () => {
+ const real = String.prototype.charCodeAt
+ String.prototype.charCodeAt = () => 0x30
+ return () => { String.prototype.charCodeAt = real }
+ }],
['String.prototype.padStart', () => {
const real = String.prototype.padStart
String.prototype.padStart = () => 'XX'
RegExp.prototype.test = () => true
return () => { RegExp.prototype.test = real }
}],
- ['Array.isArray', () => {
- const real = Array.isArray
- //@ts-expect-error
- Array.isArray = () => false
- return () => { Array.isArray = real }
- }],
- ['globalThis.Uint8Array', () => {
- const real = globalThis.Uint8Array
- //@ts-expect-error
- globalThis.Uint8Array = () => { throw new Error('patched') }
- return () => { globalThis.Uint8Array = real }
- }],
['WebAssembly.Memory.prototype.buffer', () => {
const real = Object.getOwnPropertyDescriptor(WebAssembly.Memory.prototype, 'buffer')
if (!real) throw new TypeError('Failed to backup WebAssembly.Memory.prototype.buffer')
DataView.prototype.getUint32 = () => 0x41414141
return () => { DataView.prototype.getUint32 = real }
}],
- ['globalThis.DataView', () => {
- const real = globalThis.DataView
- //@ts-expect-error
- globalThis.DataView = () => { throw new Error('patched') }
- return () => { globalThis.DataView = real }
- }],
- ['globalThis.Uint32Array', () => {
- const real = globalThis.Uint32Array
- //@ts-expect-error
- globalThis.Uint32Array = () => { throw new Error('patched') }
- return () => { globalThis.Uint32Array = real }
- }],
// An index accessor on Array.prototype intercepts every [[Set]] on an index
// an array does not own yet: assignment, push and fill alike. Results must be
// defined as own properties, or a forged block reads as verified.
/** @type {[string, () => boolean][]} */
const patchedPrimitives = [
['derive', () => derive(NANO_ORG_VECTOR.privateKeyBytes) === truth],
+ ['derive from hex', () => derive(NANO_ORG_VECTOR.privateKey) === truth],
['sign', () => sign(patchedMessage, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes) === truthSignature],
['verify', () => verify(truthSignature, patchedMessage, NANO_ORG_VECTOR.publicKeyBytes) === true],
['verify_blocks', () => {
return r.length === 2 && Object.keys(r).length === 2 && r[0] === true && r[1] === false
}]
]
-for (const [name, apply] of patches) {
+// Under frozen intrinsics (test:frozen) none of these patches can be applied,
+// which is the point of freezing them, so the list is skipped there.
+const frozen = Object.isFrozen(Uint8Array.prototype)
+for (const [name, apply] of frozen ? [] : patches) {
for (const [primitive, run] of patchedPrimitives) {
const undo = apply()
try {