Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

home/webext: bento/id agent core (W1a) — generated statement code, passkey-wrapped account key, recovery code (#773)

nyblnet86883a50945c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c3756be3..e1684aa6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -947,6 +947,14 @@ jobs:
# member key never follows.
run: node scripts/test-webext-store.ts
+ - name: WebExtension bento/id rig
+ # The extension's statement code must be the kernel reference, unaltered
+ # (a generated type-strip, checked current), and must pass the whole
+ # conformance contract in kernel/fixtures/identity-v1.json. The
+ # passkey-wrapped account key must fail closed for the wrong passkey,
+ # credential or binding; the recovery code is 80 random bits.
+ run: node scripts/test-webext-id.ts
+
- name: WebExtension localisation rig
# Every failure mode of a message catalogue is silent: a key the code
# uses but English lacks renders as the key name, a locale missing a key
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 1e5bab7d..f15053b1 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -11035,3 +11035,20 @@ requires NFC, and caps the length. No filter stops homoglyphs, though: "Аlice"
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 in the extension: the statement code is generated from kernel
+
+`kernel/src/statements.ts` and `address.ts` are the one definition of every
+byte a host signs or checks, and `kernel/fixtures/identity-v1.json` is the
+contract. The native hosts must reimplement them (Swift, Kotlin and Rust can't
+import TypeScript). The extension ships plain JavaScript, so it doesn't have
+to: `scripts/gen-webext-id.mjs` type-strips the two files into
+`home/webext/src/id/gen/`, and `scripts/test-webext-id.ts` fails if the copy is
+stale. The same rig runs kernel's own conformance rig with its imports pointed
+at the extension's copy, so every fixture row is checked against the code the
+extension ships. A hand port would pass the vectors today and drift later.
+
+The passkey blob and the recovery code follow the exact bytes in the identity
+design's §2f (raw 32-byte scalars checked to lie in 1..n−1 and to match the
+binding; the code is 16 Crockford base-32 characters plus a mod-37 check
+symbol, and the 10 decoded bytes, never the string, feed the derivation).
diff --git a/home/webext/src/id/blob.js b/home/webext/src/id/blob.js
new file mode 100644
index 00000000..22cc52c6
--- /dev/null
+++ b/home/webext/src/id/blob.js
@@ -0,0 +1,154 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento/id — the passkey-wrapped account key (identity-design §2f).
+//
+// At setup, and whenever a passkey is added, the agent runs ONE WebAuthn
+// ceremony (rp bento.page, user verification) with the PRF extension over the
+// FIXED input "bento/id/prf/v1". The 32-byte PRF output never leaves the
+// authenticator except into this function, and becomes the key that wraps the
+// account private key:
+//
+// KEK = HKDF-SHA-256(ikm = PRF output, salt = 32 random bytes,
+// info = "bento/id/acct-wrap/v1")
+// blob = { v:1, cred: b64url(sha256(credentialId)), salt, iv,
+// ct: AES-256-GCM(KEK, iv, account private key ‖ kx private key,
+// aad = "bento/id/acct-wrap/v1." ‖ cred) }
+//
+// The blob is opaque to the directory that stores it; only the passkey that
+// made it can open it. A device that opens one checks the recovered key
+// against the PUBLIC key the directory-signed binding states (`importAccount`
+// signs and verifies), so a swapped blob fails closed.
+//
+// EXACT BYTES (identity-design §2f, K2b, signed by security §28):
+// · private keys are RAW 32-byte big-endian P-256 scalars, each checked on
+// import to lie in 1..n−1 AND to match the directory-signed public half;
+// · the plaintext is the account scalar alone while kx is unruled, or the
+// account scalar ‖ the kx scalar (64 bytes) under ruling A or C;
+// · salt 32 bytes, iv 12 bytes, all binary fields base64url without padding.
+//
+// THE ACCOUNT KEY (security §28): generated extractable only inside the setup
+// ceremony, used to make the blobs, then re-imported NON-extractable. Stated
+// exactly: never exported or stored as raw bytes by our code. Dropping a key
+// in JavaScript is best effort (heap until garbage collection), and
+// non-extractable is a JavaScript-API property: the browser keeps the
+// material in the profile's IndexedDB, readable by same-user malware.
+//
+// Pure: WebCrypto only, so the rig runs the same code in node.
+
+const te = new TextEncoder()
+export const PRF_INPUT = te.encode('bento/id/prf/v1')
+const INFO = te.encode('bento/id/acct-wrap/v1')
+const AAD_PREFIX = 'bento/id/acct-wrap/v1.'
+const subtle = () => globalThis.crypto.subtle
+
+export const b64u = (u8) => {
+ let s = ''
+ for (const b of u8) s += String.fromCharCode(b)
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
+}
+export const unb64u = (s) => {
+ if (typeof s !== 'string' || !/^[A-Za-z0-9_-]*$/.test(s)) throw new Error('not base64url')
+ const t = s.replace(/-/g, '+').replace(/_/g, '/')
+ const bin = atob(t + '='.repeat((4 - (t.length % 4)) % 4))
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0))
+}
+
+/** b64url(sha256(credentialId)) — how a blob names its passkey without naming it. */
+export async function credHash(credentialId) {
+ return b64u(new Uint8Array(await subtle().digest('SHA-256', credentialId)))
+}
+
+async function kek(prf, salt) {
+ if (!(prf instanceof Uint8Array) || prf.length !== 32) throw new Error('PRF output must be 32 bytes')
+ const ikm = await subtle().importKey('raw', prf, 'HKDF', false, ['deriveKey'])
+ return subtle().deriveKey({ name: 'HKDF', hash: 'SHA-256', salt, info: INFO }, ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
+}
+
+/**
+ * Wrap the account private scalar (and the kx scalar, once that slot exists)
+ * under a passkey's PRF output. `rand(n)` is injectable for test vectors only.
+ */
+export async function wrapAccount({ prf, credentialId, accountD, kxD = null }, rand = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n))) {
+ if (!(accountD instanceof Uint8Array) || accountD.length !== 32) throw new Error('account key must be a 32-byte scalar')
+ if (kxD !== null && (!(kxD instanceof Uint8Array) || kxD.length !== 32)) throw new Error('kx key must be a 32-byte scalar')
+ const cred = await credHash(credentialId)
+ const salt = rand(32)
+ const iv = rand(12)
+ const pt = kxD ? new Uint8Array([...accountD, ...kxD]) : accountD
+ const ct = new Uint8Array(await subtle().encrypt({ name: 'AES-GCM', iv, additionalData: te.encode(AAD_PREFIX + cred) }, await kek(prf, salt), pt))
+ return { v: 1, cred, salt: b64u(salt), iv: b64u(iv), ct: b64u(ct) }
+}
+
+/**
+ * Open a blob with the PRF output of the passkey that made it. Throws on any
+ * mismatch — a wrong passkey, a blob for another credential, a tampered field.
+ */
+export async function unwrapAccount(blob, { prf, credentialId }) {
+ if (!blob || blob.v !== 1) throw new Error('unknown blob version')
+ const cred = await credHash(credentialId)
+ if (blob.cred !== cred) throw new Error('blob is for another passkey')
+ const salt = unb64u(blob.salt), iv = unb64u(blob.iv)
+ if (salt.length !== 32 || iv.length !== 12) throw new Error('bad blob')
+ const pt = new Uint8Array(await subtle().decrypt({ name: 'AES-GCM', iv, additionalData: te.encode(AAD_PREFIX + cred) }, await kek(prf, salt), unb64u(blob.ct)))
+ if (pt.length !== 32 && pt.length !== 64) throw new Error('bad blob')
+ return { accountD: pt.slice(0, 32), kxD: pt.length === 64 ? pt.slice(32) : null }
+}
+
+/** The raw scalar `d` of an EXTRACTABLE P-256 private key (inside a ceremony only). */
+export async function scalarOf(privateKey) {
+ return unb64u((await subtle().exportKey('jwk', privateKey)).d)
+}
+
+/** The raw uncompressed public point (65 bytes) as base64url — the contract's `accountPub` form. */
+export async function rawPub(publicKey) {
+ return b64u(new Uint8Array(await subtle().exportKey('raw', publicKey)))
+}
+
+/**
+ * Bring a recovered account scalar back as a signing key — NON-extractable by
+ * default — and PROVE it belongs to `accountPubRaw` (the binding's key): sign
+ * a fresh challenge with it and verify under the stated public key. A blob the
+ * directory swapped yields a key that fails here.
+ */
+/** the P-256 group order, as 32 big-endian bytes */
+const N_BYTES = Uint8Array.from([
+ 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,
+])
+
+/**
+ * 1 ≤ d < n for a 32-byte big-endian scalar (security §28) — WITHOUT branching
+ * on its bytes. These are recovered PRIVATE scalars, so the check must not take
+ * a different time for different values (no BigInt, no early exit). The same
+ * branch-free compare as kernel/src/recovery.ts.
+ */
+export const scalarInRange = (d) => {
+ if (!(d instanceof Uint8Array) || d.length !== 32) return false
+ 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
+}
+
+export async function importAccount(d, accountPubRaw, { extractable = false, crypto: c = globalThis.crypto } = {}) {
+ if (!scalarInRange(d)) throw new Error('the recovered scalar is not in 1..n-1')
+ const pub = unb64u(accountPubRaw)
+ if (pub.length !== 65 || pub[0] !== 4) throw new Error('account public key must be an uncompressed P-256 point')
+ const jwk = { kty: 'EC', crv: 'P-256', d: b64u(d), x: b64u(pub.slice(1, 33)), y: b64u(pub.slice(33)), ext: extractable }
+ // Chrome and Node already REFUSE a JWK whose d does not match its x/y
+ // (DataError), so a swapped blob fails here. The sign-and-verify probe below
+ // is defence in depth for any engine that does not check that (measured by
+ // security, 2026-10-18; not yet measured on Firefox). `crypto` is injectable
+ // so the rig can prove the probe alone catches it.
+ const key = await c.subtle.importKey('jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, extractable, ['sign'])
+ const verifyKey = await c.subtle.importKey('raw', pub, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'])
+ const probe = c.getRandomValues(new Uint8Array(32))
+ const sig = await c.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, probe)
+ if (!(await c.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, verifyKey, sig, probe))) throw new Error('recovered key does not match the binding')
+ return key
+}
diff --git a/home/webext/src/id/gen/address.js b/home/webext/src/id/gen/address.js
new file mode 100644
index 00000000..cdce532a
--- /dev/null
+++ b/home/webext/src/id/gen/address.js
@@ -0,0 +1,78 @@
+// GENERATED from kernel/src/address.ts by scripts/gen-webext-id.mjs — do not edit.
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento/id — the ONE definition of "which mailbox is this address".
+//
+// The directory binds an address to a key, and an agent looks an address up. If
+// the two normalise differently, a lookup and a binding can disagree about which
+// mailbox they mean, and someone else's key could answer for yours. So both use
+// this rule: the directory imports this module, and the native agents (Swift,
+// Kotlin, Rust, which cannot import it) must pass every row of the vector fixture
+// (kernel/fixtures/identity-v1.json). The VECTORS are the contract for them; this
+// file is the reference.
+//
+// Phase 1 accepts ASCII addresses only (a maintainer decision). International
+// domain handling diverges between platforms (WHATWG URL uses UTS #46
+// non-transitional processing; java.net.IDN is IDNA2003, so "ß" becomes a
+// different domain), and an address two hosts read differently is exactly the
+// bug this module exists to prevent. A domain typed in its ASCII `xn--` form is
+// accepted as typed. The limit lifts once vectors prove every host agrees.
+//
+// No provider folding of any kind: Gmail's dots and +tags are part of the
+// address. Folding is a guess about one provider's policy, and a wrong guess
+// merges two people's mailboxes.
+
+
+
+
+
+
+
+  
+
+
+
+ // the last label is all digits (an IPv4 address)
+
+const MAX_ADDRESS = 254
+const MAX_LOCAL = 64
+const MAX_LABEL = 63
+
+/** RFC 5322 atext, lower-cased (the input is lower-cased before this runs). */
+const ATEXT = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+$/
+
+/** Normalise an address typed by a person, or say why it is refused. */
+export function normalizeAddress(input ) {
+ const s = input.trim()
+ if (s.length > MAX_ADDRESS) return { ok: false, reason: 'too-long' }
+ for (let i = 0; i < s.length; i++) {
+ const c = s.charCodeAt(i)
+ if (c < 0x21 || c > 0x7e) return { ok: false, reason: 'not-ascii' }
+ }
+ const at = s.indexOf('@')
+ if (at <= 0 || at !== s.lastIndexOf('@') || at === s.length - 1) return { ok: false, reason: 'at-sign' }
+ const local = s.slice(0, at).toLowerCase()
+ const domain = s.slice(at + 1).toLowerCase()
+
+ if (local.length > MAX_LOCAL) return { ok: false, reason: 'too-long' }
+ // dot-atom: atext runs separated by single dots, none leading or trailing
+ for (const atom of local.split('.')) if (!ATEXT.test(atom)) return { ok: false, reason: 'local-part' }
+
+ const labels = domain.split('.')
+ if (labels.length < 2) return { ok: false, reason: 'domain' }
+ for (const label of labels) {
+ if (label.length < 1 || label.length > MAX_LABEL) return { ok: false, reason: 'domain' }
+ if (!/^[a-z0-9-]+$/.test(label)) return { ok: false, reason: 'domain' } // also refuses '[' IP literals
+ if (label.startsWith('-') || label.endsWith('-')) return { ok: false, reason: 'domain' }
+ }
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return { ok: false, reason: 'numeric-tld' }
+
+ return { ok: true, address: `${local}@${domain}` }
+}
+
+/** True when `s` is already in normal form (what a signed statement must carry). */
+export function isNormalAddress(s ) {
+ const r = normalizeAddress(s)
+ return r.ok && r.address === s
+}
diff --git a/home/webext/src/id/gen/display-table.js b/home/webext/src/id/gen/display-table.js
new file mode 100644
index 00000000..a3ea8650
--- /dev/null
+++ b/home/webext/src/id/gen/display-table.js
@@ -0,0 +1,763 @@
+// GENERATED from kernel/src/display-table.ts by scripts/gen-webext-id.mjs — do not edit.
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// GENERATED by scripts/gen-display-table.ts — do not edit by hand.
+//
+// The code points a bento/id display name may not contain, frozen at Unicode
+// 17.0: controls, private use, unassigned (with the noncharacters), line and
+// paragraph separators, format characters except ZWNJ/ZWJ, and the Hangul fill
+// letters. 746 inclusive ranges, sorted and disjoint, as a flat list of
+// [first, last] pairs. kernel/fixtures/identity-v1.json carries the same table
+// for the native hosts, which embed it rather than reading their own platform's
+// (drifting) Unicode tables.
+
+export const DISPLAY_FORBIDDEN_UNICODE = '17.0'
+
+export const DISPLAY_FORBIDDEN_FLAT = Object.freeze([
+ 0x0,0x1f,
+ 0x7f,0x9f,
+ 0xad,0xad,
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dd7,0xdd7,
+ 0xde0,0xde5,
+ 0xdf0,0xdf1,
+ 0xdf5,0xe00,
+ 0xe3b,0xe3e,
+ 0xe5c,0xe80,
+ 0xe83,0xe83,
+ 0xe85,0xe85,
+ 0xe8b,0xe8b,
+ 0xea4,0xea4,
+ 0xea6,0xea6,
+ 0xebe,0xebf,
+ 0xec5,0xec5,
+ 0xec7,0xec7,
+ 0xecf,0xecf,
+ 0xeda,0xedb,
+ 0xee0,0xeff,
+ 0xf48,0xf48,
+ 0xf6d,0xf70,
+ 0xf98,0xf98,
+ 0xfbd,0xfbd,
+ 0xfcd,0xfcd,
+ 0xfdb,0xfff,
+ 0x10c6,0x10c6,
+ 0x10c8,0x10cc,
+ 0x10ce,0x10cf,
+ 0x115f,0x1160,
+ 0x1249,0x1249,
+ 0x124e,0x124f,
+ 0x1257,0x1257,
+ 0x1259,0x1259,
+ 0x125e,0x125f,
+ 0x1289,0x1289,
+ 0x128e,0x128f,
+ 0x12b1,0x12b1,
+ 0x12b6,0x12b7,
+ 0x12bf,0x12bf,
+ 0x12c1,0x12c1,
+ 0x12c6,0x12c7,
+ 0x12d7,0x12d7,
+ 0x1311,0x1311,
+ 0x1316,0x1317,
+ 0x135b,0x135c,
+ 0x137d,0x137f,
+ 0x139a,0x139f,
+ 0x13f6,0x13f7,
+ 0x13fe,0x13ff,
+ 0x169d,0x169f,
+ 0x16f9,0x16ff,
+ 0x1716,0x171e,
+ 0x1737,0x173f,
+ 0x1754,0x175f,
+ 0x176d,0x176d,
+ 0x1771,0x1771,
+ 0x1774,0x177f,
+ 0x17de,0x17df,
+ 0x17ea,0x17ef,
+ 0x17fa,0x17ff,
+ 0x180e,0x180e,
+ 0x181a,0x181f,
+ 0x1879,0x187f,
+ 0x18ab,0x18af,
+ 0x18f6,0x18ff,
+ 0x191f,0x191f,
+ 0x192c,0x192f,
+ 0x193c,0x193f,
+ 0x1941,0x1943,
+ 0x196e,0x196f,
+ 0x1975,0x197f,
+ 0x19ac,0x19af,
+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c8,0xffc9,
+ 0xffd0,0xffd1,
+ 0xffd8,0xffd9,
+ 0xffdd,0xffdf,
+ 0xffe7,0xffe7,
+ 0xffef,0xfffb,
+ 0xfffe,0xffff,
+ 0x1000c,0x1000c,
+ 0x10027,0x10027,
+ 0x1003b,0x1003b,
+ 0x1003e,0x1003e,
+ 0x1004e,0x1004f,
+ 0x1005e,0x1007f,
+ 0x100fb,0x100ff,
+ 0x10103,0x10106,
+ 0x10134,0x10136,
+ 0x1018f,0x1018f,
+ 0x1019d,0x1019f,
+ 0x101a1,0x101cf,
+ 0x101fe,0x1027f,
+ 0x1029d,0x1029f,
+ 0x102d1,0x102df,
+ 0x102fc,0x102ff,
+ 0x10324,0x1032c,
+ 0x1034b,0x1034f,
+ 0x1037b,0x1037f,
+ 0x1039e,0x1039e,
+ 0x103c4,0x103c7,
+ 0x103d6,0x103ff,
+ 0x1049e,0x1049f,
+ 0x104aa,0x104af,
+ 0x104d4,0x104d7,
+ 0x104fc,0x104ff,
+ 0x10528,0x1052f,
+ 0x10564,0x1056e,
+ 0x1057b,0x1057b,
+ 0x1058b,0x1058b,
+ 0x10593,0x10593,
+ 0x10596,0x10596,
+ 0x105a2,0x105a2,
+ 0x105b2,0x105b2,
+ 0x105ba,0x105ba,
+ 0x105bd,0x105bf,
+ 0x105f4,0x105ff,
+ 0x10737,0x1073f,
+ 0x10756,0x1075f,
+ 0x10768,0x1077f,
+ 0x10786,0x10786,
+ 0x107b1,0x107b1,
+ 0x107bb,0x107ff,
+ 0x10806,0x10807,
+ 0x10809,0x10809,
+ 0x10836,0x10836,
+ 0x10839,0x1083b,
+ 0x1083d,0x1083e,
+ 0x10856,0x10856,
+ 0x1089f,0x108a6,
+ 0x108b0,0x108df,
+ 0x108f3,0x108f3,
+ 0x108f6,0x108fa,
+ 0x1091c,0x1091e,
+ 0x1093a,0x1093e,
+ 0x1095a,0x1097f,
+ 0x109b8,0x109bb,
+ 0x109d0,0x109d1,
+ 0x10a04,0x10a04,
+ 0x10a07,0x10a0b,
+ 0x10a14,0x10a14,
+ 0x10a18,0x10a18,
+ 0x10a36,0x10a37,
+ 0x10a3b,0x10a3e,
+ 0x10a49,0x10a4f,
+ 0x10a59,0x10a5f,
+ 0x10aa0,0x10abf,
+ 0x10ae7,0x10aea,
+ 0x10af7,0x10aff,
+ 0x10b36,0x10b38,
+ 0x10b56,0x10b57,
+ 0x10b73,0x10b77,
+ 0x10b92,0x10b98,
+ 0x10b9d,0x10ba8,
+ 0x10bb0,0x10bff,
+ 0x10c49,0x10c7f,
+ 0x10cb3,0x10cbf,
+ 0x10cf3,0x10cf9,
+ 0x10d28,0x10d2f,
+ 0x10d3a,0x10d3f,
+ 0x10d66,0x10d68,
+ 0x10d86,0x10d8d,
+ 0x10d90,0x10e5f,
+ 0x10e7f,0x10e7f,
+ 0x10eaa,0x10eaa,
+ 0x10eae,0x10eaf,
+ 0x10eb2,0x10ec1,
+ 0x10ec8,0x10ecf,
+ 0x10ed9,0x10ef9,
+ 0x10f28,0x10f2f,
+ 0x10f5a,0x10f6f,
+ 0x10f8a,0x10faf,
+ 0x10fcc,0x10fdf,
+ 0x10ff7,0x10fff,
+ 0x1104e,0x11051,
+ 0x11076,0x1107e,
+ 0x110bd,0x110bd,
+ 0x110c3,0x110cf,
+ 0x110e9,0x110ef,
+ 0x110fa,0x110ff,
+ 0x11135,0x11135,
+ 0x11148,0x1114f,
+ 0x11177,0x1117f,
+ 0x111e0,0x111e0,
+ 0x111f5,0x111ff,
+ 0x11212,0x11212,
+ 0x11242,0x1127f,
+ 0x11287,0x11287,
+ 0x11289,0x11289,
+ 0x1128e,0x1128e,
+ 0x1129e,0x1129e,
+ 0x112aa,0x112af,
+ 0x112eb,0x112ef,
+ 0x112fa,0x112ff,
+ 0x11304,0x11304,
+ 0x1130d,0x1130e,
+ 0x11311,0x11312,
+ 0x11329,0x11329,
+ 0x11331,0x11331,
+ 0x11334,0x11334,
+ 0x1133a,0x1133a,
+ 0x11345,0x11346,
+ 0x11349,0x1134a,
+ 0x1134e,0x1134f,
+ 0x11351,0x11356,
+ 0x11358,0x1135c,
+ 0x11364,0x11365,
+ 0x1136d,0x1136f,
+ 0x11375,0x1137f,
+ 0x1138a,0x1138a,
+ 0x1138c,0x1138d,
+ 0x1138f,0x1138f,
+ 0x113b6,0x113b6,
+ 0x113c1,0x113c1,
+ 0x113c3,0x113c4,
+ 0x113c6,0x113c6,
+ 0x113cb,0x113cb,
+ 0x113d6,0x113d6,
+ 0x113d9,0x113e0,
+ 0x113e3,0x113ff,
+ 0x1145c,0x1145c,
+ 0x11462,0x1147f,
+ 0x114c8,0x114cf,
+ 0x114da,0x1157f,
+ 0x115b6,0x115b7,
+ 0x115de,0x115ff,
+ 0x11645,0x1164f,
+ 0x1165a,0x1165f,
+ 0x1166d,0x1167f,
+ 0x116ba,0x116bf,
+ 0x116ca,0x116cf,
+ 0x116e4,0x116ff,
+ 0x1171b,0x1171c,
+ 0x1172c,0x1172f,
+ 0x11747,0x117ff,
+ 0x1183c,0x1189f,
+ 0x118f3,0x118fe,
+ 0x11907,0x11908,
+ 0x1190a,0x1190b,
+ 0x11914,0x11914,
+ 0x11917,0x11917,
+ 0x11936,0x11936,
+ 0x11939,0x1193a,
+ 0x11947,0x1194f,
+ 0x1195a,0x1199f,
+ 0x119a8,0x119a9,
+ 0x119d8,0x119d9,
+ 0x119e5,0x119ff,
+ 0x11a48,0x11a4f,
+ 0x11aa3,0x11aaf,
+ 0x11af9,0x11aff,
+ 0x11b0a,0x11b5f,
+ 0x11b68,0x11bbf,
+ 0x11be2,0x11bef,
+ 0x11bfa,0x11bff,
+ 0x11c09,0x11c09,
+ 0x11c37,0x11c37,
+ 0x11c46,0x11c4f,
+ 0x11c6d,0x11c6f,
+ 0x11c90,0x11c91,
+ 0x11ca8,0x11ca8,
+ 0x11cb7,0x11cff,
+ 0x11d07,0x11d07,
+ 0x11d0a,0x11d0a,
+ 0x11d37,0x11d39,
+ 0x11d3b,0x11d3b,
+ 0x11d3e,0x11d3e,
+ 0x11d48,0x11d4f,
+ 0x11d5a,0x11d5f,
+ 0x11d66,0x11d66,
+ 0x11d69,0x11d69,
+ 0x11d8f,0x11d8f,
+ 0x11d92,0x11d92,
+ 0x11d99,0x11d9f,
+ 0x11daa,0x11daf,
+ 0x11ddc,0x11ddf,
+ 0x11dea,0x11edf,
+ 0x11ef9,0x11eff,
+ 0x11f11,0x11f11,
+ 0x11f3b,0x11f3d,
+ 0x11f5b,0x11faf,
+ 0x11fb1,0x11fbf,
+ 0x11ff2,0x11ffe,
+ 0x1239a,0x123ff,
+ 0x1246f,0x1246f,
+ 0x12475,0x1247f,
+ 0x12544,0x12f8f,
+ 0x12ff3,0x12fff,
+ 0x13430,0x1343f,
+ 0x13456,0x1345f,
+ 0x143fb,0x143ff,
+ 0x14647,0x160ff,
+ 0x1613a,0x167ff,
+ 0x16a39,0x16a3f,
+ 0x16a5f,0x16a5f,
+ 0x16a6a,0x16a6d,
+ 0x16abf,0x16abf,
+ 0x16aca,0x16acf,
+ 0x16aee,0x16aef,
+ 0x16af6,0x16aff,
+ 0x16b46,0x16b4f,
+ 0x16b5a,0x16b5a,
+ 0x16b62,0x16b62,
+ 0x16b78,0x16b7c,
+ 0x16b90,0x16d3f,
+ 0x16d7a,0x16e3f,
+ 0x16e9b,0x16e9f,
+ 0x16eb9,0x16eba,
+ 0x16ed4,0x16eff,
+ 0x16f4b,0x16f4e,
+ 0x16f88,0x16f8e,
+ 0x16fa0,0x16fdf,
+ 0x16fe5,0x16fef,
+ 0x16ff7,0x16fff,
+ 0x18cd6,0x18cfe,
+ 0x18d1f,0x18d7f,
+ 0x18df3,0x1afef,
+ 0x1aff4,0x1aff4,
+ 0x1affc,0x1affc,
+ 0x1afff,0x1afff,
+ 0x1b123,0x1b131,
+ 0x1b133,0x1b14f,
+ 0x1b153,0x1b154,
+ 0x1b156,0x1b163,
+ 0x1b168,0x1b16f,
+ 0x1b2fc,0x1bbff,
+ 0x1bc6b,0x1bc6f,
+ 0x1bc7d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f094,0x1f09f,
+ 0x1f0af,0x1f0b0,
+ 0x1f0c0,0x1f0c0,
+ 0x1f0d0,0x1f0d0,
+ 0x1f0f6,0x1f0ff,
+ 0x1f1ae,0x1f1e5,
+ 0x1f203,0x1f20f,
+ 0x1f23c,0x1f23f,
+ 0x1f249,0x1f24f,
+ 0x1f252,0x1f25f,
+ 0x1f266,0x1f2ff,
+ 0x1f6d9,0x1f6db,
+ 0x1f6ed,0x1f6ef,
+ 0x1f6fd,0x1f6ff,
+ 0x1f7da,0x1f7df,
+ 0x1f7ec,0x1f7ef,
+ 0x1f7f1,0x1f7ff,
+ 0x1f80c,0x1f80f,
+ 0x1f848,0x1f84f,
+ 0x1f85a,0x1f85f,
+ 0x1f888,0x1f88f,
+ 0x1f8ae,0x1f8af,
+ 0x1f8bc,0x1f8bf,
+ 0x1f8c2,0x1f8cf,
+ 0x1f8d9,0x1f8ff,
+ 0x1fa58,0x1fa5f,
+ 0x1fa6e,0x1fa6f,
+ 0x1fa7d,0x1fa7f,
+ 0x1fa8b,0x1fa8d,
+ 0x1fac7,0x1fac7,
+ 0x1fac9,0x1facc,
+ 0x1fadd,0x1fade,
+ 0x1faeb,0x1faee,
+ 0x1faf9,0x1faff,
+ 0x1fb93,0x1fb93,
+ 0x1fbfb,0x1ffff,
+ 0x2a6e0,0x2a6ff,
+ 0x2b81e,0x2b81f,
+ 0x2ceae,0x2ceaf,
+ 0x2ebe1,0x2ebef,
+ 0x2ee5e,0x2f7ff,
+ 0x2fa1e,0x2ffff,
+ 0x3134b,0x3134f,
+ 0x3347a,0xe00ff,
+ 0xe01f0,0x10ffff,
+])
diff --git a/home/webext/src/id/gen/statements.js b/home/webext/src/id/gen/statements.js
new file mode 100644
index 00000000..cd848c62
--- /dev/null
+++ b/home/webext/src/id/gen/statements.js
@@ -0,0 +1,657 @@
+// GENERATED from kernel/src/statements.ts by scripts/gen-webext-id.mjs — do not edit.
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento/id — the signed statements: one definition of every byte, for every host.
+//
+// Identity is keys, and everything anyone trusts is a SIGNED STATEMENT: "this
+// device is mine" (dev.), "this key is [email protected]" (bind.), "the directory
+// checked that binding" (att.), "this person consented to exactly this action"
+// (cns.), and the directory's deletion record, delete request and email-code
+// completion (tomb., del., cmp.). The agents (Swift, Kotlin, Rust, and the
+// extension's JS) build and check them, and so do the directory and the
+// document. If two of them read the same bytes differently, a signature means
+// different things to different verifiers. So this module is the reference,
+// and kernel/fixtures/identity-v1.json is the conformance contract every host
+// must pass.
+//
+// THE FAMILY RULES — the same as the shipped collab statements (inv./dlg./rev.):
+// - A statement is dot-joined UTF-8 text, signed over its EXACT bytes. Nobody
+// re-serialises or canonicalises; the text is stored and hashed verbatim.
+// No JSON ever sits inside a signed statement.
+// - Every field is either a token from a CLOSED, dot-free grammar (a purpose
+// word, a kid, an integer) or FREE TEXT encoded as base64url without padding
+// (an email address, a display name). A raw email would break the split: it
+// has dots.
+// - Parsing is strict: split on '.', keep empty fields, require the EXACT field
+// count, check every field against its grammar. A stray field is a rejection,
+// never a re-join. The whole text must be printable ASCII.
+// - An ABSENT value is an EMPTY field, and only where its grammar allows one.
+// - Times are epoch MILLISECONDS, everywhere.
+// - The VERSION is the prefix: `bind.` is version 1; a breaking change is `bind2.`.
+// - Keys are raw uncompressed P-256 points (65 bytes), base64url. Signatures are
+// raw r‖s (64 bytes), base64url, LOW-S — never DER. A host whose platform
+// emits DER converts before anything crosses the bridge; a high-S or DER
+// signature here is a rejection, so a forgotten conversion fails loudly.
+
+import { isNormalAddress } from './address.js'
+import { DISPLAY_FORBIDDEN_FLAT, DISPLAY_FORBIDDEN_UNICODE } from './display-table.js'
+
+
+// --- strict base64url --------------------------------------------------------
+
+const B64U_RE = /^[A-Za-z0-9_-]*$/
+
+export function b64uEnc(bytes ) {
+ let s = ''
+ for (const b of bytes) s += String.fromCharCode(b)
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
+}
+
+/** Canonical base64url only: the alphabet, no padding, and it must re-encode to
+ * exactly the same string (so trailing bits are zero). Null otherwise. */
+export function b64uDec(s ) {
+ if (typeof s !== 'string' || !B64U_RE.test(s) || s.length % 4 === 1) return null
+ let bin
+ try { bin = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4)) } catch { return null }
+ const out = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
+ return b64uEnc(out) === s ? out : null
+}
+
+const te = new TextEncoder()
+const utf8 = (s ) => te.encode(s)
+const strictUtf8 = new TextDecoder('utf-8', { fatal: true })
+
+/** base64url-of-UTF-8 → text, canonical both ways; null if not. */
+function freeText(f ) {
+ const b = b64uDec(f)
+ if (!b) return null
+ let t
+ try { t = strictUtf8.decode(b) } catch { return null }
+ return b64uEnc(utf8(t)) === f ? t : null
+}
+
+/**
+ * Display text a person sees (a name, a device label): bounded, in NFC, and free
+ * of anything invisible or layout-changing that could make "alice ✓" read as
+ * something else on screen. Refused:
+ * - controls (Cc), private use (Co), line and paragraph separators (Zl, Zp);
+ * - UNASSIGNED code points (Cn), the 66 noncharacters among them: one assigned
+ * later could be an invisible format character, and NFC is stable across
+ * Unicode versions only for assigned characters (security, #764);
+ * - every format character (Cf): bidi overrides and marks (including U+061C),
+ * zero-width space, word joiner, BOM, soft hyphen, the Mongolian vowel
+ * separator — EXCEPT ZWNJ/ZWJ (U+200C/U+200D), which Persian, Indic scripts
+ * and emoji sequences need, and which are refused only at either end;
+ * - the Hangul fill letters U+115F, U+1160, U+3164, U+FFA0, which render blank.
+ * No filter stops homoglyphs, so a name is SELF-ASSERTED and must never be shown
+ * without the verified address beside it (docs/DECISIONS.md).
+ *
+ * The set is FROZEN as explicit code-point ranges, not resolved through `\p{…}`.
+ * General categories come from each platform's Unicode tables, so a character
+ * newly assigned to Cf would be refused by one host and accepted by another until
+ * both updated, and a name would verify on one device and not the next. These
+ * ranges are the categories above as of Unicode 17.0, generated into
+ * kernel/src/display-table.ts by scripts/gen-display-table.ts (which refuses to
+ * run on any other Unicode version); the fixture carries the same table for the
+ * native hosts, and the rig recomputes it. Changing it is a deliberate format
+ * decision, never a side effect of a platform update.
+ */
+const MAX_DISPLAY = 64
+export { DISPLAY_FORBIDDEN_UNICODE }
+/** The frozen table as [first, last] pairs (kernel/src/display-table.ts, generated). */
+export const DISPLAY_FORBIDDEN_RANGES = Object.freeze(
+ Array.from({ length: DISPLAY_FORBIDDEN_FLAT.length / 2 },
+ (_, i) => Object.freeze([DISPLAY_FORBIDDEN_FLAT[2 * i], DISPLAY_FORBIDDEN_FLAT[2 * i + 1]]) )
+)
+/** Is this code point refused in display text? A binary search over the frozen ranges. */
+export function displayForbidden(cp ) {
+ let lo = 0, hi = DISPLAY_FORBIDDEN_RANGES.length - 1
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1
+ const [a, b] = DISPLAY_FORBIDDEN_RANGES[mid]
+ if (cp < a) hi = mid - 1
+ else if (cp > b) lo = mid + 1
+ else return true
+ }
+ return false
+}
+const ZWNJ = 0x200c, ZWJ = 0x200d
+function displayText(f ) {
+ const t = freeText(f)
+ if (t === null || t.length === 0) return null
+ const cps = [...t].map((c) => c.codePointAt(0) )
+ if (cps.length > MAX_DISPLAY) return null
+ if (t.normalize('NFC') !== t) return null
+ if (cps.some(displayForbidden)) return null
+ const ends = [cps[0], cps[cps.length - 1]]
+ if (ends.some((c) => c === ZWNJ || c === ZWJ)) return null
+ return t
+}
+
+export async function sha256b64u(text ) {
+ return b64uEnc(new Uint8Array(await crypto.subtle.digest('SHA-256', utf8(text) )))
+}
+
+// --- keys and signatures -----------------------------------------------------
+
+const EC_SIGN = { name: 'ECDSA', namedCurve: 'P-256' }
+const EC_KX = { name: 'ECDH', namedCurve: 'P-256' }
+const SIGN_ALG = { name: 'ECDSA', hash: 'SHA-256' }
+/** the P-256 group order */
+const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n
+const HALF_N = N >> 1n
+
+const toBig = (b ) => b.reduce((x, v) => (x << 8n) | BigInt(v), 0n)
+function to32(x ) {
+ const out = new Uint8Array(32)
+ for (let i = 31; i >= 0; i--) { out[i] = Number(x & 0xffn); x >>= 8n }
+ return out
+}
+
+/** A raw r‖s signature in range with s in the lower half. */
+function sigInRange(sig ) {
+ if (sig.length !== 64) return false
+ const r = toBig(sig.subarray(0, 32)), s = toBig(sig.subarray(32))
+ return r > 0n && r < N && s > 0n && s <= HALF_N
+}
+
+/** The low-S form of a raw r‖s signature (what every signer must emit). */
+export function lowS(sig ) {
+ const s = toBig(sig.subarray(32))
+ if (s <= HALF_N) return sig
+ const out = new Uint8Array(64)
+ out.set(sig.subarray(0, 32))
+ out.set(to32(N - s), 32)
+ return out
+}
+
+/** A raw uncompressed P-256 point that the platform accepts for `alg`. */
+async function point(b64 , alg ) {
+ const raw = b64uDec(b64)
+ if (!raw || raw.length !== 65 || raw[0] !== 0x04) return null
+ try {
+ return await crypto.subtle.importKey('raw', raw , alg, false,
+ alg.name === 'ECDSA' ? ['verify'] : [])
+ } catch { return null }
+}
+export const isSigningKey = async (b64 ) => (await point(b64, EC_SIGN)) !== null
+export const isKxKey = async (b64 ) => (await point(b64, EC_KX)) !== null
+
+/** Verify `sigB64` (raw r‖s, low-S) by `pubB64` over the exact UTF-8 of `text`. */
+export async function verifyStatementSig(pubB64 , sigB64 , text ) {
+ const sig = b64uDec(sigB64)
+ if (!sig || !sigInRange(sig)) return false
+ const key = await point(pubB64, EC_SIGN)
+ if (!key) return false
+ try { return await crypto.subtle.verify(SIGN_ALG, key, sig , utf8(text) ) } catch { return false }
+}
+
+/** Sign `text` with `key`, emitting the low-S raw form. For JS agents and the
+ * vector generator; native agents produce the same bytes from their key stores. */
+export async function signStatement(key , text ) {
+ const sig = new Uint8Array(await crypto.subtle.sign(SIGN_ALG, key, utf8(text) ))
+ return b64uEnc(lowS(sig))
+}
+
+// --- strict parsing ------------------------------------------------------------
+
+
+const no = (reason ) => ({ ok: false, reason })
+
+const MAX_STATEMENT = 4096
+
+/** Split a statement: printable ASCII only, exact prefix and field count, empty
+ * fields kept. `count` includes the prefix. */
+function fields(text , prefix , count ) {
+ if (typeof text !== 'string' || text.length === 0 || text.length > MAX_STATEMENT) return null
+ for (let i = 0; i < text.length; i++) {
+ const c = text.charCodeAt(i)
+ if (c < 0x21 || c > 0x7e) return null
+ }
+ const parts = text.split('.')
+ return parts.length === count && parts[0] === prefix ? parts : null
+}
+
+const INT_RE = /^(0|[1-9][0-9]{0,15})$/
+function int(f ) {
+ if (!INT_RE.test(f)) return null
+ const n = Number(f)
+ return Number.isSafeInteger(n) ? n : null
+}
+const ms = (f ) => { const n = int(f); return n !== null && n > 0 ? n : null }
+/** a SHA-256 digest, base64url (32 bytes, 43 characters) */
+const isHash = (f ) => b64uDec(f)?.length === 32
+
+const KID_RE = /^[a-z0-9][a-z0-9-]{0,62}$/
+const RP_RE = /^(bento|vault-[a-z0-9][a-z0-9-]{0,62})$/
+const DOCID_RE = /^[A-Za-z0-9_-]{1,128}$/ // security §19i
+const ROOM_RE = /^w[A-Za-z0-9_-]{43}$/ // 'w' + b64u(sha256(owner pub))
+/** The email code: exactly 8 characters from a 31-character alphabet with no
+ * 0/O or 1/I/L, always UPPERCASE (agents uppercase what was typed before
+ * signing). About 39.6 bits, behind 5 attempts and a 20-minute TTL. */
+const CODE_RE = /^[23456789ABCDEFGHJKMNPQRSTUVWXYZ]{8}$/
+
+/** Clock skew tolerated for "issued in the future". */
+export const SKEW_MS = 5 * 60_000
+const DAY = 86_400_000
+/** A certificate lives at most 13 months, plus a day of slack: 13 × 30.5 days + 1. */
+export const CERT_MAX_MS = (13 * 30.5 + 1) * DAY
+
+function lifetime(created , expires , now ) {
+ if (expires <= created) return 'lifetime'
+ if (expires - created > CERT_MAX_MS) return 'lifetime'
+ if (created > now + SKEW_MS) return 'not-yet-valid'
+ if (now >= expires) return 'expired'
+ return null
+}
+
+// --- kx placement (pending the maintainer, identity-design §6b) ----------------
+
+/**
+ * Where the key-agreement key lives is a maintainer decision (§6b): A shared kx
+ * in bind.; B per-device kx in dev.; C per-device kx in dev. AND a recovery kx in
+ * bind. Both certificates carry a kx SLOT now, so the ruling changes which slot
+ * is required, never the format. Until it is ruled, the strictest reading holds:
+ * BOTH slots must be empty, so nothing accepts a placement nobody chose. Phase 1
+ * shares nothing, so it needs no kx.
+ */
+
+export const KX_MODE = 'unruled'
+const KX_SLOT = {
+ unruled: { bind: 'empty', dev: 'empty' },
+ A: { bind: 'required', dev: 'empty' },
+ B: { bind: 'empty', dev: 'required' },
+ C: { bind: 'required', dev: 'required' },
+}
+
+/** Check a kx slot: present only when the mode requires it, a valid ECDH point,
+ * and never equal to any signing key in the same certificate. */
+async function kxSlot(f , rule , others ) {
+ if (rule === 'empty') return f === '' ? null : false
+ if (f === '' || !(await isKxKey(f)) || others.includes(f)) return false
+ return f
+}
+
+// --- dev. — the device certificate (signed by the account key) ---------------
+
+/**
+ * `dev.<devicePub>.<consentPub|empty>.<accountPub>.<kx|empty>.<b64u(label)|empty>.<created>.<expires>`
+ *
+ * Binds this device's ROUTINE key and its hardware CONSENT key to the account.
+ * The consent key is a separate, non-exportable key (Secure Enclave
+ * `.userPresence`, a BiometricPrompt-bound Keystore key, Windows Hello); a
+ * consent statement (cns.) is accepted only from a key certified here. The light
+ * tier has no hardware consent key, so consentPub is empty there, and that
+ * device can never produce an accepted cns.
+ */
+
+
+
+
+
+
+
+
+
+
+export function buildDev(c ) {
+ return ['dev', c.devicePub, c.consentPub ?? '', c.accountPub, c.kx ?? '',
+ c.label ? b64uEnc(utf8(c.label)) : '', c.created, c.expires].join('.')
+}
+
+export async function verifyDev(text , sig , opts )
+ {
+ const p = fields(text, 'dev', 8)
+ if (!p) return no('grammar')
+ const [, devicePub, consentF, accountPub, kxF, labelF, createdF, expiresF] = p
+ if (!(await isSigningKey(devicePub)) || !(await isSigningKey(accountPub))) return no('key')
+ if (devicePub === accountPub) return no('key')
+ let consentPub = null
+ if (consentF !== '') {
+ if (!(await isSigningKey(consentF)) || consentF === devicePub || consentF === accountPub) return no('consent-key')
+ consentPub = consentF
+ }
+ const kx = await kxSlot(kxF, KX_SLOT[opts.kxMode ?? KX_MODE].dev, [devicePub, accountPub, consentF])
+ if (kx === false) return no('kx')
+ let label = null
+ if (labelF !== '') { label = displayText(labelF); if (label === null) return no('label') }
+ const created = ms(createdF), expires = ms(expiresF)
+ if (created === null || expires === null) return no('grammar')
+ const life = lifetime(created, expires, opts.now)
+ if (life) return no(life)
+ if (!(await verifyStatementSig(accountPub, sig, text))) return no('signature')
+ return { ok: true, value: { devicePub, consentPub, accountPub, kx, label, created, expires } }
+}
+
+// --- bind. — the person certificate (signed by the account key) --------------
+
+/**
+ * `bind.<b64u(address)>.<accountPub>.<kx|empty>.<b64u(name)|empty>.<seq>.<prev|empty>.<created>.<expires>`
+ *
+ * "This account key is this address", signed by the holder; the directory then
+ * attests it (att.). `address` must already be in normal form (address.ts).
+ * `seq` starts at 1; `prev` is the hash of the previous bind. text for this
+ * address, empty exactly when seq is 1, so a rotation chain cannot be forked
+ * silently.
+ */
+
+
+
+
+
+
+
+
+
+
+
+export function buildBind(c ) {
+ return ['bind', b64uEnc(utf8(c.address)), c.accountPub, c.kx ?? '',
+ c.name ? b64uEnc(utf8(c.name)) : '', c.seq, c.prev ?? '', c.created, c.expires].join('.')
+}
+
+export async function verifyBind(text , sig , opts )
+ {
+ const p = fields(text, 'bind', 9)
+ if (!p) return no('grammar')
+ const [, addressF, accountPub, kxF, nameF, seqF, prevF, createdF, expiresF] = p
+ const address = freeText(addressF)
+ if (address === null || !isNormalAddress(address)) return no('address')
+ if (!(await isSigningKey(accountPub))) return no('key')
+ const kx = await kxSlot(kxF, KX_SLOT[opts.kxMode ?? KX_MODE].bind, [accountPub])
+ if (kx === false) return no('kx')
+ let name = null
+ if (nameF !== '') { name = displayText(nameF); if (name === null) return no('name') }
+ const seq = int(seqF)
+ if (seq === null || seq < 1) return no('seq')
+ if ((seq === 1) !== (prevF === '')) return no('prev')
+ if (prevF !== '' && !isHash(prevF)) return no('prev')
+ const created = ms(createdF), expires = ms(expiresF)
+ if (created === null || expires === null) return no('grammar')
+ const life = lifetime(created, expires, opts.now)
+ if (life) return no(life)
+ if (!(await verifyStatementSig(accountPub, sig, text))) return no('signature')
+ return { ok: true, value: { address, accountPub, kx, name, seq, prev: prevF || null, created, expires } }
+}
+
+// --- att. — the directory's attestation (signed by a directory key) ----------
+
+
+
+/**
+ * `att.<sha256(bind text)>.<verifiedAt>.<issuedAt>.<kid>.<active|pending|frozen>`
+ *
+ * The directory's signed answer to a lookup. `issuedAt` is fresh on every
+ * answer, so a client can refuse a replayed one; `state` is inside the
+ * signature, so a directory answer cannot be replayed as "active" during a
+ * rotation freeze (security §25). Signed by the directory's ONLINE key named by
+ * `kid` — never the release key.
+ */
+
+
+
+
+
+
+
+
+export function buildAtt(a ) {
+ return ['att', a.bindHash, a.verifiedAt, a.issuedAt, a.kid, a.state].join('.')
+}
+
+export async function verifyAtt(text , sig , opts
+
+
+
+
+ ) {
+ const p = fields(text, 'att', 6)
+ if (!p) return no('grammar')
+ const [, bindHash, verifiedF, issuedF, kid, state] = p
+ if (!isHash(bindHash) || !KID_RE.test(kid)) return no('grammar')
+ if (state !== 'active' && state !== 'pending' && state !== 'frozen') return no('grammar')
+ const verifiedAt = ms(verifiedF), issuedAt = ms(issuedF)
+ if (verifiedAt === null || issuedAt === null || verifiedAt > issuedAt) return no('grammar')
+ if (issuedAt > opts.now + SKEW_MS) return no('not-yet-valid')
+ if (opts.now - issuedAt > opts.maxAgeMs) return no('stale')
+ if (bindHash !== (await sha256b64u(opts.bindText))) return no('bind-mismatch')
+ if (!Object.hasOwn(opts.directoryKeys, kid)) return no('unknown-kid')
+ if (!(await verifyStatementSig(opts.directoryKeys[kid], sig, text))) return no('signature')
+ return { ok: true, value: { bindHash, verifiedAt, issuedAt, kid, state: state } }
+}
+
+// --- tomb. — the directory's deletion record ---------------------------------
+
+
+
+/**
+ * `tomb.<sha256(last bind text)|empty>.<seq>.<deletedAt>.<holder|mailbox|operator>.<kid>`
+ *
+ * Lets a client tell "deleted" from "never bound". The hash is empty when the
+ * directory holds no previous binding text for the address.
+ */
+
+
+
+
+
+
+
+
+export function buildTomb(t ) {
+ return ['tomb', t.lastBindHash ?? '', t.seq, t.deletedAt, t.by, t.kid].join('.')
+}
+
+export async function verifyTomb(text , sig , opts
+
+
+ ) {
+ const p = fields(text, 'tomb', 6)
+ if (!p) return no('grammar')
+ const [, hashF, seqF, deletedF, by, kid] = p
+ if (hashF !== '' && !isHash(hashF)) return no('grammar')
+ const seq = int(seqF), deletedAt = ms(deletedF)
+ if (seq === null || seq < 1 || deletedAt === null) return no('grammar')
+ if (by !== 'holder' && by !== 'mailbox' && by !== 'operator') return no('grammar')
+ if (!KID_RE.test(kid)) return no('grammar')
+ if (deletedAt > opts.now + SKEW_MS) return no('not-yet-valid')
+ if (!Object.hasOwn(opts.directoryKeys, kid)) return no('unknown-kid')
+ if (!(await verifyStatementSig(opts.directoryKeys[kid], sig, text))) return no('signature')
+ return { ok: true, value: { lastBindHash: hashF || null, seq, deletedAt, by: by , kid } }
+}
+
+// --- del. — a holder's delete request (signed by the account key) ------------
+
+/** `del.<b64u(address)>.<ts>`, valid within ±5 minutes of `ts`. */
+export const DELETE_WINDOW_MS = 5 * 60_000
+
+export function buildDel(address , ts ) {
+ return ['del', b64uEnc(utf8(address)), ts].join('.')
+}
+
+export async function verifyDel(text , sig , opts )
+ {
+ const p = fields(text, 'del', 3)
+ if (!p) return no('grammar')
+ const address = freeText(p[1])
+ if (address === null || !isNormalAddress(address)) return no('address')
+ const ts = ms(p[2])
+ if (ts === null) return no('grammar')
+ if (Math.abs(opts.now - ts) > DELETE_WINDOW_MS) return no('expired')
+ if (!(await verifyStatementSig(opts.accountPub, sig, text))) return no('signature')
+ return { ok: true, value: { address, ts } }
+}
+
+// --- cmp. — the email-code completion (signed by the binding's account key) --
+
+/** `cmp.<sha256(bind text)>.<code>`: the person typed `code` into their agent,
+ * and the agent signs that it completes THIS binding. */
+export function buildCmp(bindHash , code ) {
+ return ['cmp', bindHash, code].join('.')
+}
+
+export async function verifyCmp(text , sig , opts )
+ {
+ const p = fields(text, 'cmp', 3)
+ if (!p) return no('grammar')
+ const [, bindHash, code] = p
+ if (!isHash(bindHash) || !CODE_RE.test(code)) return no('grammar')
+ if (bindHash !== (await sha256b64u(opts.bindText))) return no('bind-mismatch')
+ if (!(await verifyStatementSig(opts.accountPub, sig, text))) return no('signature')
+ return { ok: true, value: { bindHash, code } }
+}
+
+// --- cns. — host-stamped consent (signed by a certified consent key) ---------
+
+/**
+ * The consent purposes a cns. may carry, a CLOSED set, and the statement family
+ * each one authorises. `grant` and `role` are reserved for phase 2 and refused
+ * until defined. (Distinct from identity.ts SignPurpose, which is about routine
+ * signing with the device key.)
+ */
+
+const CONSENT_FAMILY = {
+ invite: 'inv.', revoke: 'rev.', link: 'dev.', rotate: 'bind.', unbind: 'del.',
+}
+const RESERVED_PURPOSES = new Set(['grant', 'role'])
+/** Purposes about one document carry its docId; account-scoped ones carry none. */
+const DOC_SCOPED = new Set (['invite', 'revoke'])
+
+/** A consent signature is good for at most this long after it is made. */
+export const CONSENT_MAX_TTL_MS = 5 * 60_000
+
+const AUDIENCE_RE = new RegExp(`^(dir|room:${ROOM_RE.source.slice(1, -1)})$`)
+
+/**
+ * The channel binding (security §24): it ties the consent to WHO verifies it
+ * (the audience: `dir`, or `room:<roomName>`), to the single-use CHALLENGE that
+ * verifier issued, and to the EXACT statement being authorised. A relayed
+ * signature fails the audience, a replayed one the spent challenge, and a swapped
+ * payload the hash. Null if a part breaks its grammar.
+ *
+ * transcript = b64u( SHA-256( UTF-8( "cnst.v1." ‖ audience ‖ "." ‖ challenge ‖ "." ‖ b64u(SHA-256(payload)) ) ) )
+ */
+export async function consentTranscript(audience , challenge , payloadText ) {
+ if (!AUDIENCE_RE.test(audience)) return null
+ const c = b64uDec(challenge)
+ if (!c || c.length < 16 || c.length > 64) return null
+ return sha256b64u(`cnst.v1.${audience}.${challenge}.${await sha256b64u(payloadText)}`)
+}
+
+
+
+
+
+
+
+
+
+/** `cns.<rp>.<purpose>.<docId|empty>.<transcript>.<exp>`, every field host-stamped. */
+export function buildConsent(c ) {
+ return ['cns', c.rp, c.purpose, c.docId ?? '', c.transcript, c.exp].join('.')
+}
+
+/**
+ * Verify a consent signature. The verifier RECOMPUTES the transcript from its
+ * OWN audience, the challenge it issued and the payload it is about to apply —
+ * it never trusts a transcript from the request. `spend(challenge)` must mark
+ * the challenge used and return false if it was already spent or has expired;
+ * it is called first, so any attempt consumes the challenge. That is the right
+ * default for races (no second try against one challenge), and it relies on
+ * challenges being SESSION-BOUND: one issued to one session, so a stranger who
+ * spends it can only fail that session's attempt, never take it over.
+ *
+ * `consentPub` must come from a verified dev. certificate's consentPub field;
+ * that is what makes it a consent key and not merely a key.
+ */
+export async function verifyConsent(text , sig , opts
+
+
+
+
+
+
+
+
+ ) {
+ const p = fields(text, 'cns', 6)
+ if (!p) return no('grammar')
+ if (!opts.spend(opts.challenge)) return no('replay')
+ const [, rp, purposeF, docIdF, transcript, expF] = p
+ if (!RP_RE.test(rp) || !isHash(transcript)) return no('grammar')
+ if (RESERVED_PURPOSES.has(purposeF)) return no('reserved-purpose')
+ if (!Object.hasOwn(CONSENT_FAMILY, purposeF)) return no('grammar')
+ const purpose = purposeF
+ const exp = ms(expF)
+ if (exp === null) return no('grammar')
+ if (rp !== opts.rp) return no('rp')
+ // the payload must be of the family this purpose authorises
+ if (!opts.payloadText.startsWith(CONSENT_FAMILY[purpose])) return no('payload-family')
+ // document-scoped purposes name the document; account-scoped ones name none
+ if (DOC_SCOPED.has(purpose)) {
+ if (!DOCID_RE.test(docIdF) || docIdF !== opts.docId) return no('docid')
+ } else if (docIdF !== '' || opts.docId !== null) return no('docid')
+ const expected = await consentTranscript(opts.audience, opts.challenge, opts.payloadText)
+ if (expected === null || transcript !== expected) return no('transcript')
+ if (opts.now >= exp) return no('expired')
+ if (exp - opts.now > CONSENT_MAX_TTL_MS) return no('lifetime')
+ if (!(await verifyStatementSig(opts.consentPub, sig, text))) return no('signature')
+ return { ok: true, value: { rp, purpose, docId: docIdF || null, transcript, exp } }
+}
+
+/**
+ * The light tier has no hardware consent key (its dev. consentPub is empty). In
+ * phase 1 its consent is a WebAuthn assertion verified only by the directory
+ * (every phase-1 cns. has audience `dir`), and the assertion carries the
+ * statement as `clientDataJSON.challenge` = this value: base64url of SHA-256 over
+ * the EXACT cns. bytes (security §27).
+ */
+export const webauthnChallengeFor = (cnsText ) => sha256b64u(cnsText)
+
+/**
+ * Prefixes reserved for statements not defined yet, so nothing else takes them:
+ * pk. — an account-signed passkey statement (phase 2), for room-audience
+ * verifiers of light-tier consent. Never the dev. consentPub slot.
+ * drev. — an account-signed device revocation. Not needed in phase 1: a device
+ * retired without rotating the account key is one whose hardware-wrapped
+ * keys were destroyed by a confirmed wipe, so its dev. cert names a key
+ * nobody holds. It arrives with per-device kx, when senders wrap to
+ * device keys (security §25b).
+ */
+export const RESERVED_PREFIXES = Object.freeze(['pk', 'drev'])
+
+// --- routine signing: what payload each SignPurpose (identity.ts) may sign ----
+
+/** A canonical base64url field decoding to at least `min` (exactly `exact`) bytes. */
+const b64Len = (f , min , exact ) => {
+ const b = b64uDec(f)
+ return !!b && (exact === undefined ? b.length >= min : b.length === exact)
+}
+const isPubField = (f ) => { const b = b64uDec(f); return !!b && b.length === 65 && b[0] === 0x04 }
+const IV = (f ) => b64Len(f, 0, 12) // AES-GCM iv
+const CT = (f ) => b64Len(f, 16) // ciphertext with its 16-byte tag
+
+/**
+ * Does `payload` have the exact shape of the statement `purpose` names? The
+ * agent signs only a matching payload, so a prompt shown for one kind of action
+ * can never yield a signature on another. Shapes are the shipped collab
+ * statements (kernel/src/sync/online.ts, verified by the relay).
+ */
+export function payloadMatchesPurpose(purpose , payload ) {
+ if (typeof payload !== 'string' || payload.length > MAX_STATEMENT) return false
+ const p = payload.split('.')
+ switch (purpose) {
+ case 'frame': return p.length === 2 && IV(p[0]) && CT(p[1]) // `${i}.${d}`
+ case 'prove': return p.length === 3 && p[0] === 'prove' && b64Len(p[1], 16) && /^[rw][A-Za-z0-9_-]{1,64}$/.test(p[2])
+ case 'delegate': return p.length === 2 && p[0] === 'dlg' && isPubField(p[1])
+ case 'show':
+ return (p.length === 1 && (p[0] === 'live' || p[0] === 'end')) ||
+ (p.length === 4 && (p[0] === 'nav' || p[0] === 'black') && p[1] === 'aud' && IV(p[2]) && CT(p[3]))
+ case 'invite': return p.length === 4 && p[0] === 'inv' && isPubField(p[1]) &&
+ (p[2] === 'writer' || p[2] === 'commenter' || p[2] === 'audience') && INT_RE.test(p[3])
+ case 'revoke': return p.length === 2 && p[0] === 'rev' && isPubField(p[1])
+ default: return false
+ }
+}
diff --git a/home/webext/src/id/recovery.js b/home/webext/src/id/recovery.js
new file mode 100644
index 00000000..9518f706
--- /dev/null
+++ b/home/webext/src/id/recovery.js
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento/id — the recovery code (identity-design §2f "Exact bytes", security §28).
+//
+// RANDOM, never chosen: 80 bits as 16 Crockford base-32 characters plus one
+// Crockford CHECK symbol (the 80-bit value mod 37), 17 characters, shown
+// XXXX-XXXX-XXXX-XXXX-C. The check symbol catches a typo LOCALLY, before it
+// spends one of the directory's five daily attempts.
+//
+// Typing it back: uppercase, spaces and hyphens stripped, O→0, I/L→1 (Crockford's
+// own rules). What the key derivation takes is the 10 DECODED BYTES, never the
+// string — every host derives the same key from the same code however it was
+// typed.
+//
+// The wrap itself (Argon2id over the decoded bytes, then HKDF) lands with the
+// vendored Argon2id and K2b's vectors.
+
+const SYMBOLS = '0123456789ABCDEFGHJKMNPQRSTVWXYZ' // the 32 data symbols
+const CHECK = SYMBOLS + '*~$=U' // the 37 check symbols
+export const CODE_BITS = 80
+
+const toBig = (u8) => u8.reduce((x, b) => (x << 8n) | BigInt(b), 0n)
+const checkOf = (bytes) => CHECK[Number(toBig(bytes) % 37n)]
+
+function encode(bytes) {
+ let v = toBig(bytes), out = ''
+ for (let i = 0; i < 16; i++) { out = SYMBOLS[Number(v & 31n)] + out; v >>= 5n }
+ return out
+}
+
+/** A fresh code, displayed form. `rand` injectable for tests only. */
+export function newRecoveryCode(rand = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n))) {
+ const bytes = rand(10)
+ if (!(bytes instanceof Uint8Array) || bytes.length !== 10) throw new Error('10 random bytes')
+ return displayCode(encode(bytes) + checkOf(bytes))
+}
+
+/** XXXX-XXXX-XXXX-XXXX-C */
+export const displayCode = (c) => `${c.slice(0, 4)}-${c.slice(4, 8)}-${c.slice(8, 12)}-${c.slice(12, 16)}-${c.slice(16)}`
+
+/**
+ * What the person typed → { bytes (10), code (17 canonical) }, or null when it
+ * is not a code: a wrong length, a symbol outside the alphabet, or a check
+ * symbol that does not match (a typo).
+ */
+export function parseRecoveryCode(typed) {
+ const s = String(typed ?? '').toUpperCase().replace(/[\s-]/g, '')
+ .replace(/O/g, '0').replace(/[IL]/g, '1')
+ if (s.length !== 17) return null
+ let v = 0n
+ for (const c of s.slice(0, 16)) {
+ const i = SYMBOLS.indexOf(c)
+ if (i < 0) return null
+ v = (v << 5n) | BigInt(i)
+ }
+ const bytes = new Uint8Array(10)
+ for (let i = 9; i >= 0; i--) { bytes[i] = Number(v & 0xffn); v >>= 8n }
+ if (!CHECK.includes(s[16]) || checkOf(bytes) !== s[16]) return null
+ return { bytes, code: s }
+}
diff --git a/scripts/gen-webext-id.mjs b/scripts/gen-webext-id.mjs
new file mode 100644
index 00000000..5633c16a
--- /dev/null
+++ b/scripts/gen-webext-id.mjs
@@ -0,0 +1,64 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The extension's copy of the bento/id statement code, GENERATED from the
+// kernel reference by stripping TypeScript types — never hand-edited.
+//
+// node scripts/gen-webext-id.mjs # write home/webext/src/id/gen/*.js
+// node scripts/gen-webext-id.mjs --check # exit 1 if they are stale
+//
+// WHY GENERATED. kernel/src/statements.ts is the one definition of every byte
+// a host signs or checks; kernel/fixtures/identity-v1.json is the contract.
+// The extension ships plain JavaScript (no bundler), so it cannot import the
+// TypeScript. A hand port would pass the vectors today and drift tomorrow; a
+// type-strip keeps the extension on the reference's exact logic, and --check
+// (run by scripts/test-webext-id.ts) fails the build the moment they differ.
+
+import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { stripTypeScriptTypes } from 'node:module'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const OUT = join(root, 'home/webext/src/id/gen')
+// The entry points; every module they import from kernel/src comes with them.
+const ENTRY = ['statements.ts', 'address.ts']
+const VALUE_IMPORT = /^import (?!type )[^;]*?from '\.\/([a-z0-9-]+)\.ts'/gm
+
+export function generate() {
+ const out = {}
+ const todo = [...ENTRY]
+ const seen = new Set()
+ while (todo.length) {
+ const f = todo.shift()
+ if (seen.has(f)) continue
+ seen.add(f)
+ const src = readFileSync(join(root, 'kernel/src', f), 'utf8')
+ for (const m of src.matchAll(VALUE_IMPORT)) todo.push(`${m[1]}.ts`)
+ let js = stripTypeScriptTypes(src, { mode: 'strip' })
+ // a type-only import vanishes; value imports point at the generated siblings
+ js = js.replace(/^import type .*$/gm, '').replace(/from '\.\/([a-z0-9-]+)\.ts'/g, "from './$1.js'")
+ if (/from '[^']*\.ts'/.test(js)) throw new Error(`${f}: an import still points at a .ts file`)
+ out[f.replace(/\.ts$/, '.js')] = `// GENERATED from kernel/src/${f} by scripts/gen-webext-id.mjs — do not edit.\n` + js
+ }
+ return out
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const files = generate()
+ if (process.argv.includes('--check')) {
+ let stale = 0
+ for (const [name, js] of Object.entries(files)) {
+ let have = ''
+ try { have = readFileSync(join(OUT, name), 'utf8') } catch { /* missing */ }
+ if (have !== js) { stale++; console.log(`stale: home/webext/src/id/gen/${name}`) }
+ }
+ if (stale) { console.log('run: node scripts/gen-webext-id.mjs'); process.exit(1) }
+ console.log('home/webext/src/id/gen is current')
+ } else {
+ mkdirSync(OUT, { recursive: true })
+ for (const [name, js] of Object.entries(files)) writeFileSync(join(OUT, name), js)
+ console.log(`wrote ${Object.keys(files).join(', ')}`)
+ }
+}
diff --git a/scripts/pack-webext.mjs b/scripts/pack-webext.mjs
index 184ccb3c..799d4349 100644
--- a/scripts/pack-webext.mjs
+++ b/scripts/pack-webext.mjs
@@ -48,6 +48,9 @@ const INCLUDE = [
/^manifest\.json$/,
/^icons\/[^/]+\.(png|svg)$/,
/^src\/[^/]+\.(js|html|css)$/,
+ // bento/id: the agent's modules, and the statement code generated from kernel
+ // (scripts/gen-webext-id.mjs) — one level for src/id, one for src/id/gen
+ /^src\/id\/(gen\/)?[^/]+\.js$/,
/^_locales\/[a-zA-Z_]+\/messages\.json$/,
]
/** Present on purpose, deliberately NOT shipped. */
diff --git a/scripts/test-webext-id.ts b/scripts/test-webext-id.ts
new file mode 100644
index 00000000..278b3f15
--- /dev/null
+++ b/scripts/test-webext-id.ts
@@ -0,0 +1,160 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// home/webext bento/id agent rig.
+//
+// node scripts/test-webext-id.ts
+//
+// WHAT THIS PROVES.
+// 1. The extension's statement code is the kernel reference, unaltered: the
+// generated copy in home/webext/src/id/gen/ is current (a type-strip of
+// kernel/src/statements.ts and address.ts).
+// 2. That copy passes the WHOLE conformance contract,
+// kernel/fixtures/identity-v1.json: kernel's own rig is run again with its
+// imports pointed at the extension's files, so every row kernel checks is
+// checked against the code the extension ships.
+// 3. The passkey-wrapped account key (identity-design §2f) round-trips, and
+// fails closed for the wrong passkey, the wrong credential, any tampered
+// field, and a recovered key that does not match the binding.
+// 4. The recovery code is 80 random bits as 16 Crockford base-32 symbols plus a
+// mod-37 check symbol: typing it back is forgiving, and a typo is refused locally.
+
+import { readFileSync, writeFileSync, mkdtempSync, readdirSync } from 'node:fs'
+import { join, dirname } from 'node:path'
+import { tmpdir } from 'node:os'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { spawnSync } from 'node:child_process'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const { generate } = await import('./gen-webext-id.mjs')
+const blob = await import('../home/webext/src/id/blob.js')
+const rec = await import('../home/webext/src/id/recovery.js')
+
+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}`)
+}
+
+console.log('\n— the extension runs the kernel reference, unaltered')
+const fresh = generate() as Record<string, string>
+for (const [name, js] of Object.entries(fresh)) {
+ let have = ''
+ try { have = readFileSync(join(root, 'home/webext/src/id/gen', name), 'utf8') } catch { /* missing */ }
+ ok(have === js, `home/webext/src/id/gen/${name} is the current type-strip of kernel/src (run node scripts/gen-webext-id.mjs if not)`)
+}
+const extra = readdirSync(join(root, 'home/webext/src/id/gen')).filter((f) => !(f in fresh))
+ok(extra.length === 0, `no leftover files in home/webext/src/id/gen${extra.length ? ` (${extra.join(', ')})` : ''}`)
+ok(Object.values(fresh).every((js) => !/from '[^']*\.ts'/.test(js)), 'every import in the generated copy resolves to a generated .js sibling')
+
+console.log('\n— the conformance contract (kernel/fixtures/identity-v1.json), against the extension\'s copy')
+{
+ const src = readFileSync(join(root, 'scripts/test-statements.ts'), 'utf8')
+ const gen = (f: string) => pathToFileURL(join(root, 'home/webext/src/id/gen', f)).href
+ const swapped = src
+ .replace("from '../kernel/src/statements.ts'", `from '${gen('statements.js')}'`)
+ .replace("from '../kernel/src/address.ts'", `from '${gen('address.js')}'`)
+ .replace("from '../kernel/src/identity.ts'", `from '${pathToFileURL(join(root, 'kernel/src/identity.ts')).href}'`)
+ .replace("const root = join(dirname(fileURLToPath(import.meta.url)), '..')", `const root = ${JSON.stringify(root)}`)
+ ok(swapped !== src && !swapped.includes("'../kernel/src/statements.ts'") && !swapped.includes("'../kernel/src/address.ts'"), 'kernel\'s rig is re-pointed at the extension\'s generated files')
+ const dir = mkdtempSync(join(tmpdir(), 'webext-id-'))
+ const f = join(dir, 'conformance.ts')
+ writeFileSync(f, swapped)
+ const run = (file: string) => {
+ const r = spawnSync(process.execPath, [file], { encoding: 'utf8' })
+ const tail = (r.stdout.trim().split('\n').at(-1) ?? '')
+ const m = tail.match(/^(\d+)\/(\d+) checks passed$/)
+ return { ok: r.status === 0 && !!m && m[1] === m[2], total: m ? Number(m[2]) : 0, tail: tail || r.stderr.trim().split('\n').slice(-3).join(' | ') }
+ }
+ const kernel = run(join(root, 'scripts/test-statements.ts'))
+ const ext = run(f)
+ ok(kernel.ok, `kernel's own rig passes on kernel's source (${kernel.tail})`)
+ ok(ext.ok && ext.total === kernel.total, `every conformance row passes on the extension's code, and as many rows as kernel's own run (${ext.tail} vs kernel ${kernel.total})`)
+}
+
+console.log('\n— the passkey-wrapped account key (identity-design §2f)')
+{
+ const subtle = globalThis.crypto.subtle
+ const prf = crypto.getRandomValues(new Uint8Array(32))
+ const credentialId = crypto.getRandomValues(new Uint8Array(32))
+ const kp = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'])
+ const accountD = await blob.scalarOf(kp.privateKey)
+ const accountPub = await blob.rawPub(kp.publicKey)
+ const b = await blob.wrapAccount({ prf, credentialId, accountD })
+ ok(b.v === 1 && b.cred === await blob.credHash(credentialId) && blob.unb64u(b.salt).length === 32 && blob.unb64u(b.iv).length === 12, 'the blob has the §2f shape: v, cred = b64u(sha256(credentialId)), 32-byte salt, 12-byte iv')
+ ok(!JSON.stringify(b).includes(blob.b64u(accountD)), 'the account scalar does not appear in the blob')
+ const out = await blob.unwrapAccount(b, { prf, credentialId })
+ ok(blob.b64u(out.accountD) === blob.b64u(accountD) && out.kxD === null, 'the same passkey opens it (kx slot empty)')
+ const fails = async (p: Promise<unknown>) => p.then(() => false, () => true)
+ ok(await fails(blob.unwrapAccount(b, { prf: crypto.getRandomValues(new Uint8Array(32)), credentialId })), 'another passkey\'s PRF output cannot open it')
+ ok(await fails(blob.unwrapAccount(b, { prf, credentialId: crypto.getRandomValues(new Uint8Array(32)) })), 'a blob presented for another credential is refused')
+ for (const field of ['ct', 'iv', 'salt'] as const) {
+ const t = { ...b, [field]: blob.b64u(blob.unb64u(b[field]).map((x: number, i: number) => (i === 0 ? x ^ 1 : x))) }
+ ok(await fails(blob.unwrapAccount(t, { prf, credentialId })), `a tampered ${field} fails closed`)
+ }
+ // the aad binds the credential hash: moving a blob under another cred label fails even with the right PRF
+ const other = crypto.getRandomValues(new Uint8Array(32))
+ ok(await fails(blob.unwrapAccount({ ...b, cred: await blob.credHash(other) }, { prf, credentialId: other })), 'relabelling a blob for another credential fails (cred is in the AAD)')
+ const key = await blob.importAccount(out.accountD, accountPub)
+ ok(key.extractable === false && key.usages.join() === 'sign', 'the recovered key comes back NON-extractable, sign-only')
+ const stranger = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign'])
+ ok(await fails(blob.importAccount(out.accountD, await blob.rawPub(stranger.publicKey))), 'a recovered key that does not match the binding\'s public key is refused (a swapped blob fails closed)')
+ // the probe ALONE: an engine whose JWK import does not check d against x/y
+ // (simulated: importKey hands back the scalar's own key, whatever x/y said)
+ const lax: any = {
+ getRandomValues: (a: Uint8Array) => crypto.getRandomValues(a),
+ subtle: new Proxy(subtle, { get: (t: any, k: string) => k === 'importKey'
+ ? async (fmt: string, data: any, alg: any, ext: boolean, use: string[]) => {
+ if (fmt !== 'jwk') return t.importKey(fmt, data, alg, ext, use)
+ return t.importKey('pkcs8', await t.exportKey('pkcs8', kp.privateKey), alg, ext, use) // the scalar's own key, x/y ignored
+ }
+ : typeof t[k] === 'function' ? t[k].bind(t) : t[k] }),
+ }
+ ok(await fails(blob.importAccount(out.accountD, await blob.rawPub(stranger.publicKey), { crypto: lax })), 'with an import that does not check the key pair, the sign-and-verify probe alone still refuses a mismatched key')
+ ok(!(await fails(blob.importAccount(out.accountD, accountPub, { crypto: lax }))), 'and accepts the matching one (the lax import is not just failing everything)')
+ const kx = crypto.getRandomValues(new Uint8Array(32))
+ const b2 = await blob.wrapAccount({ prf, credentialId, accountD, kxD: kx })
+ const out2 = await blob.unwrapAccount(b2, { prf, credentialId })
+ ok(blob.b64u(out2.kxD) === blob.b64u(kx), 'with the kx slot filled (after the ruling), both scalars round-trip')
+ ok(await fails(blob.wrapAccount({ prf: new Uint8Array(31), credentialId, accountD })) && await fails(blob.wrapAccount({ prf, credentialId, accountD: new Uint8Array(31) })), 'wrong-length PRF output or scalar is refused')
+ const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n
+ const big = (v: bigint) => { const o = new Uint8Array(32); for (let i = 31; i >= 0; i--) { o[i] = Number(v & 0xffn); v >>= 8n } return o }
+ ok(!blob.scalarInRange(new Uint8Array(32)) && !blob.scalarInRange(big(N)) && !blob.scalarInRange(big(N + 5n)) && blob.scalarInRange(big(N - 1n)) && blob.scalarInRange(big(1n)), 'a scalar must lie in 1..n−1')
+ ok(await fails(blob.importAccount(new Uint8Array(32), accountPub)), 'an out-of-range recovered scalar is refused before import')
+ ok(new TextDecoder().decode(blob.PRF_INPUT) === 'bento/id/prf/v1', 'the PRF input is the fixed "bento/id/prf/v1"')
+}
+
+console.log('\n— the recovery code (80 bits: 16 Crockford base-32 + a mod-37 check symbol)')
+{
+ const codes = new Set(Array.from({ length: 200 }, () => rec.newRecoveryCode()))
+ ok(codes.size === 200 && [...codes].every((c) => /^[0-9A-HJKMNP-TV-Z]{4}(-[0-9A-HJKMNP-TV-Z]{4}){3}-[0-9A-HJKMNP-TV-Z*~$=U]$/.test(c)), 'shown XXXX-XXXX-XXXX-XXXX-C from the Crockford alphabet, fresh every time')
+ const zero = rec.newRecoveryCode(() => new Uint8Array(10))
+ const ones = rec.newRecoveryCode(() => new Uint8Array(10).fill(255))
+ ok(zero === '0000-0000-0000-0000-0' && ones.startsWith('ZZZZ-ZZZZ-ZZZZ-ZZZZ-'), '10 bytes map to exactly 16 symbols (all 80 bits used)')
+ ok(ones.endsWith('-' + '0123456789ABCDEFGHJKMNPQRSTVWXYZ*~$=U'[Number(((1n << 80n) - 1n) % 37n)]), 'the check symbol is the 80-bit value mod 37')
+ for (const c of [...codes].slice(0, 20)) {
+ const p = rec.parseRecoveryCode(c)
+ ok(!!p && p.bytes.length === 10 && rec.displayCode(p.code) === c, `round-trips to 10 bytes and back: ${c}`)
+ if (!p) break
+ }
+ const c = [...codes][0]
+ const p = rec.parseRecoveryCode(c)!
+ ok(rec.parseRecoveryCode(c.toLowerCase().replace(/-/g, ' '))?.code === p.code, 'typing ignores case, spaces and hyphens')
+ const lookalike = p.code.replace(/0/g, 'O').replace(/1/g, 'L')
+ ok(rec.parseRecoveryCode(lookalike)?.code === p.code, 'O reads as 0, and I or L as 1 (Crockford)')
+ // a single-symbol typo in the data is caught by the check symbol
+ let caught = 0, tried = 0
+ for (let i = 0; i < 16; i++) {
+ const sym = p.code[i]
+ const sub = sym === 'A' ? 'B' : 'A'
+ tried++
+ if (rec.parseRecoveryCode(p.code.slice(0, i) + sub + p.code.slice(i + 1)) === null) caught++
+ }
+ ok(caught === tried, `every single-symbol typo is refused locally (${caught}/${tried})`)
+ ok(rec.parseRecoveryCode(p.code.slice(0, 16)) === null && rec.parseRecoveryCode(p.code + 'A') === null && rec.parseRecoveryCode('U' + p.code.slice(1)) === null, 'a wrong length, or U in a data position, is refused')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)