From b23bbc72a92a6b540ac0ca568af98b1e75aeff8d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 22:22:53 +0000 Subject: [PATCH 1/5] feat(prism-id): recovery codes, so a prism outlives its devices Prism id's next milestone: a recovery device is an ordinary prism/device/1 linked by the ordinary link flow, whose private keys are sealed (AES-GCM, HKDF from a 32-byte seed) in a public-safe prism/recovery-escrow/1 object with the private boundary and the log. The owner keeps the seed as a 56-character Crockford recovery code with three check bytes. recoverOnto opens the escrow and links the new browser's own non-extractable device through createLinkOffer/acceptLinkRequest/completeLink, so Stitch.PrismId decides it like any link; a recovery device revoked in a newer log links nothing. No model rule is added. Lives in src/prism-id.js so the product register's modeled artifacts are unchanged (contracts.json regenerated). tests/prism-recovery.test.js: code round trip and typo refusal, recovery onto a new device with the private boundary, escrow bound to its code, revoked recovery refused. node --test tests/prism-*.test.js: 15 pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Asa3NdLCxdzL1iQw9rg5T --- docs/prism-id.md | 20 ++++- product/contracts.json | 12 ++- src/prism-id.js | 169 +++++++++++++++++++++++++++++++++++ tests/prism-recovery.test.js | 60 +++++++++++++ 4 files changed, 256 insertions(+), 5 deletions(-) create mode 100644 tests/prism-recovery.test.js diff --git a/docs/prism-id.md b/docs/prism-id.md index 5737713..ff392fc 100644 --- a/docs/prism-id.md +++ b/docs/prism-id.md @@ -34,7 +34,7 @@ merging two logs is set union: commutative, associative and idempotent. Revocation wins over a concurrent bind: a bind made by a revoked device counts only if the revocation lists it in `keep`. Rotating away from the genesis device keeps every device that was already linked. Two devices that revoke each other -are both revoked; recovery (a later milestone) is the way out. +are both revoked; a recovery code (below) is the way out. ## Linking a device out of band @@ -64,3 +64,21 @@ they can find it. Each message is the log sealed in the private boundary, bound to the prism id. The bus contract is `publish(topic, bytes)` and `subscribe(topic, fn)`. `createMemoryBus` implements it for tests; the stitch substrate implements it across peers and federation nodes. + +## Recovery + +Recovery lives in `src/prism-id.js`. A recovery device is an ordinary `prism/device/1`, +linked by the ordinary link flow, whose private keys live outside every +browser: sealed (AES-GCM) in a `prism/recovery-escrow/1` object under a key +derived (HKDF) from a 32-byte seed. The owner keeps the seed as a recovery +code: 56 Crockford base32 characters, the seed and three check bytes. The +escrow carries the recovery device's keys, the private boundary key and the +log as it stood, so it alone restores the prism. It is public-safe ciphertext, +kept in any content-addressed store and found by its locator, the kappa of a +value derived from the seed. + +With the code, `recoverOnto` opens the escrow and links the new browser's own +non-extractable device to the prism, again through `createLinkOffer`, +`acceptLinkRequest` and `completeLink`, so `Stitch.PrismId` decides it like any +link. A recovery device revoked in a newer log links nothing. The new device +can then revoke the lost one. No rule is added to the model. diff --git a/product/contracts.json b/product/contracts.json index 7ffc6c9..1c3d61d 100644 --- a/product/contracts.json +++ b/product/contracts.json @@ -1372,8 +1372,8 @@ "origin": "Project-owned source checkout", "licenseStatus": "Project declares MIT; audit applies", "redistributionCleared": true, - "bytes": 21252, - "sha256": "313a472c8995e72815a9fe64c53eda9fb55c3866ec1f335253da32e91d0953a7" + "bytes": 29553, + "sha256": "09040245f0257f5d3bebdec9432485a5869cd901d76e5a6ca6d68fb5e6c569c0" }, { "declaration": "assetProductExperience", @@ -2838,7 +2838,7 @@ }, { "path": "docs/prism-id.md", - "sha256": "41a47c92a79755332d705b0a20cae7f625901ef58a1a68258c2950964e70e2bb" + "sha256": "12205abdc46b488fc3d84ee87ee2853fc5b23c901795599c6de39182ab179198" }, { "path": "docs/prism-model.md", @@ -3116,6 +3116,10 @@ "path": "tests/prism-id.test.js", "sha256": "a67d5856cc44ef15ec87443917236e532da281a1067ea9661f57de68b64ff8f5" }, + { + "path": "tests/prism-recovery.test.js", + "sha256": "413bac3360a69d773bea0167f2676dfad81ab960bcf55cf5f4d16e7a428e266e" + }, { "path": "tests/product-experience.test.js", "sha256": "a519f9b5c014eada46bd6c016be966c7fbe6f84971ac9408185c89422f68439b" @@ -3185,5 +3189,5 @@ "sha256": "02263c2d4bf1a1913a673466554c19593b5a6c39b22a2da32ce4375675868347" } ], - "sourceDigest": "sha256:54e807b4f0ae48004d76c74891bbe03bb99893cd977e83106f8dc02d83affbf5" + "sourceDigest": "sha256:6790710949fdd1e3c0c498979a78fadacb8ec615c43236e9a78bd8582e8bb5d6" } diff --git a/src/prism-id.js b/src/prism-id.js index 4baa3d0..463d37f 100644 --- a/src/prism-id.js +++ b/src/prism-id.js @@ -451,3 +451,172 @@ export function createMemoryBus() { } }; } + +// ---------------------------------------------------------------- recovery + +/** + * Recovery: a prism outlives every device it was made on. + * + * A recovery device is an ordinary prism device (prism/device/1), linked + * through the same out-of-band link flow as any other device, whose private + * keys are kept outside every browser: sealed in an escrow object under a + * key derived from a short recovery code the owner writes down. With the code + * and its escrow, any new device links itself to the prism, receives the + * private boundary, and carries on. Every authorization decision is still + * taken by Stitch.PrismId (bindAllowed, linkOfferAccepted, deviceMaySign) + * above; recovery adds no rule of its own. + * + * The code is the escrow key's 32-byte seed and three check bytes (the start + * of its SHA-256), in Crockford base32: 56 characters, written in groups of + * four. Readers ignore spaces, hyphens and case, read I and L as 1 and O as 0, + * and refuse a code whose check bytes differ. + * + * The escrow is public-safe: AES-GCM ciphertext bound to its locator. It can + * sit in any content-addressed store (its kappa is its address) and be found + * by its locator, which is derived from the seed and reveals nothing about it. + * It carries the log as it stood when the code was made, so recovery needs no + * other service; later records arrive by sync. + */ +export const RECOVERY_KIND = Object.freeze({ + escrow: 'prism/recovery-escrow/1', + sealed: 'prism/recovery/1', + locator: 'prism/recovery-locator/1' +}); + + +// ---------------------------------------------------------------- the code + +const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; + +export async function encodeCode(seed) { + if (!(seed instanceof Uint8Array) || seed.length !== 32) refuse('code', 'a recovery seed is 32 bytes'); + const bytes = [...seed, ...new Uint8Array(await subtle.digest('SHA-256', seed)).slice(0, 3)]; + const bits = bytes.map(b => b.toString(2).padStart(8, '0')).join(''); + const chars = bits.match(/.{5}/g).map(five => CROCKFORD[parseInt(five, 2)]).join(''); + return chars.match(/.{4}/g).join(' '); +} + +export async function decodeCode(text) { + const clean = String(text).toUpperCase().replace(/[\s-]/g, '').replace(/[IL]/g, '1').replace(/O/g, '0'); + if (!/^[0-9A-HJKMNP-TV-Z]{56}$/.test(clean)) refuse('code', 'a recovery code is 56 letters and digits'); + const bits = [...clean].map(c => CROCKFORD.indexOf(c).toString(2).padStart(5, '0')).join(''); + const bytes = Uint8Array.from(bits.match(/.{8}/g), byte => parseInt(byte, 2)); + const seed = bytes.slice(0, 32); + const check = new Uint8Array(await subtle.digest('SHA-256', seed)).slice(0, 3); + if (check.some((b, i) => b !== bytes[32 + i])) refuse('code', 'the recovery code has a typo'); + return seed; +} + +// ---------------------------------------------------------------- keys from the seed + +async function derive(seed, info, length) { + const material = await subtle.importKey('raw', seed, 'HKDF', false, ['deriveBits']); + return new Uint8Array(await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(32), info: encoder.encode(info) }, material, length * 8)); +} + +async function escrowKey(seed) { + return subtle.importKey('raw', await derive(seed, 'prism/recovery/key/1', 32), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']); +} + +/** Where the escrow is kept: derived from the seed, revealing nothing about it. */ +export async function recoveryLocator(seed) { + return kappa({ kind: RECOVERY_KIND.locator, locator: toBase64Url(await derive(seed, 'prism/recovery/locator/1', 32)) }); +} + +// ---------------------------------------------------------------- making a code + +/** A device whose private keys can be sealed into an escrow. Used only for recovery. */ +async function createEscrowedDevice() { + const signing = await subtle.generateKey(SIGN, true, ['sign', 'verify']); + const agreement = await subtle.generateKey(AGREE, true, ['deriveBits']); + const record = { + kind: KIND.device, + sign: publicJwk(await subtle.exportKey('jwk', signing.publicKey)), + agree: publicJwk(await subtle.exportKey('jwk', agreement.publicKey)) + }; + return { id: await kappa(record), record, signingKey: signing.privateKey, agreementKey: agreement.privateKey }; +} + +/** Link `device` to the prism of `session`, entirely on this page: the ordinary link flow. */ +async function linkLocally(session, device, now) { + const { uri, pending } = await createLinkOffer(session, { now }); + const offer = parseLinkUri(uri); + const request = await requestLink(device, offer); + const accepted = await acceptLinkRequest(session, pending, request, { now }); + const joined = await completeLink(device, offer, accepted.response); + return { session: accepted.session, joined }; +} + +/** + * Make a recovery code for the prism of `session` (an active device). Links a + * new recovery device, then seals its private keys, the private boundary and + * the log in an escrow. Returns the code (show it once, store it nowhere), + * the escrow (keep it anywhere; its locator finds it) and the session with + * the recovery device's bind in its log. + */ +export async function createRecovery(session, { now }) { + const recoveryDevice = await createEscrowedDevice(); + const { session: next, joined } = await linkLocally(session, recoveryDevice, now); + const seed = random(32); + const sealed = { + kind: RECOVERY_KIND.sealed, + prism: next.prism, + device: recoveryDevice.record, + sign: toBase64Url(await subtle.exportKey('pkcs8', recoveryDevice.signingKey)), + agree: toBase64Url(await subtle.exportKey('pkcs8', recoveryDevice.agreementKey)), + boundary: toBase64Url(await subtle.exportKey('raw', joined.boundaryKey)), + records: [...joined.log.values()] + }; + const locator = await recoveryLocator(seed); + const iv = random(12); + const ciphertext = await subtle.encrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(locator) }, await escrowKey(seed), canonicalBytes(sealed)); + const escrow = { kind: RECOVERY_KIND.escrow, locator, iv: toBase64Url(iv), ciphertext: toBase64Url(ciphertext) }; + const code = await encodeCode(seed); + seed.fill(0); + return { code, escrow, device: recoveryDevice.id, session: next }; +} + +// ---------------------------------------------------------------- using a code + +/** Open an escrow with its code: the recovery device's session. */ +export async function openRecovery(code, escrow) { + const seed = await decodeCode(code); + const locator = await recoveryLocator(seed); + if (escrow?.kind !== RECOVERY_KIND.escrow || escrow.locator !== locator) refuse('escrow', 'the escrow is not this code\'s'); + let sealed; + try { + const bytes = await subtle.decrypt({ name: 'AES-GCM', iv: fromBase64Url(escrow.iv), additionalData: encoder.encode(locator) }, await escrowKey(seed), fromBase64Url(escrow.ciphertext)); + sealed = JSON.parse(decoder.decode(bytes)); + } catch (error) { + if (error instanceof PrismIdError) throw error; + refuse('escrow', 'the escrow does not open with this code'); + } finally { + seed.fill(0); + } + if (sealed?.kind !== RECOVERY_KIND.sealed) refuse('escrow', 'the escrow does not hold a recovery device'); + const device = { + id: await kappa(sealed.device), + record: sealed.device, + signingKey: await subtle.importKey('pkcs8', fromBase64Url(sealed.sign), SIGN, false, ['sign']), + agreementKey: await subtle.importKey('pkcs8', fromBase64Url(sealed.agree), AGREE, false, ['deriveBits']) + }; + const boundaryKey = await subtle.importKey('raw', fromBase64Url(sealed.boundary), { name: 'AES-GCM' }, true, ['encrypt', 'decrypt']); + const log = await logFromRecords(sealed.records); + await resolvePrism(sealed.prism, log); + return { prism: sealed.prism, device, boundaryKey, log }; +} + +/** + * Link `device` (this browser's own, non-extractable) to the prism with a + * recovery code. `log` may add records newer than the escrow's, from sync or + * any store; a recovery device revoked there cannot link anything. Returns the + * new device's session. + */ +export async function recoverOnto(code, escrow, device, { now, log } = {}) { + const recovery = await openRecovery(code, escrow); + if (log) { + for (const [k, v] of log) recovery.log.set(k, v); + } + const { joined } = await linkLocally(recovery, device, now); + return joined; +} diff --git a/tests/prism-recovery.test.js b/tests/prism-recovery.test.js new file mode 100644 index 0000000..7be4ed3 --- /dev/null +++ b/tests/prism-recovery.test.js @@ -0,0 +1,60 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + createPrism, createDevice, resolvePrism, revokeDevice, sealPrivate, openPrivate, PrismIdError, + createRecovery, openRecovery, recoverOnto, encodeCode, decodeCode, recoveryLocator, RECOVERY_KIND +} from '../src/prism-id.js'; + +const NOW = 1_800_000_000_000; +const refused = code => error => error instanceof PrismIdError && error.code === code; + +test('a recovery code is 56 Crockford characters that survive retyping', async () => { + const seed = crypto.getRandomValues(new Uint8Array(32)); + const code = await encodeCode(seed); + assert.match(code, /^([0-9A-HJKMNP-TV-Z]{4} ){13}[0-9A-HJKMNP-TV-Z]{4}$/); + assert.deepEqual(await decodeCode(code), seed); + assert.deepEqual(await decodeCode(code.toLowerCase().replace(/ /g, '-').replace(/1/g, 'l').replace(/0/g, 'o')), seed); + const typo = code.slice(0, 5) + (code[5] === 'A' ? 'B' : 'A') + code.slice(6); + await assert.rejects(decodeCode(typo), refused('code')); + await assert.rejects(decodeCode('0000 0000'), refused('code')); +}); + +test('a lost device: the code links a new device to the same prism, with its private boundary', async () => { + const lost = await createPrism(); + const secret = await sealPrivate(lost, { note: 'kept through the loss' }); + const made = await createRecovery(lost, { now: NOW }); + assert.equal(made.escrow.kind, RECOVERY_KIND.escrow); + assert.equal(made.escrow.locator, await recoveryLocator(await decodeCode(made.code))); + assert.ok(!JSON.stringify(made.escrow).includes(made.code.replace(/ /g, ''))); + assert.deepEqual((await resolvePrism(lost.prism, made.session.log)).active, [lost.device.id, made.device].sort()); + + const fresh = await createDevice(); + const joined = await recoverOnto(made.code, made.escrow, fresh, { now: NOW + 1000 }); + assert.equal(joined.prism, lost.prism); + const state = await resolvePrism(lost.prism, joined.log); + assert.ok(state.active.includes(fresh.id)); + assert.deepEqual(await openPrivate(joined, secret.sealed), { note: 'kept through the loss' }); + + // The new device takes the lost one out; the prism carries on. + const cleaned = await revokeDevice(joined, lost.device.id); + const after = await resolvePrism(lost.prism, cleaned.log); + assert.ok(!after.active.includes(lost.device.id)); + assert.ok(after.active.includes(fresh.id)); +}); + +test('an escrow opens only with its own code', async () => { + const session = await createPrism(); + const one = await createRecovery(session, { now: NOW }); + const two = await createRecovery(one.session, { now: NOW }); + await assert.rejects(openRecovery(one.code, two.escrow), refused('escrow')); + const tampered = { ...one.escrow, ciphertext: one.escrow.ciphertext.slice(0, -4) + 'AAAA' }; + await assert.rejects(openRecovery(one.code, tampered), refused('escrow')); + assert.equal((await openRecovery(one.code, one.escrow)).prism, session.prism); +}); + +test('a revoked recovery code links nothing', async () => { + const session = await createPrism(); + const made = await createRecovery(session, { now: NOW }); + const revoked = await revokeDevice(made.session, made.device); + await assert.rejects(recoverOnto(made.code, made.escrow, await createDevice(), { now: NOW, log: revoked.log }), refused('unauthorized')); +}); From b85ef0d157ee8ee79c01bcf5f488c5802279c571 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 22:33:00 +0000 Subject: [PATCH 2/5] feat(prism-id): recovery codes over escrowed recovery devices A recovery device (class recovery) is linked through the ordinary link flow; its keys, keyring and log are sealed under a key derived from a 56-char Crockford recovery code. recoverOnto links the new browser's own device; later rotations reach the recovery device as a member, so old codes keep opening newly sealed content. Revoked recovery devices link nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Asa3NdLCxdzL1iQw9rg5T --- docs/prism-id.md | 23 ++++- product/contracts.json | 12 ++- src/prism-id.js | 175 ++++++++++++++++++++++++++++++++++- tests/prism-recovery.test.js | 71 ++++++++++++++ 4 files changed, 275 insertions(+), 6 deletions(-) create mode 100644 tests/prism-recovery.test.js diff --git a/docs/prism-id.md b/docs/prism-id.md index 944d19b..c404bab 100644 --- a/docs/prism-id.md +++ b/docs/prism-id.md @@ -21,7 +21,7 @@ LexLean's `kappa` package and PrismPM ADR-017. It differs from the older | Kind | Signed by | Meaning | | --- | --- | --- | -| `prism/device/1` | none (public record) | A device's class (`browser`, `native`, `mobile`, `embedded`), its claimed key protection (`software`, `platform`, `secure-element`), and its P-256 signing and agreement public keys. Its kappa is the device id. Private keys are non-extractable. | +| `prism/device/1` | none (public record) | A device's class (`browser`, `native`, `mobile`, `embedded`, `recovery`), its claimed key protection (`software`, `platform`, `secure-element`), and its P-256 signing and agreement public keys. Its kappa is the device id. Private keys are non-extractable. | | `prism/genesis/1` | the first device | Creates the prism. prism id = kappa of this body. The first device is a member. | | `prism/bind/1` | an active member | Links a device as a `member` (no scope) or a `delegate` (a non-empty list of actions). | | `prism/revoke/1` | a linked member | Removes a device. `keep` lists the binds the revoked device made that stay valid. `epoch` and `wraps` carry a new private boundary key wrapped to each remaining member. | @@ -94,6 +94,27 @@ to its members (`Stitch.PrismId.boundaryShared`). A published boundary is public to all. `sealPrivate` and `openPrivate` keep content in the private boundary; the sealed object's kappa is its address. +## Recovery + +Recovery lives in `src/prism-id.js`. A recovery device is an ordinary `prism/device/1` of class `recovery`, +linked by the ordinary link flow, whose private keys live outside every +browser: sealed (AES-GCM) in a `prism/recovery-escrow/1` object under a key +derived (HKDF) from a 32-byte seed. The owner keeps the seed as a recovery +code: 56 Crockford base32 characters, the seed and three check bytes. The +escrow carries the recovery device's keys, every private boundary key it holds +and the log as it stood, so it alone restores the prism. It is public-safe ciphertext, +kept in any content-addressed store and found by its locator, the kappa of a +value derived from the seed. + +With the code, `recoverOnto` opens the escrow and links the new browser's own +non-extractable device to the prism, again through `createLinkOffer`, +`acceptLinkRequest` and `completeLink`, so `Stitch.PrismId` decides it like any +link (the page itself supplies the six-digit confirmation, since both ends are +its own). As a member, the recovery device receives the wrap of every later +rotation, so a code made before a revocation still opens what is sealed +after it. A recovery device revoked in a newer log links nothing. The new device +can then revoke the lost one. No rule is added to the model. + ## Sync over the substrate Linked devices sync on a topic derived from the private boundary key, so only diff --git a/product/contracts.json b/product/contracts.json index 5caa2a2..a31f5b0 100644 --- a/product/contracts.json +++ b/product/contracts.json @@ -1372,8 +1372,8 @@ "origin": "Project-owned source checkout", "licenseStatus": "Project declares MIT; audit applies", "redistributionCleared": true, - "bytes": 33707, - "sha256": "687a564565004eb22b5b7792f5a8ebc031a00ebbf43cbde0cab774b87ebd8da9" + "bytes": 42179, + "sha256": "eb176b04bf3181c8f868946d1338e83e9f510361a30dce37a750b32f3e7edd07" }, { "declaration": "assetProductExperience", @@ -2842,7 +2842,7 @@ }, { "path": "docs/prism-id.md", - "sha256": "eed334c69d3d7d4030bdf6947cd0664bfb35b7370a9d97c8594dbfd2db531127" + "sha256": "7de74e257abb675860df9a5bb543d175a7e0912db97e9e8a019789ab42751671" }, { "path": "docs/prism-model.md", @@ -3128,6 +3128,10 @@ "path": "tests/prism-id.test.js", "sha256": "f6d4a5a8f6c3e049acbdc6fdf42504bc065d8e3b520bca8d4f6dd08269a6c85b" }, + { + "path": "tests/prism-recovery.test.js", + "sha256": "848343b850bd11dd0cfed058a9156b8f7440d88676f5abbac5b74f9a7bfd0208" + }, { "path": "tests/product-experience.test.js", "sha256": "a519f9b5c014eada46bd6c016be966c7fbe6f84971ac9408185c89422f68439b" @@ -3197,5 +3201,5 @@ "sha256": "02263c2d4bf1a1913a673466554c19593b5a6c39b22a2da32ce4375675868347" } ], - "sourceDigest": "sha256:55e5fa9d5d39f0c2a75065eeff34190009f8e708dff569e1c1857f9e3b429635" + "sourceDigest": "sha256:d052bf56dcfa460f7788edb6141a5372aef1c7291cddbcca138e00f3e03ba8b1" } diff --git a/src/prism-id.js b/src/prism-id.js index 8da9d58..6ed6f72 100644 --- a/src/prism-id.js +++ b/src/prism-id.js @@ -40,7 +40,7 @@ export const KIND = Object.freeze({ }); /** Kinds of device that take part. Every one uses the same records and primitives. */ -export const DEVICE_CLASSES = Object.freeze(['browser', 'native', 'mobile', 'embedded']); +export const DEVICE_CLASSES = Object.freeze(['browser', 'native', 'mobile', 'embedded', 'recovery']); /** Where a device says its private keys live. Self-asserted unless an attestation verifier confirms it. */ export const KEY_PROTECTION = Object.freeze(['software', 'platform', 'secure-element']); /** member: full device of the prism. delegate: scoped device that never holds the private boundary. */ @@ -658,3 +658,176 @@ export function createMemoryBus() { } }; } + +// ---------------------------------------------------------------- recovery + +/** + * Recovery: a prism outlives every device it was made on. + * + * A recovery device is an ordinary prism device (prism/device/1), linked + * through the same out-of-band link flow as any other device, whose private + * keys are kept outside every browser: sealed in an escrow object under a + * key derived from a short recovery code the owner writes down. With the code + * and its escrow, any new device links itself to the prism, receives the + * private boundary, and carries on. Every authorization decision is still + * taken by Stitch.PrismId (bindAllowed, linkOfferAccepted, deviceMaySign) + * above; recovery adds no rule of its own. + * + * The code is the escrow key's 32-byte seed and three check bytes (the start + * of its SHA-256), in Crockford base32: 56 characters, written in groups of + * four. Readers ignore spaces, hyphens and case, read I and L as 1 and O as 0, + * and refuse a code whose check bytes differ. + * + * The escrow is public-safe: AES-GCM ciphertext bound to its locator. It can + * sit in any content-addressed store (its kappa is its address) and be found + * by its locator, which is derived from the seed and reveals nothing about it. + * It carries the log as it stood when the code was made, so recovery needs no + * other service; later records arrive by sync. + */ +export const RECOVERY_KIND = Object.freeze({ + escrow: 'prism/recovery-escrow/1', + sealed: 'prism/recovery/1', + locator: 'prism/recovery-locator/1' +}); + + +// ---------------------------------------------------------------- the code + +const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; + +export async function encodeCode(seed) { + if (!(seed instanceof Uint8Array) || seed.length !== 32) refuse('code', 'a recovery seed is 32 bytes'); + const bytes = [...seed, ...new Uint8Array(await subtle.digest('SHA-256', seed)).slice(0, 3)]; + const bits = bytes.map(b => b.toString(2).padStart(8, '0')).join(''); + const chars = bits.match(/.{5}/g).map(five => CROCKFORD[parseInt(five, 2)]).join(''); + return chars.match(/.{4}/g).join(' '); +} + +export async function decodeCode(text) { + const clean = String(text).toUpperCase().replace(/[\s-]/g, '').replace(/[IL]/g, '1').replace(/O/g, '0'); + if (!/^[0-9A-HJKMNP-TV-Z]{56}$/.test(clean)) refuse('code', 'a recovery code is 56 letters and digits'); + const bits = [...clean].map(c => CROCKFORD.indexOf(c).toString(2).padStart(5, '0')).join(''); + const bytes = Uint8Array.from(bits.match(/.{8}/g), byte => parseInt(byte, 2)); + const seed = bytes.slice(0, 32); + const check = new Uint8Array(await subtle.digest('SHA-256', seed)).slice(0, 3); + if (check.some((b, i) => b !== bytes[32 + i])) refuse('code', 'the recovery code has a typo'); + return seed; +} + +// ---------------------------------------------------------------- keys from the seed + +async function derive(seed, info, length) { + const material = await subtle.importKey('raw', seed, 'HKDF', false, ['deriveBits']); + return new Uint8Array(await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(32), info: encoder.encode(info) }, material, length * 8)); +} + +async function escrowKey(seed) { + return subtle.importKey('raw', await derive(seed, 'prism/recovery/key/1', 32), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']); +} + +/** Where the escrow is kept: derived from the seed, revealing nothing about it. */ +export async function recoveryLocator(seed) { + return kappa({ kind: RECOVERY_KIND.locator, locator: toBase64Url(await derive(seed, 'prism/recovery/locator/1', 32)) }); +} + +// ---------------------------------------------------------------- making a code + +/** A device whose private keys can be sealed into an escrow. Used only for recovery. */ +async function createEscrowedDevice() { + const signing = await subtle.generateKey(SIGN, true, ['sign', 'verify']); + const agreement = await subtle.generateKey(AGREE, true, ['deriveBits']); + const record = { + kind: KIND.device, + class: 'recovery', + protection: 'software', + sign: publicJwk(await subtle.exportKey('jwk', signing.publicKey)), + agree: publicJwk(await subtle.exportKey('jwk', agreement.publicKey)) + }; + return { id: await kappa(record), record, signingKey: signing.privateKey, agreementKey: agreement.privateKey }; +} + +/** Link `device` to the prism of `session`, entirely on this page: the ordinary link flow. */ +async function linkLocally(session, device, now) { + const { uri, pending } = await createLinkOffer(session, { now }); + const offer = parseLinkUri(uri); + const request = await requestLink(device, offer); + const confirmCode = await linkCode(offer.secret, device.record); + const accepted = await acceptLinkRequest(session, pending, request, { now, confirmCode }); + const joined = await completeLink(device, offer, accepted.response); + return { session: accepted.session, joined }; +} + +/** + * Make a recovery code for the prism of `session` (an active device). Links a + * new recovery device, then seals its private keys, every private boundary key + * it holds and the log in an escrow. Returns the code (show it once, store it nowhere), + * the escrow (keep it anywhere; its locator finds it) and the session with + * the recovery device's bind in its log. + */ +export async function createRecovery(session, { now }) { + const recoveryDevice = await createEscrowedDevice(); + const { session: next, joined } = await linkLocally(session, recoveryDevice, now); + const seed = random(32); + const sealed = { + kind: RECOVERY_KIND.sealed, + prism: next.prism, + device: recoveryDevice.record, + sign: toBase64Url(await subtle.exportKey('pkcs8', recoveryDevice.signingKey)), + agree: toBase64Url(await subtle.exportKey('pkcs8', recoveryDevice.agreementKey)), + keyring: toBase64Url(await exportKeyring(joined.keyring)), + records: [...joined.log.values()] + }; + const locator = await recoveryLocator(seed); + const iv = random(12); + const ciphertext = await subtle.encrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(locator) }, await escrowKey(seed), canonicalBytes(sealed)); + const escrow = { kind: RECOVERY_KIND.escrow, locator, iv: toBase64Url(iv), ciphertext: toBase64Url(ciphertext) }; + const code = await encodeCode(seed); + seed.fill(0); + return { code, escrow, device: recoveryDevice.id, session: next }; +} + +// ---------------------------------------------------------------- using a code + +/** Open an escrow with its code: the recovery device's session. */ +export async function openRecovery(code, escrow) { + const seed = await decodeCode(code); + const locator = await recoveryLocator(seed); + if (escrow?.kind !== RECOVERY_KIND.escrow || escrow.locator !== locator) refuse('escrow', 'the escrow is not this code\'s'); + let sealed; + try { + const bytes = await subtle.decrypt({ name: 'AES-GCM', iv: fromBase64Url(escrow.iv), additionalData: encoder.encode(locator) }, await escrowKey(seed), fromBase64Url(escrow.ciphertext)); + sealed = JSON.parse(decoder.decode(bytes)); + } catch (error) { + if (error instanceof PrismIdError) throw error; + refuse('escrow', 'the escrow does not open with this code'); + } finally { + seed.fill(0); + } + if (sealed?.kind !== RECOVERY_KIND.sealed) refuse('escrow', 'the escrow does not hold a recovery device'); + const device = { + id: await kappa(sealed.device), + record: sealed.device, + signingKey: await subtle.importKey('pkcs8', fromBase64Url(sealed.sign), SIGN, false, ['sign']), + agreementKey: await subtle.importKey('pkcs8', fromBase64Url(sealed.agree), AGREE, false, ['deriveBits']) + }; + const keyring = await importKeyring(fromBase64Url(sealed.keyring)); + const log = await logFromRecords(sealed.records); + await resolvePrism(sealed.prism, log); + return { prism: sealed.prism, device, keyring, log }; +} + +/** + * Link `device` (this browser's own, non-extractable) to the prism with a + * recovery code. `log` may add records newer than the escrow's, from sync or + * any store; a recovery device revoked there cannot link anything. Returns the + * new device's session. + */ +export async function recoverOnto(code, escrow, device, { now, log } = {}) { + const recovery = await openRecovery(code, escrow); + if (log) { + recovery.log = mergeLogs(recovery.log, log); + recovery.keyring = await absorbRekeys(recovery, await resolvePrism(recovery.prism, recovery.log)); + } + const { joined } = await linkLocally(recovery, device, now); + return joined; +} diff --git a/tests/prism-recovery.test.js b/tests/prism-recovery.test.js new file mode 100644 index 0000000..3392dbe --- /dev/null +++ b/tests/prism-recovery.test.js @@ -0,0 +1,71 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + createPrism, createDevice, resolvePrism, revokeDevice, sealPrivate, openPrivate, PrismIdError, + createRecovery, openRecovery, recoverOnto, encodeCode, decodeCode, recoveryLocator, RECOVERY_KIND +} from '../src/prism-id.js'; + +const NOW = 1_800_000_000_000; +const refused = code => error => error instanceof PrismIdError && error.code === code; + +test('a recovery code is 56 Crockford characters that survive retyping', async () => { + const seed = crypto.getRandomValues(new Uint8Array(32)); + const code = await encodeCode(seed); + assert.match(code, /^([0-9A-HJKMNP-TV-Z]{4} ){13}[0-9A-HJKMNP-TV-Z]{4}$/); + assert.deepEqual(await decodeCode(code), seed); + assert.deepEqual(await decodeCode(code.toLowerCase().replace(/ /g, '-').replace(/1/g, 'l').replace(/0/g, 'o')), seed); + const typo = code.slice(0, 5) + (code[5] === 'A' ? 'B' : 'A') + code.slice(6); + await assert.rejects(decodeCode(typo), refused('code')); + await assert.rejects(decodeCode('0000 0000'), refused('code')); +}); + +test('a lost device: the code links a new device to the same prism, with its private boundary', async () => { + const lost = await createPrism(); + const secret = await sealPrivate(lost, { note: 'kept through the loss' }); + const made = await createRecovery(lost, { now: NOW }); + assert.equal(made.escrow.kind, RECOVERY_KIND.escrow); + assert.equal(made.escrow.locator, await recoveryLocator(await decodeCode(made.code))); + assert.ok(!JSON.stringify(made.escrow).includes(made.code.replace(/ /g, ''))); + assert.deepEqual((await resolvePrism(lost.prism, made.session.log)).active, [lost.device.id, made.device].sort()); + + const fresh = await createDevice(); + const joined = await recoverOnto(made.code, made.escrow, fresh, { now: NOW + 1000 }); + assert.equal(joined.prism, lost.prism); + const state = await resolvePrism(lost.prism, joined.log); + assert.ok(state.active.includes(fresh.id)); + assert.deepEqual(await openPrivate(joined, secret.sealed), { note: 'kept through the loss' }); + + // The new device takes the lost one out; the prism carries on. + const cleaned = await revokeDevice(joined, lost.device.id); + const after = await resolvePrism(lost.prism, cleaned.log); + assert.ok(!after.active.includes(lost.device.id)); + assert.ok(after.active.includes(fresh.id)); +}); + +test('an escrow opens only with its own code', async () => { + const session = await createPrism(); + const one = await createRecovery(session, { now: NOW }); + const two = await createRecovery(one.session, { now: NOW }); + await assert.rejects(openRecovery(one.code, two.escrow), refused('escrow')); + const tampered = { ...one.escrow, ciphertext: one.escrow.ciphertext.slice(0, -4) + 'AAAA' }; + await assert.rejects(openRecovery(one.code, tampered), refused('escrow')); + assert.equal((await openRecovery(one.code, one.escrow)).prism, session.prism); +}); + +test('a revoked recovery code links nothing', async () => { + const session = await createPrism(); + const made = await createRecovery(session, { now: NOW }); + const revoked = await revokeDevice(made.session, made.device); + await assert.rejects(recoverOnto(made.code, made.escrow, await createDevice(), { now: NOW, log: revoked.log }), refused('unauthorized')); +}); + +test('a code made before a rotation still opens what was sealed after it', async () => { + const session = await createPrism(); + const other = await createRecovery(session, { now: NOW }); + const made = await createRecovery(other.session, { now: NOW }); + const rotated = await revokeDevice(made.session, other.device); + const later = await sealPrivate(rotated, { note: 'sealed under the new key' }); + const joined = await recoverOnto(made.code, made.escrow, await createDevice(), { now: NOW, log: rotated.log }); + assert.deepEqual(await openPrivate(joined, later.sealed), { note: 'sealed under the new key' }); + await assert.rejects(recoverOnto(other.code, other.escrow, await createDevice(), { now: NOW, log: rotated.log }), refused('unauthorized')); +}); From 78159ba712d33a9c94266967099da2c2899295f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 22:35:56 +0000 Subject: [PATCH 3/5] fix(prism-id): a copied genesis cannot make a log unresolvable ECDSA signatures are malleable and envelopes are keyed by their own kappa, so anyone could add a second genesis envelope for a prism (same body, other signature) and resolvePrism refused every log that held both. Resolution now takes any genesis of the prism whose signature verifies. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Asa3NdLCxdzL1iQw9rg5T --- product/contracts.json | 8 ++++---- src/prism-id.js | 14 +++++++++----- tests/prism-recovery.test.js | 9 +++++++++ 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/product/contracts.json b/product/contracts.json index a31f5b0..af07b5f 100644 --- a/product/contracts.json +++ b/product/contracts.json @@ -1372,8 +1372,8 @@ "origin": "Project-owned source checkout", "licenseStatus": "Project declares MIT; audit applies", "redistributionCleared": true, - "bytes": 42179, - "sha256": "eb176b04bf3181c8f868946d1338e83e9f510361a30dce37a750b32f3e7edd07" + "bytes": 42350, + "sha256": "9cce41fa322f9fcffa9292de3ddc5ea7e0aa614ba4357d10f24872d5fe2884a7" }, { "declaration": "assetProductExperience", @@ -3130,7 +3130,7 @@ }, { "path": "tests/prism-recovery.test.js", - "sha256": "848343b850bd11dd0cfed058a9156b8f7440d88676f5abbac5b74f9a7bfd0208" + "sha256": "2af0887f0f258a3bc4793d350f07c7fa4b0851d2dda5fbcaa2bb4da242ef063e" }, { "path": "tests/product-experience.test.js", @@ -3201,5 +3201,5 @@ "sha256": "02263c2d4bf1a1913a673466554c19593b5a6c39b22a2da32ce4375675868347" } ], - "sourceDigest": "sha256:d052bf56dcfa460f7788edb6141a5372aef1c7291cddbcca138e00f3e03ba8b1" + "sourceDigest": "sha256:9199326643b6f6863f4e350c1e38446bb693afa6e62360d13588d5913fe2d624" } diff --git a/src/prism-id.js b/src/prism-id.js index 6ed6f72..3e4d9de 100644 --- a/src/prism-id.js +++ b/src/prism-id.js @@ -232,11 +232,15 @@ function bindShape(body) { */ export async function resolvePrism(prism, log) { const entries = [...log.entries()].sort(byKey); - const geneses = []; - for (const [, e] of entries) if (e?.body?.kind === KIND.genesis && await kappa(e.body) === prism) geneses.push(e); - if (geneses.length !== 1) refuse('genesis', 'the log does not hold exactly one genesis for this prism'); - const genesis = geneses[0]; - if (!await signatureValid(genesis, genesis.body.device)) refuse('genesis', 'genesis signature does not verify'); + // Every genesis of this prism has the same body (its kappa is the prism); + // envelopes differ only by signature encoding (ECDSA signatures are + // malleable), so any one that verifies is the genesis. A copy with a bad + // signature cannot make the log unresolvable. + let genesis = null; + for (const [, e] of entries) { + if (e?.body?.kind === KIND.genesis && await kappa(e.body) === prism && await signatureValid(e, e.body.device)) { genesis = e; break; } + } + if (!genesis) refuse('genesis', 'the log holds no genesis of this prism that verifies'); const devices = new Map([[genesis.signer, genesis.body.device]]); const binds = [], revokes = []; diff --git a/tests/prism-recovery.test.js b/tests/prism-recovery.test.js index 3392dbe..5a32458 100644 --- a/tests/prism-recovery.test.js +++ b/tests/prism-recovery.test.js @@ -69,3 +69,12 @@ test('a code made before a rotation still opens what was sealed after it', async assert.deepEqual(await openPrivate(joined, later.sealed), { note: 'sealed under the new key' }); await assert.rejects(recoverOnto(other.code, other.escrow, await createDevice(), { now: NOW, log: rotated.log }), refused('unauthorized')); }); + +test('a copied genesis with another signature cannot make the log unresolvable', async () => { + const session = await createPrism(); + const [genesis] = session.log.values(); + const forged = { ...genesis, signature: genesis.signature.slice(0, -4) + 'AAAA' }; + const log = new Map([...session.log, ['forged', forged]]); + assert.deepEqual((await resolvePrism(session.prism, log)).active, [session.device.id]); + await assert.rejects(resolvePrism(session.prism, new Map([['forged', forged]])), refused('genesis')); +}); From 216e38c84f45708e2a7acf409e53705d7220133b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:00:28 +0000 Subject: [PATCH 4/5] feat(prism-id): a substrate bus on stitch's relay, and copied geneses resolve - createRelayBus implements the prism bus contract (publish, subscribe) on stitch's own transport: the warm relay with stitch's relay framing across devices and origins, BroadcastChannel within one origin. The relay topic is a domain-separated hash of the prism topic (at most 64 characters), every message names its prism topic, a subscriber delivers only that topic, and a bus never hears itself. subscribe first delivers what the relay still holds (the warm lifetime), then live messages; fetch returns what it holds. Effects (fetch, WebSocket, BroadcastChannel) are injectable. - resolvePrism takes any genesis of the prism whose signature verifies. ECDSA signatures are malleable and envelopes are keyed by their own kappa, so a second genesis envelope (same body, other signature) made every log that held both unresolvable. tests/prism-bus.test.js: framing and hashed topics over an ntfy-shaped relay, a multi-frame message, two devices linking over the rendezvous topic with the six-digit code then syncing a removal, and the copied genesis. npm test 445 of 446; the one failure (source-authoring, prism-code axioms.mjs missing in this checkout) fails identically on the base commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Asa3NdLCxdzL1iQw9rg5T --- docs/prism-id.md | 12 ++- product/contracts.json | 12 ++- src/prism-id.js | 157 ++++++++++++++++++++++++++++++++++++++-- tests/prism-bus.test.js | 133 ++++++++++++++++++++++++++++++++++ 4 files changed, 302 insertions(+), 12 deletions(-) create mode 100644 tests/prism-bus.test.js diff --git a/docs/prism-id.md b/docs/prism-id.md index 3c65630..c32447b 100644 --- a/docs/prism-id.md +++ b/docs/prism-id.md @@ -7,7 +7,7 @@ account, password, email, OAuth provider or server is involved. - Model: `app/src/Stitch/PrismId.lex.tex` (`Stitch.PrismId`). Every authorization decision in the runtime calls its generated binding. - Runtime: `src/prism-id.js`. -- Tests: `tests/prism-id.test.js`. +- Tests: `tests/prism-id.test.js`; the substrate bus, `tests/prism-bus.test.js`. ## Kappa @@ -150,7 +150,13 @@ they can find it. Each message is the log and the persona logs, sealed in the private boundary, bound to the prism id, and padded (ISO 7816-4) to a power-of-two bucket of at least 1 KiB so relays learn only the bucket. Messages over 4 MiB and logs over 4096 records are refused before any parsing or signature work. The bus contract is `publish(topic, bytes)` and -`subscribe(topic, fn)`. `createMemoryBus` implements it for tests; the stitch -substrate implements it across peers and federation nodes. +`subscribe(topic, fn)`. `createMemoryBus` implements it for tests. +`createRelayBus` implements it on stitch's substrate: +stitch's warm relay with its relay framing across devices and origins, and +BroadcastChannel within one origin. The relay sees a name hashed from the +prism topic and the sealed or HMAC-bound bytes; it holds a message for the +warm lifetime (30 minutes) and promises no retention, so a device that was +away longer catches up from the next message another member publishes. Link +offers use the same bus on their `prism-rendezvous:` topic. The threat and security model is in `docs/prism-id-threat-model.md`. diff --git a/product/contracts.json b/product/contracts.json index 9b4cb8e..e481e8f 100644 --- a/product/contracts.json +++ b/product/contracts.json @@ -1372,8 +1372,8 @@ "origin": "Project-owned source checkout", "licenseStatus": "Project declares MIT; audit applies", "redistributionCleared": true, - "bytes": 62758, - "sha256": "7a581a7ae1828cace37a16376691370cfafff06ebbec1a59bb16844eac5d219a" + "bytes": 69165, + "sha256": "556e725270602f5706a61d5682fe5fdb50aa699c174a19d5cd900db09b719b74" }, { "declaration": "assetProductExperience", @@ -2842,7 +2842,7 @@ }, { "path": "docs/prism-id.md", - "sha256": "7c5c769aa1193e7adf04a5feefa39cefcae99c6a4fb63eed5bcf95d123289009" + "sha256": "7fedacc15e26bb53ff16241601c2f13aa930f254b2170699e07cd43cd8fcfb34" }, { "path": "docs/prism-model.md", @@ -3124,6 +3124,10 @@ "path": "tests/primitive-operations.test.js", "sha256": "e3c00e18d47db0de4dd19bffeba1edcb58f82b106f8f66d429a725248ec14a98" }, + { + "path": "tests/prism-bus.test.js", + "sha256": "38c294c072ad7067818252c0be0e1fcbc67cb4e4dded921aa9977b05acea05ac" + }, { "path": "tests/prism-id.test.js", "sha256": "1536964878588a95439d68c747318a7939302c973f8401db8aed8eb83dd375ad" @@ -3197,5 +3201,5 @@ "sha256": "02263c2d4bf1a1913a673466554c19593b5a6c39b22a2da32ce4375675868347" } ], - "sourceDigest": "sha256:b0b3527236eee1ff0f3b3bfac474da968b2a44a316c7d7d26621f819c4f18921" + "sourceDigest": "sha256:9c584ab5955b72e4d840fef570b766808b1846f23a22e93f0eaf8252cb489693" } diff --git a/src/prism-id.js b/src/prism-id.js index 9a39756..37d641b 100644 --- a/src/prism-id.js +++ b/src/prism-id.js @@ -18,6 +18,8 @@ * See docs/prism-id.md and docs/prism-id-threat-model.md. */ import { model } from './layer1-uor/generated-model.js'; +import { RELAY_EVENT_BYTES, RELAY_LIFETIMES, RelayReassembler, frameRelayMessage, newRelaySession, relayChannel, snapshotRelayMessage } + from './layer5-transport/relay-framing.js'; const subtle = globalThis.crypto.subtle; const encoder = new TextEncoder(); @@ -384,11 +386,15 @@ function bindShape(body) { */ export async function resolvePrism(prism, log) { const entries = [...log.entries()].sort(byKey); - const geneses = []; - for (const [, e] of entries) if (e?.body?.kind === KIND.genesis && await kappa(e.body) === prism) geneses.push(e); - if (geneses.length !== 1) refuse('genesis', 'the log does not hold exactly one genesis for this prism'); - const genesis = geneses[0]; - if (!await signatureValid(genesis, genesis.body.device)) refuse('genesis', 'genesis signature does not verify'); + // Every genesis of this prism has the same body (its kappa is the prism); + // envelopes differ only by signature encoding (ECDSA signatures are + // malleable), so any one that verifies is the genesis. A copy with a bad + // signature cannot make the log unresolvable. + let genesis = null; + for (const [, e] of entries) { + if (e?.body?.kind === KIND.genesis && await kappa(e.body) === prism && await signatureValid(e, e.body.device)) { genesis = e; break; } + } + if (!genesis) refuse('genesis', 'the log holds no genesis of this prism that verifies'); const devices = new Map([[genesis.signer, genesis.body.device]]); const binds = [], revokes = []; @@ -1176,3 +1182,144 @@ export function createMemoryBus() { } }; } + +// ---------------------------------------------------------------- the substrate bus + +/* + * The bus contract above on stitch's own transport, so a prism needs no + * server of its own: + * + * - Across devices and origins: stitch's warm relay (ntfy, with stitch's relay + * framing, docs/relay-framing.md). The relay topic is hashed from the prism + * topic, which only holders of the secret can derive, so the relay sees an + * opaque name and sealed or HMAC-bound bytes. A message stays fetchable for + * the warm lifetime (30 minutes); the relay promises no retention. + * - In one origin: BroadcastChannel, so tabs of one app hear each other at once. + * + * Every message carries its prism topic, a subscriber delivers only messages + * for the topic it asked for, and a bus never hears itself. Bytes are + * delivered as received; receiveSync and completeLink check every one. + */ +const BUS_KIND = 'prism/bus/1'; +const BUS_TOPIC = /^prism-[a-z]+:[0-9a-f]{64}$/; +const WARM_SINCE = `${Math.floor(RELAY_LIFETIMES.warm / 60000)}m`; +const POLL_BYTES = 2 * 1024 * 1024; + +function checkBusTopic(topic) { + if (typeof topic !== 'string' || !BUS_TOPIC.test(topic)) throw new TypeError('not a prism topic'); + return topic; +} + +/** The relay's name for a prism topic: a domain-separated hash, at most 64 characters as ntfy requires. */ +export async function relayTopic(topic) { + return 'prism-' + (await relayChannel(checkBusTopic(topic))).slice(7, 65); +} + +/** + * The bus. `relay` is the warm relay's base URL; `relay: null` keeps the bus + * in this origin. Effects are injectable for tests and other hosts. + */ +export function createRelayBus({ + relay = 'https://ntfy.sh', + fetch: fetchImpl = globalThis.fetch?.bind(globalThis), + WebSocket: Socket = globalThis.WebSocket, + BroadcastChannel: Channel = globalThis.BroadcastChannel +} = {}) { + const from = newRelaySession(); + const wsBase = relay && relay.replace(/^http/, 'ws'); + const channels = new Map(); + const local = topic => { + if (!Channel) return null; + if (!channels.has(topic)) channels.set(topic, new Channel(`stitch:${topic}`)); + return channels.get(topic); + }; + const envelope = (topic, bytes) => ({ kind: BUS_KIND, from, topic, bytes: toBase64Url(bytes) }); + // A message for this topic from another bus, or null. + const unwrap = (topic, value) => value?.kind === BUS_KIND && value.topic === topic && value.from !== from && typeof value.bytes === 'string' + ? fromBase64Url(value.bytes) : null; + const assembler = topic => new RelayReassembler({ channelKey: topic, scope: 'warm' }); + // One bounded line of ntfy's JSON stream: a framed stitch message, or nothing. + const frameOf = line => { + if (typeof line !== 'string' || !line || line.length > RELAY_EVENT_BYTES) return null; + const event = JSON.parse(line); + return event.event === 'message' && typeof event.message === 'string' && !event.attachment ? event.message : null; + }; + + /** Resolves true when every frame was acknowledged by the relay (or there is no relay). Not a delivery receipt. */ + async function publish(topic, bytes) { + checkBusTopic(topic); + const value = envelope(topic, bytes); + local(topic)?.postMessage(value); + if (!relay || !fetchImpl) return true; + const snapshot = snapshotRelayMessage(value); + const { frames } = await frameRelayMessage(snapshot, { channelKey: topic, session: from, scope: 'warm' }); + const url = `${relay}/${await relayTopic(topic)}`; + for (const body of frames) { + const response = await fetchImpl(url, { method: 'POST', body, headers: { 'Content-Type': 'text/plain; charset=utf-8', Cache: 'yes' } }); + if (!response.ok) return false; + } + return true; + } + + /** The messages other buses left on the relay for a topic within the warm lifetime, oldest first. */ + async function fetchTopic(topic) { + checkBusTopic(topic); + if (!relay || !fetchImpl) return []; + const response = await fetchImpl(`${relay}/${await relayTopic(topic)}/json?poll=1&since=${WARM_SINCE}`); + if (!response.ok) return []; + const text = await response.text(); + if (text.length > POLL_BYTES) return []; + const reassembler = assembler(topic), out = []; + try { + for (const line of text.split('\n')) { + try { + const frame = frameOf(line); + const message = frame && unwrap(topic, await reassembler.accept(frame)); + if (message) out.push(message); + } catch { /* a refused frame is skipped; the others still count */ } + } + } finally { reassembler.dispose(); } + return out; + } + + /** + * Calls fn(bytes) for each message on the topic: those the relay still + * holds, then new ones from the relay and from this origin. Returns a + * function that stops it. A failing fn does not stop the subscription. + */ + function subscribe(topic, fn) { + checkBusTopic(topic); + let open = true, socket = null, reassembler = null; + const deliver = bytes => { if (open && bytes) Promise.resolve().then(() => fn(bytes)).catch(() => {}); }; + const channel = local(topic); + const onLocal = event => deliver(unwrap(topic, event.data)); + channel?.addEventListener('message', onLocal); + if (relay && fetchImpl) fetchTopic(topic).then(list => list.forEach(deliver), () => {}); + if (relay && Socket) { + reassembler = assembler(topic); + relayTopic(topic).then(name => { + if (!open) return; + socket = new Socket(`${wsBase}/${name}/ws`); + socket.onmessage = async event => { + try { + const frame = frameOf(event.data); + deliver(frame && unwrap(topic, await reassembler.accept(frame))); + } catch { /* a refused frame is skipped */ } + }; + }, () => {}); + } + return () => { + open = false; + channel?.removeEventListener('message', onLocal); + socket?.close(); + reassembler?.dispose(); + }; + } + + function close() { + for (const channel of channels.values()) channel.close(); + channels.clear(); + } + + return { publish, subscribe, fetch: fetchTopic, close }; +} diff --git a/tests/prism-bus.test.js b/tests/prism-bus.test.js new file mode 100644 index 0000000..5930af0 --- /dev/null +++ b/tests/prism-bus.test.js @@ -0,0 +1,133 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + createPrism, createDevice, resolvePrism, revokeDevice, createLinkOffer, parseLinkUri, requestLink, acceptLinkRequest, + completeLink, rendezvousTopic, linkCode, currentBoundary, syncTopic, publishSync, receiveSync, signAction, verifyAction, PrismIdError, + createRelayBus, relayTopic +} from '../src/prism-id.js'; + +const HOST = 'https://foundry.uor.foundation'; +const json = value => new TextEncoder().encode(JSON.stringify(value)); +const parse = bytes => JSON.parse(new TextDecoder().decode(bytes)); +const refused = code => error => error instanceof PrismIdError && error.code === code; +const settle = () => new Promise(resolve => setTimeout(resolve, 20)); + +/** An ntfy-shaped relay in memory: POST keeps a message, GET ?poll=1 lists them, a socket hears new ones. */ +function fakeRelay() { + const topics = new Map(), sockets = new Set(), posted = []; + const lines = name => topics.get(name) ?? []; + async function fetch(url, init = {}) { + const { pathname } = new URL(url); + const name = pathname.split('/')[1]; + if (init.method === 'POST') { + posted.push({ name, body: init.body }); + topics.set(name, [...lines(name), init.body]); + for (const socket of sockets) if (socket.name === name) socket.onmessage?.({ data: JSON.stringify({ event: 'message', message: init.body }) }); + return { ok: true, status: 200 }; + } + const body = lines(name).map(message => JSON.stringify({ event: 'message', message })).join('\n'); + return { ok: true, status: 200, text: async () => body }; + } + class WebSocket { + constructor(url) { this.name = new URL(url).pathname.split('/')[1]; sockets.add(this); } + close() { sockets.delete(this); } + } + return { fetch, WebSocket, posted, sockets }; +} + +const bus = relay => createRelayBus({ relay: 'https://relay.test', fetch: relay.fetch, WebSocket: relay.WebSocket, BroadcastChannel: null }); + +test('the relay sees a hashed topic and the framed bytes; another bus gets them, live and from what the relay holds', async () => { + const relay = fakeRelay(); + const a = bus(relay), b = bus(relay); + const topic = 'prism-sync:' + 'ab'.repeat(32); + const live = []; + const stop = b.subscribe(topic, bytes => live.push(parse(bytes))); + await settle(); + assert.equal(await a.publish(topic, json({ n: 1 })), true); + await settle(); + assert.deepEqual(live, [{ n: 1 }]); + assert.equal(relay.posted[0].name, await relayTopic(topic)); + assert.ok(!relay.posted[0].name.includes('ab'.repeat(8)) && relay.posted[0].name.length <= 64); + // Later, and only for this topic: what the relay still holds. + assert.deepEqual((await b.fetch(topic)).map(parse), [{ n: 1 }]); + assert.deepEqual(await b.fetch('prism-sync:' + 'cd'.repeat(32)), []); + // A bus never hears itself. + assert.deepEqual(await a.fetch(topic), []); + stop(); + assert.equal(relay.sockets.size, 0); + assert.throws(() => a.subscribe('not-a-topic', () => {}), TypeError); +}); + +test('a message larger than one relay frame arrives whole', async () => { + const relay = fakeRelay(); + const big = new Uint8Array(40000).map((_, i) => i % 251); + await bus(relay).publish('prism-sync:' + '01'.repeat(32), big); + assert.ok(relay.posted.length > 1); + const [got] = await bus(relay).fetch('prism-sync:' + '01'.repeat(32)); + assert.deepEqual(got, big); +}); + +test('two devices link over the relay, with the six-digit code, and then sync a removal', async () => { + const relay = fakeRelay(); + const now = Date.now(); + // The person's first device, and the browser they want to add. + let first = await createPrism(); + const firstBus = bus(relay), newBus = bus(relay); + const { uri, pending } = await createLinkOffer(first, { now }); + const joining = await createDevice(); + + // Out of band: the new device reads the offer (QR code or pasted text) and answers on the rendezvous topic. + const offer = parseLinkUri(uri); + const topic = await rendezvousTopic(offer.secret); + const requests = []; + const stopFirst = firstBus.subscribe(topic, bytes => requests.push(parse(bytes))); + const responses = []; + const stopNew = newBus.subscribe(topic, bytes => responses.push(parse(bytes))); + await settle(); + await newBus.publish(topic, json(await requestLink(joining, offer))); + await settle(); + assert.equal(requests.length, 1); + + // Both screens show the same code; the person confirms it on the first device. + const code = await linkCode(offer.secret, joining.record); + const accepted = await acceptLinkRequest(first, pending, requests[0], { now: now + 1000, confirmCode: code }); + first = accepted.session; + await firstBus.publish(topic, json(accepted.response)); + await settle(); + const second = await completeLink(joining, offer, responses[0]); + stopFirst(); stopNew(); + assert.equal(second.prism, first.prism); + + // The same prism id signs in from the new device. + const signed = await signAction(second, 'prism/session/1', { app: 1 }, { now: now + 2000, audience: HOST }); + await verifyAction(second.prism, second.log, signed, { audience: HOST, now: now + 2000 }); + + // The first device removes a lost device; the second hears it on the sync topic. + const lost = await createDevice(); + const linkedLost = await createLinkOffer(first, { now }); + const lostRequest = await requestLink(lost, parseLinkUri(linkedLost.uri)); + first = (await acceptLinkRequest(first, linkedLost.pending, lostRequest, { now: now + 1000, + confirmCode: await linkCode(parseLinkUri(linkedLost.uri).secret, lost.record) })).session; + const { keyId: before } = await currentBoundary(first); + first = await revokeDevice(first, lost.id); + // After a rotation, once under the previous key too: the second device still listens there. + await publishSync(first, firstBus); + await publishSync(first, firstBus, { keyId: before }); + let synced = second; + for (const bytes of await bus(relay).fetch(await syncTopic(second))) { + try { synced = await receiveSync(synced, bytes); } catch (error) { if (!(error instanceof PrismIdError)) throw error; } + } + const state = await resolvePrism(synced.prism, synced.log); + assert.ok(state.revoked.includes(lost.id)); + assert.ok(state.active.includes(joining.id)); +}); + +test('a copied genesis with another signature cannot make the log unresolvable', async () => { + const session = await createPrism(); + const [genesis] = session.log.values(); + const forged = { ...genesis, signature: genesis.signature.slice(0, -4) + 'AAAA' }; + const log = new Map([...session.log, ['forged', forged]]); + assert.deepEqual((await resolvePrism(session.prism, log)).active, [session.device.id]); + await assert.rejects(resolvePrism(session.prism, new Map([['forged', forged]])), refused('genesis')); +}); From 7c0ccebfa00e5c09e135901be4c9fad149d1b420 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 06:37:19 +0000 Subject: [PATCH 5/5] feat(prism-id): QR codes for link offers, a public log hosts hear revocations from, refreshing cadence linkQr(uri) encodes a prism-link URI as an ISO/IEC 18004 QR code (byte mode, level M, smallest version, lowest-penalty mask) and returns {size, modules}. Checked against jsQR 1.4.0 over versions 1 to 38; the test pins one vector's module digest and the finder patterns. logTopic(prism) is a public topic derived from the prism id alone. publishLog puts the signed public records there; heardLog merges what the bus retains on it, skipping other prisms, oversize and malformed messages. verifyAction takes { bus } and merges heardLog first, so a removed device that never syncs is refused once another device published its removal. createSyncCadence({ refresh }) sends a real sync and the public log every refresh ticks, so the warm relay (30 minutes) keeps a recent copy while any member is online. docs/prism-id.md documents all three and lists what stays open (a replayed old recovery, retention when every member is offline). The threat model is left unchanged so the retained proof evidence holds; product/contracts.json rebinds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Asa3NdLCxdzL1iQw9rg5T --- docs/prism-id.md | 50 ++++++- product/contracts.json | 10 +- src/prism-id.js | 284 +++++++++++++++++++++++++++++++++++++++- tests/prism-bus.test.js | 70 +++++++++- 4 files changed, 397 insertions(+), 17 deletions(-) diff --git a/docs/prism-id.md b/docs/prism-id.md index 4e2226d..163af57 100644 --- a/docs/prism-id.md +++ b/docs/prism-id.md @@ -72,7 +72,10 @@ A native implementation checks itself against `tests/fixtures/prism-id-vectors.j unwraps the keyring if it is a member, and holds the full log. The offer URI is plain text, so any channel works: a QR code, NFC, a USB or -serial provisioning line, or typed text. +serial provisioning line, or typed text. `linkQr(uri)` gives its QR code +(ISO/IEC 18004, byte mode, level M, the smallest version and the mask with the +lowest penalty) as `{ size, modules }`, `modules[y][x]` true for dark; a host +draws it with a four-module quiet zone. ## Revocation rotates the private boundary @@ -150,6 +153,14 @@ device inside its scope (`Stitch.PrismId.actionAllowed`). This is how foundry grants a stakeholder the permissions of their prism context. Hosts are given the persona for their audience, not the main prism. +A host also hears revocations the signing device does not present. Every +prism has a public log topic (`logTopic(prism)`, derived from the prism id +alone) where devices publish the signed public records (`publishLog`) after a +bind or revocation and on the refresh cadence. `verifyAction(..., { bus })` +merges what that topic retains (`heardLog`) before deciding, so a stolen +device that never syncs is refused once any other device has published its +removal. Only signed records count, so anything else on the topic is ignored. + ## Actions the person approves A host can require the person's approval for chosen actions: @@ -181,7 +192,10 @@ power-of-two bucket of at least 1 KiB so relays learn only the bucket. `createSyncCadence` goes further: called on a fixed timer, its `tick` sends a pending sync or else a cover message (`publishCover`) padded to the same bucket, so relays see one message of one size per interval either way. -Receivers ignore cover messages. Messages over 4 MiB and logs over 4096 records are refused +Receivers ignore cover messages. With `refresh: n`, every n-th tick sends a +real sync and the public log even when nothing changed, so a substrate that +keeps messages only for a while always holds a recent one while any member +is online. Messages over 4 MiB and logs over 4096 records are refused before any parsing or signature work. The bus contract is `publish(topic, bytes)` and `subscribe(topic, fn)`, and `retained(topic)` returns the messages the substrate kept for that topic, which offline devices and recovery read. @@ -189,9 +203,35 @@ substrate kept for that topic, which offline devices and recovery read. stitch's substrate: stitch's warm relay with its relay framing across devices and origins, and BroadcastChannel within one origin. The relay sees a name hashed from the prism topic and the sealed or HMAC-bound bytes. It retains a -message for the warm lifetime (30 minutes) and promises nothing longer, so a -device away longer, or a log-free recovery after that window, catches up only -from the next message another member publishes. Link offers use the same bus +message for the warm lifetime (30 minutes) and promises nothing longer; a +cadence whose refresh is shorter keeps a recent sync there while a member is +online. A device away longer, or a log-free recovery after every member has +been offline that long, catches up only from the next message a member +publishes. Link offers use the same bus on their `prism-rendezvous:` topic. The threat and security model is in `docs/prism-id-threat-model.md`. + +## Open + +These belong in the threat model's residuals (section 10) and designs +(section 12) when its next revision is attested; they are kept here so that +change does not invalidate the retained proof evidence. + +- **A replayed old recovery.** Recovery replaces its recovery device, but the + old shares still combine. Run against a log from before that recovery, they + bind a second recovery device and members of their own; merged with the + current log, the prism has two active recovery devices. Set union has no + order, so no rule on the log alone tells the replay from the real recovery. + Every device and host that merges the logs sees both (the public log topic + carries them), and the Foundry frame refuses a recovery that shows another + active recovery device. Design: order recoveries by the witnessed time of + threat-model D4, so a recovery device's binds after its replacement was + witnessed count for nothing (`recoveryBindCounts(replacedWitnessedAt, bindWitnessedAt)`). +- **Retention when every member is offline.** The refresh cadence keeps a + recent sync and public log on the warm relay while a member is online. After + every member has been offline longer than the relay keeps messages, log-free + recovery and hosts wait for the next publish, until a colder tier of the + substrate retains them. +- **Hosts that do not read the public log** hear a removal only from the log + the signing device presents (threat-model G1 2a). diff --git a/product/contracts.json b/product/contracts.json index 1bfff43..09036fe 100644 --- a/product/contracts.json +++ b/product/contracts.json @@ -1372,8 +1372,8 @@ "origin": "Project-owned source checkout", "licenseStatus": "Project declares MIT; audit applies", "redistributionCleared": true, - "bytes": 82867, - "sha256": "00ece32b01c21bb7c3793ebb645e2ff0cf2a7f06a785dc459ccf8f0ce7fb70b8" + "bytes": 94894, + "sha256": "eefc04c53d581308dee9033384050616849ef93996e8cb7858cd1435934b16d7" }, { "declaration": "assetProductExperience", @@ -2842,7 +2842,7 @@ }, { "path": "docs/prism-id.md", - "sha256": "c85da2a3c70d10bb653189d2c2d401441ac7d8f8d577f1565726f0e0e097260b" + "sha256": "bd27711d3dcbaef87a013a44127affc605343b3867b3d037e09079e7d5386612" }, { "path": "docs/prism-model.md", @@ -3126,7 +3126,7 @@ }, { "path": "tests/prism-bus.test.js", - "sha256": "c2ce6296b6b0537f5bd73edad89c163c16ef0eb59aab72fac03c8d49ca5a82c5" + "sha256": "37d02bfcf831de90c9651f84f95a6fa745a3605bbb449ec242a27530a0c50dde" }, { "path": "tests/prism-id.test.js", @@ -3201,5 +3201,5 @@ "sha256": "02263c2d4bf1a1913a673466554c19593b5a6c39b22a2da32ce4375675868347" } ], - "sourceDigest": "sha256:366ed4e0dcab4a7017bb6ad64ad7cd7127e9604682adc124132ce63bd4846723" + "sourceDigest": "sha256:ee763415941e91dd262b72a8176388aa693156d38d88e1fc5fbb23cf29d96fcd" } diff --git a/src/prism-id.js b/src/prism-id.js index 95d8dc6..c9ce692 100644 --- a/src/prism-id.js +++ b/src/prism-id.js @@ -48,7 +48,8 @@ export const KIND = Object.freeze({ persona: 'prism/persona/1', personaKey: 'prism/persona-key/1', personaRecovery: 'prism/persona-recovery/1', - cover: 'prism/cover/1' + cover: 'prism/cover/1', + publicLog: 'prism/public-log/1' }); /** Kinds of device that take part. Every one uses the same records and primitives. */ @@ -685,6 +686,218 @@ export function parseLinkUri(uri) { return offer; } +/** + * The QR code for a link offer (ISO/IEC 18004: byte mode, error correction + * level M, the smallest version that holds it, the mask with the lowest + * penalty). Returns `{ size, modules }`, where `modules[y][x]` is true for a + * dark module; draw it with a quiet zone of four modules. A host renders it + * however it likes; the person scans it on the new device (TB2). + */ +export function linkQr(uri) { + parseLinkUri(uri); + return qrEncode(encoder.encode(uri)); +} + +// Error correction codewords per block and blocks, level M, versions 1 to 40. +const QR_ECC_M = [0, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28]; +const QR_BLOCKS_M = [0, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49]; +const QR_MASKS = [ + (x, y) => (x + y) % 2 === 0, (x, y) => y % 2 === 0, x => x % 3 === 0, (x, y) => (x + y) % 3 === 0, + (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0, (x, y) => x * y % 2 + x * y % 3 === 0, + (x, y) => (x * y % 2 + x * y % 3) % 2 === 0, (x, y) => ((x + y) % 2 + x * y % 3) % 2 === 0 +]; +const qrBit = (value, i) => ((value >>> i) & 1) !== 0; + +function qrRawModules(version) { + let n = (16 * version + 128) * version + 64; + if (version >= 2) { + const align = Math.floor(version / 7) + 2; + n -= (25 * align - 10) * align - 55; + if (version >= 7) n -= 36; + } + return n; +} +const qrDataCodewords = version => Math.floor(qrRawModules(version) / 8) - QR_ECC_M[version] * QR_BLOCKS_M[version]; + +function qrGfMul(x, y) { + let z = 0; + for (let i = 7; i >= 0; i--) { z = (z << 1) ^ ((z >>> 7) * 0x11d); z ^= ((y >>> i) & 1) * x; } + return z; +} + +function rsDivisor(degree) { + const out = new Array(degree).fill(0); + out[degree - 1] = 1; + let root = 1; + for (let i = 0; i < degree; i++) { + for (let j = 0; j < degree; j++) { out[j] = qrGfMul(out[j], root); if (j + 1 < degree) out[j] ^= out[j + 1]; } + root = qrGfMul(root, 2); + } + return out; +} + +function rsRemainder(data, divisor) { + const out = divisor.map(() => 0); + for (const b of data) { + const factor = b ^ out.shift(); + out.push(0); + divisor.forEach((c, i) => { out[i] ^= qrGfMul(c, factor); }); + } + return out; +} + +function qrEncode(bytes) { + let version = 1; + for (; ; version++) { + if (version > 40) refuse('offer', 'the link is too long for a QR code'); + if (4 + (version < 10 ? 8 : 16) + 8 * bytes.length <= qrDataCodewords(version) * 8) break; + } + const capacity = qrDataCodewords(version) * 8; + const bits = []; + const put = (value, length) => { for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1); }; + put(4, 4); + put(bytes.length, version < 10 ? 8 : 16); + for (const b of bytes) put(b, 8); + put(0, Math.min(4, capacity - bits.length)); + put(0, (8 - bits.length % 8) % 8); + for (let pad = 0xec; bits.length < capacity; pad ^= 0xec ^ 0x11) put(pad, 8); + const data = []; + for (let i = 0; i < bits.length; i += 8) data.push(bits.slice(i, i + 8).reduce((a, b) => (a << 1) | b, 0)); + + // Split into blocks, add error correction, interleave. + const blocks = QR_BLOCKS_M[version], eccLength = QR_ECC_M[version]; + const raw = Math.floor(qrRawModules(version) / 8); + const shortBlocks = blocks - raw % blocks, shortLength = Math.floor(raw / blocks); + const divisor = rsDivisor(eccLength), split = []; + for (let i = 0, k = 0; i < blocks; i++) { + const block = data.slice(k, k + shortLength - eccLength + (i < shortBlocks ? 0 : 1)); + k += block.length; + const ecc = rsRemainder(block, divisor); + if (i < shortBlocks) block.push(0); + split.push(block.concat(ecc)); + } + const codewords = []; + for (let i = 0; i < split[0].length; i++) { + for (let j = 0; j < split.length; j++) if (i !== shortLength - eccLength || j >= shortBlocks) codewords.push(split[j][i]); + } + + const size = version * 4 + 17; + const modules = Array.from({ length: size }, () => new Array(size).fill(false)); + const fixed = Array.from({ length: size }, () => new Array(size).fill(false)); + const set = (x, y, dark) => { modules[y][x] = dark; fixed[y][x] = true; }; + for (let i = 0; i < size; i++) { set(6, i, i % 2 === 0); set(i, 6, i % 2 === 0); } + for (const [cx, cy] of [[3, 3], [size - 4, 3], [3, size - 4]]) { + for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) { + const x = cx + dx, y = cy + dy, d = Math.max(Math.abs(dx), Math.abs(dy)); + if (x >= 0 && x < size && y >= 0 && y < size) set(x, y, d !== 2 && d !== 4); + } + } + const align = []; + if (version > 1) { + const count = Math.floor(version / 7) + 2; + const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2; + align.push(6); + for (let pos = size - 7; align.length < count; pos -= step) align.splice(1, 0, pos); + } + const last = align.length - 1; + align.forEach((ay, i) => align.forEach((ax, j) => { + if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return; + for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) set(ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1); + })); + const drawFormat = mask => { + const value = mask; // level M is 00 + let rem = value; + for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537); + const f = ((value << 10) | rem) ^ 0x5412; + for (let i = 0; i <= 5; i++) set(8, i, qrBit(f, i)); + set(8, 7, qrBit(f, 6)); set(8, 8, qrBit(f, 7)); set(7, 8, qrBit(f, 8)); + for (let i = 9; i < 15; i++) set(14 - i, 8, qrBit(f, i)); + for (let i = 0; i < 8; i++) set(size - 1 - i, 8, qrBit(f, i)); + for (let i = 8; i < 15; i++) set(8, size - 15 + i, qrBit(f, i)); + set(8, size - 8, true); + }; + drawFormat(0); + if (version >= 7) { + let rem = version; + for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25); + const v = (version << 12) | rem; + for (let i = 0; i < 18; i++) { + const a = size - 11 + i % 3, b = Math.floor(i / 3); + set(a, b, qrBit(v, i)); set(b, a, qrBit(v, i)); + } + } + + // Codewords in the zigzag order, skipping function modules. + let i = 0; + for (let right = size - 1; right >= 1; right -= 2) { + if (right === 6) right = 5; + for (let vert = 0; vert < size; vert++) { + for (let j = 0; j < 2; j++) { + const x = right - j, upward = ((right + 1) & 2) === 0, y = upward ? size - 1 - vert : vert; + if (!fixed[y][x] && i < codewords.length * 8) { modules[y][x] = qrBit(codewords[i >>> 3], 7 - (i & 7)); i++; } + } + } + } + + const applyMask = mask => { + for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) if (!fixed[y][x] && QR_MASKS[mask](x, y)) modules[y][x] = !modules[y][x]; + }; + let best = 0, bestPenalty = Infinity; + for (let mask = 0; mask < 8; mask++) { + applyMask(mask); + drawFormat(mask); + const penalty = qrPenalty(modules, size); + if (penalty < bestPenalty) { best = mask; bestPenalty = penalty; } + applyMask(mask); + } + applyMask(best); + drawFormat(best); + return Object.freeze({ size, modules: modules.map(row => Object.freeze(row)) }); +} + +// The mask penalty of ISO/IEC 18004 section 7.8.3: runs, 2x2 blocks, finder-like patterns, dark balance. +function qrPenalty(modules, size) { + let score = 0; + const addHistory = (run, history) => { if (history[0] === 0) run += size; history.pop(); history.unshift(run); }; + const countPatterns = h => { + const n = h[1]; + const core = n > 0 && h[2] === n && h[3] === n * 3 && h[4] === n && h[5] === n; + return (core && h[0] >= n * 4 && h[6] >= n ? 1 : 0) + (core && h[6] >= n * 4 && h[0] >= n ? 1 : 0); + }; + for (const line of [i => modules[i], i => modules.map(row => row[i])]) { + for (let a = 0; a < size; a++) { + const row = line(a); + let color = false, run = 0; + const history = new Array(7).fill(0); + for (let b = 0; b < size; b++) { + if (row[b] === color) { + run++; + if (run === 5) score += 3; else if (run > 5) score++; + } else { + addHistory(run, history); + if (!color) score += countPatterns(history) * 40; + color = row[b]; + run = 1; + } + } + if (color) { addHistory(run, history); run = 0; } + addHistory(run + size, history); + score += countPatterns(history) * 40; + } + } + let dark = 0; + for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) { + if (modules[y][x]) dark++; + if (y < size - 1 && x < size - 1) { + const c = modules[y][x]; + if (c === modules[y][x + 1] && c === modules[y + 1][x] && c === modules[y + 1][x + 1]) score += 3; + } + } + const total = size * size; + score += (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10; + return score; +} + const requestProofBody = (prism, device) => ({ kind: KIND.request, prism, device }); const linkContext = offer => ({ salt: fromBase64Url(offer.secret), info: 'prism/link-wrap/1', aad: offer.prism }); @@ -1223,9 +1436,12 @@ async function presenceEvidence(record, body, presence) { * `requirePresence` (true, or a list of action names) makes the host accept * those actions only with the person's user-verified WebAuthn approval of * exactly this action (Stitch.PrismId.presenceSatisfied). `requirePostQuantum` - * refuses an action whose ML-DSA signature this host cannot check. + * refuses an action whose ML-DSA signature this host cannot check. `bus` + * makes the host also merge what the prism's public topic retains (heardLog), + * so it hears revocations the signing device does not present. */ -export async function verifyAction(prism, log, envelope, { audience, now, window = 60000, seen = new Set(), requirePresence = false, requirePostQuantum = false }) { +export async function verifyAction(prism, log, envelope, { audience, now, window = 60000, seen = new Set(), requirePresence = false, requirePostQuantum = false, bus }) { + if (bus) log = await heardLog(prism, log, bus); const body = envelope?.body; if (body?.kind !== KIND.action || body.prism !== prism || !Number.isSafeInteger(body.at) || body.at < 0 || typeof body.nonce !== 'string') return { allowed: false, reason: 'not an action of this prism' }; @@ -1365,14 +1581,27 @@ export async function publishCover(session, bus, { bucket = 1024 } = {}) { * sync if there is one, otherwise a cover message, always padded to the same * bucket. A relay then sees one message of one size per interval whether or * not anything changed. The bucket only grows, when the log outgrows it. + * + * `refresh` keeps the substrate holding the prism: every `refresh` ticks a + * real sync goes out even with nothing pending, so a relay that keeps messages + * only for a while (the warm relay keeps them 30 minutes) always holds a + * recent one for offline devices and log-free recovery. Choose it so that + * `refresh` intervals are shorter than the relay's lifetime. Each real sync + * also publishes the public log (publishLog), so hosts hear revocations. + * Cover ticks publish nothing there; the public log holds no secret, but its + * timing shows which ticks were real. */ -export function createSyncCadence({ bucket = 1024 } = {}) { - let pending = false, size = bucket; +export function createSyncCadence({ bucket = 1024, refresh = Infinity } = {}) { + if (!(refresh === Infinity || (Number.isSafeInteger(refresh) && refresh > 0))) refuse('sync', 'refresh is a whole number of ticks'); + let pending = false, size = bucket, since = 0; return { queue() { pending = true; }, get bucket() { return size; }, async tick(session, bus) { - const sent = pending ? await publishSync(session, bus, { bucket: size }) : await publishCover(session, bus, { bucket: size }); + since++; + const real = pending || since >= refresh; + const sent = real ? await publishSync(session, bus, { bucket: size }) : await publishCover(session, bus, { bucket: size }); + if (real) { await publishLog(session, bus); since = 0; } pending = false; size = Math.max(size, sent.bucket); } @@ -1394,6 +1623,49 @@ export async function receiveSync(session, bytes) { return servicePersonas(next); } +// ---------------------------------------------------------------- what hosts hear + +/** + * The public topic of a prism's log, derived from the prism id alone, so a + * host that knows the prism reads it with no secret. It carries only the + * signed public records (genesis, binds and revocations) a host already + * receives with every action. Publish a persona's own log under the persona, + * so hosts still cannot link personas; the main prism's log goes here only + * when the main prism is what hosts see. + */ +export async function logTopic(prism) { + if (!isKappa(prism)) refuse('log', 'not a prism id'); + return 'prism-log:' + (await kappa({ kind: KIND.publicLog, prism })).slice(7); +} + +/** Publish this prism's public log where hosts hear it: after every bind or revocation, and on the refresh cadence. */ +export async function publishLog(session, bus) { + await bus.publish(await logTopic(session.prism), canonicalBytes({ kind: KIND.publicLog, prism: session.prism, records: [...session.log.values()] })); +} + +/** + * `log` merged with what the substrate retains on the prism's public topic, + * so a host hears a revocation the signing device never presents. Messages + * for another prism, over the bounds, or malformed are skipped. Every record + * is still checked by resolvePrism, so a forged one counts for nothing. + */ +export async function heardLog(prism, log, bus) { + let merged = log; + for (const bytes of await bus.retained(await logTopic(prism))) { + try { + if (!(bytes instanceof Uint8Array) || bytes.length > MAX_SYNC_BYTES) continue; + const message = JSON.parse(decoder.decode(bytes)); + if (message?.kind !== KIND.publicLog || message.prism !== prism) continue; + const next = mergeLogs(merged, await logFromRecords(message.records)); + if (next.size <= MAX_LOG_RECORDS) merged = next; + } catch (error) { + // A message that does not parse as this prism's log is not evidence of anything; skip it. + if (!(error instanceof PrismIdError || error instanceof SyntaxError || error instanceof TypeError)) throw error; + } + } + return merged; +} + /** How many messages per topic the in-memory bus retains. */ export const MAX_RETAINED = 256; diff --git a/tests/prism-bus.test.js b/tests/prism-bus.test.js index 7e55ec3..a3b6570 100644 --- a/tests/prism-bus.test.js +++ b/tests/prism-bus.test.js @@ -1,9 +1,10 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; import { createPrism, createDevice, resolvePrism, revokeDevice, createLinkOffer, parseLinkUri, requestLink, acceptLinkRequest, completeLink, rendezvousTopic, linkCode, currentBoundary, syncTopic, publishSync, receiveSync, signAction, verifyAction, PrismIdError, - createRelayBus, relayTopic + createRelayBus, relayTopic, linkQr, createMemoryBus, publishLog, heardLog, logTopic, createSyncCadence } from '../src/prism-id.js'; const HOST = 'https://foundry.uor.foundation'; @@ -131,3 +132,70 @@ test('a copied genesis with another signature cannot make the log unresolvable', assert.deepEqual((await resolvePrism(session.prism, log)).active, [session.device.id]); await assert.rejects(resolvePrism(session.prism, new Map([['forged', forged]])), refused('genesis')); }); + +test('a link offer becomes a QR code: version 13 at level M for a 301-character link, finder patterns in three corners, the same modules every time', async () => { + const offer = { expires: 1800000000000, kind: 'prism/link-offer/1', prism: 'sha256:' + 'ab'.repeat(32), role: 'member', scope: [], secret: 'A'.repeat(43) }; + const uri = 'prism-link:' + Buffer.from(JSON.stringify(offer)).toString('base64url'); + const qr = linkQr(uri); + assert.equal(qr.size, 69); + const finder = (x, y) => [0, 1, 2, 3, 4, 5, 6].map(dy => [0, 1, 2, 3, 4, 5, 6].map(dx => qr.modules[y + dy][x + dx] ? 1 : 0).join('')).join('/'); + const expected = '1111111/1000001/1011101/1011101/1011101/1000001/1111111'; + assert.deepEqual([finder(0, 0), finder(qr.size - 7, 0), finder(0, qr.size - 7)], [expected, expected, expected]); + // Checked against an independent decoder (jsQR 1.4.0), which reads this matrix back as the URI. + const digest = createHash('sha256').update(qr.modules.map(row => row.map(Number).join('')).join('\n')).digest('hex'); + assert.equal(digest, 'a9f2dd10239cef525de976795c8ab9a771fb05381e1f0b81b0b3bcfe2628687e'); + + const prism = await createPrism(); + const { uri: live } = await createLinkOffer(prism, { now: Date.now() }); + assert.equal(linkQr(live).size, linkQr(live).modules.length); + assert.throws(() => linkQr('https://example.test'), refused('offer')); +}); + +// Link a second member device directly, as the relay test above does over the bus. +async function linkMember(session, now) { + const joining = await createDevice(); + const { uri, pending } = await createLinkOffer(session, { now }); + const offer = parseLinkUri(uri); + const accepted = await acceptLinkRequest(session, pending, await requestLink(joining, offer), { now, confirmCode: await linkCode(offer.secret, joining.record) }); + return { first: accepted.session, second: await completeLink(joining, offer, accepted.response) }; +} + +test('a host hears a removal the removed device never presents, from the prism public log', async () => { + const now = Date.now(); + const relay = fakeRelay(); + const { first, second } = await linkMember(await createPrism(), now); + const removed = await revokeDevice(first, second.device.id); + await publishLog(removed, bus(relay)); + + // The removed device never syncs: it signs with the log it holds, where it is still active. + const action = await signAction(second, 'prism/session/1', { app: 1 }, { now, audience: HOST }); + assert.equal((await verifyAction(second.prism, second.log, action, { audience: HOST, now })).allowed, true); + const heard = await verifyAction(second.prism, second.log, action, { audience: HOST, now, bus: bus(relay) }); + assert.deepEqual([heard.allowed, heard.reason], [false, 'signature or revocation']); + + // Anything else on the topic counts for nothing: another prism's log, junk, a forged revocation. + const other = await createPrism(); + const memory = createMemoryBus(), topic = await logTopic(second.prism); + await memory.publish(topic, json({ kind: 'prism/public-log/1', prism: other.prism, records: [...other.log.values()] })); + await memory.publish(topic, new TextEncoder().encode('not json')); + const [revocation] = [...removed.log.values()].filter(e => e.body.kind === 'prism/revoke/1'); + const forged = { ...revocation, signature: revocation.signature.slice(0, -4) + 'AAAA' }; + await memory.publish(topic, json({ kind: 'prism/public-log/1', prism: second.prism, records: [...second.log.values(), forged] })); + const log = await heardLog(second.prism, second.log, memory); + assert.ok((await resolvePrism(second.prism, log)).active.includes(second.device.id)); + assert.equal((await verifyAction(second.prism, second.log, action, { audience: HOST, now, bus: memory })).allowed, true); +}); + +test('the sync cadence refreshes: a real sync and the public log every refresh ticks, cover otherwise', async () => { + const relay = fakeRelay(); + const session = await createPrism(); + const cadence = createSyncCadence({ refresh: 3 }); + const syncName = await relayTopic(await syncTopic(session)), logName = await relayTopic(await logTopic(session.prism)); + for (let i = 0; i < 6; i++) await cadence.tick(session, bus(relay)); + assert.equal(relay.posted.filter(p => p.name === syncName).length >= 6, true); + assert.equal(relay.posted.filter(p => p.name === logName).length > 0, true); + const kept = await bus(relay).retained(await logTopic(session.prism)); + assert.equal(kept.length, 2); + assert.equal((await heardLog(session.prism, new Map(), bus(relay))).size, session.log.size); + assert.throws(() => createSyncCadence({ refresh: 0 }), refused('sync')); +});