Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
home/webext bento/connect (W1b-1): Argon2id vendored from @noble/hashes; the recovery code and key blobs generated from kernel (#826)
nyblnete98542062c40
diff --git a/.github/actions/validate-home-webext/action.yml b/.github/actions/validate-home-webext/action.ymlindex d63ef55a..4f502adc 100644--- a/.github/actions/validate-home-webext/action.yml+++ b/.github/actions/validate-home-webext/action.yml@@ -130,12 +130,13 @@ runs:shell: bento-step {0}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.+ - name: WebExtension bento/connect rig+ # The extension's identity code must be the kernel reference, unaltered+ # (a generated type-strip, checked current), and pass kernel's own rigs+ # for identity-v1.json and recovery-v1.json with the same row counts.+ # The vendored Argon2id (@noble/hashes) must match its pinned file+ # hashes, RFC 9106 and every recovery vector, agree with Node's native+ # Argon2id, zero its block array, and fail closed on allocation failure.shell: bento-step {0}run: node scripts/test-webext-id.tsdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex b55cdc5b..d2fae44e 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -11790,3 +11790,30 @@ fonts: `validFont` accepts a `FONT_STACKS` name, or an `asset:` key thatresolves to a `data:` font in the document's own assets, and drops anythingelse to the base design's font. It is recorded so that a later change does notadd a web-font fetch.++## 2026-10-21 — bento/connect in the extension: Argon2id is @noble/hashes, and the recovery code is generated from kernel++**Argon2id is `@noble/hashes` 2.4.0, vendored, not hash-wasm.** The recovery+code is stretched with Argon2id, which WebCrypto lacks, so the extension+vendors one. hash-wasm was the first choice, but its Argon2id takes no+associated data, so it can't run the RFC 9106 §5.3 test vector, which has+some. Security requires that vector. Noble's `argon2idAsync` runs it, equals+Node's native Argon2id at Bento's parameters, and is pure JavaScript, so the+extension needs no `'wasm-unsafe-eval'` anywhere. It takes about a second per+derivation at 64 MiB, which is fine for a code used at setup and recovery.++The files are copied unmodified from the npm tarball, each pinned by sha256 in+`home/webext/src/id/vendor/noble-hashes/VENDOR.json`. `scripts/test-webext-id.ts`+recomputes the hashes on every run, then checks RFC 9106, every+`recovery-v1.json` derivation, and a randomized cross-check against Node's+native Argon2id. It proves by probe that the 64 MiB block array reads zero+afterwards. A derivation that can't allocate that memory reports "recovery+unavailable on this device" and never retries with weaker parameters.++**The recovery code and the key blobs are generated from kernel too.**+`kernel/src/recovery.ts` now covers everything the extension's hand-written+`id/blob.js` and `id/recovery.js` did, plus the recovery wrap. So it is+type-stripped into `id/gen/` like the statements, and the hand-written+modules are gone: one implementation, held to `recovery-v1.json` by kernel's+own rig run against the extension's copy.+diff --git a/home/webext/src/id/argon2.js b/home/webext/src/id/argon2.jsnew file mode 100644index 00000000..4f84a8ad--- /dev/null+++ b/home/webext/src/id/argon2.js@@ -0,0 +1,49 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// bento/connect — Argon2id for the recovery code, with the parameters signed by+// security §28 (kernel/src/recovery.ts ARGON2: v0x13, p = 1, 64 MiB, t = 3,+// 32-byte tag) and nothing else.+//+// The implementation is @noble/hashes 2.4.0, vendored unmodified in+// ./vendor/noble-hashes/ and pinned file by file (VENDOR.json; the rig+// recomputes every hash). It is pure JavaScript: no WASM, so the extension+// needs no 'wasm-unsafe-eval' anywhere. (hash-wasm was the first choice; its+// Argon2id has no associated-data input, so it could not run the RFC 9106+// vector security requires.)+//+// MEMORY. Noble allocates the 64 MiB block array per derivation and zeroes it+// when the derivation ends, or aborts (its argon2Output / abort `clean`); the+// rig proves it by probe. Residual, stated: a JavaScript engine may have+// copied or moved that memory before it was zeroed (GC compaction), and that+// copy is not reachable from here.+//+// ALLOCATION FAILURE. A device that cannot spare 64 MiB gets "recovery+// unavailable on this device" (RecoveryUnavailable), never a crash and never a+// retry with weaker parameters.+//+// `argon2id` has kernel's Argon2id shape (password, salt) → 32 bytes, so it is+// what gen/recovery.js's recoveryWrapKey and recoveryVerifier take.++import { argon2idAsync } from './vendor/noble-hashes/argon2.js'+import { ARGON2 } from './gen/recovery.js'++export class RecoveryUnavailable extends Error {+ constructor() { super('recovery is unavailable on this device: it cannot allocate the memory the recovery code needs') }+ get name() { return 'RecoveryUnavailable' }+}++/** The exact options the signed parameters map to. Frozen: nothing may soften them. */+export const NOBLE_OPTS = Object.freeze({+ t: ARGON2.passes, m: ARGON2.memoryKiB, p: ARGON2.parallelism, dkLen: ARGON2.tagLength, version: ARGON2.version,+})++/** Argon2id(password, salt) with the signed parameters; `onProgress(0..1)` for the page's progress line. */+export async function argon2id(password, salt, { onProgress } = {}) {+ try {+ return await argon2idAsync(password, salt, { ...NOBLE_OPTS, asyncTick: 10, ...(onProgress ? { onProgress } : {}) })+ } catch (e) {+ if (e instanceof RangeError) throw new RecoveryUnavailable()+ throw e+ }+}diff --git a/home/webext/src/id/blob.js b/home/webext/src/id/blob.jsdeleted file mode 100644index 22cc52c6..00000000--- a/home/webext/src/id/blob.js+++ /dev/null@@ -1,154 +0,0 @@-// 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/recovery.js b/home/webext/src/id/gen/recovery.jsnew file mode 100644index 00000000..8dbe11e5--- /dev/null+++ b/home/webext/src/id/gen/recovery.js@@ -0,0 +1,357 @@+// GENERATED from kernel/src/recovery.ts by scripts/gen-webext-id.mjs — do not edit.+// 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, KX_MODE } from './statements.js'++// --- 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. */+++const no = (reason ) => ({ 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 ) => 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 ) => code.reduce((r, b) => (r * 256 + b) % 37, 0)++/** The printed form: XXXX-XXXX-XXXX-XXXX-C. */+export function formatRecoveryCode(code ) {+ 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)]}`+}++++/**+ * 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 ) {+ 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 , salt , info ) {+ const k = await crypto.subtle.importKey('raw', ikm , 'HKDF', false, ['deriveBits'])+ return new Uint8Array(await crypto.subtle.deriveBits(+ { name: 'HKDF', hash: 'SHA-256', salt: salt , info: te.encode(info) }, 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 , salt , argon2 ) {+ 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 , saltV , argon2 ) {+ checkLen(code, CODE_BYTES, 'code'); checkLen(saltV, SALT_LEN, 'salt_v')+ return argon2(code, saltV)+}++/**+ * The PRF extension's FIXED input (identity-design §2f), as UTF-8 bytes: every+ * ceremony evaluates exactly this, so one passkey always yields one PRF output.+ */+export const PRF_INPUT = 'bento/id/prf/v1'++/**+ * What a host that speaks CTAP directly (libfido2 hmac-secret, no WebAuthn PRF+ * API) must send as the hmac-secret salt so the authenticator returns the SAME+ * 32 bytes a browser's PRF extension would. WebAuthn Level 3 §10.1.4:+ * salt = SHA-256(UTF-8("WebAuthn PRF") ‖ 0x00 ‖ input). Forget the 0x00, or+ * send the raw input, and the blob you seal can never be opened by a browser+ * (and vice versa). Browsers do this themselves; never apply it twice.+ */+export async function prfHmacSecretSalt(input = te.encode(PRF_INPUT)) {+ const label = te.encode('WebAuthn PRF')+ const msg = new Uint8Array(label.length + 1 + input.length)+ msg.set(label); msg[label.length] = 0; msg.set(input, label.length + 1)+ return new Uint8Array(await crypto.subtle.digest('SHA-256', msg ))+}++/** The PRF blob's key: HKDF-SHA-256(PRF output, 32-byte salt, "bento/id/acct-wrap/v1"). */+export async function prfKek(prfOutput , salt ) {+ checkLen(prfOutput, 32, 'PRF output'); checkLen(salt, 32, 'salt')+ return hkdf(prfOutput, salt, 'bento/id/acct-wrap/v1')+}++function checkLen(b , n , what ) {+ 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 ) => ((a % P) + P) % P+function inv(a ) { // 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+}+ // Jacobian; Z = 0 is the point at infinity+function dbl([x, y, z] ) {+ 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 , q ) {+ 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 ) {+ 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 ) {+ let acc = [0n, 1n, 0n], base = [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 = { unruled: false, A: true, B: false, C: true }+++++++++/** account d ‖ kx d (when the mode carries one), each 32 bytes big-endian. */+export function packScalars(keys , mode = KX_MODE) {+ 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 , expected , mode = KX_MODE,+ subtle = crypto.subtle) {+ 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 ) {+ 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 , pub , subtle ) {+ 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 , ECDSA_P256, false, ['verify'])+ const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, priv, PROBE )+ return await subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, pubKey, sig, PROBE )+ } catch { return false }+}++// --- AES-256-GCM ---------------------------------------------------------------------++async function gcm(op , key , iv , aad , data ) {+ checkLen(key, 32, 'key'); checkLen(iv, 12, 'iv')+ const k = await crypto.subtle.importKey('raw', key , 'AES-GCM', false, [op])+ const params = { name: 'AES-GCM', iv: iv , additionalData: te.encode(aad) , tagLength: 128 }+ return new Uint8Array(op === 'encrypt'+ ? await crypto.subtle.encrypt(params, k, data )+ : await crypto.subtle.decrypt(params, k, data ))+}+const accountTag = async (accountPub ) => sha256b64u(accountPub)++// --- the PRF blob (one per passkey) -----------------------------------------------++++/** cred = b64u(sha256(credentialId)); aad = "bento/id/acct-wrap/v1." ‖ cred; ct = ciphertext ‖ tag. */+export async function sealPrfBlob(a++ ) {+ const cred = b64uEnc(new Uint8Array(await crypto.subtle.digest('SHA-256', a.credentialId )))+ 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 , a++ ) {+ if (blob?.v !== 1) return no('version')+ const cred = b64uEnc(new Uint8Array(await crypto.subtle.digest('SHA-256', a.credentialId )))+ 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+ 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 )+ {+ 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 , a++ ) {+ let pt+ 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 , accountPub ) {+ 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 , verifier ) {+ const k = await crypto.subtle.importKey('raw', verifyKey , { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])+ return new Uint8Array(await crypto.subtle.sign('HMAC', k, verifier ))+}++export async function pepperSeal(wrapKey , iv , inner , accountPub ) {+ return gcm('encrypt', wrapKey, iv, `bento/id/rc-pepper/v1.${await accountTag(accountPub)}`, inner)+}++export async function pepperOpen(wrapKey , iv , outer , accountPub ) {+ try { return await gcm('decrypt', wrapKey, iv, `bento/id/rc-pepper/v1.${await accountTag(accountPub)}`, outer) } catch { return null }+}diff --git a/home/webext/src/id/recovery.js b/home/webext/src/id/recovery.jsdeleted file mode 100644index 9518f706..00000000--- a/home/webext/src/id/recovery.js+++ /dev/null@@ -1,61 +0,0 @@-// 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/home/webext/src/id/vendor/noble-hashes/LICENSE b/home/webext/src/id/vendor/noble-hashes/LICENSEnew file mode 100644index 00000000..9297a046--- /dev/null+++ b/home/webext/src/id/vendor/noble-hashes/LICENSE@@ -0,0 +1,21 @@+The MIT License (MIT)++Copyright (c) 2022 Paul Miller (https://paulmillr.com)++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the “Software”), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.\ No newline at end of filediff --git a/home/webext/src/id/vendor/noble-hashes/VENDOR.json b/home/webext/src/id/vendor/noble-hashes/VENDOR.jsonnew file mode 100644index 00000000..75db44be--- /dev/null+++ b/home/webext/src/id/vendor/noble-hashes/VENDOR.json@@ -0,0 +1,17 @@+{+ "package": "@noble/hashes",+ "version": "2.4.0",+ "license": "MIT",+ "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",+ "tarball": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",+ "why": "Argon2id for the bento/connect recovery code (pure JS: no WASM, so no 'wasm-unsafe-eval'). Exact files from the npm tarball, unmodified; argon2.js and its import closure.",+ "files": {+ "LICENSE": "4f221aee6e072336700c408c68ab3b96a3fc09f6aebe6f48f1bd99e5ef13faec",+ "_blake.js": "cabbff61d1f373bac45594ad758df7c42e176464ddbb94b44f5533fa977a4f56",+ "_md.js": "60cf3010fda89e3e4d3f0e7ff1ce249e9c467f34b4fd41b6fd6101d9f69be763",+ "_u64.js": "b09da8c07fe8187c07649494cdb7cd0bcf13df90b506a9473d19e4d5f8c2e102",+ "argon2.js": "f39753324bdf2f484150731d24b1d71236f26bf10bedd594f7d190fcdfdefdc9",+ "blake2.js": "03f00237bcc0b4d822a80f7c0ac22e42632c48e246c3b6da584e6452186e32f0",+ "utils.js": "037ad49adb78168b6b699598fd33f85f7877456b1d28b4d032e2a1a16807947c"+ }+}\ No newline at end of filediff --git a/home/webext/src/id/vendor/noble-hashes/_blake.js b/home/webext/src/id/vendor/noble-hashes/_blake.jsnew file mode 100644index 00000000..2e70d9f4--- /dev/null+++ b/home/webext/src/id/vendor/noble-hashes/_blake.js@@ -0,0 +1,59 @@+/**+ * Internal helpers for blake hash.+ * @module+ */+import { rotr } from "./utils.js";+// Unrealized speed-up: a file-local copy of rotr measured ~1-2% faster blake2s/blake256/blake3+// on Node 24 (V8 does not inline it into G1s/G2s across the module boundary). Reused from+// utils for deduplication.+/**+ * Internal blake permutation table.+ * Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also+ * reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows+ * `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants.+ */+// prettier-ignore+export const BSIGMA = /* @__PURE__ */ Uint8Array.from([+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,+ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,+ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,+ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,+ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,+ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,+ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,+ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,+ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,+ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,+ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,+ // Blake1, unused in others+ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,+ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,+ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,+ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,+]);+// Unrealized speed-up: G1s/G2s return a fresh {a,b,c,d} per call (160×/blake2s block), which+// V8's escape analysis does not eliminate when G stays a real call. Writing into one reused+// module-level slot instead measured +4-6% blake2s/blake256 1MB throughput on Node 24 — but+// ~2% slower blake3 (whose profile inlines G and scalar-replaces the fresh object) and no+// difference on 32-byte inputs. Kept simple.+// 32-bit / BLAKE2s first half of G, with the fixed `(16, 12)` rotation pair.+// Parameter `x` is the RFC 7693 first-half message word, or Blake1's pre-mixed+// `m[sigma[r][2i]] ^ u[sigma[r][2i+1]]` addend in the 32-bit path.+export function G1s(a, b, c, d, x) {+ a = (a + b + x) | 0;+ d = rotr(d ^ a, 16);+ c = (c + d) | 0;+ b = rotr(b ^ c, 12);+ return { a, b, c, d };+}+// 32-bit / BLAKE2s second half of G.+// Parameter `x` is the RFC 7693 second-half (`y`) message word, or Blake1's pre-mixed+// `m[sigma[r][2i + 1]] ^ u[sigma[r][2i]]` addend in the 32-bit path.+export function G2s(a, b, c, d, x) {+ a = (a + b + x) | 0;+ d = rotr(d ^ a, 8);+ c = (c + d) | 0;+ b = rotr(b ^ c, 7);+ return { a, b, c, d };+}diff --git a/home/webext/src/id/vendor/noble-hashes/_md.js b/home/webext/src/id/vendor/noble-hashes/_md.jsnew file mode 100644index 00000000..13049ffb--- /dev/null+++ b/home/webext/src/id/vendor/noble-hashes/_md.js@@ -0,0 +1,209 @@+/**+ * Internal Merkle-Damgard hash utils.+ * @module+ */+import { setU64FromNum } from "./_u64.js";+import { abytes, aexists, aoutput, createView } from "./utils.js";+/**+ * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.+ * Returns bits from `b` when `a` is set, otherwise from `c`.+ * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never+ * set the same bit.+ * @param a - selector word+ * @param b - word chosen when selector bit is set+ * @param c - word chosen when selector bit is clear+ * @returns Mixed 32-bit word.+ * @example+ * Combine three words with the shared 32-bit choice primitive.+ * ```ts+ * Chi(0xffffffff, 0x12345678, 0x87654321);+ * ```+ */+export function Chi(a, b, c) {+ return (a & b) ^ (~a & c);+}+/**+ * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.+ * Returns bits shared by at least two inputs.+ * @param a - first input word+ * @param b - second input word+ * @param c - third input word+ * @returns Mixed 32-bit word.+ * @example+ * Combine three words with the shared 32-bit majority primitive.+ * ```ts+ * Maj(0xffffffff, 0x12345678, 0x87654321);+ * ```+ */+export function Maj(a, b, c) {+ return (a & b) ^ (a & c) ^ (b & c);+}+/**+ * Merkle-Damgard hash construction base class.+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.+ * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit+ * strings with partial-byte tails.+ * @param blockLen - internal block size in bytes+ * @param outputLen - digest size in bytes+ * @param padOffset - trailing length field size in bytes+ * @param isLE - whether length and state words are encoded in little-endian+ * @example+ * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.+ * ```ts+ * import { _SHA1 } from '@noble/hashes/legacy.js';+ * const hash = new _SHA1();+ * hash.update(new Uint8Array([97, 98, 99]));+ * hash.digest();+ * ```+ */+export class HashMD {+ blockLen;+ outputLen;+ canXOF = false;+ padOffset;+ isLE;+ // For partial updates less than block size+ buffer;+ view;+ finished = false;+ length = 0;+ pos = 0;+ destroyed = false;+ constructor(blockLen, outputLen, padOffset, isLE) {+ this.blockLen = blockLen;+ this.outputLen = outputLen;+ this.padOffset = padOffset;+ this.isLE = isLE;+ this.buffer = new Uint8Array(blockLen);+ this.view = createView(this.buffer);+ }+ update(data) {+ aexists(this);+ abytes(data);+ const { view, buffer, blockLen } = this;+ const len = data.length;+ let processed = false;+ for (let pos = 0; pos < len;) {+ const take = Math.min(blockLen - this.pos, len - pos);+ // Fast path only when there is no buffered partial block: `take === blockLen` implies+ // `this.pos === 0`, so we can process full blocks directly from the input view.+ if (take === blockLen) {+ const dataView = createView(data);+ for (; blockLen <= len - pos; pos += blockLen)+ this.process(dataView, pos);+ processed = true;+ continue;+ }+ // When the whole input is buffered in one go (common for short messages), passing `data`+ // directly avoids allocating a subarray view.+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);+ this.pos += take;+ pos += take;+ if (this.pos === blockLen) {+ this.process(view, 0);+ this.pos = 0;+ processed = true;+ }+ }+ this.length += data.length;+ // Shared schedule buffers only pick up input-derived words inside process(); if everything+ // was buffered without processing, there is nothing to zero.+ if (processed)+ this.roundClean();+ return this;+ }+ digestInto(out) {+ aexists(this);+ aoutput(out, this);+ this.finished = true;+ // Padding+ // We can avoid allocation of buffer for padding completely if it+ // was previously not allocated here. But it won't change performance.+ const { buffer, view, blockLen, isLE } = this;+ let { pos } = this;+ // append the bit '1' to the message, then zero-pad the rest of the block+ buffer[pos++] = 0b10000000;+ buffer.fill(0, pos);+ // we have less than padOffset left in buffer, so we cannot put length in+ // current block, need process it and pad again+ if (this.padOffset > blockLen - pos) {+ this.process(view, 0);+ buffer.fill(0);+ }+ // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from+ // the padding fill above, and JS will overflow before user input can make that half non-zero.+ // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an+ // integer below 2**53, so the split inside the helper stays exact).+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);+ this.process(view, 0);+ // The final block above is processed outside update(), so the shared message-schedule+ // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().+ this.roundClean();+ // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.+ const oview = out === buffer ? view : createView(out);+ const len = this.outputLen;+ // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT+ const outLen = len / 4;+ const state = this.get();+ // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.+ if (len % 4 || outLen > state.length)+ throw new Error('invalid outputLen');+ for (let i = 0; i < outLen; i++)+ oview.setUint32(4 * i, state[i], isLE);+ }+ digest() {+ const { buffer, outputLen } = this;+ this.digestInto(buffer);+ // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return+ // fresh bytes to the caller.+ const res = buffer.slice(0, outputLen);+ this.destroy();+ return res;+ }+ _cloneIntoMeta(to) {+ const { buffer, length, finished, destroyed, pos } = this;+ to.destroyed = destroyed;+ to.finished = finished;+ to.length = length;+ to.pos = pos;+ // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and+ // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.+ if (pos)+ to.buffer.set(buffer); // Avoid a hot modulo guard.+ return to;+ }+ clone() {+ return this._cloneInto();+ }+}+/**+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.+ */+/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the+ * square roots of the first eight prime numbers. Exported as a shared table; callers must treat+ * it as read-only because constructors copy words from it by index. */+export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,+]);+/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must+ * treat it as read-only because constructors copy words from it by index. */+export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([+ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,+]);+/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen+ * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth+ * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only+ * because constructors copy halves from it by index. */+export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([+ 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,+ 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,+]);+/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen+ * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first+ * eight prime numbers. Exported as a shared table; callers must treat it as read-only because+ * constructors copy halves from it by index. */+export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([+ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,+ 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,+]);diff --git a/home/webext/src/id/vendor/noble-hashes/_u64.js b/home/webext/src/id/vendor/noble-hashes/_u64.jsnew file mode 100644index 00000000..a57c31c2--- /dev/null+++ b/home/webext/src/id/vendor/noble-hashes/_u64.js@@ -0,0 +1,77 @@+const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();+const _32n = /* @__PURE__ */ BigInt(32);+// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high+// }` to match little-endian word order rather than the property names.+function fromBig(n, le = false) {+ if (le)+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };+}+// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array+// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.+function split(lst, le = false) {+ const len = lst.length;+ let Ah = new Uint32Array(len);+ let Al = new Uint32Array(len);+ for (let i = 0; i < len; i++) {+ const { h, l } = fromBig(lst[i], le);+ [Ah[i], Al[i]] = [h, l];+ }+ return [Ah, Al];+}+// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS+// bitwise results back to uint32 first, and little-endian callers must swap.+const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);+// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers+// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below+// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).+const fromNumH = (n) => (n / 2 ** 32) | 0;+const fromNumL = (n) => n >>> 0;+// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call+// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.+function setU64FromNum(view, byteOffset, n, isLE) {+ const h = fromNumH(n);+ const l = fromNumL(n);+ view.setUint32(byteOffset, isLE ? l : h, isLE);+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);+}+// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.+const shrSH = (h, _l, s) => h >>> s;+// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.+const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);+// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.+const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));+// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.+const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);+// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.+const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));+// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.+const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));+// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.+const rotr32H = (_h, l) => l;+// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.+const rotr32L = (h, _l) => h;+// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps+// local copies so V8 inlines them into keccakP.+// Add two split 64-bit words and return the split `{ h, l }` sum.+// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out+// of the low sum and instead use division.+function add(Ah, Al, Bh, Bl) {+ const l = (Al >>> 0) + (Bl >>> 0);+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };+}+// Addition with more than 2 elements+// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.+const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);+// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.+const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;+// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.+const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);+// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.+const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;+// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.+const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);+// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.+const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;+// prettier-ignore+export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };diff --git a/home/webext/src/id/vendor/noble-hashes/argon2.js b/home/webext/src/id/vendor/noble-hashes/argon2.jsnew file mode 100644index 00000000..f0a23e54--- /dev/null+++ b/home/webext/src/id/vendor/noble-hashes/argon2.js@@ -0,0 +1,577 @@+/**+ * Argon2 KDF from RFC 9106. Can be used to create a key from password and salt.+ * We suggest to use Scrypt. JS Argon is 2-10x slower than native code because of 64-bitness:+ * * argon uses uint64, but JS doesn't have fast uint64array+ * * uint64 multiplication is 1/3 of time+ * * `P` function would be very nice with u64, because most of value will be in registers,+ * hovewer with u32 it will require 32 registers, which is too much.+ * * JS arrays do slow bound checks, so reading from `A2_BUF` slows it down+ * @module+ */+import { blake2b } from "./blake2.js";+import { anumber, checkOpts, clean, kdfInputToBytes, nextTick, swap32IfBE, swap8IfBE, u32, u8, } from "./utils.js";+// RFC 9106 §3.1 type `y`: 0 = Argon2d, 1 = Argon2i, 2 = Argon2id. The numeric values are the+// spec-bound part here; the object keys are internal labels.+const AT = { Argon2d: 0, Argon2i: 1, Argon2id: 2 };+// RFC 9106 sync points constant `SL = 4`, fixed by the design rather than exposed as a tuning knob.+const ARGON2_SYNC_POINTS = 4;+// Preserve Argon2's `LE32(len(X)) || X` encoding for omitted+// optional fields by emitting empty bytes.+const abytesOrZero = (buf, errorTitle = '') => {+ if (buf === undefined)+ return Uint8Array.of();+ return kdfInputToBytes(buf, errorTitle);+};+// Temporary block buffer.+// 1024-byte block: 256 u32 = 128 interleaved low/high halves = RFC's+// 8x8 matrix of 16-byte registers.+const A2_BUF = new Uint32Array(256);+// Quarter-round over 64-bit word indices into `A2_BUF`; each index maps to adjacent low/high u32s.+// Each BlaMka step `X = X + Y + 2 * trunc(X) * trunc(Y)` (trunc = low 32 bits) starts+// with an exact low product from `Math.imul`. The rounded double product is within 1024 of the+// exact u64 product; subtracting that exact low half and rounding to the nearest multiple of+// 2^32 therefore recovers the exact high half. RFC 9106 Figure 19 GB then rotates by 32, 24,+// 16, and 63 bits after each XOR.+function G(a, b, c, d) {+ let Al = A2_BUF[2 * a], Ah = A2_BUF[2 * a + 1]; // prettier-ignore+ let Bl = A2_BUF[2 * b], Bh = A2_BUF[2 * b + 1]; // prettier-ignore+ let Cl = A2_BUF[2 * c], Ch = A2_BUF[2 * c + 1]; // prettier-ignore+ let Dl = A2_BUF[2 * d], Dh = A2_BUF[2 * d + 1]; // prettier-ignore+ let ml = 0, mh = 0, rl = 0, xh = 0, xl = 0; // prettier-ignore+ // A = blamka(A, B); D = rotr64(D ^ A, 32)+ ml = Math.imul(Al, Bl);+ mh = (((Al >>> 0) * (Bl >>> 0) - (ml >>> 0)) / 0x100000000 + 0.5) | 0; // prettier-ignore+ rl = (Al >>> 0) + (Bl >>> 0) + ((ml << 1) >>> 0);+ Ah = (Ah + Bh + ((mh << 1) | (ml >>> 31)) + ((rl / 0x100000000) | 0)) | 0;+ Al = rl | 0; // prettier-ignore+ xh = Dh ^ Ah;+ xl = Dl ^ Al; // prettier-ignore+ Dh = xl;+ Dl = xh; // prettier-ignore+ // C = blamka(C, D); B = rotr64(B ^ C, 24)+ ml = Math.imul(Cl, Dl);+ mh = (((Cl >>> 0) * (Dl >>> 0) - (ml >>> 0)) / 0x100000000 + 0.5) | 0; // prettier-ignore+ rl = (Cl >>> 0) + (Dl >>> 0) + ((ml << 1) >>> 0);+ Ch = (Ch + Dh + ((mh << 1) | (ml >>> 31)) + ((rl / 0x100000000) | 0)) | 0;+ Cl = rl | 0; // prettier-ignore+ xh = Bh ^ Ch;+ xl = Bl ^ Cl; // prettier-ignore+ Bh = (xh >>> 24) | (xl << 8);+ Bl = (xh << 8) | (xl >>> 24); // prettier-ignore+ // A = blamka(A, B); D = rotr64(D ^ A, 16)+ ml = Math.imul(Al, Bl);+ mh = (((Al >>> 0) * (Bl >>> 0) - (ml >>> 0)) / 0x100000000 + 0.5) | 0; // prettier-ignore+ rl = (Al >>> 0) + (Bl >>> 0) + ((ml << 1) >>> 0);+ Ah = (Ah + Bh + ((mh << 1) | (ml >>> 31)) + ((rl / 0x100000000) | 0)) | 0;+ Al = rl | 0; // prettier-ignore+ xh = Dh ^ Ah;+ xl = Dl ^ Al; // prettier-ignore+ Dh = (xh >>> 16) | (xl << 16);+ Dl = (xh << 16) | (xl >>> 16); // prettier-ignore+ // C = blamka(C, D); B = rotr64(B ^ C, 63)+ ml = Math.imul(Cl, Dl);+ mh = (((Cl >>> 0) * (Dl >>> 0) - (ml >>> 0)) / 0x100000000 + 0.5) | 0; // prettier-ignore+ rl = (Cl >>> 0) + (Dl >>> 0) + ((ml << 1) >>> 0);+ Ch = (Ch + Dh + ((mh << 1) | (ml >>> 31)) + ((rl / 0x100000000) | 0)) | 0;+ Cl = rl | 0; // prettier-ignore+ xh = Bh ^ Ch;+ xl = Bl ^ Cl; // prettier-ignore+ Bh = (xh << 1) | (xl >>> 31);+ Bl = (xh >>> 31) | (xl << 1); // prettier-ignore+ ((A2_BUF[2 * a] = Al), (A2_BUF[2 * a + 1] = Ah));+ ((A2_BUF[2 * b] = Bl), (A2_BUF[2 * b + 1] = Bh));+ ((A2_BUF[2 * c] = Cl), (A2_BUF[2 * c + 1] = Ch));+ ((A2_BUF[2 * d] = Dl), (A2_BUF[2 * d + 1] = Dh));+}+// Argon2 permutation over 16 register indices into `A2_BUF`, not the register values themselves.+// RFC 9106 Figure 17: these arguments are the 16 `v0..v15` 64-bit word+// indices inside eight 16-byte inputs, not copied word values.+// prettier-ignore+function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) {+ // RFC 9106 Figure 18: first apply GB across rows, then across columns of the 8x8 register matrix.+ G(v00, v04, v08, v12);+ G(v01, v05, v09, v13);+ G(v02, v06, v10, v14);+ G(v03, v07, v11, v15);+ G(v00, v05, v10, v15);+ G(v01, v06, v11, v12);+ G(v02, v07, v08, v13);+ G(v03, v04, v09, v14);+}+function block(x, xPos, yPos, outPos, needXor) {+ // Stage R = X xor Y in the destination before permuting it. This avoids rereading both source+ // blocks when folding R into the permuted scratch block below.+ if (needXor) {+ for (let i = 0; i < 256; i++) {+ const r = x[xPos + i] ^ x[yPos + i];+ A2_BUF[i] = r;+ x[outPos + i] ^= r;+ }+ }+ else {+ for (let i = 0; i < 256; i++) {+ const r = x[xPos + i] ^ x[yPos + i];+ A2_BUF[i] = r;+ x[outPos + i] = r;+ }+ }+ // rows (8 consecutive 16-register groups)+ for (let i = 0; i < 128; i += 16) {+ // prettier-ignore+ P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15);+ }+ // columns (8 strided 16-register groups)+ for (let i = 0; i < 16; i += 2) {+ // prettier-ignore+ P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113);+ }+ // RFC 9106 step 6: passes after the first XOR the old destination block into the new G(X, Y).+ for (let i = 0; i < 256; i++)+ x[outPos + i] ^= A2_BUF[i];+ clean(A2_BUF);+}+// Variable-Length Hash Function H'+// Returns bytes, not words; 1024-byte block callers explicitly reinterpret with `u32(...)`.+function Hp(A, dkLen) {+ const A8 = u8(A);+ const T = new Uint32Array(1);+ const T8 = u8(T);+ // Argon2 H' prefixes dkLen as LE32; native Uint32Array writes would serialize as BE on s390x.+ T[0] = swap8IfBE(dkLen);+ // Fast path+ if (dkLen <= 64)+ return blake2b.create({ dkLen }).update(T8).update(A8).digest();+ const out = new Uint8Array(dkLen);+ let V = blake2b.create({}).update(T8).update(A8).digest();+ let pos = 0;+ // RFC 9106 Figure 8: each intermediate `V_i` contributes only `W_i`, its first 32 bytes; only+ // `V_{r+1}` is emitted in full at the remaining length.+ out.set(V.subarray(0, 32));+ pos += 32;+ // Rest blocks+ for (; dkLen - pos > 64; pos += 32) {+ const Vh = blake2b.create({}).update(V);+ Vh.digestInto(V);+ Vh.destroy();+ out.set(V.subarray(0, 32), pos);+ }+ // Last block+ out.set(blake2b(V, { dkLen: dkLen - pos }), pos);+ clean(V, T);+ // H' is byte-oriented; returning `u32(out)` would silently drop dkLen % 4 tail bytes.+ return out;+}+// Used only inside argon2Blocks!+function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) {+ // RFC 9106 §3.4.2 Figures 12-13: map `J1` / `J2` into the current lane's reference area `W`.+ let area;+ if (r === 0) {+ if (s === 0)+ area = index - 1;+ else if (sameLane)+ area = s * segmentLen + index - 1;+ else+ area = s * segmentLen + (index == 0 ? -1 : 0);+ }+ else if (sameLane)+ area = laneLen - segmentLen + index - 1;+ else+ area = laneLen - segmentLen + (index == 0 ? -1 : 0);+ const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0;+ // Use the same exact-high recovery as G. `areaHigh` is floor(|W| * J1^2/2^32 / 2^32).+ const randLow = Math.imul(randL, randL);+ const randHigh = (((randL >>> 0) * (randL >>> 0) - (randLow >>> 0)) / 0x100000000 + 0.5) | 0;+ const areaLow = Math.imul(area, randHigh);+ const areaHigh = (((area >>> 0) * (randHigh >>> 0) - (areaLow >>> 0)) / 0x100000000 + 0.5) | 0;+ const rel = area - 1 - areaHigh;+ return (startPos + rel) % laneLen;+}+// Exclusive `2^32` sentinel used by `isU32(...)`, not the inclusive maximum u32 value.+const maxUint32 = Math.pow(2, 32);+const ARGON2_DEFAULT_MEMORY = 1024 ** 2; // KiB: 1 GiB+const ARGON2_DEFAULT_MAXMEM = ARGON2_DEFAULT_MEMORY * 1024;+// Validate safe JS integers in `[0, 2^32 - 1]`.+function isU32(num) {+ return Number.isSafeInteger(num) && num >= 0 && num < maxUint32;+}+function argon2Opts(opts = {}) {+ opts = checkOpts({}, opts);+ const merged = {+ t: 3,+ m: ARGON2_DEFAULT_MEMORY,+ p: 1,+ version: 0x13,+ dkLen: 32,+ maxmem: ARGON2_DEFAULT_MAXMEM,+ asyncTick: 10,+ };+ // Unknown keys are copied through unchanged here and later ignored unless+ // destructuring consumes them.+ for (let [k, v] of Object.entries(opts))+ if (v !== undefined)+ merged[k] = v;+ const { dkLen, p, m, t, version, onProgress, asyncTick } = merged;+ // RFC 9106 §3.1: tag length `T` MUST be an integer number of bytes from 4 to 2^32-1.+ if (!isU32(dkLen) || dkLen < 4)+ throw new Error('"dkLen" must be 4..');+ if (!isU32(p) || p < 1 || p >= Math.pow(2, 24))+ throw new Error('"p" must be 1..2^24');+ if (!isU32(m))+ throw new Error('"m" must be 0..2^32');+ if (!isU32(t) || t < 1)+ throw new Error('"t" (iterations) must be 1..2^32');+ if (onProgress !== undefined && typeof onProgress !== 'function')+ throw new Error('"onProgress" must be a function');+ anumber(asyncTick, 'asyncTick');+ /*+ Memory size m MUST be an integer number of kibibytes from 8*p+ to 2^(32)-1. The actual number of blocks is m', which is m+ rounded down to the nearest multiple of 4*p.+ */+ if (!isU32(m) || m < 8 * p)+ throw new Error('"m" (memory) must be at least 8*p bytes');+ // Accept legacy `0x10` for compatibility even though RFC 9106 profiles standardize `0x13`.+ if (version !== 0x10 && version !== 0x13)+ throw new Error('"version" must be 0x10 or 0x13, got ' + version);+ return merged;+}+function argon2InitialHash(password, salt, type, opts) {+ const ownedInputs = [];+ const BUF = new Uint32Array(1);+ const BUF8 = u8(BUF);+ let h;+ let H0;+ let succeeded = false;+ const rememberOwned = (input, bytes) => {+ if (typeof input === 'string')+ ownedInputs.push(bytes);+ return bytes;+ };+ try {+ const passwordBytes = rememberOwned(password, kdfInputToBytes(password, 'password'));+ const saltBytes = rememberOwned(salt, kdfInputToBytes(salt, 'salt'));+ if (!isU32(passwordBytes.length))+ throw new Error('"password" must be less of length 1..4Gb');+ // RFC 9106 §3.1 only requires S <= 2^32-1 bytes and says 16 bytes is RECOMMENDED for password+ // hashing; this library intentionally takes the stricter common >=8-byte salt path.+ if (!isU32(saltBytes.length) || saltBytes.length < 8)+ throw new Error('"salt" must be of length 8..4Gb');+ if (!Object.values(AT).includes(type))+ throw new Error('"type" was invalid');+ let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress, asyncTick } = argon2Opts(opts);+ // Validation+ const keyInput = key;+ key = rememberOwned(keyInput, abytesOrZero(keyInput, 'key'));+ const personalizationInput = personalization;+ personalization = rememberOwned(personalizationInput, abytesOrZero(personalizationInput, 'personalization'));+ // H_0 = H^(64)(LE32(p) || LE32(T) || LE32(m) || LE32(t) ||+ // LE32(v) || LE32(y) || LE32(length(P)) || P ||+ // LE32(length(S)) || S || LE32(length(K)) || K ||+ // LE32(length(X)) || X)+ h = blake2b.create();+ for (let item of [p, dkLen, m, t, version, type]) {+ // RFC 9106 H0 encodes these scalars as LE32, so normalize the host word before+ // exposing bytes.+ BUF[0] = swap8IfBE(item);+ h.update(BUF8);+ }+ for (let i of [passwordBytes, saltBytes, key, personalization]) {+ BUF[0] = swap8IfBE(i.length); // BUF is u32 array, this is valid once normalized to LE bytes+ h.update(BUF8).update(i);+ }+ // Reserve two extra LE32 words after the 64-byte `H_0` so Figures 3-4 can append+ // `LE32(0 or 1) || LE32(i)` in place for the lane-starting blocks.+ H0 = new Uint32Array(18);+ h.digestInto(u8(H0));+ succeeded = true;+ return { H0, p, dkLen, m, t, version, maxmem, onProgress, asyncTick };+ }+ finally {+ // digestInto() does not destroy BLAKE2 state. It and all string-derived inputs contain secrets.+ if (h)+ h.destroy();+ clean(BUF, ...ownedInputs);+ if (!succeeded && H0)+ clean(H0);+ }+}+function argon2Init(password, salt, type, opts) {+ const { H0, p, dkLen, m, t, version, maxmem, onProgress, asyncTick } = argon2InitialHash(password, salt, type, opts);+ // 256 u32 = 1024 (BLOCK_SIZE), fills A2_BUF on processing+ try {+ // Params+ const lanes = p;+ // m' = 4 * p * floor (m / 4p)+ const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p));+ //q = m' / p columns+ const laneLen = Math.floor(mP / p);+ const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS);+ // `maxmem` is documented in bytes; compare against the actual 1024-byte block allocation.+ const memUsed = mP * 1024;+ if (!isU32(maxmem))+ throw new Error('"maxmem" expected <2**32, got ' + maxmem);+ if (memUsed > maxmem)+ throw new Error('"maxmem" limit was hit: memUsed(mP*1024)=' + memUsed + ', maxmem=' + maxmem);+ const B = new Uint32Array(memUsed / 4);+ // Fill first blocks+ for (let l = 0; l < p; l++) {+ const i = 256 * laneLen * l;+ // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))+ H0[17] = swap8IfBE(l);+ H0[16] = swap8IfBE(0);+ B.set(swap32IfBE(u32(Hp(H0, 1024))), i);+ // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))+ H0[16] = swap8IfBE(1);+ B.set(swap32IfBE(u32(Hp(H0, 1024))), i + 256);+ }+ let perBlock = () => { };+ if (onProgress) {+ // The first segment of the first pass skips two preinitialized blocks per lane.+ const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen - 2 * p;+ // Invoke callback if progress changes from 10.01 to 10.02+ // Allows to draw smooth progress bar on up to 8K screen+ const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1);+ let blockCnt = 0;+ perBlock = () => {+ blockCnt++;+ if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock))+ onProgress(blockCnt / totalBlock);+ };+ }+ return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick };+ }+ finally {+ clean(H0);+ }+}+function argon2Output(B, p, laneLen, dkLen) {+ const B_final = new Uint32Array(256);+ for (let l = 0; l < p; l++)+ for (let j = 0; j < 256; j++)+ B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j];+ // RFC 9106 steps 7-8 feed the byte string `C` into `H'^T(C)`, so normalize the xor'ed words+ // back to spec byte order before `Hp(...)` reinterprets them as bytes.+ const res = Hp(swap32IfBE(B_final), dkLen);+ // Wipe both the xor scratch and the full working matrix once final digest bytes exist.+ // JS cleanup is still only best-effort, but this local buffer is no longer needed here.+ clean(B, B_final);+ return res;+}+/**+ * Fills every Argon2 block for all passes / slices / lanes, yielding once per+ * processed block so callers control pacing: the sync driver just drains the+ * generator, while the async driver awaits `nextTick()` between time slices.+ */+function* argon2Blocks(ctx, address) {+ const { type, mP, p, t, version, B, laneLen, lanes, segmentLen, perBlock } = ctx;+ // [address, input, zero_block] format so we can pass single U32 to block function+ address[256 + 6] = mP;+ address[256 + 8] = t;+ address[256 + 10] = type;+ for (let r = 0; r < t; r++) {+ // RFC 9106 step 6 applies the XOR-on-later-passes rule only for version `0x13`; legacy+ // `0x10` keeps the older overwrite behavior used by the v16 test vectors.+ const needXor = r !== 0 && version === 0x13;+ address[256 + 0] = r;+ for (let s = 0; s < ARGON2_SYNC_POINTS; s++) {+ address[256 + 4] = s;+ // RFC 9106 §3.4.1.3: Argon2id uses Argon2i's data-independent `J1` / `J2` generation only+ // in pass 0, slices 0 and 1; Argon2i uses it in every segment.+ const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2);+ for (let l = 0; l < p; l++) {+ address[256 + 2] = l;+ address[256 + 12] = 0;+ let startPos = 0;+ if (r === 0 && s === 0) {+ startPos = 2;+ if (dataIndependent) {+ address[256 + 12]++;+ block(address, 256, 2 * 256, 0, false);+ block(address, 0, 2 * 256, 0, false);+ }+ }+ // current block position+ let offset = l * laneLen + s * segmentLen + startPos;+ for (let index = startPos; index < segmentLen; index++, offset++) {+ perBlock();+ // Previous block position: wraps to the lane's last block only at lane start,+ // which can happen here only for the first block of slice 0 on passes > 0.+ const prev = offset % laneLen ? offset - 1 : offset + laneLen - 1;+ let randL, randH;+ if (dataIndependent) {+ let i128 = index % 128;+ // RFC 9106 §3.4.1.2: each 1024-byte address block yields 128 `(J1, J2)` pairs, so+ // regenerate it whenever the segment index crosses a multiple of 128.+ if (i128 === 0) {+ address[256 + 12]++;+ block(address, 256, 2 * 256, 0, false);+ block(address, 0, 2 * 256, 0, false);+ }+ randL = address[2 * i128];+ randH = address[2 * i128 + 1];+ }+ else {+ const T = 256 * prev;+ randL = B[T];+ randH = B[T + 1];+ }+ // Address-block path selects `J1` / `J2`, then maps them to the reference+ // lane/block per RFC 9106 §3.4.+ const refLane = r === 0 && s === 0 ? l : randH % lanes;+ const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l);+ const refBlock = laneLen * refLane + refPos;+ // B[i][j] = G(B[i][j-1], B[l][z])+ block(B, 256 * prev, 256 * refBlock, offset * 256, needXor);+ yield;+ }+ }+ }+ }+ clean(address);+}+function argon2(type, password, salt, opts) {+ const ctx = argon2Init(password, salt, type, opts);+ const blocks = argon2Blocks(ctx, new Uint32Array(3 * 256));+ while (!blocks.next().done) { }+ return argon2Output(ctx.B, ctx.p, ctx.laneLen, ctx.dkLen);+}+/**+ * Argon2d GPU-resistant version.+ * @param password - password or input key material+ * @param salt - unique salt value+ * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.+ * @returns Derived key bytes.+ * @throws If the Argon2 input or cost parameters are invalid. {@link Error}+ * @example+ * Derive a key with Argon2d.+ * ```ts+ * argon2d('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });+ * ```+ * @example+ * Derive a key with optional secret and scheduler controls.+ * ```ts+ * const progressLog: number[] = [];+ * argon2d('password', 'salt1234', {+ * t: 1,+ * m: 8,+ * p: 1,+ * dkLen: 32,+ * version: 0x13,+ * key: 'secret',+ * personalization: 'application',+ * maxmem: 1024 * 1024,+ * asyncTick: 1,+ * onProgress(progress) {+ * progressLog.push(progress);+ * },+ * });+ * ```+ */+export const argon2d = (password, salt, opts = {}) => argon2(AT.Argon2d, password, salt, opts);+/**+ * Argon2i side-channel-resistant version.+ * @param password - password or input key material+ * @param salt - unique salt value+ * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.+ * @returns Derived key bytes.+ * @throws If the Argon2 input or cost parameters are invalid. {@link Error}+ * @example+ * Derive a key with Argon2i.+ * ```ts+ * argon2i('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });+ * ```+ */+export const argon2i = (password, salt, opts = {}) => argon2(AT.Argon2i, password, salt, opts);+/**+ * Argon2id, combining i+d, the most popular version from RFC 9106.+ * @param password - password or input key material+ * @param salt - unique salt value+ * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.+ * @returns Derived key bytes.+ * @throws If the Argon2 input or cost parameters are invalid. {@link Error}+ * @example+ * Derive a key with Argon2id.+ * ```ts+ * argon2id('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });+ * ```+ */+export const argon2id = (password, salt, opts = {}) => argon2(AT.Argon2id, password, salt, opts);+async function argon2Async(type, password, salt, opts) {+ const ctx = argon2Init(password, salt, type, opts);+ // Keep the generator-local address block reachable so an aborted scheduler yield can wipe it.+ const address = new Uint32Array(3 * 256);+ const blocks = argon2Blocks(ctx, address);+ const abort = () => clean(address, ctx.B);+ let ts = Date.now();+ while (!blocks.next().done) {+ // Date.now() is not monotonic. If the clock goes backwards,+ // still yield control.+ const diff = Date.now() - ts;+ if (diff >= 0 && diff < ctx.asyncTick)+ continue;+ await nextTick(abort);+ // Scheduler delay is outside the synchronous work budget.+ ts = Date.now();+ }+ return argon2Output(ctx.B, ctx.p, ctx.laneLen, ctx.dkLen);+}+/**+ * Argon2d async GPU-resistant version.+ * @param password - password or input key material+ * @param salt - unique salt value+ * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.+ * @returns Promise resolving to derived key bytes.+ * @throws If the Argon2 input or cost parameters are invalid. {@link Error}+ * @example+ * Derive a key with Argon2d asynchronously.+ * ```ts+ * await argon2dAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });+ * ```+ * @example+ * Derive a key asynchronously with optional secret and scheduler controls.+ * ```ts+ * await argon2dAsync('password', 'salt1234', {+ * t: 1,+ * m: 8,+ * p: 1,+ * dkLen: 32,+ * version: 0x13,+ * key: 'secret',+ * personalization: 'application',+ * maxmem: 1024 * 1024,+ * asyncTick: 1,+ * onProgress(progress) {+ * if (progress > 1) throw new Error('invalid progress');+ * },+ * });+ * ```+ */+export const argon2dAsync = (password, salt, opts = {}) => argon2Async(AT.Argon2d, password, salt, opts);+/**+ * Argon2i async side-channel-resistant version.+ * @param password - password or input key material+ * @param salt - unique salt value+ * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.+ * @returns Promise resolving to derived key bytes.+ * @throws If the Argon2 input or cost parameters are invalid. {@link Error}+ * @example+ * Derive a key with Argon2i asynchronously.+ * ```ts+ * await argon2iAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });+ * ```+ */+export const argon2iAsync = (password, salt, opts = {}) => argon2Async(AT.Argon2i, password, salt, opts);+/**+ * Argon2id async, combining i+d, the most popular version from RFC 9106.+ * @param password - password or input key material+ * @param salt - unique salt value+ * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.+ * @returns Promise resolving to derived key bytes.+ * @throws If the Argon2 input or cost parameters are invalid. {@link Error}+ * @example+ * Derive a key with Argon2id asynchronously.+ * ```ts+ * await argon2idAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });+ * ```+ */+export const argon2idAsync = (password, salt, opts = {}) => argon2Async(AT.Argon2id, password, salt, opts);diff --git a/home/webext/src/id/vendor/noble-hashes/blake2.js b/home/webext/src/id/vendor/noble-hashes/blake2.jsnew file mode 100644index 00000000..38ead2e2--- /dev/null+++ b/home/webext/src/id/vendor/noble-hashes/blake2.js@@ -0,0 +1,573 @@+/**+ * blake2b (64-bit) & blake2s (8 to 32-bit) hash functions.+ * b could have been faster, but there is no fast u64 in js, so s is 1.5x faster.+ * @module+ */+import { BSIGMA, G1s, G2s } from "./_blake.js";+import { SHA256_IV } from "./_md.js";+import * as u64 from "./_u64.js";+// prettier-ignore+import { abytes, aexists, anumber, aoutput, checkOpts, clean, copyBytes, createHasher, swap32IfBE, swap8IfBE, u32 } from "./utils.js";+// Same IV words as `SHA512_IV`, but endian-swapped into LE u32 low/high halves+// for the BLAKE2b u64 helpers below.+const B2B_IV = /* @__PURE__ */ Uint32Array.from([+ 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,+ 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,+]);+// Shared synchronous BLAKE2b work vector as LE u32 low/high halves.+const BBUF = /* @__PURE__ */ new Uint32Array(32);+// BLAKE2b G mix split into two half-rounds over LE u32 low/high limbs.+function G1b(a, b, c, d, msg, x) {+ // NOTE: V is LE here+ const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore+ let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore+ let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore+ let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore+ let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore+ // v[a] = (v[a] + v[b] + x) | 0;+ const ll = u64.add3L(Al, Bl, Xl);+ Ah = u64.add3H(ll, Ah, Bh, Xh);+ Al = ll | 0;+ // v[d] = rotr(v[d] ^ v[a], 32)+ let xh = Dh ^ Ah, xl = Dl ^ Al; // prettier-ignore+ Dh = u64.rotr32H(xh, xl);+ Dl = u64.rotr32L(xh, xl);+ // v[c] = (v[c] + v[d]) | 0;+ ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));+ // v[b] = rotr(v[b] ^ v[c], 24)+ xh = Bh ^ Ch;+ xl = Bl ^ Cl;+ Bh = u64.rotrSH(xh, xl, 24);+ Bl = u64.rotrSL(xh, xl, 24);+ BBUF[2 * a] = Al;+ BBUF[2 * a + 1] = Ah;+ BBUF[2 * b] = Bl;+ BBUF[2 * b + 1] = Bh;+ BBUF[2 * c] = Cl;+ BBUF[2 * c + 1] = Ch;+ BBUF[2 * d] = Dl;+ BBUF[2 * d + 1] = Dh;+}+// Second half-round of the same LE-limb BLAKE2b G mix; `x` is the message word offset.+function G2b(a, b, c, d, msg, x) {+ // NOTE: V is LE here+ const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore+ let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore+ let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore+ let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore+ let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore+ // v[a] = (v[a] + v[b] + x) | 0;+ const ll = u64.add3L(Al, Bl, Xl);+ Ah = u64.add3H(ll, Ah, Bh, Xh);+ Al = ll | 0;+ // v[d] = rotr(v[d] ^ v[a], 16)+ let xh = Dh ^ Ah, xl = Dl ^ Al; // prettier-ignore+ Dh = u64.rotrSH(xh, xl, 16);+ Dl = u64.rotrSL(xh, xl, 16);+ // v[c] = (v[c] + v[d]) | 0;+ ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));+ // v[b] = rotr(v[b] ^ v[c], 63)+ xh = Bh ^ Ch;+ xl = Bl ^ Cl;+ Bh = u64.rotrBH(xh, xl, 63);+ Bl = u64.rotrBL(xh, xl, 63);+ BBUF[2 * a] = Al;+ BBUF[2 * a + 1] = Ah;+ BBUF[2 * b] = Bl;+ BBUF[2 * b + 1] = Bh;+ BBUF[2 * c] = Cl;+ BBUF[2 * c + 1] = Ch;+ BBUF[2 * d] = Dl;+ BBUF[2 * d + 1] = Dh;+}+function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {+ anumber(keyLen);+ // RFC 7693 §2.1 requires digest length nn in 1..keyLen (keyLen doubles as+ // the per-variant max for both key and digest lengths: 64 for b, 32 for s).+ if (outputLen <= 0 || outputLen > keyLen)+ throw new Error('"dkLen" must be 1..' + keyLen + ', got ' + outputLen);+ const { key, salt, personalization } = opts;+ // This API uses `undefined` for the RFC 7693 `kk = 0` case, so a provided key must be non-empty.+ if (key !== undefined && (key.length < 1 || key.length > keyLen))+ throw new Error('"key" expected to be undefined or of length=1..' + keyLen);+ if (salt !== undefined)+ abytes(salt, saltLen, 'salt');+ if (personalization !== undefined)+ abytes(personalization, persLen, 'personalization');+}+/** Internal base class for BLAKE2. */+export class _BLAKE2 {+ buffer;+ buffer32;+ finished = false;+ destroyed = false;+ length = 0;+ pos = 0;+ blockLen;+ outputLen;+ canXOF = false;+ constructor(blockLen, outputLen) {+ anumber(blockLen);+ anumber(outputLen);+ this.blockLen = blockLen;+ this.outputLen = outputLen;+ this.buffer = new Uint8Array(blockLen);+ this.buffer32 = u32(this.buffer);+ }+ update(data) {+ aexists(this);+ abytes(data);+ // Main difference with other hashes: there is flag for last block,+ // so we cannot process current block before we know that there+ // is the next one. This significantly complicates logic and reduces ability+ // to do zero-copy processing+ const { blockLen, buffer, buffer32 } = this;+ const len = data.length;+ const offset = data.byteOffset;+ const buf = data.buffer;+ for (let pos = 0; pos < len;) {+ // If buffer is full and we still have input (don't process last block, same as blake2s)+ if (this.pos === blockLen) {+ swap32IfBE(buffer32);+ this.compress(buffer32, 0, false);+ swap32IfBE(buffer32);+ this.pos = 0;+ }+ const take = Math.min(blockLen - this.pos, len - pos);+ const dataOffset = offset + pos;+ // Zero-copy only for full, 4-byte-aligned, non-final blocks.+ if (take === blockLen && !(dataOffset % 4) && pos + take < len) {+ const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));+ swap32IfBE(data32);+ for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {+ this.length += blockLen;+ this.compress(data32, pos32, false);+ }+ swap32IfBE(data32);+ continue;+ }+ // When the whole input is buffered in one go (common for short messages), passing `data`+ // directly avoids allocating a subarray view.+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);+ this.pos += take;+ this.length += take;+ pos += take;+ }+ return this;+ }+ digestInto(out) {+ aexists(this);+ aoutput(out, this);+ // Reject unaligned views explicitly instead of hiding them behind a full scratch copy.+ if (out.byteOffset & 3)+ throw new RangeError('"output" expected 4-byte aligned byteOffset, got ' + out.byteOffset);+ const { pos, buffer32 } = this;+ this.finished = true;+ // Padding+ this.buffer.fill(0, pos);+ swap32IfBE(buffer32);+ this.compress(buffer32, 0, true);+ swap32IfBE(buffer32);+ const state = this.get();+ // digest() passes our own `buffer` as `out`; reuse its cached u32 view instead of allocating.+ const out32 = out === this.buffer ? buffer32 : u32(out);+ const full = Math.floor(this.outputLen / 4);+ for (let i = 0; i < full; i++)+ out32[i] = swap8IfBE(state[i]);+ const tail = this.outputLen % 4;+ if (!tail)+ return;+ const off = full * 4;+ const word = state[full];+ for (let i = 0; i < tail; i++)+ out[off + i] = word >>> (8 * i);+ }+ digest() {+ const { buffer, outputLen } = this;+ this.digestInto(buffer);+ // Return a copy so callers do not alias the instance scratch buffer used during finalization.+ const res = buffer.slice(0, outputLen);+ this.destroy();+ return res;+ }+ _cloneInto(to) {+ const { buffer, length, finished, destroyed, outputLen, pos } = this;+ // Recreate only `dkLen`; key/salt/personalization are already absorbed into the copied state.+ to ||= new this.constructor({ dkLen: outputLen });+ to.set(...this.get());+ // Last-block-aware lazy compression keeps the pending block live even when full.+ to.buffer.set(buffer);+ to.destroyed = destroyed;+ to.finished = finished;+ to.length = length;+ to.pos = pos;+ // @ts-ignore+ to.outputLen = outputLen;+ return to;+ }+ clone() {+ return this._cloneInto();+ }+}+/** Internal blake2b hash class with state stored as LE u32 low/high halves. */+export class _BLAKE2b extends _BLAKE2 {+ // Same IV words as SHA-512 / BLAKE2b, encoded as LE u32 low/high halves.+ v0l = B2B_IV[0] | 0;+ v0h = B2B_IV[1] | 0;+ v1l = B2B_IV[2] | 0;+ v1h = B2B_IV[3] | 0;+ v2l = B2B_IV[4] | 0;+ v2h = B2B_IV[5] | 0;+ v3l = B2B_IV[6] | 0;+ v3h = B2B_IV[7] | 0;+ v4l = B2B_IV[8] | 0;+ v4h = B2B_IV[9] | 0;+ v5l = B2B_IV[10] | 0;+ v5h = B2B_IV[11] | 0;+ v6l = B2B_IV[12] | 0;+ v6h = B2B_IV[13] | 0;+ v7l = B2B_IV[14] | 0;+ v7h = B2B_IV[15] | 0;+ constructor(opts = {}) {+ opts = checkOpts({}, opts);+ const olen = opts.dkLen === undefined ? 64 : opts.dkLen;+ super(128, olen);+ checkBlake2Opts(olen, opts, 64, 16, 16);+ let { key, personalization, salt } = opts;+ let keyLength = 0;+ if (key !== undefined) {+ abytes(key, undefined, 'key');+ keyLength = key.length;+ }+ // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` into the low 32 bits of `h[0]`;+ // the high 32 bits stay at `IV[0]`.+ this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);+ if (salt !== undefined) {+ abytes(salt, undefined, 'salt');+ // Copy: u32() would throw on views with byteOffset not divisible by 4.+ const slt = u32(copyBytes(salt));+ this.v4l ^= swap8IfBE(slt[0]);+ this.v4h ^= swap8IfBE(slt[1]);+ this.v5l ^= swap8IfBE(slt[2]);+ this.v5h ^= swap8IfBE(slt[3]);+ }+ if (personalization !== undefined) {+ abytes(personalization, undefined, 'personalization');+ // Copy: u32() would throw on views with byteOffset not divisible by 4.+ const pers = u32(copyBytes(personalization));+ this.v6l ^= swap8IfBE(pers[0]);+ this.v6h ^= swap8IfBE(pers[1]);+ this.v7l ^= swap8IfBE(pers[2]);+ this.v7h ^= swap8IfBE(pers[3]);+ }+ if (key !== undefined) {+ // Pad to blockLen and update+ const tmp = new Uint8Array(this.blockLen);+ tmp.set(key);+ this.update(tmp);+ // The padded copy holds key material; buffer/state keep what they need.+ clean(tmp);+ }+ }+ // prettier-ignore+ get() {+ let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;+ return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];+ }+ // prettier-ignore+ set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {+ this.v0l = v0l | 0;+ this.v0h = v0h | 0;+ this.v1l = v1l | 0;+ this.v1h = v1h | 0;+ this.v2l = v2l | 0;+ this.v2h = v2h | 0;+ this.v3l = v3l | 0;+ this.v3h = v3h | 0;+ this.v4l = v4l | 0;+ this.v4h = v4h | 0;+ this.v5l = v5l | 0;+ this.v5h = v5h | 0;+ this.v6l = v6l | 0;+ this.v6h = v6h | 0;+ this.v7l = v7l | 0;+ this.v7h = v7h | 0;+ }+ compress(msg, offset, isLast) {+ // First half from state. Direct writes: get() would allocate an array ++ // closure per block.+ // prettier-ignore+ const { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;+ // prettier-ignore+ {+ BBUF[0] = v0l;+ BBUF[1] = v0h;+ BBUF[2] = v1l;+ BBUF[3] = v1h;+ BBUF[4] = v2l;+ BBUF[5] = v2h;+ BBUF[6] = v3l;+ BBUF[7] = v3h;+ BBUF[8] = v4l;+ BBUF[9] = v4h;+ BBUF[10] = v5l;+ BBUF[11] = v5h;+ BBUF[12] = v6l;+ BBUF[13] = v6h;+ BBUF[14] = v7l;+ BBUF[15] = v7h;+ }+ BBUF.set(B2B_IV, 16); // Second half from IV.+ const l = u64.fromNumL(this.length);+ const h = u64.fromNumH(this.length);+ BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset.+ BBUF[25] = B2B_IV[9] ^ h; // High word.+ // Invert all bits for last block+ if (isLast) {+ BBUF[28] = ~BBUF[28];+ BBUF[29] = ~BBUF[29];+ }+ let j = 0;+ const s = BSIGMA;+ // SIGMA selects 64-bit message words; multiply by 2 because `msg` stores+ // each word as [low32, high32].+ for (let i = 0; i < 12; i++) {+ G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);+ G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);+ G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);+ G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);+ G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);+ G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);+ G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);+ G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);+ G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);+ G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);+ G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);+ G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);+ G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);+ G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);+ G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);+ G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);+ }+ this.v0l ^= BBUF[0] ^ BBUF[16];+ this.v0h ^= BBUF[1] ^ BBUF[17];+ this.v1l ^= BBUF[2] ^ BBUF[18];+ this.v1h ^= BBUF[3] ^ BBUF[19];+ this.v2l ^= BBUF[4] ^ BBUF[20];+ this.v2h ^= BBUF[5] ^ BBUF[21];+ this.v3l ^= BBUF[6] ^ BBUF[22];+ this.v3h ^= BBUF[7] ^ BBUF[23];+ this.v4l ^= BBUF[8] ^ BBUF[24];+ this.v4h ^= BBUF[9] ^ BBUF[25];+ this.v5l ^= BBUF[10] ^ BBUF[26];+ this.v5h ^= BBUF[11] ^ BBUF[27];+ this.v6l ^= BBUF[12] ^ BBUF[28];+ this.v6h ^= BBUF[13] ^ BBUF[29];+ this.v7l ^= BBUF[14] ^ BBUF[30];+ this.v7h ^= BBUF[15] ^ BBUF[31];+ clean(BBUF);+ }+ destroy() {+ this.destroyed = true;+ clean(this.buffer32);+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);+ }+}+/**+ * Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.+ * @param msg - message that would be hashed+ * @param opts - Optional output, MAC, salt, and personalization settings.+ * `dkLen` must be 1..64 bytes; `salt` and `personalization`, if present,+ * must be 16 bytes each. See {@link Blake2Opts}.+ * @returns Digest bytes.+ * @example+ * Hash a message with Blake2b.+ * ```ts+ * blake2b(new Uint8Array([97, 98, 99]));+ * ```+ * @example+ * Hash a message with Blake2b while selecting output, MAC, salt, and personalization settings.+ * ```ts+ * blake2b(new Uint8Array([97, 98, 99]), {+ * dkLen: 32,+ * key: new Uint8Array(32),+ * salt: new Uint8Array(16),+ * personalization: new Uint8Array(16),+ * });+ * ```+ */+export const blake2b = /* @__PURE__ */ createHasher((opts) => new _BLAKE2b(opts));+/**+ * BLAKE2-compress core method.+ * Runs only the round function over a caller-supplied local vector; callers initialize `v0..v15`+ * and apply the final `h[i] ^= v[i] ^ v[i + 8]` fold themselves.+ * @param s - flattened sigma schedule bytes+ * @param offset - starting word offset inside `msg`, not a byte offset+ * @param msg - message words+ * @param rounds - round count to execute+ * @param v0 - state word 0+ * @param v1 - state word 1+ * @param v2 - state word 2+ * @param v3 - state word 3+ * @param v4 - state word 4+ * @param v5 - state word 5+ * @param v6 - state word 6+ * @param v7 - state word 7+ * @param v8 - state word 8+ * @param v9 - state word 9+ * @param v10 - state word 10+ * @param v11 - state word 11+ * @param v12 - state word 12+ * @param v13 - state word 13+ * @param v14 - state word 14+ * @param v15 - state word 15+ * @returns Updated compression state words.+ * @example+ * Run the BLAKE2 compression core on zeroed state and message words.+ * ```ts+ * import { _compress } from '@noble/hashes/blake2.js';+ * const state = _compress(+ * new Uint8Array(16),+ * 0,+ * new Uint32Array(16),+ * 1,+ * 0, 0, 0, 0, 0, 0, 0, 0,+ * 0, 0, 0, 0, 0, 0, 0, 0+ * );+ * state.v0;+ * ```+ */+// prettier-ignore+export function _compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {+ let j = 0;+ for (let i = 0; i < rounds; i++) {+ ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));+ ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));+ ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));+ ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));+ ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));+ ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));+ ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));+ ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));+ ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));+ ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));+ ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));+ ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));+ ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));+ ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));+ ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));+ ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));+ }+ return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };+}+// Blake2s reuses the SHA-256 IV words as-is.+const B2S_IV = /* @__PURE__ */ SHA256_IV.slice();+/** Internal blake2s hash class. */+export class _BLAKE2s extends _BLAKE2 {+ // Internal state, same as SHA-256+ v0 = B2S_IV[0] | 0;+ v1 = B2S_IV[1] | 0;+ v2 = B2S_IV[2] | 0;+ v3 = B2S_IV[3] | 0;+ v4 = B2S_IV[4] | 0;+ v5 = B2S_IV[5] | 0;+ v6 = B2S_IV[6] | 0;+ v7 = B2S_IV[7] | 0;+ constructor(opts = {}) {+ opts = checkOpts({}, opts);+ const olen = opts.dkLen === undefined ? 32 : opts.dkLen;+ super(64, olen);+ checkBlake2Opts(olen, opts, 32, 8, 8);+ let { key, personalization, salt } = opts;+ let keyLength = 0;+ if (key !== undefined) {+ abytes(key, undefined, 'key');+ keyLength = key.length;+ }+ // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` directly into `h[0]`, since+ // BLAKE2s stores each state word as one `u32`.+ this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);+ if (salt !== undefined) {+ abytes(salt, undefined, 'salt');+ // Copy: u32() would throw on views with byteOffset not divisible by 4.+ const slt = u32(copyBytes(salt));+ this.v4 ^= swap8IfBE(slt[0]);+ this.v5 ^= swap8IfBE(slt[1]);+ }+ if (personalization !== undefined) {+ abytes(personalization, undefined, 'personalization');+ // Copy: u32() would throw on views with byteOffset not divisible by 4.+ const pers = u32(copyBytes(personalization));+ this.v6 ^= swap8IfBE(pers[0]);+ this.v7 ^= swap8IfBE(pers[1]);+ }+ if (key !== undefined) {+ // Pad to blockLen and update+ const tmp = new Uint8Array(this.blockLen);+ tmp.set(key);+ this.update(tmp);+ // The padded copy holds key material; buffer/state keep what they need.+ clean(tmp);+ }+ }+ get() {+ const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;+ return [v0, v1, v2, v3, v4, v5, v6, v7];+ }+ // prettier-ignore+ set(v0, v1, v2, v3, v4, v5, v6, v7) {+ this.v0 = v0 | 0;+ this.v1 = v1 | 0;+ this.v2 = v2 | 0;+ this.v3 = v3 | 0;+ this.v4 = v4 | 0;+ this.v5 = v5 | 0;+ this.v6 = v6 | 0;+ this.v7 = v7 | 0;+ }+ compress(msg, offset, isLast) {+ const l = u64.fromNumL(this.length);+ const h = u64.fromNumH(this.length);+ // Seed v8..v15 from the IV, xor the low/high 32-bit byte counter into+ // v12/v13, and invert v14 on the final block.+ // prettier-ignore+ const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);+ this.v0 ^= v0 ^ v8;+ this.v1 ^= v1 ^ v9;+ this.v2 ^= v2 ^ v10;+ this.v3 ^= v3 ^ v11;+ this.v4 ^= v4 ^ v12;+ this.v5 ^= v5 ^ v13;+ this.v6 ^= v6 ^ v14;+ this.v7 ^= v7 ^ v15;+ }+ destroy() {+ this.destroyed = true;+ clean(this.buffer32);+ this.set(0, 0, 0, 0, 0, 0, 0, 0);+ }+}+/**+ * Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.+ * @param msg - message that would be hashed+ * @param opts - Optional output, MAC, salt, and personalization settings.+ * `dkLen` must be 1..32 bytes; `salt` and `personalization`, if present,+ * must be 8 bytes each. See {@link Blake2Opts}.+ * @returns Digest bytes.+ * @example+ * Hash a message with Blake2s.+ * ```ts+ * blake2s(new Uint8Array([97, 98, 99]));+ * ```+ * @example+ * Hash a message with Blake2s while selecting output, MAC, salt, and personalization settings.+ * ```ts+ * blake2s(new Uint8Array([97, 98, 99]), {+ * dkLen: 16,+ * key: new Uint8Array(32),+ * salt: new Uint8Array(8),+ * personalization: new Uint8Array(8),+ * });+ * ```+ */+export const blake2s = /* @__PURE__ */ createHasher((opts) => new _BLAKE2s(opts));diff --git a/home/webext/src/id/vendor/noble-hashes/utils.js b/home/webext/src/id/vendor/noble-hashes/utils.jsnew file mode 100644index 00000000..8ba88270--- /dev/null+++ b/home/webext/src/id/vendor/noble-hashes/utils.js@@ -0,0 +1,687 @@+/**+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.+ * @param a - value to test+ * @returns `true` when the value is a Uint8Array-compatible view.+ * @example+ * Check whether a value is a Uint8Array-compatible view.+ * ```ts+ * isBytes(new Uint8Array([1, 2, 3]));+ * ```+ */+export function isBytes(a) {+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.+ // The fallback still requires a real ArrayBuffer view, so plain+ // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and+ // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.+ return (a instanceof Uint8Array ||+ (ArrayBuffer.isView(a) &&+ a.constructor.name === 'Uint8Array' &&+ 'BYTES_PER_ELEMENT' in a &&+ a.BYTES_PER_ELEMENT === 1));+}+// Shared error-message prefix builder. Only called on throw paths, so assert+// success paths never pay for the string concatenation.+const atitle = (title) => (title ? `"${title}" ` : '');+/**+ * Asserts something is a non-negative integer.+ * @param n - number to validate+ * @param title - label included in thrown errors+ * @returns The validated number.+ * @throws On wrong argument types. {@link TypeError}+ * @throws On wrong argument ranges or values. {@link RangeError}+ * @example+ * Validate a non-negative integer option.+ * ```ts+ * anumber(32, 'length');+ * ```+ */+export function anumber(n, title = '') {+ if (typeof n !== 'number')+ throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);+ if (!Number.isSafeInteger(n) || n < 0)+ throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);+ return n;+}+/**+ * Asserts something is a boolean.+ * @param value - value to validate+ * @param title - label included in thrown errors+ * @returns The validated boolean.+ * @throws On wrong argument types. {@link TypeError}+ * @example+ * Validate a boolean option.+ * ```ts+ * abool(true, 'enableXOF');+ * ```+ */+export function abool(value, title = '') {+ if (typeof value !== 'boolean')+ throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);+ return value;+}+/**+ * Asserts something is Uint8Array.+ * @param value - value to validate+ * @param length - optional exact length constraint+ * @param title - label included in thrown errors+ * @returns The validated byte array.+ * @throws On wrong argument types. {@link TypeError}+ * @throws On wrong argument ranges or values. {@link RangeError}+ * @example+ * Validate that a value is a byte array.+ * ```ts+ * abytes(new Uint8Array([1, 2, 3]));+ * ```+ */+export function abytes(value, length, title = '') {+ // Success path first: this runs at the start of every update() / digestInto(), and the+ // common `abytes(data)` form must not pay for length handling it does not use.+ if (isBytes(value) && (length === undefined || value.length === length))+ return value;+ // Error path: recompute freely to build the exact message.+ if (length !== undefined)+ anumber(length, 'length');+ const bytes = isBytes(value);+ const ofLen = length !== undefined ? ` of length ${length}` : '';+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;+ const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;+ if (!bytes)+ throw new TypeError(message);+ throw new RangeError(message);+}+/**+ * Copies bytes into a fresh Uint8Array.+ * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.+ * @param bytes - source bytes to clone+ * @returns Freshly allocated copy of `bytes`.+ * @throws On wrong argument types. {@link TypeError}+ * @example+ * Clone a byte array before mutating it.+ * ```ts+ * const copy = copyBytes(new Uint8Array([1, 2, 3]));+ * ```+ */+export function copyBytes(bytes) {+ // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict+ // because callers use it at byte-validation boundaries before mutating the detached copy.+ return Uint8Array.from(abytes(bytes));+}+/**+ * Asserts something is a wrapped hash constructor.+ * @param h - hash constructor to validate+ * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}+ * @throws On invalid hash metadata ranges or values. {@link RangeError}+ * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}+ * @example+ * Validate a callable hash wrapper.+ * ```ts+ * import { ahash } from '@noble/hashes/utils.js';+ * import { sha256 } from '@noble/hashes/sha2.js';+ * ahash(sha256);+ * ```+ */+export function ahash(h) {+ if (typeof h !== 'function' || typeof h.create !== 'function')+ throw new TypeError('expected hash wrapped by utils.createHasher');+ anumber(h.outputLen);+ anumber(h.blockLen);+ // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass+ // validation and can produce empty outputs instead of failing fast.+ if (h.outputLen < 1 || h.blockLen < 1)+ throw new Error('hash blockLen / outputLen must be >= 1');+}+const aobject = (value, label) => {+ if (value === null || typeof value !== 'object' || Array.isArray(value))+ throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);+};+const aopts = (value, label) => {+ aobject(value, label);+ const proto = Object.getPrototypeOf(value);+ if (proto !== Object.prototype && proto !== null)+ throw new TypeError(`"${label}" expected plain object`);+ // Object.assign() treats an own "__proto__" source key as a write to the target's legacy+ // prototype setter. Reject it before merging so inherited option values cannot be injected.+ if (Object.hasOwn(value, '__proto__'))+ throw new TypeError(`"${label}.__proto__" is not allowed`);+};+/**+ * Asserts a hash instance has not been destroyed or finished.+ * @param instance - hash instance to validate+ * @param checkFinished - whether to reject finalized instances+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}+ * @example+ * Validate that a hash instance is still usable.+ * ```ts+ * import { aexists } from '@noble/hashes/utils.js';+ * import { sha256 } from '@noble/hashes/sha2.js';+ * const hash = sha256.create();+ * aexists(hash);+ * ```+ */+export function aexists(instance, checkFinished = true) {+ // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their+ // truthiness is checked - re-validating their type per call was pure hot-path overhead.+ if (instance.destroyed)+ throw new Error('hash was destroyed');+ if (checkFinished && instance.finished)+ throw new Error('digest() was already called');+}+/**+ * Asserts output is a sufficiently-sized byte array.+ * @param out - destination buffer+ * @param instance - hash instance providing output length+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.+ * @throws On wrong argument types. {@link TypeError}+ * @throws On wrong argument ranges or values. {@link RangeError}+ * @example+ * Validate a caller-provided digest buffer.+ * ```ts+ * import { aoutput } from '@noble/hashes/utils.js';+ * import { sha256 } from '@noble/hashes/sha2.js';+ * const hash = sha256.create();+ * aoutput(new Uint8Array(hash.outputLen), hash);+ * ```+ */+export function aoutput(out, instance) {+ abytes(out, undefined, 'output');+ // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast+ // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.+ const min = instance.outputLen;+ if (!(out.length >= min)) {+ throw new RangeError('"output" expected length >= ' + min);+ }+}+/**+ * Casts a typed array view to Uint8Array.+ * @param arr - source typed array+ * @returns Uint8Array view over the same buffer.+ * @example+ * Reinterpret a typed array as bytes.+ * ```ts+ * u8(new Uint32Array([1, 2]));+ * ```+ */+export function u8(arr) {+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);+}+/**+ * Casts a typed array view to Uint32Array.+ * `arr.byteOffset` must already be 4-byte aligned or the platform+ * Uint32Array constructor will throw.+ * @param arr - source typed array+ * @returns Uint32Array view over the same buffer.+ * @example+ * Reinterpret a byte array as 32-bit words.+ * ```ts+ * u32(new Uint8Array(8));+ * ```+ */+export function u32(arr) {+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));+}+/**+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.+ * @param arrays - arrays to overwrite with zeros+ * @example+ * Zeroize sensitive buffers in place.+ * ```ts+ * clean(new Uint8Array([1, 2, 3]));+ * ```+ */+export function clean(...arrays) {+ for (let i = 0; i < arrays.length; i++) {+ arrays[i].fill(0);+ }+}+/**+ * Creates a DataView for byte-level manipulation.+ * @param arr - source typed array+ * @returns DataView over the same buffer region.+ * @example+ * Create a DataView over an existing buffer.+ * ```ts+ * createView(new Uint8Array(4));+ * ```+ */+export function createView(arr) {+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);+}+/**+ * Rotate-right operation for uint32 values.+ * @param word - source word+ * @param shift - shift amount in bits+ * @returns Rotated word.+ * @example+ * Rotate a 32-bit word to the right.+ * ```ts+ * rotr(0x12345678, 8);+ * ```+ */+export function rotr(word, shift) {+ return (word << (32 - shift)) | (word >>> shift);+}+/**+ * Rotate-left operation for uint32 values.+ * @param word - source word+ * @param shift - shift amount in bits+ * @returns Rotated word.+ * @example+ * Rotate a 32-bit word to the left.+ * ```ts+ * rotl(0x12345678, 8);+ * ```+ */+export function rotl(word, shift) {+ return (word << shift) | ((word >>> (32 - shift)) >>> 0);+}+/** Whether the current platform is little-endian. */+export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();+/**+ * Byte-swap operation for uint32 values.+ * @param word - source word+ * @returns Word with reversed byte order.+ * @example+ * Reverse the byte order of a 32-bit word.+ * ```ts+ * byteSwap(0x11223344);+ * ```+ */+export function byteSwap(word) {+ return (((word << 24) & 0xff000000) |+ ((word << 8) & 0xff0000) |+ ((word >>> 8) & 0xff00) |+ ((word >>> 24) & 0xff));+}+/**+ * Conditionally byte-swaps one 32-bit word on big-endian platforms.+ * @param n - source word+ * @returns Original or byte-swapped word depending on platform endianness.+ * @example+ * Normalize a 32-bit word for host endianness.+ * ```ts+ * swap8IfBE(0x11223344);+ * ```+ */+export const swap8IfBE = isLE+ ? (n) => n+ : (n) => byteSwap(n) >>> 0;+/**+ * Byte-swaps every word of a Uint32Array in place.+ * @param arr - array to mutate+ * @returns The same array after mutation; callers pass live state arrays here.+ * @example+ * Reverse the byte order of every word in place.+ * ```ts+ * byteSwap32(new Uint32Array([0x11223344]));+ * ```+ */+export function byteSwap32(arr) {+ for (let i = 0; i < arr.length; i++) {+ arr[i] = byteSwap(arr[i]);+ }+ return arr;+}+/**+ * Conditionally byte-swaps a Uint32Array on big-endian platforms.+ * @param u - array to normalize for host endianness+ * @returns Original or byte-swapped array depending on platform endianness.+ * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.+ * @example+ * Normalize a word array for host endianness.+ * ```ts+ * swap32IfBE(new Uint32Array([0x11223344]));+ * ```+ */+export const swap32IfBE = isLE+ ? (u) => u+ : byteSwap32;+// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex+const hasHexBuiltin = /* @__PURE__ */ (() =>+// @ts-ignore+typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();+// Array where index 0xf0 (240) is mapped to string 'f0'+const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));+/**+ * Convert byte array to hex string.+ * Uses the built-in function when available and assumes it matches the tested+ * fallback semantics.+ * @param bytes - bytes to encode+ * @returns Lowercase hexadecimal string.+ * @throws On wrong argument types. {@link TypeError}+ * @example+ * Convert bytes to lowercase hexadecimal.+ * ```ts+ * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'+ * ```+ */+export function bytesToHex(bytes) {+ abytes(bytes);+ // @ts-ignore+ if (hasHexBuiltin)+ return bytes.toHex();+ // pre-caching improves the speed 6x+ let hex = '';+ for (let i = 0; i < bytes.length; i++) {+ hex += hexes[bytes[i]];+ }+ return hex;+}+// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.+// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.+// prettier-ignore+function asciiToBase16(ch) {+ return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48+ : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)+ : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)+ : undefined;+}+/**+ * Convert hex string to byte array. Uses built-in function, when available.+ * @param hex - hexadecimal string to decode+ * @returns Decoded bytes.+ * @throws On wrong argument types. {@link TypeError}+ * @throws On wrong argument ranges or values. {@link RangeError}+ * @example+ * Decode lowercase hexadecimal into bytes.+ * ```ts+ * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])+ * ```+ */+export function hexToBytes(hex) {+ if (typeof hex !== 'string')+ throw new TypeError('hex string expected, got ' + typeof hex);+ if (hasHexBuiltin) {+ try {+ return Uint8Array.fromHex(hex);+ }+ catch (error) {+ if (error instanceof SyntaxError)+ throw new RangeError(error.message);+ throw error;+ }+ }+ const hl = hex.length;+ const al = hl / 2;+ if (hl % 2)+ throw new RangeError('hex string expected, got unpadded hex of length ' + hl);+ const array = new Uint8Array(al);+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {+ const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char+ if (n1 === undefined || n2 === undefined) {+ const char = hex[hi] + hex[hi + 1];+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);+ }+ array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9+ }+ return array;+}+/**+ * Yields to the host task scheduler so timers, I/O, and rendering can make progress.+ * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.+ * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so+ * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while+ * still allowing other event-loop work to proceed.+ * @param onReject - optional cleanup invoked only if the host yield fails+ * @example+ * Yield to the next scheduler tick.+ * ```ts+ * await nextTick();+ * ```+ */+export function nextTick(onReject) {+ const host = globalThis;+ if (typeof host.scheduler?.yield === 'function') {+ const promise = host.scheduler.yield();+ // Keep the original scheduler rejection; this handler exists only for cleanup.+ if (onReject)+ promise.catch(onReject);+ return promise;+ }+ return new Promise((resolve) => host.setTimeout(resolve, 0));+}+/**+ * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.+ * @param iters - number of loop iterations to run+ * @param tick - maximum time slice in milliseconds+ * @param cb - callback executed on each iteration+ * @param onReject - optional cleanup invoked only if a host yield fails+ * @throws On wrong argument types. {@link TypeError}+ * @throws On wrong argument ranges or values. {@link RangeError}+ * @example+ * Run a loop that periodically yields back to the event loop.+ * ```ts+ * await asyncLoop(2, 0, () => {});+ * ```+ */+export async function asyncLoop(iters, tick, cb, onReject) {+ anumber(iters, 'iters');+ anumber(tick, 'tick');+ if (typeof cb !== 'function')+ throw new TypeError('callback must be a function');+ // Callback is synchronous by contract; asyncLoop only yields between sync work windows.+ let ts = Date.now();+ for (let i = 0; i < iters; i++) {+ cb(i);+ // Date.now() is not monotonic, so in case if clock goes backwards we return return control too+ const diff = Date.now() - ts;+ if (diff >= 0 && diff < tick)+ continue;+ await nextTick(onReject);+ // Track only synchronous work time; scheduler delay after yielding is outside our budget.+ ts = Date.now();+ }+}+/**+ * Converts string to bytes using UTF8 encoding.+ * Built-in doesn't validate input to be string: we do the check.+ * Non-ASCII details are delegated to the platform `TextEncoder`.+ * @param str - string to encode+ * @returns UTF-8 encoded bytes.+ * @throws On wrong argument types. {@link TypeError}+ * @example+ * Encode a string as UTF-8 bytes.+ * ```ts+ * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])+ * ```+ */+export function utf8ToBytes(str) {+ if (typeof str !== 'string')+ throw new TypeError('string expected');+ const encoded = new TextEncoder().encode(str);+ try {+ // Copy into the current realm for Firefox extension contexts. Callers that own the returned+ // buffer can then wipe it independently of TextEncoder's temporary result.+ return new Uint8Array(encoded); // https://bugzil.la/1681809+ }+ finally {+ clean(encoded);+ }+}+/**+ * Helper for KDFs: consumes Uint8Array or string.+ * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.+ * @param data - user-provided KDF input+ * @param errorTitle - label included in thrown errors+ * @returns Byte representation of the input.+ * @throws On wrong argument types. {@link TypeError}+ * @example+ * Normalize KDF input to bytes.+ * ```ts+ * kdfInputToBytes('password');+ * ```+ */+export function kdfInputToBytes(data, errorTitle = '') {+ if (typeof data === 'string')+ return utf8ToBytes(data);+ return abytes(data, undefined, errorTitle);+}+/**+ * Copies several Uint8Arrays into one.+ * @param arrays - arrays to concatenate+ * @returns Concatenated byte array.+ * @throws On wrong argument types. {@link TypeError}+ * @example+ * Concatenate multiple byte arrays.+ * ```ts+ * concatBytes(new Uint8Array([1]), new Uint8Array([2]));+ * ```+ */+export function concatBytes(...arrays) {+ let sum = 0;+ for (let i = 0; i < arrays.length; i++) {+ const a = arrays[i];+ abytes(a);+ sum += a.length;+ }+ const res = new Uint8Array(sum);+ for (let i = 0, pad = 0; i < arrays.length; i++) {+ const a = arrays[i];+ res.set(a, pad);+ pad += a.length;+ }+ return res;+}+/**+ * Validates declared required and optional field types on a plain object.+ * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct+ * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.+ * @param object - object to validate+ * @param fields - map of required field names to expected types+ * @param optFields - map of optional field names to expected types+ * @param title - label included in thrown errors+ * @throws On wrong argument types. {@link TypeError}+ * @example+ * Validate required and optional option fields.+ * ```ts+ * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });+ * ```+ */+export const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {+ aobject(object, title);+ aobject(fields, 'fields');+ aobject(optFields, 'optFields');+ function checkField(fieldName, expectedType, isOpt) {+ const label = title === 'object' ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;+ // Config fields must be explicit own properties. Optional inherited values are rejected too+ // because callers keep reading the same options object after validation.+ const val = object[fieldName];+ // Runtime objects such as Field instances intentionally satisfy required method slots+ // via their shared prototype.+ if (!Object.hasOwn(object, fieldName) &&+ (isOpt ? val !== undefined : expectedType !== 'function')) {+ throw new TypeError(`${label} is invalid: expected own property`);+ }+ if (isOpt && val === undefined)+ return;+ const current = typeof val;+ if (current !== expectedType || val === null)+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);+ }+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));+ iter(fields, false);+ iter(optFields, true);+};+/**+ * Merges default options and passed options.+ * @param defaults - base option object+ * @param opts - user overrides+ * @param title - label included in thrown override errors+ * @returns Fresh merged option object with a null prototype.+ * @throws On wrong argument types. {@link TypeError}+ * @example+ * Merge user overrides onto default options.+ * ```ts+ * checkOpts({ dkLen: 32 }, { asyncTick: 10 });+ * ```+ */+export function checkOpts(defaults, opts, title = 'opts') {+ aopts(defaults, 'defaults');+ if (opts !== undefined)+ aopts(opts, title);+ // Callers read optional fields directly, so omitted values must not fall through to ambient+ // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).+ const merged = Object.assign(Object.create(null), defaults, opts);+ return merged;+}+/**+ * Creates a callable hash function from a stateful class constructor.+ * @param hashCons - hash constructor or factory+ * @param info - optional metadata such as DER OID+ * @returns Frozen callable hash wrapper with `.create()`.+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read+ * `outputLen` / `blockLen`, so constructor side effects happen at module+ * init time.+ * @throws On wrong argument types. {@link TypeError}+ * @example+ * Wrap a stateful hash constructor into a callable helper.+ * ```ts+ * import { createHasher } from '@noble/hashes/utils.js';+ * import { sha256 } from '@noble/hashes/sha2.js';+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });+ * wrapped(new Uint8Array([1]));+ * ```+ */+export function createHasher(hashCons, info = {}) {+ if (typeof hashCons !== 'function')+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);+ info = checkOpts({}, info, 'info');+ const hashC = (msg, opts) => hashCons(opts)+ .update(msg)+ .digest();+ const tmp = hashCons(undefined);+ hashC.outputLen = tmp.outputLen;+ hashC.blockLen = tmp.blockLen;+ hashC.canXOF = tmp.canXOF;+ hashC.create = (opts) => hashCons(opts);+ Object.assign(hashC, info);+ return Object.freeze(hashC);+}+/**+ * Cryptographically secure PRNG backed by `crypto.getRandomValues`.+ * @param bytesLength - number of random bytes to generate+ * @returns Random bytes.+ * The platform `getRandomValues()` implementation still defines any+ * single-call length cap, and this helper rejects oversize requests+ * with a stable library `RangeError` instead of host-specific errors.+ * @throws On wrong argument types. {@link TypeError}+ * @throws On wrong argument ranges or values. {@link RangeError}+ * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}+ * @example+ * Generate a fresh random key or nonce.+ * ```ts+ * const key = randomBytes(16);+ * ```+ */+export function randomBytes(bytesLength = 32) {+ // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.+ anumber(bytesLength, 'bytesLength');+ const cr = typeof globalThis === 'object' ? globalThis.crypto : null;+ if (typeof cr?.getRandomValues !== 'function')+ throw new Error('crypto.getRandomValues must be defined');+ // Web Cryptography API Level 2 §10.1.1:+ // if `byteLength > 65536`, throw `QuotaExceededError`.+ // Keep the guard explicit so callers can see the quota in code+ // instead of discovering it by reading the spec or host errors.+ // This wrapper surfaces the same quota as a stable library RangeError.+ if (bytesLength > 65536)+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);+ return cr.getRandomValues(new Uint8Array(bytesLength));+}+/**+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.+ * @param suffix - final OID byte for the selected hash.+ * The helper accepts any byte even though only the documented NIST hash+ * suffixes are meaningful downstream.+ * @returns Object containing the DER-encoded OID.+ * @example+ * Build OID metadata for a NIST hash.+ * ```ts+ * oidNist(0x01);+ * ```+ */+export const oidNist = (suffix) => ({+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.+ // Larger suffix values would need base-128 OID encoding and a different length byte.+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),+});diff --git a/scripts/gen-webext-id.mjs b/scripts/gen-webext-id.mjsindex 5633c16a..da0ff205 100644--- a/scripts/gen-webext-id.mjs+++ b/scripts/gen-webext-id.mjs@@ -2,7 +2,7 @@// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento authors//-// The extension's copy of the bento/id statement code, GENERATED from the+// The extension's copy of kernel's bento/connect code (statements, recovery), 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@@ -23,7 +23,7 @@ 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 ENTRY = ['statements.ts', 'address.ts', 'recovery.ts']const VALUE_IMPORT = /^import (?!type )[^;]*?from '\.\/([a-z0-9-]+)\.ts'/gmexport function generate() {diff --git a/scripts/pack-webext.mjs b/scripts/pack-webext.mjsindex 799d4349..d2aa5b7d 100644--- a/scripts/pack-webext.mjs+++ b/scripts/pack-webext.mjs@@ -48,13 +48,16 @@ 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+ // bento/connect: the agent's modules, the code generated from kernel+ // (scripts/gen-webext-id.mjs), and the vendored Argon2id with its licence/^src\/id\/(gen\/)?[^/]+\.js$/,+ /^src\/id\/vendor\/noble-hashes\/([^/]+\.js|LICENSE)$/,/^_locales\/[a-zA-Z_]+\/messages\.json$/,]/** Present on purpose, deliberately NOT shipped. */-const EXCLUDE = [/^probe\//, /^README\.md$/, /^STORE\.md$/]+const EXCLUDE = [/^probe\//, /^README\.md$/, /^STORE\.md$/,+ // the vendored files' pin list: checked by scripts/test-webext-id.ts, not shipped+ /^src\/id\/vendor\/[^/]+\/VENDOR\.json$/]const problems = []const fail = (m) => problems.push(m)diff --git a/scripts/test-webext-id.ts b/scripts/test-webext-id.tsindex 278b3f15..8a53915d 100644--- a/scripts/test-webext-id.ts+++ b/scripts/test-webext-id.ts@@ -1,23 +1,16 @@#!/usr/bin/env node// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento authors-// home/webext bento/id agent rig.+// home/webext bento/connect 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.+// WHAT THIS PROVES. The extension's bento/connect code IS the kernel reference,+// unaltered: home/webext/src/id/gen/ is a current type-strip of kernel/src+// (statements, address, display table, recovery), with no leftovers, and+// kernel's own rigs, re-pointed at that copy, pass every row of+// kernel/fixtures/identity-v1.json and recovery-v1.json, exactly as many rows+// as on kernel's source.import { readFileSync, writeFileSync, mkdtempSync, readdirSync } from 'node:fs'import { join, dirname } from 'node:path'@@ -27,8 +20,6 @@ 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 = 0let checks = 0@@ -49,111 +40,110 @@ const extra = readdirSync(join(root, 'home/webext/src/id/gen')).filter((f) => !(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')+// Kernel's own rigs, re-pointed at the extension's generated copy: every row+// kernel checks is checked against the code the extension ships, and must pass+// as many rows as on kernel's source, so a stale copy can't pass on old vectors.+const dir = mkdtempSync(join(tmpdir(), 'webext-id-'))+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(' | ') }+}+for (const [rig, contract] of [['test-statements.ts', 'kernel/fixtures/identity-v1.json'], ['test-recovery.ts', 'kernel/fixtures/recovery-v1.json']]) {+ console.log(`\n— ${contract}, against the extension's copy (scripts/${rig})`)+ const src = readFileSync(join(root, 'scripts', rig), 'utf8')const gen = (f: string) => pathToFileURL(join(root, 'home/webext/src/id/gen', f)).hrefconst 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\/(statements|address|recovery)\.ts'/g, (_m, f) => `from '${gen(f + '.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')+ .replace(/join\(dirname\(fileURLToPath\(import\.meta\.url\)\), '\.\.'/g, `join(${JSON.stringify(root)}`)+ ok(swapped !== src && !/from '\.\.\/kernel\/src\/(statements|address|recovery)\.ts'/.test(swapped), `${rig} is re-pointed at the extension's generated files`)+ const f = join(dir, rig)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 kernel = run(join(root, 'scripts', rig))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})`)+ ok(kernel.ok, `kernel's own ${rig} passes on kernel's source (${kernel.tail})`)+ ok(ext.ok && ext.total === kernel.total, `every row passes on the extension's code, as many as kernel's own run (${ext.tail} vs kernel ${kernel.total})`)}-console.log('\n— the passkey-wrapped account key (identity-design §2f)')+// ---------------------------------------------------------------------------+// Argon2id: @noble/hashes 2.4.0, vendored and pinned (security §28 + the+// 2026-10-21 conditions). Every row runs on every change; none is skippable.{- 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`)+ const { createHash, argon2: nodeArgon2 } = await import('node:crypto')+ const VDIR = join(root, 'home/webext/src/id/vendor/noble-hashes')+ const V = JSON.parse(readFileSync(join(VDIR, 'VENDOR.json'), 'utf8'))+ console.log('\n— the vendored files are exactly the pinned ones')+ const onDisk = readdirSync(VDIR).filter((f) => f !== 'VENDOR.json').sort()+ ok(JSON.stringify(onDisk) === JSON.stringify(Object.keys(V.files).sort()), `no file added or missing (${onDisk.length} files)`)+ for (const [f, h] of Object.entries(V.files as Record<string, string>)) {+ let got = ''+ try { got = createHash('sha256').update(readFileSync(join(VDIR, f))).digest('hex') } catch { /* missing */ }+ ok(got === h, `${f} matches its pinned sha256`)}- // 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(V.package === '@noble/hashes' && V.version === '2.4.0' && /^sha512-/.test(V.integrity), 'the manifest names the package, version and registry integrity')++ const noble = await import('../home/webext/src/id/vendor/noble-hashes/argon2.js')+ const a2 = await import('../home/webext/src/id/argon2.js')+ const rec = await import('../home/webext/src/id/gen/recovery.js')+ const RV = JSON.parse(readFileSync(join(root, 'kernel/fixtures/recovery-v1.json'), 'utf8'))+ const hex = (u: Uint8Array) => Buffer.from(u).toString('hex')+ const un = (h: string) => Uint8Array.from(Buffer.from(h, 'hex'))+ const native = (pw: Uint8Array, salt: Uint8Array, o: { t: number; m: number; p: number; dkLen: number }) =>+ new Promise<string>((res, rej) => nodeArgon2('argon2id', { message: pw, nonce: salt, parallelism: o.p, tagLength: o.dkLen, memory: o.m, passes: o.t }, (e: any, k: any) => (e ? rej(e) : res(hex(new Uint8Array(k))))))++ console.log('\n— the primitive: RFC 9106 §5.3 on the vendored copy')+ const r = RV.rfc9106+ const rfc = (opts = {}) => noble.argon2idAsync(un(r.password), un(r.salt), { t: r.passes, m: r.memoryKiB, p: r.parallelism, dkLen: r.tagLength, key: un(r.secret), personalization: un(r.ad), ...opts })+ ok(hex(await rfc()) === r.tag, 'Argon2id(RFC 9106 §5.3 inputs, with secret and associated data) = the published tag')+ ok(hex(await rfc({ version: 0x10 })) !== r.tag, 'MUTANT version 1.0 (no XOR into the existing block) does not reproduce the tag — the vector detects it')+ ok(hex(await rfc({ p: 2 })) !== r.tag, 'MUTANT a wrong lane count does not reproduce the tag')+ ok(hex(await rfc({ t: 2 })) !== r.tag, 'MUTANT a wrong pass count does not reproduce the tag')++ console.log('\n— the signed parameters, and every recovery-v1 derivation, through the wrapper')+ ok(a2.NOBLE_OPTS.t === 3 && a2.NOBLE_OPTS.m === 65536 && a2.NOBLE_OPTS.p === 1 && a2.NOBLE_OPTS.dkLen === 32 && a2.NOBLE_OPTS.version === 0x13 && Object.isFrozen(a2.NOBLE_OPTS), 'the wrapper is pinned to v0x13, p=1, 64 MiB, t=3, 32 bytes, and frozen')+ const d = RV.derivations+ ok(hex(await a2.argon2id(un(d.code), un(d.salt))) === d.argon2_A, 'A = Argon2id(code bytes, salt) — the fixture\'s value')+ ok(hex(await rec.recoveryWrapKey(un(d.code), un(d.salt), a2.argon2id)) === d.wrapKey, 'wrap key = HKDF(A, empty, "bento/id/rc-wrap/v1") — through the extension\'s own code end to end')+ ok(hex(await rec.recoveryVerifier(un(d.code), un(d.saltV), a2.argon2id)) === d.verifier, 'verifier = Argon2id(code bytes, salt_v)')++ console.log('\n— randomized cross-check against Node\'s native Argon2id')+ let agree = 0, tries = 0+ for (let i = 0; i < 24; i++) {+ const o = { t: 1 + (i % 3), m: 8 * (1 + ((i * 7) % 32)), p: 1, dkLen: 32 }+ const pw = crypto.getRandomValues(new Uint8Array(1 + (i * 5) % 40)), salt = crypto.getRandomValues(new Uint8Array(16))+ tries+++ if (hex(await noble.argon2idAsync(pw, salt, o)) === await native(pw, salt, o)) agree+++ }+ ok(agree === tries, `random inputs at small costs: ${agree}/${tries} equal to native`)+ for (let i = 0; i < 2; i++) {+ const pw = crypto.getRandomValues(new Uint8Array(10)), salt = crypto.getRandomValues(new Uint8Array(16))+ ok(hex(await a2.argon2id(pw, salt)) === await native(pw, salt, { t: 3, m: 65536, p: 1, dkLen: 32 }), `random code at the SIGNED parameters equals native (${i + 1}/2)`)}- 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+ console.log('\n— the 64 MiB block array reads zero afterwards (probe)')+ {+ const Orig = globalThis.Uint32Array+ const big: Uint32Array[] = []+ ;(globalThis as any).Uint32Array = new Proxy(Orig, { construct(T, args) { const a = Reflect.construct(T, args); if (a.length >= (64 * 1024 * 1024) / 4) big.push(a); return a } })+ let k: Uint8Array+ try { k = await a2.argon2id(crypto.getRandomValues(new Uint8Array(10)), crypto.getRandomValues(new Uint8Array(16))) } finally { (globalThis as any).Uint32Array = Orig }+ ok(big.length === 1, `the probe saw the derivation's block array (${big.length} array of ≥ 64 MiB)`)+ ok(big.length === 1 && big[0].every((x) => x === 0), 'after the derivation every word of it is zero (noble\'s clean; residual: an engine copy made before zeroing is out of reach)')+ ok(k!.length === 32 && !k!.every((x) => x === 0), 'and the derivation still produced a real 32-byte key')}- 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++++ console.log('\n— an allocation failure is "recovery unavailable", never a crash or weaker parameters')+ {+ const Orig = globalThis.Uint32Array+ const sizes: number[] = []+ ;(globalThis as any).Uint32Array = new Proxy(Orig, { construct(T, args) { const n = typeof args[0] === 'number' ? args[0] : 0; if (n >= (64 * 1024 * 1024) / 4) { sizes.push(n); throw new RangeError('Array buffer allocation failed') } return Reflect.construct(T, args) } })+ let err: any = null+ try { await a2.argon2id(new Uint8Array(10), new Uint8Array(16)) } catch (e) { err = e } finally { (globalThis as any).Uint32Array = Orig }+ ok(err?.name === 'RecoveryUnavailable' && !(err instanceof RangeError), `the failure surfaces as RecoveryUnavailable (${err?.name})`)+ ok(sizes.length === 1, `exactly one allocation attempt, at full size: no retry, no smaller fallback (${sizes.length})`)}- 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`)