Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel: the bento/id recovery code and key blobs, with deterministic vectors (K2b) (#770)

nyblnetb4e0c0dd1c05
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e1684aa6..5ac80ae8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -174,6 +174,14 @@ jobs:
# each native host is held to, and must refuse every tampered statement.
run: node scripts/test-statements.ts
+ - name: identity recovery code and key blobs
+ # bento/id: every host must derive the identical keys from the same
+ # recovery code and passkey PRF output. Deterministic vectors in
+ # kernel/fixtures/recovery-v1.json: Argon2id against RFC 9106, the
+ # code's printed form and forgiving parse (all five extra check symbols),
+ # every derivation, every blob re-sealed byte for byte, every refusal.
+ run: node scripts/test-recovery.ts
+
- name: Typecheck convert (standalone)
# convert/ is a library beside the apps (the CLI and bento.page/import
# use it; no shell does), so no app's tsc -b reaches it. Its own flags,
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index f15053b1..3122b389 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -11036,6 +11036,30 @@ with a Cyrillic А passes. So no surface ever shows a name WITHOUT the verified
address beside it, and the ✓ always belongs to the address, never to the name.
(security, #764)
+## 2026-10-18 — bento/id: the recovery code and key blobs (kernel/src/recovery.ts)
+
+The bytes behind identity-design §2f, signed by security §28, with
+deterministic vectors (`kernel/fixtures/recovery-v1.json`) that every host must
+reproduce exactly:
+- **Argon2id** v0x13 with p = 1 (safest for WASM and phones), 64 MiB, t = 3, a
+ 32-byte tag and 16-byte salts. The wrap salt and the verifier salt are
+ independent. Hosts check their primitive against RFC 9106 §5.3 first.
+- **The recovery code** is 80 random bits, printed as 16 Crockford base32
+ symbols plus a CHECK symbol (mod 37): `XXXX-XXXX-XXXX-XXXX-C`. With the check,
+ a typo is caught on the device before it costs one of the directory's five
+ daily attempts (vault, as §2f's author). Parsing forgives case, separators and
+ O/I/L. Argon2id takes the decoded bytes, never the typed string.
+- **Wrap key and verifier.** wrap key = HKDF(Argon2id(code, salt), empty,
+ "bento/id/rc-wrap/v1"); verifier = Argon2id(code, salt_v).
+- **The PRF KEK** is §2f's formula.
+- **Blob plaintext** is raw 32-byte private scalars. Each one is checked on
+ import to be in 1..n−1 and to match its directory-signed public half (computed
+ as d·G, the same on every platform). The layout follows the kx placement
+ (§6b): the account scalar alone until it's ruled.
+- **AAD binds every blob.** The PRF blob is bound to its credential, the
+ recovery blob to its account, and the pepper layer to its account.
+- **Argon2id is injected.** The kernel takes it as a parameter and ships no
+ WASM: documents never derive these keys, and only agents do.
## 2026-10-18 — bento/id in the extension: the statement code is generated from kernel
`kernel/src/statements.ts` and `address.ts` are the one definition of every
diff --git a/kernel/fixtures/README.md b/kernel/fixtures/README.md
index 294bfa7e..a9476ce1 100644
--- a/kernel/fixtures/README.md
+++ b/kernel/fixtures/README.md
@@ -14,6 +14,31 @@ random, so a regeneration changes bytes but not verdicts.
**The keys in this file are TEST KEYS ONLY.** Never use them for anything else.
+`recovery-v1.json` holds the recovery-code and key-blob vectors (identity-design
+§2f, signed by security §28). Unlike the statement vectors, every value in it is
+DETERMINISTIC (fixed codes, salts and IVs), so a host must reproduce the exact
+bytes end to end. Reference: `kernel/src/recovery.ts`. Rig:
+`scripts/test-recovery.ts`. Generator: `scripts/gen-recovery-vectors.ts`.
+
+- **Argon2id first.** Check your Argon2id against the `rfc9106` row (RFC 9106
+ §5.3, with its own parameters) before trusting it. Then use OUR parameters:
+ version 0x13, p = 1, m = 64 MiB, t = 3, a 32-byte tag, 16-byte salts.
+- **The code is 17 symbols: 16 data symbols and a check symbol**, printed
+ `XXXX-XXXX-XXXX-XXXX-C`. Data symbols are Crockford base32 (no I, L, O, U).
+ The check is the 80-bit value mod 37, with `* ~ $ = U` for 32 to 36. Every one
+ of those five has its own row, because that's where hosts disagree. Parsing
+ forgives case, spaces and hyphens, and reads O as 0 and I/L as 1. U is valid
+ ONLY as the check symbol. Argon2id takes the 10 decoded BYTES, never the
+ string.
+- **HKDF salt "empty" means zero-length** (equivalent to 32 zero bytes). AES-GCM
+ ciphertexts are `ciphertext ‖ 16-byte tag` with a 12-byte IV.
+- **Blob plaintext** is raw 32-byte big-endian private scalars: the account
+ scalar alone while kx is unruled, or with kx appended under modes A and C. On
+ import, each scalar must be in 1..n−1 AND its public point d·G must equal the
+ public key in the directory-signed binding. A swapped blob fails closed.
+- **The pepper layer** is the directory's (share implements it). Its rows exist
+ so the server code can be checked against the same bytes.
+
## What each section checks
- `statements`: one row per case. `type` names the verifier. `text` and `sig`
diff --git a/kernel/fixtures/recovery-v1.json b/kernel/fixtures/recovery-v1.json
new file mode 100644
index 00000000..41b518fd
--- /dev/null
+++ b/kernel/fixtures/recovery-v1.json
@@ -0,0 +1,308 @@
+{
+ "version": 1,
+ "note": "bento/id recovery-code and key-blob vectors (identity-design §2f, security §28). TEST KEYS ONLY. Every value is deterministic: reproduce the bytes exactly. Generated by scripts/gen-recovery-vectors.ts, checked by scripts/test-recovery.ts.",
+ "params": {
+ "argon2": {
+ "version": 19,
+ "parallelism": 1,
+ "memoryKiB": 65536,
+ "passes": 3,
+ "tagLength": 32
+ },
+ "saltLen": 16,
+ "hkdf": "HKDF-SHA-256; an empty salt is zero-length (= 32 zero bytes)",
+ "aead": "AES-256-GCM, 12-byte IV, ct = ciphertext ‖ 16-byte tag"
+ },
+ "rfc9106": {
+ "note": "RFC 9106 §5.3 Argon2id (NOT our parameters): validates the primitive itself",
+ "password": "0101010101010101010101010101010101010101010101010101010101010101",
+ "salt": "02020202020202020202020202020202",
+ "secret": "0303030303030303",
+ "ad": "040404040404040404040404",
+ "memoryKiB": 32,
+ "passes": 3,
+ "parallelism": 4,
+ "tagLength": 32,
+ "tag": "0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659"
+ },
+ "codes": [
+ {
+ "bytes": "009e01a578034a5304ef",
+ "printed": "02F0-39BR-0D55-617F-*",
+ "check": "*"
+ },
+ {
+ "bytes": "b1173856f23afbcd3ca0",
+ "printed": "P4BK-GNQJ-7BXW-TF50-F",
+ "check": "F"
+ },
+ {
+ "bytes": "629170076c72ac467351",
+ "printed": "CA8Q-01VC-EAP4-CWTH-5",
+ "check": "5"
+ },
+ {
+ "bytes": "130ba7b8e5a95dc0ab02",
+ "printed": "2C5T-FE75-N5EW-1AR2-D",
+ "check": "D"
+ },
+ {
+ "bytes": "c484df695fe00e3ae2b3",
+ "printed": "RJ2D-YTAZ-W073-NRNK-R",
+ "check": "R"
+ },
+ {
+ "bytes": "75fe161ad918bfb31a64",
+ "printed": "EQZ1-C6PS-32ZV-66K4-N",
+ "check": "N"
+ },
+ {
+ "bytes": "26784ecb534f702d5115",
+ "printed": "4SW4-XJTK-9XR2-TM8N-8",
+ "check": "8"
+ },
+ {
+ "bytes": "d7f2857ccc8721a789c6",
+ "printed": "TZS8-AZ6C-GWGT-F2E6-P",
+ "check": "P"
+ },
+ {
+ "bytes": "5fbf41049a43a974454e",
+ "printed": "BYZM-214T-8EMQ-8HAE-U",
+ "check": "U"
+ },
+ {
+ "bytes": "23a61fc880216d5b2212",
+ "printed": "4EK1-ZJ40-45PN-P8GJ-~",
+ "check": "~"
+ },
+ {
+ "bytes": "334196d81c987df69a22",
+ "printed": "6D0S-DP0W-K1YZ-D6H2-=",
+ "check": "="
+ },
+ {
+ "bytes": "02a01ca77a1e4c551ff1",
+ "printed": "0AG1-S9VT-3S65-A7ZH-$",
+ "check": "$"
+ }
+ ],
+ "parse": [
+ {
+ "input": "02F0-39BR-0D55-617F-*",
+ "bytes": "009e01a578034a5304ef",
+ "note": "as printed"
+ },
+ {
+ "input": "02f0-39br-0d55-617f-*",
+ "bytes": "009e01a578034a5304ef",
+ "note": "lowercase"
+ },
+ {
+ "input": "02F039BR0D55617F*",
+ "bytes": "009e01a578034a5304ef",
+ "note": "no separators"
+ },
+ {
+ "input": " 02F0 39BR 0D55 617F * ",
+ "bytes": "009e01a578034a5304ef",
+ "note": "spaces instead of hyphens, and around it"
+ },
+ {
+ "input": "O2F0-39BR-0D55-617F-*",
+ "bytes": "009e01a578034a5304ef",
+ "note": "O typed for 0"
+ },
+ {
+ "input": "02F0-39BR-0D55-6L7F-*",
+ "bytes": "009e01a578034a5304ef",
+ "note": "L typed for 1"
+ },
+ {
+ "input": "02F0-39BR-0D55-6I7F-*",
+ "bytes": "009e01a578034a5304ef",
+ "note": "I typed for 1"
+ },
+ {
+ "input": "02F0-39BR-0D55-617F-*",
+ "bytes": "009e01a578034a5304ef",
+ "note": "check symbol *"
+ },
+ {
+ "input": "P4BK-GNQJ-7BXW-TF50-F",
+ "bytes": "b1173856f23afbcd3ca0",
+ "note": "check symbol F"
+ },
+ {
+ "input": "CA8Q-01VC-EAP4-CWTH-5",
+ "bytes": "629170076c72ac467351",
+ "note": "check symbol 5"
+ },
+ {
+ "input": "2C5T-FE75-N5EW-1AR2-D",
+ "bytes": "130ba7b8e5a95dc0ab02",
+ "note": "check symbol D"
+ },
+ {
+ "input": "RJ2D-YTAZ-W073-NRNK-R",
+ "bytes": "c484df695fe00e3ae2b3",
+ "note": "check symbol R"
+ },
+ {
+ "input": "EQZ1-C6PS-32ZV-66K4-N",
+ "bytes": "75fe161ad918bfb31a64",
+ "note": "check symbol N"
+ },
+ {
+ "input": "4SW4-XJTK-9XR2-TM8N-8",
+ "bytes": "26784ecb534f702d5115",
+ "note": "check symbol 8"
+ },
+ {
+ "input": "TZS8-AZ6C-GWGT-F2E6-P",
+ "bytes": "d7f2857ccc8721a789c6",
+ "note": "check symbol P"
+ },
+ {
+ "input": "BYZM-214T-8EMQ-8HAE-U",
+ "bytes": "5fbf41049a43a974454e",
+ "note": "check symbol U"
+ },
+ {
+ "input": "4EK1-ZJ40-45PN-P8GJ-~",
+ "bytes": "23a61fc880216d5b2212",
+ "note": "check symbol ~"
+ },
+ {
+ "input": "6D0S-DP0W-K1YZ-D6H2-=",
+ "bytes": "334196d81c987df69a22",
+ "note": "check symbol ="
+ },
+ {
+ "input": "0AG1-S9VT-3S65-A7ZH-$",
+ "bytes": "02a01ca77a1e4c551ff1",
+ "note": "check symbol $"
+ },
+ {
+ "input": "02F0-39BR-0D55-617F-0",
+ "reason": "check",
+ "note": "a wrong check symbol (a typo) is refused locally"
+ },
+ {
+ "input": "02F039BR0D55617*",
+ "reason": "length",
+ "note": "a data symbol missing"
+ },
+ {
+ "input": "02F0-39BR-0D55-617F-*0",
+ "reason": "length",
+ "note": "one symbol too many"
+ },
+ {
+ "input": "U2F0-39BR-0D55-617F-*",
+ "reason": "character",
+ "note": "U is valid only as the check symbol"
+ },
+ {
+ "input": "02F0-39BR-0D55-617F-#",
+ "reason": "character",
+ "note": "not a Crockford symbol"
+ }
+ ],
+ "derivations": {
+ "code": "009e01a578034a5304ef",
+ "salt": "101112131415161718191a1b1c1d1e1f",
+ "saltV": "404142434445464748494a4b4c4d4e4f",
+ "argon2_A": "a940fbb721f0349f891d9a63bf3e67d9bdea73272814bf58a82dbd0c1321a001",
+ "wrapKey": "7df96d5da988fce6c37079c05072e8c413c3157700780e251f17b792d3ad589f",
+ "verifier": "2e81dc46e2b5426255c3c3eb9eab936d5b16f0d3be6143c971608ae01c5e8ba3",
+ "prf": {
+ "output": "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf",
+ "salt": "707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f"
+ },
+ "prfKek": "cb2d620d31cc776d953b939c82d8196096591589f3a5bcc12ac21218b9406f06"
+ },
+ "blobs": {
+ "keys": {
+ "accountD": "e5526afbbded1a62046b9985419c6c5023b6f341313ed2f31642c4000c5fbad4",
+ "accountPub": "BDMjqSVpdU__eyOhD6S3LfNBRdBjb9FSideiWuMH_vLj4_nMzSDeX_iQryMpbgrWsmNMGBaany5zKGX5QZpFdJU",
+ "kxD": "361743288ff8a4f9e684d21c995171d89fb0b1a7ff49deca47a30cf2ec5635d1",
+ "kxPub": "BDqYtYs39vp4GvPHOkN5JkIQRaDSghnps_FdtRStcrGU_2d3X3ZrF73bY7HUnotA80qxDjTe209e1hp76cQ6dRk",
+ "otherD": "51ef828c88b05ef95c1ae769ba189e92348be5083a168c57f7eae834ab3985d5"
+ },
+ "prf": {
+ "unruled": {
+ "v": 1,
+ "cred": "1PN26hIA9u446dJBd7iCzxBTKJkne360tuaPoT7q9f4",
+ "salt": "cHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo8",
+ "iv": "ICEiIyQlJicoKSor",
+ "ct": "oN1dBuvMmQvkPONA5BfCZRkDj0z4HAe4YUmO1gLOGVFXKmDyuXl-tWuRkTk_vhpo"
+ },
+ "modeA": {
+ "v": 1,
+ "cred": "1PN26hIA9u446dJBd7iCzxBTKJkne360tuaPoT7q9f4",
+ "salt": "cHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo8",
+ "iv": "ICEiIyQlJicoKSor",
+ "ct": "oN1dBuvMmQvkPONA5BfCZRkDj0z4HAe4YUmO1gLOGVFAiWP6Cb-kcsuCKOXPahSD_2PnwMFaW5Qoe89rdg4BcD9D3jRZOaTih3drHU4wiJI"
+ },
+ "inputs": {
+ "prfOutput": "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf",
+ "credentialId": "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf",
+ "salt": "707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f",
+ "iv": "202122232425262728292a2b"
+ }
+ },
+ "recovery": {
+ "inputs": {
+ "code": "009e01a578034a5304ef",
+ "salt": "101112131415161718191a1b1c1d1e1f",
+ "iv": "202122232425262728292a2b"
+ },
+ "inner": "6883361fa63384a7683b9be8b4d86c1256b92c15e8ed49a184608347cef99f2e1ebc60ac01d1d13a3f6f21f3fbc5d0e1"
+ },
+ "pepper": {
+ "secret": "e0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
+ "iv": "303132333435363738393a3b",
+ "verifyKey": "dbe97563c63585267b66dbe9c41292b1dc3aabfa8344a30b4a02380ea4de5aed",
+ "wrapKey": "16508846750153078f797c018e72a6d1863b643ab1ca36529f5f5881b10d4c29",
+ "verifierTag": "1922104ae5c6b1d2aaa3dc29b43344e40fd8ab195f33a0d2ef914bfdc2735f5b",
+ "outer": "cff18bdfc8a026fdf9f1884df16ea104a52c2a0348f95eac03a00166eab7662b46780b4e2bcf50e6d1e2f4e4c81880fb4933caf1b8b4e486547a73470f48f443"
+ }
+ },
+ "scalars": [
+ {
+ "name": "the account scalar matching the signed public half",
+ "d": "e5526afbbded1a62046b9985419c6c5023b6f341313ed2f31642c4000c5fbad4",
+ "pub": "BDMjqSVpdU__eyOhD6S3LfNBRdBjb9FSideiWuMH_vLj4_nMzSDeX_iQryMpbgrWsmNMGBaany5zKGX5QZpFdJU",
+ "expect": "accept"
+ },
+ {
+ "name": "scalar 0",
+ "d": "0000000000000000000000000000000000000000000000000000000000000000",
+ "pub": "BDMjqSVpdU__eyOhD6S3LfNBRdBjb9FSideiWuMH_vLj4_nMzSDeX_iQryMpbgrWsmNMGBaany5zKGX5QZpFdJU",
+ "expect": "reject",
+ "reason": "scalar-range"
+ },
+ {
+ "name": "scalar n (the group order)",
+ "d": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
+ "pub": "BDMjqSVpdU__eyOhD6S3LfNBRdBjb9FSideiWuMH_vLj4_nMzSDeX_iQryMpbgrWsmNMGBaany5zKGX5QZpFdJU",
+ "expect": "reject",
+ "reason": "scalar-range"
+ },
+ {
+ "name": "scalar n−1 for a mismatched public half",
+ "d": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550",
+ "pub": "BDMjqSVpdU__eyOhD6S3LfNBRdBjb9FSideiWuMH_vLj4_nMzSDeX_iQryMpbgrWsmNMGBaany5zKGX5QZpFdJU",
+ "expect": "reject",
+ "reason": "key-mismatch"
+ },
+ {
+ "name": "another key's scalar (a swapped blob)",
+ "d": "51ef828c88b05ef95c1ae769ba189e92348be5083a168c57f7eae834ab3985d5",
+ "pub": "BDMjqSVpdU__eyOhD6S3LfNBRdBjb9FSideiWuMH_vLj4_nMzSDeX_iQryMpbgrWsmNMGBaany5zKGX5QZpFdJU",
+ "expect": "reject",
+ "reason": "key-mismatch"
+ }
+ ]
+}
diff --git a/kernel/src/recovery.ts b/kernel/src/recovery.ts
new file mode 100644
index 00000000..4aae6539
--- /dev/null
+++ b/kernel/src/recovery.ts
@@ -0,0 +1,335 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento/id — the recovery code and the key blobs (identity-design §2f, signed by
+// security §28). The reference for every host that wraps or unwraps an account
+// key, with conformance vectors in kernel/fixtures/identity-v1.json.
+//
+// Two ways back into an account on a new device, neither held by Bento:
+// - a PASSKEY with the PRF extension: its 32-byte PRF output derives a key that
+// unwraps the account key from a blob the directory keeps per passkey;
+// - a RECOVERY CODE printed once at setup: Argon2id stretches it into the key
+// for a second blob, which the directory releases only at the end of the
+// tightened recovery (72 h wait, every device notified).
+//
+// Argon2id is not in WebCrypto, and documents never derive these keys (only an
+// agent does), so this module takes the Argon2id function as a parameter: the
+// extension passes its vendored WASM, the rigs pass Node's native one, and the
+// kernel ships no WASM. Everything else here is WebCrypto (HKDF, AES-GCM, HMAC).
+
+import { b64uEnc, b64uDec, sha256b64u, type Verdict, type KxMode, KX_MODE } from './statements.ts'
+
+// --- parameters (security §28) -------------------------------------------------
+
+/** Argon2id, version 0x13. p = 1 is safest for WASM and phones. */
+export const ARGON2 = Object.freeze({ version: 0x13, parallelism: 1, memoryKiB: 65536, passes: 3, tagLength: 32 })
+/** Salt lengths. The wrap salt and the verifier salt are separate and independent. */
+export const SALT_LEN = 16
+/** Argon2id with ARGON2's parameters, supplied by the host. */
+export type Argon2id = (password: Uint8Array, salt: Uint8Array) => Promise<Uint8Array>
+
+const no = (reason: string): { ok: false; reason: string } => ({ ok: false, reason })
+const te = new TextEncoder()
+
+// --- the recovery code: 80 bits, Crockford base32, with a check symbol ----------
+
+/** Crockford base32: digits and letters without I, L, O, U. */
+const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
+/** Check symbols: the 32 above plus * ~ $ = U for values 32–36 (mod 37). */
+const CHECK_ALPHABET = ALPHABET + '*~$=U'
+export const CODE_BYTES = 10 // 80 bits = 16 symbols
+
+const toBig = (b: Uint8Array) => b.reduce((x, v) => (x << 8n) | BigInt(v), 0n)
+
+/** The 80-bit value mod 37, in a fixed 10-step loop (no BigInt on the code). */
+const check37 = (code: Uint8Array) => code.reduce((r, b) => (r * 256 + b) % 37, 0)
+
+/** The printed form: XXXX-XXXX-XXXX-XXXX-C. */
+export function formatRecoveryCode(code: Uint8Array): string {
+ if (code.length !== CODE_BYTES) throw new Error('a recovery code is 10 bytes')
+ let s = ''
+ for (let i = 0; i < 16; i++) { // symbol i is bits 5i..5i+4 from the top
+ const bit = i * 5, byte = bit >> 3, sh = bit & 7
+ const two = (code[byte] << 8) | (code[byte + 1] ?? 0)
+ s += ALPHABET[(two >> (11 - sh)) & 31]
+ }
+ return `${s.slice(0, 4)}-${s.slice(4, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${CHECK_ALPHABET[check37(code)]}`
+}
+
+export type CodeRefusal = 'length' | 'character' | 'check'
+
+/**
+ * Read what a person typed. Forgiving where Crockford is: case, spaces and
+ * hyphens don't matter, and O reads as 0, I and L as 1. The check symbol must
+ * match, so a typo is caught HERE, before it costs one of the directory's five
+ * daily attempts. Returns the 10 bytes Argon2id takes — never the string, so no
+ * two hosts can disagree about case or separators.
+ */
+export function parseRecoveryCode(input: string): { ok: true; code: Uint8Array } | { ok: false; reason: CodeRefusal } {
+ const s = input.toUpperCase().replace(/[\s-]/g, '').replace(/O/g, '0').replace(/[IL]/g, '1')
+ if (s.length !== 17) return { ok: false, reason: 'length' }
+ const code = new Uint8Array(CODE_BYTES)
+ for (let i = 0; i < 16; i++) {
+ const v = ALPHABET.indexOf(s[i])
+ if (v < 0) return { ok: false, reason: 'character' } // includes U: valid only as the check
+ const bit = i * 5, byte = bit >> 3, sh = bit & 7
+ const two = v << (11 - sh) // the symbol placed in a 16-bit window over bytes byte, byte+1
+ code[byte] |= two >> 8
+ if (byte + 1 < CODE_BYTES) code[byte + 1] |= two & 0xff
+ }
+ const check = CHECK_ALPHABET.indexOf(s[16])
+ if (check < 0) return { ok: false, reason: 'character' }
+ if (check !== check37(code)) return { ok: false, reason: 'check' }
+ return { ok: true, code }
+}
+
+// --- derivations ------------------------------------------------------------------
+
+async function hkdf(ikm: Uint8Array, salt: Uint8Array, info: string): Promise<Uint8Array> {
+ const k = await crypto.subtle.importKey('raw', ikm as BufferSource, 'HKDF', false, ['deriveBits'])
+ return new Uint8Array(await crypto.subtle.deriveBits(
+ { name: 'HKDF', hash: 'SHA-256', salt: salt as BufferSource, info: te.encode(info) as BufferSource }, k, 256))
+}
+/** HKDF's salt is EMPTY where a step needs none (equivalent to 32 zero bytes). */
+const EMPTY = new Uint8Array(0)
+
+/** The recovery blob's wrap key: HKDF-SHA-256(Argon2id(code, salt), empty, "bento/id/rc-wrap/v1"). */
+export async function recoveryWrapKey(code: Uint8Array, salt: Uint8Array, argon2: Argon2id): Promise<Uint8Array> {
+ checkLen(code, CODE_BYTES, 'code'); checkLen(salt, SALT_LEN, 'salt')
+ return hkdf(await argon2(code, salt), EMPTY, 'bento/id/rc-wrap/v1')
+}
+
+/** What the client sends the directory to prove it knows the code: Argon2id(code, salt_v). */
+export async function recoveryVerifier(code: Uint8Array, saltV: Uint8Array, argon2: Argon2id): Promise<Uint8Array> {
+ checkLen(code, CODE_BYTES, 'code'); checkLen(saltV, SALT_LEN, 'salt_v')
+ return argon2(code, saltV)
+}
+
+/** The PRF blob's key: HKDF-SHA-256(PRF output, 32-byte salt, "bento/id/acct-wrap/v1"). */
+export async function prfKek(prfOutput: Uint8Array, salt: Uint8Array): Promise<Uint8Array> {
+ checkLen(prfOutput, 32, 'PRF output'); checkLen(salt, 32, 'salt')
+ return hkdf(prfOutput, salt, 'bento/id/acct-wrap/v1')
+}
+
+function checkLen(b: Uint8Array, n: number, what: string) {
+ if (!(b instanceof Uint8Array) || b.length !== n) throw new Error(`${what} must be ${n} bytes`)
+}
+
+// --- the blob plaintext: raw private scalars, checked on import ------------------
+
+/** P-256 */
+const P = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn
+const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n
+const GX = 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n
+const GY = 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n
+const mod = (a: bigint) => ((a % P) + P) % P
+function inv(a: bigint): bigint { // Fermat: a^(p-2)
+ let r = 1n, b = mod(a), e = P - 2n
+ while (e > 0n) { if (e & 1n) r = (r * b) % P; b = (b * b) % P; e >>= 1n }
+ return r
+}
+type J = [bigint, bigint, bigint] // Jacobian; Z = 0 is the point at infinity
+function dbl([x, y, z]: J): J {
+ if (y === 0n || z === 0n) return [0n, 1n, 0n]
+ const z2 = mod(z * z), m = mod(3n * (x - z2) * (x + z2)) // a = -3
+ const y2 = mod(y * y), s = mod(4n * x * y2)
+ const x3 = mod(m * m - 2n * s), y3 = mod(m * (s - x3) - 8n * y2 * y2), z3 = mod(2n * y * z)
+ return [x3, y3, z3]
+}
+function add(p: J, q: J): J {
+ if (p[2] === 0n) return q
+ if (q[2] === 0n) return p
+ const z1z1 = mod(p[2] * p[2]), z2z2 = mod(q[2] * q[2])
+ const u1 = mod(p[0] * z2z2), u2 = mod(q[0] * z1z1)
+ const s1 = mod(p[1] * q[2] * z2z2), s2 = mod(q[1] * p[2] * z1z1)
+ if (u1 === u2) return s1 === s2 ? dbl(p) : [0n, 1n, 0n]
+ const h = mod(u2 - u1), r = mod(s2 - s1), h2 = mod(h * h), h3 = mod(h * h2)
+ const x3 = mod(r * r - h3 - 2n * u1 * h2)
+ return [x3, mod(r * (u1 * h2 - x3) - s1 * h3), mod(h * p[2] * q[2])]
+}
+/** The public key (raw uncompressed point, base64url) of a 32-byte private
+ * scalar in 1..n−1. Plain P-256 arithmetic, so it is identical on every host;
+ * null for a scalar out of range. */
+export function publicKeyOf(scalar: Uint8Array): string | null {
+ if (!(scalar instanceof Uint8Array) || scalar.length !== 32) return null
+ const d = toBig(scalar)
+ return d >= 1n && d < N ? publicOf(d) : null
+}
+
+/** d·G as a raw uncompressed point (65 bytes), base64url. */
+function publicOf(d: bigint): string {
+ let acc: J = [0n, 1n, 0n], base: J = [GX, GY, 1n]
+ for (let k = d; k > 0n; k >>= 1n) { if (k & 1n) acc = add(acc, base); base = dbl(base) }
+ const zi = inv(acc[2]), zi2 = mod(zi * zi)
+ const x = mod(acc[0] * zi2), y = mod(acc[1] * zi2 * zi)
+ const out = new Uint8Array(65); out[0] = 4
+ for (let i = 0, v = x; i < 32; i++) { out[32 - i] = Number(v & 0xffn); v >>= 8n }
+ for (let i = 0, v = y; i < 32; i++) { out[64 - i] = Number(v & 0xffn); v >>= 8n }
+ return b64uEnc(out)
+}
+
+/** Which scalars a blob carries, by the kx placement (identity-design §6b). */
+const BLOB_KX: Record<KxMode, boolean> = { unruled: false, A: true, B: false, C: true }
+
+export interface BlobKeys {
+ /** the account signing key's private scalar, 32 bytes big-endian */
+ account: Uint8Array
+ /** the kx private scalar — the shared kx (A) or the recovery kx (C); absent otherwise */
+ kx?: Uint8Array
+}
+
+/** account d ‖ kx d (when the mode carries one), each 32 bytes big-endian. */
+export function packScalars(keys: BlobKeys, mode: KxMode = KX_MODE): Uint8Array {
+ checkLen(keys.account, 32, 'account scalar')
+ if (!BLOB_KX[mode]) {
+ if (keys.kx) throw new Error(`kx mode ${mode} carries no kx in the blob`)
+ return keys.account.slice()
+ }
+ if (!keys.kx) throw new Error(`kx mode ${mode} needs a kx in the blob`)
+ checkLen(keys.kx, 32, 'kx scalar')
+ const out = new Uint8Array(64); out.set(keys.account); out.set(keys.kx, 32)
+ return out
+}
+
+/**
+ * Read a blob's plaintext and CHECK it before anything uses it: the right length
+ * for the mode, every scalar in 1..n−1 (security §28), and each one's public
+ * half equal to the public key in the directory-signed binding. A blob swapped by
+ * a malicious directory fails closed here.
+ *
+ * These are RECOVERED PRIVATE SCALARS, so nothing here branches on their bits.
+ * The range check is a branch-free byte compare, and the match goes through the
+ * platform's crypto, never publicOf (variable-time double-and-add on BigInt,
+ * kept for the generator and the rig only). The scalar is imported as a JWK
+ * {d, x, y} with x, y from the stated public half (Chrome and Node refuse a
+ * mismatched pair), then signs a probe that must verify under that public key,
+ * so a platform that skips the pair check on import is caught too (security, #770).
+ */
+export async function unpackScalars(pt: Uint8Array, expected: { accountPub: string; kxPub?: string }, mode: KxMode = KX_MODE,
+ subtle: SubtleCrypto = crypto.subtle): Promise<Verdict<BlobKeys>> {
+ const withKx = BLOB_KX[mode]
+ if (pt.length !== (withKx ? 64 : 32)) return no('length')
+ const scalars = withKx ? [pt.slice(0, 32), pt.slice(32)] : [pt.slice(0, 32)]
+ const pubs = withKx ? [expected.accountPub, expected.kxPub] : [expected.accountPub]
+ for (let i = 0; i < scalars.length; i++) {
+ if (!scalarInRange(scalars[i])) return no('scalar-range')
+ if (pubs[i] === undefined || !(await scalarMatches(scalars[i], pubs[i]!, subtle))) return no('key-mismatch')
+ }
+ return { ok: true, value: withKx ? { account: scalars[0], kx: scalars[1] } : { account: scalars[0] } }
+}
+
+const N_BYTES = Uint8Array.from({ length: 32 }, (_, i) => Number((N >> BigInt(8 * (31 - i))) & 0xffn))
+
+/** 1 ≤ d < n for a 32-byte big-endian scalar, without branching on its bytes. */
+function scalarInRange(d: Uint8Array): boolean {
+ let nonzero = 0, lt = 0, gt = 0
+ for (let i = 0; i < 32; i++) {
+ const a = d[i], b = N_BYTES[i], open = 1 ^ (lt | gt)
+ lt |= open & (((a - b) >>> 31) & 1)
+ gt |= open & (((b - a) >>> 31) & 1)
+ nonzero |= a
+ }
+ return (lt & ((nonzero | -nonzero) >>> 31)) === 1
+}
+
+const PROBE = te.encode('bento/id/scalar-probe/v1')
+const ECDSA_P256 = { name: 'ECDSA', namedCurve: 'P-256' }
+
+/** Does the private scalar d belong to the raw public key pub? Platform crypto only.
+ * `subtle` is injectable so a rig can stand in a platform that skips the pair check on import. */
+async function scalarMatches(d: Uint8Array, pub: string, subtle: SubtleCrypto): Promise<boolean> {
+ const raw = b64uDec(pub)
+ if (!raw || raw.length !== 65 || raw[0] !== 4) return false
+ try {
+ const priv = await subtle.importKey('jwk', {
+ kty: 'EC', crv: 'P-256', d: b64uEnc(d), x: b64uEnc(raw.slice(1, 33)), y: b64uEnc(raw.slice(33)), ext: false,
+ }, ECDSA_P256, false, ['sign'])
+ const pubKey = await subtle.importKey('raw', raw as BufferSource, ECDSA_P256, false, ['verify'])
+ const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, priv, PROBE as BufferSource)
+ return await subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, pubKey, sig, PROBE as BufferSource)
+ } catch { return false }
+}
+
+// --- AES-256-GCM ---------------------------------------------------------------------
+
+async function gcm(op: 'encrypt' | 'decrypt', key: Uint8Array, iv: Uint8Array, aad: string, data: Uint8Array) {
+ checkLen(key, 32, 'key'); checkLen(iv, 12, 'iv')
+ const k = await crypto.subtle.importKey('raw', key as BufferSource, 'AES-GCM', false, [op])
+ const params = { name: 'AES-GCM', iv: iv as BufferSource, additionalData: te.encode(aad) as BufferSource, tagLength: 128 }
+ return new Uint8Array(op === 'encrypt'
+ ? await crypto.subtle.encrypt(params, k, data as BufferSource)
+ : await crypto.subtle.decrypt(params, k, data as BufferSource))
+}
+const accountTag = async (accountPub: string) => sha256b64u(accountPub)
+
+// --- the PRF blob (one per passkey) -----------------------------------------------
+
+export interface PrfBlob { v: 1; cred: string; salt: string; iv: string; ct: string }
+
+/** cred = b64u(sha256(credentialId)); aad = "bento/id/acct-wrap/v1." ‖ cred; ct = ciphertext ‖ tag. */
+export async function sealPrfBlob(a: {
+ prfOutput: Uint8Array; credentialId: Uint8Array; salt: Uint8Array; iv: Uint8Array; keys: BlobKeys; mode?: KxMode
+}): Promise<PrfBlob> {
+ const cred = b64uEnc(new Uint8Array(await crypto.subtle.digest('SHA-256', a.credentialId as BufferSource)))
+ const kek = await prfKek(a.prfOutput, a.salt)
+ const ct = await gcm('encrypt', kek, a.iv, `bento/id/acct-wrap/v1.${cred}`, packScalars(a.keys, a.mode))
+ return { v: 1, cred, salt: b64uEnc(a.salt), iv: b64uEnc(a.iv), ct: b64uEnc(ct) }
+}
+
+export async function openPrfBlob(blob: PrfBlob, a: {
+ prfOutput: Uint8Array; credentialId: Uint8Array; expected: { accountPub: string; kxPub?: string }; mode?: KxMode
+}): Promise<Verdict<BlobKeys>> {
+ if (blob?.v !== 1) return no('version')
+ const cred = b64uEnc(new Uint8Array(await crypto.subtle.digest('SHA-256', a.credentialId as BufferSource)))
+ if (blob.cred !== cred) return no('credential')
+ const salt = b64uDec(blob.salt), iv = b64uDec(blob.iv), ct = b64uDec(blob.ct)
+ if (!salt || salt.length !== 32 || !iv || iv.length !== 12 || !ct) return no('grammar')
+ let pt: Uint8Array
+ try { pt = await gcm('decrypt', await prfKek(a.prfOutput, salt), iv, `bento/id/acct-wrap/v1.${cred}`, ct) } catch { return no('decrypt') }
+ return unpackScalars(pt, a.expected, a.mode)
+}
+
+// --- the recovery-code blob, and the directory's pepper layer ---------------------
+
+/** Inner layer: AES-GCM(rc wrap key, scalars), aad = "bento/id/rc-wrap/v1." ‖ b64u(sha256(accountPub)). */
+export async function sealRecoveryInner(a: { wrapKey: Uint8Array; iv: Uint8Array; accountPub: string; keys: BlobKeys; mode?: KxMode }):
+ Promise<Uint8Array> {
+ return gcm('encrypt', a.wrapKey, a.iv, `bento/id/rc-wrap/v1.${await accountTag(a.accountPub)}`, packScalars(a.keys, a.mode))
+}
+
+export async function openRecoveryInner(ct: Uint8Array, a: {
+ wrapKey: Uint8Array; iv: Uint8Array; expected: { accountPub: string; kxPub?: string }; mode?: KxMode
+}): Promise<Verdict<BlobKeys>> {
+ let pt: Uint8Array
+ try { pt = await gcm('decrypt', a.wrapKey, a.iv, `bento/id/rc-wrap/v1.${await accountTag(a.expected.accountPub)}`, ct) } catch { return no('decrypt') }
+ return unpackScalars(pt, a.expected, a.mode)
+}
+
+/**
+ * The directory's per-account pepper (server side; share implements it, this is
+ * the reference for its vectors). From one versioned Worker secret PEPPER_vN:
+ * P = HKDF(PEPPER_vN, empty, "bento/id/pepper/v1." ‖ b64u(sha256(accountPub)))
+ * verifyKey = HKDF(P, empty, "bento/id/pepper/v1/verify")
+ * — the stored verifier is HMAC-SHA-256(verifyKey, verifier)
+ * wrapKey = HKDF(P, empty, "bento/id/pepper/v1/wrap")
+ * — the outer AES-GCM layer over the inner ciphertext,
+ * aad = "bento/id/rc-pepper/v1." ‖ b64u(sha256(accountPub))
+ * The subkey labels are fully domain-separated (security §28a).
+ */
+export async function pepperKeys(pepper: Uint8Array, accountPub: string): Promise<{ verifyKey: Uint8Array; wrapKey: Uint8Array }> {
+ const p = await hkdf(pepper, EMPTY, `bento/id/pepper/v1.${await accountTag(accountPub)}`)
+ return { verifyKey: await hkdf(p, EMPTY, 'bento/id/pepper/v1/verify'), wrapKey: await hkdf(p, EMPTY, 'bento/id/pepper/v1/wrap') }
+}
+
+export async function pepperVerifierTag(verifyKey: Uint8Array, verifier: Uint8Array): Promise<Uint8Array> {
+ const k = await crypto.subtle.importKey('raw', verifyKey as BufferSource, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
+ return new Uint8Array(await crypto.subtle.sign('HMAC', k, verifier as BufferSource))
+}
+
+export async function pepperSeal(wrapKey: Uint8Array, iv: Uint8Array, inner: Uint8Array, accountPub: string): Promise<Uint8Array> {
+ return gcm('encrypt', wrapKey, iv, `bento/id/rc-pepper/v1.${await accountTag(accountPub)}`, inner)
+}
+
+export async function pepperOpen(wrapKey: Uint8Array, iv: Uint8Array, outer: Uint8Array, accountPub: string): Promise<Uint8Array | null> {
+ try { return await gcm('decrypt', wrapKey, iv, `bento/id/rc-pepper/v1.${await accountTag(accountPub)}`, outer) } catch { return null }
+}
diff --git a/scripts/gen-recovery-vectors.ts b/scripts/gen-recovery-vectors.ts
new file mode 100644
index 00000000..95a8cb42
--- /dev/null
+++ b/scripts/gen-recovery-vectors.ts
@@ -0,0 +1,153 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Generates kernel/fixtures/recovery-v1.json — the bento/id recovery-code and
+// key-blob conformance vectors (identity-design §2f, security §28).
+//
+// node scripts/gen-recovery-vectors.ts
+//
+// Unlike the statement vectors, every row here is DETERMINISTIC: fixed codes,
+// salts and IVs, so every host (Swift, Kotlin, Rust, the extension's WASM, and the
+// directory) must reproduce the exact bytes, end to end. The keys are TEST KEYS.
+
+import { argon2 as nodeArgon2 } from 'node:crypto'
+import { writeFileSync } from 'node:fs'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import {
+ ARGON2, formatRecoveryCode, parseRecoveryCode, recoveryWrapKey, recoveryVerifier, prfKek,
+ sealPrfBlob, sealRecoveryInner, pepperKeys, pepperVerifierTag, pepperSeal, publicKeyOf, type Argon2id,
+} from '../kernel/src/recovery.ts'
+
+const OUT = join(dirname(fileURLToPath(import.meta.url)), '..', 'kernel/fixtures/recovery-v1.json')
+const hex = (b: Uint8Array) => Buffer.from(b).toString('hex')
+const bytes = (n: number, f: (i: number) => number) => Uint8Array.from({ length: n }, (_, i) => f(i) & 0xff)
+
+const argon2: Argon2id = (password, salt) => new Promise((res, rej) => nodeArgon2('argon2id', {
+ message: password, nonce: salt, parallelism: ARGON2.parallelism, tagLength: ARGON2.tagLength,
+ memory: ARGON2.memoryKiB, passes: ARGON2.passes,
+}, (e, k) => (e ? rej(e) : res(new Uint8Array(k)))))
+
+// RFC 9106 §5.3: hosts check their Argon2id against the standard before trusting it
+const rfc9106 = {
+ note: 'RFC 9106 §5.3 Argon2id (NOT our parameters): validates the primitive itself',
+ password: hex(bytes(32, () => 1)), salt: hex(bytes(16, () => 2)), secret: hex(bytes(8, () => 3)), ad: hex(bytes(12, () => 4)),
+ memoryKiB: 32, passes: 3, parallelism: 4, tagLength: 32,
+ tag: '0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659',
+}
+
+// --- codes: one per check symbol, including the five extra ones ----------------------
+const codes: Record<string, unknown>[] = []
+const want = new Set('0123456789ABCDEFGHJKMNPQRSTVWXYZ*~$=U'.split(''))
+for (let seed = 0; want.size > 0 && seed < 100000; seed++) {
+ const code = bytes(10, (i) => (seed * 2654435761 + i * 40503) >>> (i % 3) * 8)
+ const printed = formatRecoveryCode(code)
+ const check = printed.slice(-1)
+ if (!want.has(check)) continue
+ // keep every extra symbol, and a handful of ordinary ones
+ if ('*~$=U'.includes(check) || codes.length < 8) codes.push({ bytes: hex(code), printed, check })
+ want.delete(check)
+}
+for (const c of ['*', '~', '$', '=', 'U']) if (!codes.some((r) => r.check === c)) throw new Error(`no code with check ${c}`)
+
+const base = codes[0] as { bytes: string; printed: string }
+const p = base.printed
+const parse: Record<string, unknown>[] = [
+ { input: p, bytes: base.bytes, note: 'as printed' },
+ { input: p.toLowerCase(), bytes: base.bytes, note: 'lowercase' },
+ { input: p.replace(/-/g, ''), bytes: base.bytes, note: 'no separators' },
+ { input: ` ${p.replace(/-/g, ' ')} `, bytes: base.bytes, note: 'spaces instead of hyphens, and around it' },
+]
+// O→0 and I/L→1, when the code has a 0 or a 1 to substitute
+const data = p.replace(/-/g, '').slice(0, 16)
+if (data.includes('0')) parse.push({ input: p.replace('0', 'O'), bytes: base.bytes, note: 'O typed for 0' })
+if (data.includes('1')) parse.push({ input: p.replace('1', 'L'), bytes: base.bytes, note: 'L typed for 1' }, { input: p.replace('1', 'I'), bytes: base.bytes, note: 'I typed for 1' })
+for (const c of codes) parse.push({ input: c.printed, bytes: c.bytes, note: `check symbol ${c.check}` })
+const wrongCheck = p.slice(0, -1) + (p.endsWith('0') ? '1' : '0')
+parse.push(
+ { input: wrongCheck, reason: 'check', note: 'a wrong check symbol (a typo) is refused locally' },
+ { input: p.slice(0, 4) + p.slice(5, 9) + p.slice(10, 14) + p.slice(15, 18) + p.slice(-1), reason: 'length', note: 'a data symbol missing' },
+ { input: p + '0', reason: 'length', note: 'one symbol too many' },
+ { input: 'U' + p.slice(1), reason: 'character', note: 'U is valid only as the check symbol' },
+ { input: p.slice(0, -1) + '#', reason: 'character', note: 'not a Crockford symbol' },
+)
+// sanity: the reference agrees with every row it is about to publish
+for (const r of parse) {
+ const got = parseRecoveryCode(r.input as string)
+ const ok = r.bytes ? got.ok && hex(got.code) === r.bytes : !got.ok && got.reason === r.reason
+ if (!ok) throw new Error(`parse row disagrees: ${JSON.stringify(r)}`)
+}
+
+// --- derivations -----------------------------------------------------------------------
+const code = Uint8Array.from(Buffer.from(base.bytes, 'hex'))
+const salt = bytes(16, (i) => 0x10 + i), saltV = bytes(16, (i) => 0x40 + i)
+const A = await argon2(code, salt)
+const derivations = {
+ code: base.bytes, salt: hex(salt), saltV: hex(saltV),
+ argon2_A: hex(A),
+ wrapKey: hex(await recoveryWrapKey(code, salt, argon2)),
+ verifier: hex(await recoveryVerifier(code, saltV, argon2)),
+ prf: { output: hex(bytes(32, (i) => 0xa0 + i)), salt: hex(bytes(32, (i) => 0x70 + i)) },
+ prfKek: '',
+}
+derivations.prfKek = hex(await prfKek(bytes(32, (i) => 0xa0 + i), bytes(32, (i) => 0x70 + i)))
+
+// --- whole blobs (end to end) --------------------------------------------------------------
+// Test keys are DETERMINISTIC (fixed scalars), so regenerating this file changes
+// nothing unless a rule changes: porters can build against stable bytes.
+async function testKey(name: string) {
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`bento/id test key ${name}`)))
+ const pub = publicKeyOf(d)
+ if (!pub) throw new Error(`test scalar for ${name} out of range`)
+ return { d, pub }
+}
+const account = await testKey('account'), kx = await testKey('kx'), other = await testKey('other')
+const credentialId = bytes(16, (i) => 0xc0 + i)
+const prfOutput = bytes(32, (i) => 0xa0 + i), prfSalt = bytes(32, (i) => 0x70 + i), iv = bytes(12, (i) => 0x20 + i)
+
+const blobs = {
+ keys: { accountD: hex(account.d), accountPub: account.pub, kxD: hex(kx.d), kxPub: kx.pub, otherD: hex(other.d) },
+ prf: {
+ unruled: await sealPrfBlob({ prfOutput, credentialId, salt: prfSalt, iv, keys: { account: account.d } }),
+ modeA: await sealPrfBlob({ prfOutput, credentialId, salt: prfSalt, iv, keys: { account: account.d, kx: kx.d }, mode: 'A' }),
+ inputs: { prfOutput: hex(prfOutput), credentialId: hex(credentialId), salt: hex(prfSalt), iv: hex(iv) },
+ },
+ recovery: {
+ inputs: { code: base.bytes, salt: hex(salt), iv: hex(iv) },
+ inner: hex(await sealRecoveryInner({ wrapKey: await recoveryWrapKey(code, salt, argon2), iv, accountPub: account.pub, keys: { account: account.d } })),
+ },
+ pepper: { secret: hex(bytes(32, (i) => 0xe0 + i)), iv: hex(bytes(12, (i) => 0x30 + i)), verifyKey: '', wrapKey: '', verifierTag: '', outer: '' },
+}
+{
+ const pk = await pepperKeys(bytes(32, (i) => 0xe0 + i), account.pub)
+ blobs.pepper.verifyKey = hex(pk.verifyKey)
+ blobs.pepper.wrapKey = hex(pk.wrapKey)
+ blobs.pepper.verifierTag = hex(await pepperVerifierTag(pk.verifyKey, await recoveryVerifier(code, saltV, argon2)))
+ blobs.pepper.outer = hex(await pepperSeal(pk.wrapKey, bytes(12, (i) => 0x30 + i), Uint8Array.from(Buffer.from(blobs.recovery.inner, 'hex')), account.pub))
+}
+
+const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n
+const scalarHex = (x: bigint) => x.toString(16).padStart(64, '0')
+const scalars = [
+ { name: 'the account scalar matching the signed public half', d: hex(account.d), pub: account.pub, expect: 'accept' },
+ { name: 'scalar 0', d: scalarHex(0n), pub: account.pub, expect: 'reject', reason: 'scalar-range' },
+ { name: 'scalar n (the group order)', d: scalarHex(N), pub: account.pub, expect: 'reject', reason: 'scalar-range' },
+ { name: 'scalar n−1 for a mismatched public half', d: scalarHex(N - 1n), pub: account.pub, expect: 'reject', reason: 'key-mismatch' },
+ { name: "another key's scalar (a swapped blob)", d: hex(other.d), pub: account.pub, expect: 'reject', reason: 'key-mismatch' },
+]
+
+const fixture = {
+ version: 1,
+ note: 'bento/id recovery-code and key-blob vectors (identity-design §2f, security §28). TEST KEYS ONLY. ' +
+ 'Every value is deterministic: reproduce the bytes exactly. Generated by scripts/gen-recovery-vectors.ts, ' +
+ 'checked by scripts/test-recovery.ts.',
+ params: { argon2: ARGON2, saltLen: 16, hkdf: 'HKDF-SHA-256; an empty salt is zero-length (= 32 zero bytes)', aead: 'AES-256-GCM, 12-byte IV, ct = ciphertext ‖ 16-byte tag' },
+ rfc9106,
+ codes,
+ parse,
+ derivations,
+ blobs,
+ scalars,
+}
+writeFileSync(OUT, JSON.stringify(fixture, null, 2) + '\n')
+console.log(`wrote ${OUT}: ${codes.length} codes, ${parse.length} parse rows, ${scalars.length} scalar rows`)
diff --git a/scripts/test-recovery.ts b/scripts/test-recovery.ts
new file mode 100644
index 00000000..362195f4
--- /dev/null
+++ b/scripts/test-recovery.ts
@@ -0,0 +1,196 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/id recovery rig: kernel/src/recovery.ts against kernel/fixtures/recovery-v1.json.
+//
+// node scripts/test-recovery.ts
+//
+// WHAT THIS PROVES. Five hosts must derive the identical keys from the same
+// recovery code and the same passkey PRF output, or a person who sets up on one
+// device can never recover on another. The vectors are deterministic, so the
+// reference must reproduce every byte: the Argon2id primitive against RFC 9106,
+// the code's printed form and its forgiving parse (including all five extra
+// check symbols), every derivation, every blob re-sealed byte for byte, and
+// every refusal: a wrong PRF, a wrong credential, a blob bound to another
+// account, a scalar out of range or not matching the signed public half.
+
+import { argon2 as nodeArgon2 } from 'node:crypto'
+import { readFileSync } from 'node:fs'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import {
+ ARGON2, formatRecoveryCode, parseRecoveryCode, recoveryWrapKey, recoveryVerifier, prfKek,
+ sealPrfBlob, openPrfBlob, sealRecoveryInner, openRecoveryInner, unpackScalars,
+ pepperKeys, pepperVerifierTag, pepperSeal, pepperOpen, publicKeyOf, type Argon2id,
+} from '../kernel/src/recovery.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const F = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'kernel/fixtures/recovery-v1.json'), 'utf8'))
+const hex = (b: Uint8Array) => Buffer.from(b).toString('hex')
+const unhex = (s: string) => Uint8Array.from(Buffer.from(s, 'hex'))
+
+const raw = (o: { message: Uint8Array; nonce: Uint8Array; secret?: Uint8Array; associatedData?: Uint8Array; parallelism: number; tagLength: number; memory: number; passes: number }) =>
+ new Promise<Uint8Array>((res, rej) => nodeArgon2('argon2id', o, (e, k) => (e ? rej(e) : res(new Uint8Array(k)))))
+const argon2: Argon2id = (password, salt) => raw({
+ message: password, nonce: salt, parallelism: ARGON2.parallelism, tagLength: ARGON2.tagLength, memory: ARGON2.memoryKiB, passes: ARGON2.passes,
+})
+
+console.log('\nthe Argon2id primitive matches RFC 9106 §5.3')
+{
+ const v = F.rfc9106
+ const tag = await raw({ message: unhex(v.password), nonce: unhex(v.salt), secret: unhex(v.secret), associatedData: unhex(v.ad),
+ parallelism: v.parallelism, tagLength: v.tagLength, memory: v.memoryKiB, passes: v.passes })
+ ok(hex(tag) === v.tag, 'Argon2id(RFC 9106 §5.3 inputs) = the published tag')
+ ok(F.params.argon2.parallelism === 1 && F.params.argon2.memoryKiB === 65536 && F.params.argon2.passes === 3 &&
+ F.params.argon2.tagLength === 32 && F.params.argon2.version === 0x13, 'the fixture states the signed parameters (p=1, 64 MiB, t=3, 32-byte tag, v0x13)')
+}
+
+console.log('\nthe printed code, including every extra check symbol')
+for (const c of F.codes) ok(formatRecoveryCode(unhex(c.bytes)) === c.printed, `${c.printed} (check ${c.check})`)
+for (const s of ['*', '~', '$', '=', 'U']) ok(F.codes.some((c: { check: string }) => c.check === s), `a code whose check symbol is ${s}`)
+
+console.log('\nreading what a person typed')
+for (const r of F.parse) {
+ const got = parseRecoveryCode(r.input)
+ const pass = r.bytes ? got.ok && hex(got.code) === r.bytes : !got.ok && got.reason === r.reason
+ ok(pass, `${JSON.stringify(r.input)} → ${r.bytes ? 'the code' : `refused: ${r.reason}`} (${r.note})`)
+}
+
+console.log('\nderivations')
+{
+ const d = F.derivations
+ const code = unhex(d.code), salt = unhex(d.salt), saltV = unhex(d.saltV)
+ ok(hex(await argon2(code, salt)) === d.argon2_A, 'A = Argon2id(code bytes, salt)')
+ ok(hex(await recoveryWrapKey(code, salt, argon2)) === d.wrapKey, 'wrap key = HKDF(A, empty, "bento/id/rc-wrap/v1")')
+ ok(hex(await recoveryVerifier(code, saltV, argon2)) === d.verifier, 'verifier = Argon2id(code bytes, salt_v)')
+ ok(d.verifier !== d.argon2_A, 'the verifier is not the wrap input (independent salts)')
+ ok(hex(await prfKek(unhex(d.prf.output), unhex(d.prf.salt))) === d.prfKek, 'PRF KEK = HKDF(PRF output, salt, "bento/id/acct-wrap/v1")')
+}
+
+console.log('\nwhole blobs, end to end')
+{
+ const b = F.blobs, k = b.keys, i = b.prf.inputs
+ const prfIn = { prfOutput: unhex(i.prfOutput), credentialId: unhex(i.credentialId), salt: unhex(i.salt), iv: unhex(i.iv) }
+ const resealed = await sealPrfBlob({ ...prfIn, keys: { account: unhex(k.accountD) } })
+ ok(JSON.stringify(resealed) === JSON.stringify(b.prf.unruled), 'the PRF blob re-seals byte for byte (account key only)')
+ const resealedA = await sealPrfBlob({ ...prfIn, keys: { account: unhex(k.accountD), kx: unhex(k.kxD) }, mode: 'A' })
+ ok(JSON.stringify(resealedA) === JSON.stringify(b.prf.modeA), 'the PRF blob under kx mode A (account ‖ kx) re-seals byte for byte')
+
+ const opened = await openPrfBlob(b.prf.unruled, { prfOutput: prfIn.prfOutput, credentialId: prfIn.credentialId, expected: { accountPub: k.accountPub } })
+ ok(opened.ok && hex(opened.value.account) === k.accountD, 'it opens to the account scalar, checked against the signed public half')
+ const openedA = await openPrfBlob(b.prf.modeA, { prfOutput: prfIn.prfOutput, credentialId: prfIn.credentialId, expected: { accountPub: k.accountPub, kxPub: k.kxPub }, mode: 'A' })
+ ok(openedA.ok && hex(openedA.value.kx!) === k.kxD, 'mode A opens to account ‖ kx, both checked')
+ const wrongPrf = await openPrfBlob(b.prf.unruled, { prfOutput: unhex(i.prfOutput).map((x: number) => x ^ 1), credentialId: prfIn.credentialId, expected: { accountPub: k.accountPub } })
+ ok(!wrongPrf.ok && wrongPrf.reason === 'decrypt', 'a different passkey PRF output cannot open it')
+ const wrongCred = await openPrfBlob(b.prf.unruled, { prfOutput: prfIn.prfOutput, credentialId: unhex(i.credentialId).map((x: number) => x ^ 1), expected: { accountPub: k.accountPub } })
+ ok(!wrongCred.ok && wrongCred.reason === 'credential', 'a blob for another credential is refused')
+ const unruledAsA = await openPrfBlob(b.prf.unruled, { prfOutput: prfIn.prfOutput, credentialId: prfIn.credentialId, expected: { accountPub: k.accountPub, kxPub: k.kxPub }, mode: 'A' })
+ ok(!unruledAsA.ok && unruledAsA.reason === 'length', 'a blob opened under the wrong kx mode is refused (length)')
+
+ const r = b.recovery.inputs
+ const wk = await recoveryWrapKey(unhex(r.code), unhex(r.salt), argon2)
+ const inner = await sealRecoveryInner({ wrapKey: wk, iv: unhex(r.iv), accountPub: k.accountPub, keys: { account: unhex(k.accountD) } })
+ ok(hex(inner) === b.recovery.inner, 'the recovery blob (inner layer) re-seals byte for byte')
+ const rOpen = await openRecoveryInner(unhex(b.recovery.inner), { wrapKey: wk, iv: unhex(r.iv), expected: { accountPub: k.accountPub } })
+ ok(rOpen.ok && hex(rOpen.value.account) === k.accountD, 'the recovery code opens it')
+ const otherCode = parseRecoveryCode(F.codes[1].printed)
+ const wk2 = await recoveryWrapKey(otherCode.ok ? otherCode.code : new Uint8Array(10), unhex(r.salt), argon2)
+ const rWrong = await openRecoveryInner(unhex(b.recovery.inner), { wrapKey: wk2, iv: unhex(r.iv), expected: { accountPub: k.accountPub } })
+ ok(!rWrong.ok && rWrong.reason === 'decrypt', 'a different recovery code cannot open it')
+ // the aad binds the blob to its account: presented as another account's, it fails
+ const rOther = await openRecoveryInner(unhex(b.recovery.inner), { wrapKey: wk, iv: unhex(r.iv), expected: { accountPub: F.blobs.keys.kxPub } })
+ ok(!rOther.ok && rOther.reason === 'decrypt', "a recovery blob presented as another account's fails (aad binds the account)")
+
+ const pp = b.pepper
+ const pk = await pepperKeys(unhex(pp.secret), k.accountPub)
+ ok(hex(pk.verifyKey) === pp.verifyKey && hex(pk.wrapKey) === pp.wrapKey, 'pepper: P → the "verify" and "wrap" subkeys')
+ const verifier = await recoveryVerifier(unhex(F.derivations.code), unhex(F.derivations.saltV), argon2)
+ ok(hex(await pepperVerifierTag(pk.verifyKey, verifier)) === pp.verifierTag, 'pepper: stored verifier = HMAC(verifyKey, verifier)')
+ ok(hex(await pepperSeal(pk.wrapKey, unhex(pp.iv), unhex(b.recovery.inner), k.accountPub)) === pp.outer, 'pepper: the outer layer re-seals byte for byte')
+ const back = await pepperOpen(pk.wrapKey, unhex(pp.iv), unhex(pp.outer), k.accountPub)
+ ok(!!back && hex(back) === b.recovery.inner, 'pepper: the outer layer opens to the inner blob')
+ ok((await pepperOpen(pk.wrapKey, unhex(pp.iv), unhex(pp.outer), k.kxPub)) === null, "pepper: presented as another account's, it fails")
+}
+
+console.log('\nscalars on import: in range, and matching the signed public half')
+for (const s of F.scalars) {
+ const v = await unpackScalars(unhex(s.d), { accountPub: s.pub })
+ ok(s.expect === 'accept' ? v.ok : !v.ok && v.reason === s.reason, `${s.name} → ${s.expect === 'accept' ? 'accept' : `refused: ${s.reason}`}`)
+}
+
+// The fixture's test keys are deterministic, their public halves computed by
+// publicKeyOf itself, so the rows above cannot validate d·G on their own. Check
+// it INDEPENDENTLY against keys the platform generated.
+console.log('\nd·G agrees with the platform on keys it generated')
+for (const alg of ['ECDSA', 'ECDH'] as const) {
+ let agree = 0
+ for (let i = 0; i < 8; i++) {
+ const kp = (await crypto.subtle.generateKey({ name: alg, namedCurve: 'P-256' }, true,
+ alg === 'ECDSA' ? ['sign', 'verify'] : ['deriveBits'])) as CryptoKeyPair
+ const d = Uint8Array.from(Buffer.from((await crypto.subtle.exportKey('jwk', kp.privateKey)).d!, 'base64url'))
+ const pub = Buffer.from(new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))).toString('base64url')
+ if (publicKeyOf(d) === pub) agree++
+ }
+ ok(agree === 8, `${alg}: publicKeyOf(d) equals WebCrypto's public key for 8 fresh key pairs`)
+}
+ok(publicKeyOf(new Uint8Array(32)) === null, 'publicKeyOf refuses scalar 0')
+
+// The sign-and-verify probe is a second line of defence: Chrome and Node already
+// refuse a mismatched {d, x, y} on import, so it can't be reached above. Stand in a
+// LAX platform that ignores x, y (imports d alone as PKCS#8, no public key) and
+// the probe must still catch every mismatch. (security, #770)
+console.log('\non a platform that skips the pair check on import, the probe still refuses')
+{
+ const PKCS8_P256 = '308141020100301306072a8648ce3d020106082a8648ce3d030107042730250201010420'
+ // the real methods, BOUND: SubtleCrypto's methods throw on any other `this`, and
+ // scalarMatches reads a throw as a mismatch, so an unbound stand-in refuses
+ // everything and these rows would pass vacuously
+ const lax = {
+ sign: crypto.subtle.sign.bind(crypto.subtle),
+ verify: crypto.subtle.verify.bind(crypto.subtle),
+ importKey: (format: string, data: JsonWebKey, alg: AlgorithmIdentifier, ext: boolean, uses: KeyUsage[]) =>
+ format === 'jwk'
+ ? crypto.subtle.importKey('pkcs8', unhex(PKCS8_P256 + Buffer.from(data.d!, 'base64url').toString('hex')), alg, ext, uses)
+ : crypto.subtle.importKey(format as 'raw', data as unknown as BufferSource, alg, ext, uses),
+ } as unknown as SubtleCrypto
+ // positive control: the lax import really does accept a mismatched pair
+ const mismatched = F.scalars.find((s: { reason?: string; name: string }) => s.name.startsWith("another key's"))
+ const accepted = await lax.importKey('jwk', { kty: 'EC', crv: 'P-256', d: Buffer.from(unhex(mismatched.d)).toString('base64url'),
+ x: 'x', y: 'y' }, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']).then(() => true, () => false)
+ ok(accepted, 'control: the lax platform imports a scalar without checking its public half')
+ for (const s of F.scalars) {
+ const v = await unpackScalars(unhex(s.d), { accountPub: s.pub }, undefined, lax)
+ ok(s.expect === 'accept' ? v.ok : !v.ok && v.reason === s.reason, `lax: ${s.name} → ${s.expect === 'accept' ? 'accept' : `refused: ${s.reason}`}`)
+ }
+}
+
+// SHAPE: the recovered scalar never reaches the variable-time BigInt path. A
+// call graph over recovery.ts's top-level declarations: publicOf and its point
+// arithmetic must be unreachable from unpackScalars (security, #770).
+console.log('\nthe recovered scalar never reaches the variable-time path')
+{
+ const src = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'kernel/src/recovery.ts'), 'utf8')
+ .replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')
+ const starts = [...src.matchAll(/^(?:export )?(?:async )?(?:function|const) ([A-Za-z_]\w*)/gm)].map((m) => ({ name: m[1], at: m.index! }))
+ const body = new Map(starts.map((s, i) => [s.name, src.slice(s.at, starts[i + 1]?.at ?? src.length)]))
+ const calls = (name: string) => [...body.keys()].filter((n) => n !== name && new RegExp(`\\b${n}\\b`).test(body.get(name)!))
+ const reach = (from: string) => {
+ const seen = new Set([from]), todo = [from]
+ while (todo.length) for (const c of calls(todo.pop()!)) if (!seen.has(c)) { seen.add(c); todo.push(c) }
+ return seen
+ }
+ const r = reach('unpackScalars')
+ for (const bad of ['publicOf', 'publicKeyOf', 'add', 'dbl', 'inv', 'toBig']) ok(!r.has(bad), `${bad} is unreachable from unpackScalars`)
+ // non-vacuous: the graph sees these edges where they exist
+ ok(reach('publicKeyOf').has('dbl') && reach('openPrfBlob').has('scalarMatches'), 'the call graph sees real edges (publicKeyOf → dbl, openPrfBlob → scalarMatches)')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)