diff --git a/.github/workflows/try-page.yml b/.github/workflows/try-page.yml
index 675c888..78ab599 100644
--- a/.github/workflows/try-page.yml
+++ b/.github/workflows/try-page.yml
@@ -42,12 +42,10 @@ jobs:
"$RUNNER_TEMP/frame-draw/bin/python" -I bootstrap/og.py
- name: The frame verifies in a real module worker, refuses bad archives and works offline
run: node --test site/worker-browser.test.mjs
- - name: Prism accounts - every signature check refuses, and the passkey flow signs in
+ - name: Prism ids - the pinned stitch copy matches its lock, every session check refuses, and two apps share one id
run: npm run test:identity
- name: Build the canonical frame every Prism app loads
run: node frame/publish.mjs "$RUNNER_TEMP/frame" "$GITHUB_SHA"
- - name: Build the sign-in page for id.uor.foundation, pinned by hash
- run: node identity/publish.mjs "$RUNNER_TEMP/identity" "$GITHUB_SHA"
deploy:
name: publish the try page and the canonical frame
diff --git a/bootstrap/page.mjs b/bootstrap/page.mjs
index 6e00344..e8811d1 100644
--- a/bootstrap/page.mjs
+++ b/bootstrap/page.mjs
@@ -104,10 +104,6 @@ const prismRegistry = new URL(`https://${DEFAULT_REGISTRY}/`);
// a frame change reaches this app without rebuilding it. app.json may name
// another frame host, for a test or a mirror.
const frameHost = new URL(meta.frame ?? "https://uor-foundation.github.io/template/frame/");
-// Prism accounts: the sign-in page the frame's account panel shows. The
-// page's policy frames that one origin and no other. app.json may name
-// another, for a test.
-const accounts = new URL(meta.accounts ?? "https://id.uor.foundation/");
const shareUrl = live.href;
// The one speculation rule: the frame marks the pages a visitor is about to
@@ -121,23 +117,26 @@ const speculationRules = JSON.stringify({
// with the page's, so the frame does not wait for a TLS handshake.
const frameConnect = frameHost.origin !== live.origin ? `` : "";
-// The frame's Unsplash worker, which this page's connect-src must name for
-// the theme panel's search: read from the live frame at build, after its
-// SHA-256 is checked as the browser checks it. The frame itself is not
-// written into the page: the page's own stand-in (prism-page.css) shows,
-// drawn as the bar, until the module arrives, which keeps the first load
-// inside the Lighthouse budget.
-async function frameUnsplash() {
+// The origins this page's connect-src must name for the frame: its Unsplash
+// worker, for the theme panel's search, and stitch's relay (with its
+// WebSocket origin), where a visitor's Prism id devices meet. Both are read
+// from the live frame at build, after its SHA-256 is checked as the browser
+// checks it. The frame itself is not written into the page: the page's own
+// stand-in (prism-page.css) shows, drawn as the bar, until the module
+// arrives, which keeps the first load inside the Lighthouse budget.
+async function frameAllowed() {
try {
const pointer = await (await fetch(new URL("current.json", frameHost), { cache: "no-store" })).json();
if (!/^[0-9a-f]{64}$/.test(pointer.sha256 ?? "")) throw new Error("the frame pointer names no sha256");
const bytes = Buffer.from(await (await fetch(new URL(pointer.module, frameHost))).arrayBuffer());
if (hex(bytes) !== pointer.sha256) throw new Error(`the frame is ${hex(bytes)}, its pointer says ${pointer.sha256}`);
const frame = await import(`data:text/javascript;base64,${bytes.toString("base64")}`);
- return /^https:\/\/[a-z0-9.-]+$/.test(frame.UNSPLASH_ORIGIN ?? "") ? frame.UNSPLASH_ORIGIN : "";
+ const origin = (value) => (/^https:\/\/[a-z0-9.-]+$/.test(value ?? "") ? value : "");
+ const relay = origin(/^https:\/\/[a-z0-9.-]+/.exec(frame.PRISM_RELAY ?? "")?.[0]);
+ return { unsplash: origin(frame.UNSPLASH_ORIGIN), relay: relay ? `${relay} ${relay.replace(/^https:/, "wss:")}` : "" };
} catch (error) {
- console.warn(`page: the frame could not be read at build (${error.message}); no Unsplash origin in connect-src`);
- return "";
+ console.warn(`page: the frame could not be read at build (${error.message}); no Unsplash or relay origin in connect-src`);
+ return { unsplash: "", relay: "" };
}
}
// The repository's GitHub stars at build, so the bar shows them from its
@@ -166,7 +165,7 @@ async function githubStars() {
}
}
const stars = await githubStars();
-const unsplashOrigin = await frameUnsplash();
+const frameOrigins = await frameAllowed();
// ---------------------------------------------------------------------------
// The workspace and the spec, rendered here so the page says everything
@@ -432,9 +431,8 @@ const fill = {
HOLO_SEARCH_ORIGIN: holoSearch.origin,
REGISTRY_ORIGIN: prismRegistry.origin,
FRAME_ORIGIN: frameHost.origin,
- ACCOUNTS: escape(accounts.href),
- ACCOUNTS_ORIGIN: accounts.origin,
- UNSPLASH_ORIGIN: unsplashOrigin,
+ UNSPLASH_ORIGIN: frameOrigins.unsplash,
+ PRISM_RELAY_ORIGINS: frameOrigins.relay,
OG_IMAGE: escape(new URL("og.png", live).href),
OG_ALT: escape(`${meta.name}: ${meta.purpose}`),
NAME: escape(meta.name),
diff --git a/frame.lock b/frame.lock
index 6f5bdab..cd4c7f9 100644
--- a/frame.lock
+++ b/frame.lock
@@ -15,7 +15,7 @@
},
{
"path": "bootstrap/page.mjs",
- "sha256": "2df4ef057d37e778b04f67e4f63d862c7da6a77c301d0862b2bb8681fc8ec9d4"
+ "sha256": "8eee238bce9206ca58fc9be5471c28c0bdab82e2350ed78f1972da2a1da6581f"
},
{
"path": "bootstrap/precache.mjs",
@@ -51,7 +51,7 @@
},
{
"path": "site/page.template.html",
- "sha256": "d7df0bc4d5190ca38ee768bdbd54cbc665ede811608de846068c8a92bd02c14d"
+ "sha256": "b48b9d18e23e959c9e96b4bec58e2e7d80b7b977e981d8a7b0fd369293819b08"
},
{
"path": "site/prism-page.css",
diff --git a/frame/frame.css b/frame/frame.css
index db9cb45..b233c1c 100644
--- a/frame/frame.css
+++ b/frame/frame.css
@@ -252,8 +252,8 @@ svg.gh, svg.fill { fill: currentColor; stroke: none; }
#github[hidden] + .sep { display: none; }
/* Full screen: the corners point out to enter, in to leave. */
:host([fullscreen]) #fullscreen .expand, :host(:not([fullscreen])) #fullscreen .shrink { display: none; }
-/* The account: a line drawing signed out; while the device is asked for its
- * passkey it breathes; signed in, the same figure filled, in the full text
+/* The account: a line drawing signed out; while the Prism id window is open
+ * it breathes; signed in, the same figure filled, in the full text
* colour, so who is signed in reads at a glance and nothing else changes. */
#account.signed-in { color: var(--foreground); }
#account.signed-in svg.person { fill: currentColor; }
diff --git a/frame/frame.mjs b/frame/frame.mjs
index 74ad3d6..7085b64 100644
--- a/frame/frame.mjs
+++ b/frame/frame.mjs
@@ -7,7 +7,7 @@
//
// The contract (prism/frame/1):
//
+// verdict verdict-label fingerprint proof proof-url examples>
// … optional: shown in the bar, e.g. "Update available"
//
// name the app's name ("Luhn check")
@@ -25,11 +25,10 @@
// proof-url optional: the proof's attestation
// examples optional: "passed/total" once the page has replayed the holo's
// examples, "running" while it does, "error" when it could not
-// accounts optional: the Prism accounts origin (https://id.uor.foundation)
-// The element's account is the visitor's Prism account (null when signed
-// out); sign(bytes) signs with this browser's session key and returns the
-// signature with the passkey's delegation; "accountchange" fires on sign-in
-// and sign-out. identity/PROTOCOL.md is the account contract.
+// The element's account is the visitor's Prism id (null when signed out);
+// sign(bytes) signs with this browser's session key and returns the
+// signature with the id's delegation; "accountchange" fires on sign-in and
+// sign-out. identity/PROTOCOL.md is the account contract.
// The shield sums the three: green only when the bytes are authentic and
// every example gives its proved answer; its panel shows each check, as a
// browser shows a page's security.
@@ -346,12 +345,14 @@ function holoIndex() {
const githubMark = '';
const starMark = '';
-// Prism accounts (prism/identity/1, identity/PROTOCOL.md). An account is a
-// passkey: its private key stays in the device's secure hardware, and the
-// account's name is the hash of its public key. The frame keeps the session
-// and signs with it; the panels module runs the sign-in and checks every
-// signature the sign-in page hands back, in the visitor's browser.
-const ACCOUNTS = "https://id.uor.foundation";
+// Prism ids (prism/identity/4, identity/PROTOCOL.md): stitch's Prism id,
+// named by the κ of its genesis and held by devices whose keys never leave
+// them, with a recovery kit its owner keeps, so losing a device never loses
+// the id. The frame keeps this app's session and signs with it; the panels
+// module holds this origin's device and runs the sign-in, in the visitor's
+// browser. Devices of one id meet on stitch's relay, which the page build
+// reads from here into the page's connect-src (with its WebSocket origin).
+export const PRISM_RELAY = "https://ntfy.sh";
const SESSION_DAYS = 7;
const b64u = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
// The session, in this app's IndexedDB: the browser key cannot be read out
@@ -373,11 +374,11 @@ function store(mode, work) {
const accountChannel = { session: null, loaded: null };
function loadSession() {
return (accountChannel.loaded ??= store("readonly", (s) => s.get("current"))
- .then((saved) => (accountChannel.session = saved && saved.delegation.expires > Date.now() ? saved : null))
+ .then((saved) => (accountChannel.session = saved?.delegation?.envelope && saved.expires > Date.now() ? saved : null))
.catch(() => null));
}
// What the account panel, in the panels module, borrows from the frame.
-const ACCOUNT_CORE = { SESSION_DAYS, b64u, store, accountChannel, loadSession };
+const ACCOUNT_CORE = { SESSION_DAYS, b64u, store, accountChannel, loadSession, PRISM_RELAY };
// Everything the markup needs, from the attributes (get), the page's title
// and its address: one function, for the element and for the shell.
@@ -400,7 +401,6 @@ function modelOf(get, title, base) {
...starsOf(Number(get("stars"))),
card: get("card") ?? new URL("og.png", url).href,
identity: get("identity") ?? "#identity-title",
- accounts: get("accounts") ?? ACCOUNTS,
host: (url.host + url.pathname).replace(/\/$/, ""),
x: `https://x.com/intent/post?${query({ text, url: url.href })}`,
linkedin: `https://www.linkedin.com/sharing/share-offsite/?${query({ url: url.href })}`,
@@ -448,7 +448,7 @@ export function shell(attributes, base) {
// there is none, to write the shell.
const Element = globalThis.HTMLElement ?? class {};
class PrismFrame extends Element {
- static observedAttributes = ["name", "address", "live", "repo", "home", "purpose", "card", "identity", "verdict", "verdict-label", "fingerprint", "proof", "proof-url", "examples", "stars", "accounts"];
+ static observedAttributes = ["name", "address", "live", "repo", "home", "purpose", "card", "identity", "verdict", "verdict-label", "fingerprint", "proof", "proof-url", "examples", "stars"];
constructor() {
super();
@@ -831,32 +831,32 @@ class PrismFrame extends Element {
// The visitor's Prism account, for the app: null when signed out.
get account() {
const saved = accountChannel.session;
- return saved ? { id: saved.account, key: saved.key, expires: saved.delegation.expires } : null;
+ return saved ? { id: saved.account, key: saved.key, expires: saved.expires } : null;
}
// Signs bytes with this browser's session key. The delegation proves the
- // account's passkey let that key act for it here; verifySession checks it.
+ // Prism id let that key act for it here; verifySession checks it.
async sign(data) {
const saved = accountChannel.session;
- if (!saved || saved.delegation.expires <= Date.now()) throw Object.assign(new Error("No one is signed in"), { name: "IdentityError", code: "signed-out" });
+ if (!saved || saved.expires <= Date.now()) throw Object.assign(new Error("No one is signed in"), { name: "IdentityError", code: "signed-out" });
const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, saved.privateKey, data);
return { signature: b64u(signature), delegation: saved.delegation };
}
- // The account icon, after full screen: a line drawing signed out, a soft
- // pulse while a passkey is asked, filled once signed in. Its panel and the
+ // The account icon, after full screen: a line drawing signed out, filled
+ // once signed in. Its panel and the
// sign-in itself come with the panels module (accounts() there), fetched
// when the visitor reaches for the icon, so an app's first load carries
- // none of it. Where passkeys cannot work (no secure context, no WebAuthn,
- // no IndexedDB, no popover) the icon is not shown, so it never offers
- // what would fail.
+ // none of it. Where a Prism id cannot work (no secure context, no
+ // WebCrypto, no IndexedDB, no popover) the icon is not shown, so it never
+ // offers what would fail.
accountPanel() {
const button = this.$("account");
const panel = this.$("account-panel");
this.accountWatch?.abort();
this.accountReady = null;
let wired = false;
- if (typeof panel.showPopover !== "function" || !window.isSecureContext || !window.PublicKeyCredential || !globalThis.indexedDB) {
+ if (typeof panel.showPopover !== "function" || !window.isSecureContext || !globalThis.crypto?.subtle || !globalThis.indexedDB) {
button.hidden = true;
return;
}
diff --git a/frame/panels.css b/frame/panels.css
index 9ea77de..98005af 100644
--- a/frame/panels.css
+++ b/frame/panels.css
@@ -462,21 +462,27 @@
.account-in { display: grid; gap: 0.382rem; }
.account-id { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); margin-bottom: 0.618rem !important; padding: 0.618rem 1rem; border: var(--border-width) solid var(--border); border-radius: var(--radius-control); background: var(--background); }
.account-id code { font-family: var(--font-mono); color: var(--muted-foreground); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.account-qr { display: block; width: min(100%, 14rem); aspect-ratio: 1; margin: 0 auto 0.618rem; background: #fff; border-radius: var(--radius-control); }
+.account-qr path { fill: #000; }
.account-panel .text { padding: 0; border: 0; background: none; color: var(--foreground); font-weight: 500; text-decoration: underline; text-decoration-color: var(--border-strong); text-underline-offset: 0.2em; cursor: pointer; }
.account-panel .row { justify-content: flex-start; width: 100%; min-height: 2.618rem; padding: 0 1rem; border: 0; border-radius: var(--radius-control); background: none; color: var(--foreground); font-size: 1rem; text-align: start; cursor: pointer; }
.account-panel .row:hover { background: var(--accent); }
.account-panel .row:focus-visible, .account-panel .text:focus-visible, .account-close:focus-visible { outline: var(--ring-width) solid var(--ring); outline-offset: var(--ring-offset); }
-.account-ceremony:empty { display: none; }
-/* The iframe's colour scheme matches the page inside it; a mismatch would
- * make the browser paint it an opaque ground over the dialog. */
-.account-ceremony iframe { display: block; width: 100%; height: 2.618rem; border: 0; color-scheme: light; }
-:host([dark]) .account-ceremony iframe { color-scheme: dark; }
-/* Shown only once the sign-in page has answered, so a page that fails to
- * load never shows the browser's error page in the dialog. */
-.account-ceremony iframe:not(.ready) { visibility: hidden; height: 0 !important; }
-#account-window { width: 100%; min-height: 2.618rem; font-size: 1rem; }
+.account-panel .primary { width: 100%; min-height: 2.618rem; font-size: 1rem; }
+.account-panel .account-in > p { margin-bottom: 0.618rem; color: var(--muted-foreground); }
+.account-panel .account-in > p b { color: var(--foreground); font-weight: 600; }
+.account-panel input:not([type="file"]) { width: 100%; min-height: 2.618rem; padding: 0 1rem; border: var(--border-width) solid var(--border); border-radius: var(--radius-control); background: var(--background); color: var(--foreground); font: inherit; font-size: 1rem; }
+.account-panel #account-code { margin-top: 0.382rem; font-family: var(--font-mono); letter-spacing: 0.2em; }
+.account-panel label { display: grid; color: var(--muted-foreground); }
+.account-panel input:focus-visible { outline: var(--ring-width) solid var(--ring); outline-offset: var(--ring-offset); }
+.account-code { margin-top: 0.618rem !important; color: var(--foreground); font-size: 1rem; }
+.account-devices { display: grid; gap: 0.382rem; margin: 0; padding: 0; list-style: none; }
+.account-devices li { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); min-height: 2.618rem; padding: 0 1rem; border: var(--border-width) solid var(--border); border-radius: var(--radius-control); }
+.account-devices code { font-family: var(--font-mono); color: var(--muted-foreground); }
+.account-error { margin-top: 1rem !important; color: var(--destructive, #c2410c); }
+.account-panel.busy > :not(.account-close) { opacity: 0.618; pointer-events: none; }
@media (pointer: coarse) {
- .account-panel .row, #account-window { min-height: var(--touch); }
+ .account-panel .row, .account-panel .primary, .account-panel input:not([type="file"]) { min-height: var(--touch); }
.account-close { top: 0.618rem; right: 0.618rem; width: var(--touch); height: var(--touch); min-height: var(--touch); }
}
@media (prefers-reduced-transparency: reduce) { .account-panel::backdrop { -webkit-backdrop-filter: none; backdrop-filter: none; background: rgb(0 0 0 / 0.618); } }
diff --git a/frame/panels.mjs b/frame/panels.mjs
index 61e1170..8fee36e 100644
--- a/frame/panels.mjs
+++ b/frame/panels.mjs
@@ -341,19 +341,23 @@ export function panel(frame, core) {
return { open: () => query || home() };
}
-// The theme panel's contents, which the frame puts in its empty panel.
-// Prism accounts (prism/identity/1, identity/PROTOCOL.md): the checks the
-// sign-in page's answer must pass. The page is trusted with nothing; every
-// signature is checked here, in the visitor's browser, as the frame checks
-// the holo's bytes. A failed check is an IdentityError naming which one.
-const MAX_CHAIN = 5;
-const enc = new TextEncoder();
+// Prism ids (prism/identity/4, identity/PROTOCOL.md). A visitor's Prism id
+// is stitch's Prism id (afflom/stitch, pinned in identity/stitch.lock): the
+// κ of its genesis, held by devices whose keys never leave them. Each app's
+// origin keeps its own device of the id, made here with no prompt; another
+// device or app joins the same id by stitch's link offer, confirmed with a
+// six-digit code, and a recovery kit brings it back after every device is
+// lost. Devices meet on stitch's substrate (its relay), so nothing here
+// needs a server of Prism's own.
+//
+// Signing in is the device signing one action for this app,
+// "prism/session/1", which lets a session key made here act for the id on
+// this origin until it expires. verifySession checks that action against the
+// id's log with Prism id's own verifyAction, here and for anyone the app
+// shows a signature to. A failed check is an IdentityError naming which.
+const SESSION_ACTION = "prism/session/1";
+const MAX_SESSION_MS = 8 * 24 * 60 * 60 * 1000;
const b64u = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
-const unb64u = (text) => {
- if (typeof text !== "string" || !/^[\w-]*$/.test(text)) throw new IdentityError("encoding", "A value is not base64url");
- return Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
-};
-const digest = async (bytes) => new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
export class IdentityError extends Error {
constructor(code, message) {
@@ -366,307 +370,537 @@ const deny = (code, message) => {
throw new IdentityError(code, message);
};
-// The origins whose signatures count, each with its WebAuthn rpId.
-export const originsOf = (accounts) => ({ [new URL(accounts).origin]: new URL(accounts).hostname });
-
-const ALGORITHMS = {
- [-7]: { key: { name: "ECDSA", namedCurve: "P-256" }, verify: { name: "ECDSA", hash: "SHA-256" } },
- [-257]: { key: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, verify: { name: "RSASSA-PKCS1-v1_5" } },
-};
-
-// WebAuthn's ECDSA signatures are DER; WebCrypto's are the two 32-byte halves.
-function rawSignature(der) {
- let at = 2;
- const integer = () => {
- if (der[at++] !== 0x02) deny("signature", "The signature is not DER");
- const length = der[at++];
- let value = der.slice(at, (at += length));
- while (value.length > 32 && value[0] === 0) value = value.slice(1);
- if (value.length > 32 || at > der.length) deny("signature", "The signature is not DER");
- const out = new Uint8Array(32);
- out.set(value, 32 - value.length);
- return out;
- };
- if (der[0] !== 0x30 || der[1] !== der.length - 2) deny("signature", "The signature is not DER");
- const r = integer();
- const s = integer();
- return new Uint8Array([...r, ...s]);
-}
+// Prism id itself (identity/prism-id.mjs), published beside the frame and
+// named by its SHA-256, which frame/publish.mjs writes here. It is fetched
+// when the visitor reaches for the account icon, and checked as the frame
+// checks this module. Unpublished (tests, a checkout), it is read from the
+// repository.
+const PRISM_ID = "/*PRISM_ID*/";
+let prismModule = null;
+export const prismId = () =>
+ (prismModule ??= (async () => {
+ if (!/^[0-9a-f]{64}$/.test(PRISM_ID)) return import("../identity/prism-id.mjs");
+ const bytes = await (await fetch(new URL(`${PRISM_ID}/prism-id.mjs`, FRAME_HOST))).arrayBuffer();
+ const hex = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (b) => b.toString(16).padStart(2, "0")).join("");
+ if (hex !== PRISM_ID) throw new Error("Prism id is not the module this frame names");
+ const url = URL.createObjectURL(new Blob([bytes], { type: "text/javascript" }));
+ try {
+ return await import(url);
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ })().catch((error) => {
+ prismModule = null;
+ throw error;
+ }));
-// One WebAuthn assertion: the passkey of record signed message. The six
-// checks of PROTOCOL.md, in its order, failing closed.
-export async function verifySigned(record, signed, message, origins) {
- if (signed?.credential !== record.credential) deny("credential", "The signature is from another passkey");
- let client;
+// A session: { app, envelope, records }. The envelope is the id's
+// "prism/session/1" action for `app`, naming the session key and its expiry;
+// records are the id's log as the signing device knew it. `fresh` is the
+// window in which it must be checked after signing (Prism id's actionFresh);
+// anyone checking a kept session later checks it as of its own signing
+// (fresh: 0), and its expiry bounds it.
+export async function verifySession(session, { now = Date.now(), fresh = 60000 } = {}) {
+ const Prism = await prismId();
+ const { app, envelope, records } = session ?? {};
+ const body = envelope?.body;
+ if (typeof app !== "string" || !/^https?:\/\/[^/]+$/.test(app)) deny("app", "The session names no app");
+ if (body?.action !== SESSION_ACTION) deny("action", "The signature is not a session");
+ const { sessionKey, expires } = body.payload ?? {};
+ if (typeof sessionKey !== "string" || !/^[\w-]{87}$/.test(sessionKey)) deny("key", "The session key is malformed");
+ if (!Number.isSafeInteger(expires) || expires <= now) deny("expired", "The session has expired");
+ if (expires > body.at + MAX_SESSION_MS) deny("expired", "The session lasts too long");
+ let log;
try {
- client = JSON.parse(new TextDecoder().decode(unb64u(signed.clientDataJSON)));
- } catch {
- deny("client", "The signed client data is not JSON");
+ log = await Prism.logFromRecords(records);
+ } catch (error) {
+ if (error instanceof Prism.PrismIdError) deny("log", "The log does not parse");
+ throw error;
+ }
+ const at = fresh ? now : body.at;
+ let verdict;
+ try {
+ // With the relay known, also hear removals the signing device did not present (the id's public log).
+ verdict = await Prism.verifyAction(body.prism, log, envelope, { audience: app, now: at, window: fresh || 1, ...(relay ? { bus: bus(Prism) } : {}) });
+ } catch (error) {
+ if (error instanceof Prism.PrismIdError) deny("log", `The log does not resolve: ${error.message}`);
+ throw error;
}
- if (client.type !== "webauthn.get") deny("type", "The signature is not a sign-in");
- if (client.challenge !== b64u(await digest(enc.encode(message)))) deny("challenge", "The signature is for another request");
- const rp = Object.hasOwn(origins, client.origin) ? origins[client.origin] : null;
- if (!rp) deny("origin", "The signature was made on another site");
- const data = unb64u(signed.authenticatorData);
- if (data.length < 37 || b64u(data.slice(0, 32)) !== b64u(await digest(enc.encode(rp)))) deny("rp", "The passkey belongs to another site");
- if ((data[32] & 0x05) !== 0x05) deny("flags", "The device did not verify its user");
- const algorithm = ALGORITHMS[record.alg] ?? deny("algorithm", "The passkey's algorithm is not ES256 or RS256");
- const key = await crypto.subtle.importKey("spki", unb64u(record.spki), algorithm.key, false, ["verify"]).catch(() => deny("key", "The public key does not parse"));
- let signature = unb64u(signed.signature);
- if (record.alg === -7) signature = rawSignature(signature);
- const body = new Uint8Array([...data, ...(await digest(unb64u(signed.clientDataJSON)))]);
- if (!(await crypto.subtle.verify(algorithm.verify, key, signature, body))) deny("signature", "The signature does not verify");
+ if (!verdict.allowed) deny(verdict.reason === "scope" ? "scope" : "signature", `The session was refused (${verdict.reason})`);
+ return { account: body.prism, key: envelope.signer, sessionKey, expires };
+}
+
+// ---------------------------------------------------------------- this origin's device
+
+// The device and its view of the id, in this origin's IndexedDB. IndexedDB
+// keeps CryptoKeys as they are: a non-extractable key stays one.
+function deviceStore(mode, work) {
+ return new Promise((done, fail) => {
+ const open = indexedDB.open("prism-id", 1);
+ open.onupgradeneeded = () => open.result.createObjectStore("prism");
+ open.onerror = () => fail(open.error);
+ open.onsuccess = () => {
+ const tx = open.result.transaction("prism", mode);
+ const request = work(tx.objectStore("prism"));
+ tx.oncomplete = () => (open.result.close(), done(request?.result));
+ tx.onerror = () => (open.result.close(), fail(tx.error));
+ };
+ });
}
+export const loadDevice = () => deviceStore("readonly", (s) => s.get("self")).catch(() => null);
+const saveDevice = (held) => deviceStore("readwrite", (s) => s.put(held, "self"));
+const forgetDevice = () => deviceStore("readwrite", (s) => s.delete("self"));
+
+// The bus to the id's other devices: stitch's relay (the frame's
+// PRISM_RELAY), which the page's connect-src must name; the page build reads
+// it from the frame. A page that does not admit it keeps the id on this
+// device: sign-in and recovery work, linking and syncing wait.
+let relay = null;
+let relayBus = null;
+const relayAdmitted = (origin) => {
+ const policy = [...document.querySelectorAll('meta[http-equiv="Content-Security-Policy" i]')].map((meta) => meta.content).join(";");
+ const connect = /(?:^|;)\s*connect-src([^;]*)/.exec(policy)?.[1] ?? /(?:^|;)\s*default-src([^;]*)/.exec(policy)?.[1];
+ return connect === undefined || connect.includes(origin);
+};
+const bus = (Prism) => (relayBus ??= Prism.createRelayBus({ relay: relay && relayAdmitted(new URL(relay).origin) ? relay : null }));
-// A key record, accepted only when its name is its key's hash and it is the
-// account's first key or bound to it by a key already accepted.
-export async function acceptRecord(credential, records, origins, depth = 0) {
- const record = records.find((r) => r?.credential === credential);
- if (!record || record.spec !== "prism/identity/key/1") deny("record", "The passkey has no record");
- if (b64u(await digest(unb64u(record.spki))) !== record.key) deny("key", "The record's name is not its key's hash");
- if (record.key === record.account) {
- if (record.binding) deny("binding", "An account's first key has no binding");
- return record;
+// Share this device's log with the id's other devices, under every boundary
+// key it holds, so a device that has not taken up a rotation still hears,
+// and publish its public records where apps hear removals.
+async function share(Prism, held) {
+ for (const keyId of held.keyring.keys()) await Prism.publishSync(held, bus(Prism), { keyId }).catch(() => {});
+ await Prism.publishLog(held, bus(Prism)).catch(() => {});
+}
+// Take in what the other devices shared. A message that does not open or
+// resolve is someone else's or stale: it is skipped, never trusted.
+async function pull(Prism, held) {
+ for (const keyId of [...held.keyring.keys()]) {
+ const topic = await Prism.syncTopic(held, keyId).catch(() => null);
+ if (!topic) continue;
+ for (const bytes of await bus(Prism).retained(topic).catch(() => [])) {
+ try {
+ held = await Prism.receiveSync(held, bytes);
+ } catch (error) {
+ if (!(error instanceof Prism.PrismIdError) && !(error instanceof DOMException) && !(error instanceof SyntaxError)) throw error;
+ }
+ }
}
- if (depth >= MAX_CHAIN || !record.binding) deny("binding", "The key is not bound to its account");
- const parent = await acceptRecord(record.binding.credential, records, origins, depth + 1);
- if (parent.account !== record.account) deny("binding", "The key is bound by another account");
- await verifySigned(parent, record.binding, `prism/identity/bind/1\n${record.account}\n${record.key}`, origins);
- return record;
+ return held;
}
+// The id's log as apps see it: this device's, with what the public log holds.
+const heard = (Prism, held) => Prism.heardLog(held.prism, held.log, bus(Prism)).catch(() => held.log);
-// A session: the account's passkey let one browser key act for it, on one
-// app's origin, until it expires. Anyone holding the session can check it.
-export async function verifySession(session, origins, now = Date.now()) {
- const { app, nonce, sessionKey, expires, assertion, records } = session ?? {};
- if (!Number.isSafeInteger(expires) || expires <= now) deny("expired", "The session has expired");
- const record = await acceptRecord(assertion?.credential, records ?? [], origins);
- await verifySigned(record, assertion, `prism/identity/session/1\n${app}\n${nonce}\n${sessionKey}\n${expires}`, origins);
- return { account: record.account, key: record.key, credential: record.credential, expires };
+// A recovery kit: the paper share of the id's recovery device (stitch's
+// threshold recovery, one share of one) and the id's log. It is as secret as
+// the id: whoever holds it can take the id over.
+const KIT = "prism/recovery-kit/1";
+const ONE_PAPER_SHARE = { threshold: 1, guardians: [{ paper: true }] };
+const kitOf = (held, share) => ({ kind: KIT, prism: held.prism, share, records: [...held.log.values()] });
+
+// A QR code as one SVG path, with its four-module quiet zone.
+function drawQr(svg, { size, modules }) {
+ let d = "";
+ modules.forEach((row, y) => row.forEach((dark, x) => dark && (d += `M${x + 4} ${y + 4}h1v1h-1z`)));
+ svg.setAttribute("viewBox", `0 0 ${size + 8} ${size + 8}`);
+ const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
+ path.setAttribute("d", d);
+ svg.replaceChildren(path);
}
+const json = (value) => new TextEncoder().encode(JSON.stringify(value));
+const parse = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
+const short = (id) => `${id.slice(0, 15)}…${id.slice(-4)}`;
+const sentence = (text) => (text ? text[0].toUpperCase() + text.slice(1) + (/[.!?]$/.test(text) ? "" : ".") : text);
+const KIND_LABEL = { browser: "Browser", native: "App", mobile: "Phone", embedded: "Device", recovery: "Recovery kit" };
const ACCOUNT_PANEL = `
Sign in
-
One account for every Prism app. No password.
-
+
One Prism id for every Prism app. No password.
+
+
+
+
+
+
-
-
+
+
+
+
+
+
+
+
+
If you lose every device, this file brings your Prism id back. Anyone holding it can take your id, so keep it offline.
+
+
-
-
+
+
On a phone, scan this code. On another app or computer, open the person icon, choose Use my Prism id from another device or app, and paste the link. It works once, for five minutes.
+
+
+
+
+
+
+
On a device or app already signed in, open the person icon, choose Add a device or app, and paste its link here.
+
+
+
+
+
+
Choose the recovery kit you downloaded. This browser becomes your Prism id's device, every other device is removed, and you get a new kit.
+
+
+
+
+
+
+
`;
-// The account panel (prism/identity/1, identity/PROTOCOL.md): the sign-in
-// page from the accounts origin in an iframe, loaded when the visitor reaches
-// for the icon, so the panel opens ready. A page whose policy will not frame
-// that origin gets the same page in a small window instead. The page says
-// nothing the frame takes on trust: every signature is checked here (core's
-// verifySession) before a session is kept.
+const TITLES = {
+ none: ["Sign in", "One Prism id for every Prism app. No password."],
+ held: ["Sign in", "This device holds your Prism id."],
+ signed: ["Prism id", "Signed in on this device."],
+ kit: ["Save your recovery kit", ""],
+ offer: ["Add a device or app", ""],
+ join: ["Use your Prism id here", ""],
+ recover: ["Use a recovery kit", ""],
+ devices: ["Devices", "Removing one stops it signing the next time it syncs."],
+ removed: ["This device was removed", "Another device of your Prism id removed this one. Join again from a device you still have, or use your recovery kit."],
+};
+
+// The account panel, drawn in the frame. Every step is stitch's Prism id
+// running in this page; the relay only carries what the devices exchange.
export function accounts(frame, core) {
const { SESSION_DAYS, store, accountChannel, loadSession } = core;
+ relay = core.PRISM_RELAY ?? null;
frame.$("account-panel").innerHTML = ACCOUNT_PANEL;
- const button = frame.$("account");
+ const $ = (id) => frame.$(`account-${id}`);
const panel = frame.$("account-panel");
- const target = new URL(frame.data.accounts);
- const origin = target.origin;
- const origins = originsOf(target.href);
- const SPEC = "prism/identity/1";
- const box = frame.$("account-ceremony");
- const windowButton = frame.$("account-window");
- let ceremony = null;
-
- const policy = [...document.querySelectorAll('meta[http-equiv="Content-Security-Policy" i]')].map((meta) => meta.content).join(";");
- const directive = (name) => new RegExp(`(?:^|;)\\s*${name}([^;]*)`).exec(policy)?.[1];
- const frames = directive("frame-src") ?? directive("child-src") ?? directive("default-src");
- const framed = frames === undefined || frames.split(/\s+/).some((source) => source === "*" || source === origin || (source === "'self'" && origin === location.origin));
+ let held = null;
+ let view = "none";
+ let kit = null;
+ let afterKit = null;
+ let link = null;
const say = (words) => {
frame.$("bar-status").textContent = words;
setTimeout(() => (frame.$("bar-status").textContent = ""), 1600);
};
- const paint = () => {
- const saved = accountChannel.session;
- core.paint();
- frame.$("account-in").hidden = !saved;
- frame.$("account-title").textContent = saved ? "Prism account" : "Sign in";
- frame.$("account-sub").textContent = saved ? "Signed in on this device." : "One account for every Prism app. No password.";
- if (saved) {
- frame.$("account-id").textContent = `${saved.account.slice(0, 8)}…${saved.account.slice(-4)}`;
- frame.$("account-id").title = saved.account;
- }
- };
const changed = () => {
paint();
frame.dispatchEvent(new CustomEvent("accountchange", { detail: frame.account, bubbles: true, composed: true }));
};
- const close = () => {
- box.replaceChildren();
- ceremony?.popup?.close();
- ceremony = null;
- windowButton.hidden = true;
- button.classList.remove("busy");
- };
-
- // One ceremony at a time, each with its own session key and nonce, used once.
- const begin = (mode) => {
- if (ceremony?.mode === mode) return;
- close();
+ function paint() {
+ core.paint();
+ const signed = Boolean(accountChannel.session);
+ const shown = view === "held" && signed ? "signed" : view;
+ for (const name of ["none", "held", "kit", "offer", "join", "recover", "devices"]) $(`view-${name}`).hidden = name !== (view === "removed" ? "none" : view);
+ const [title, sub] = TITLES[shown];
+ $("title").textContent = title;
+ $("sub").textContent = sub;
+ $("sub").hidden = !sub;
+ $("signed").hidden = !signed;
+ $("continue").hidden = signed;
+ $("back").hidden = ["none", "held", "removed"].includes(view) || (view === "kit" && !afterKit?.back);
+ if (held) {
+ $("id").textContent = short(held.prism);
+ $("id").title = held.prism;
+ }
+ }
+ const show = (next) => {
+ view = next;
+ $("error").hidden = true;
paint();
- if (mode === "add") {
- frame.$("account-title").textContent = "Add a device";
- frame.$("account-sub").textContent = "Your phone or another computer joins this account.";
+ };
+ const fail = (words) => {
+ $("error").textContent = words;
+ $("error").hidden = false;
+ };
+ const run = async (task) => {
+ panel.classList.add("busy");
+ frame.$("account").classList.add("busy");
+ $("error").hidden = true;
+ try {
+ const Prism = await prismId();
+ try {
+ await task(Prism);
+ } catch (error) {
+ if (error instanceof Prism.PrismIdError || error instanceof IdentityError) fail(sentence(error.message));
+ else throw error;
+ }
+ } catch {
+ fail("That did not work. Try again.");
+ } finally {
+ panel.classList.remove("busy");
+ frame.$("account").classList.remove("busy");
}
- const saved = accountChannel.session;
- ceremony = {
- mode,
- ready: crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]).then(async (keys) => ({
- keys,
- request: {
- type: `${SPEC}/request`,
- mode,
- nonce: b64u(crypto.getRandomValues(new Uint8Array(32))),
- sessionKey: b64u(await crypto.subtle.exportKey("raw", keys.publicKey)),
- expires: Date.now() + SESSION_DAYS * 864e5,
- ...(mode === "add" ? { account: saved.account, credential: saved.credential } : {}),
- },
- })),
- };
- if (!framed) {
- windowButton.hidden = false;
- return;
+ };
+ const keep = async (Prism, next) => {
+ held = next;
+ await saveDevice(held);
+ await share(Prism, held);
+ };
+
+ // Sign in: take in what the other devices shared first, so a device
+ // removed elsewhere stops here, then sign this app's session.
+ const signIn = async (Prism) => {
+ held = await pull(Prism, held);
+ await saveDevice(held);
+ if (!(await Prism.canSign(held.prism, await heard(Prism, held), held.device.id))) {
+ await forgetDevice();
+ held = null;
+ return show("removed");
}
- const iframe = document.createElement("iframe");
- const page = new URL(target);
- page.hash = `theme=${document.documentElement.classList.contains("dark") ? "dark" : "light"}`;
- iframe.src = page.href;
- iframe.title = mode === "add" ? "Add device" : "Sign in";
- iframe.allow = "publickey-credentials-get; publickey-credentials-create";
- iframe.referrerPolicy = "no-referrer";
- box.replaceChildren(iframe);
- ceremony.iframe = iframe;
- const waiting = ceremony;
- // A policy the frame cannot read (a header, not a meta tag) that will
- // not frame the accounts origin says so here: the window takes over.
- document.addEventListener(
- "securitypolicyviolation",
- (event) => {
- if (ceremony !== waiting || !/^(frame|child|default)-src/.test(event.effectiveDirective) || !String(event.blockedURI).startsWith(origin)) return;
- waiting.answered = true;
- box.replaceChildren();
- windowButton.hidden = false;
- },
- { signal: frame.accountWatch.signal },
- );
- // The iframe shows only once the page answers, so a page that fails
- // leaves no browser error page in the panel. A slow network is not a
- // failure: past 8 s the panel says it is still trying and keeps the
- // page, which shows the moment it answers. Only past 30 s does it give
- // up, with one plain sentence, and the next reach tries again.
- setTimeout(() => {
- if (ceremony !== waiting || waiting.answered) return;
- waiting.slow = true;
- frame.$("account-sub").textContent = "Accounts are slow to answer. Still trying.";
- }, 8000);
- setTimeout(() => {
- if (ceremony !== waiting || waiting.answered) return;
- close();
- frame.$("account-sub").textContent = "Accounts are unreachable right now. Try again soon.";
- }, 30000);
+ const keys = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
+ const sessionKey = b64u(await crypto.subtle.exportKey("raw", keys.publicKey));
+ const expires = Date.now() + SESSION_DAYS * 864e5;
+ const envelope = await Prism.signAction(held, SESSION_ACTION, { sessionKey, expires }, { now: Date.now(), audience: location.origin });
+ const delegation = { app: location.origin, envelope, records: [...held.log.values()] };
+ const who = await verifySession(delegation);
+ const saved = { ...who, delegation, privateKey: keys.privateKey };
+ await store("readwrite", (s) => s.put(saved, "current"));
+ accountChannel.session = saved;
+ show("held");
+ panel.hidePopover();
+ changed();
+ say("Signed in");
+ };
+
+ const showKit = (share, next) => {
+ kit = kitOf(held, share);
+ afterKit = next;
+ show("kit");
+ $("kit-save").focus();
};
- windowButton.addEventListener("click", () => {
- const page = new URL(target);
- page.hash = `popup&theme=${document.documentElement.classList.contains("dark") ? "dark" : "light"}`;
- ceremony.popup = open(page.href, "prism-identity", "popup,width=420,height=420");
- if (!ceremony.popup) say("Allow pop-ups for this page to sign in");
+ // ---- a new id: this device, then its recovery kit, then sign in.
+ $("create").addEventListener("click", () =>
+ run(async (Prism) => {
+ const made = await Prism.createRecovery(await Prism.createPrism({ deviceClass: "browser", protection: "software" }), ONE_PAPER_SHARE);
+ await keep(Prism, made.session);
+ showKit(made.shares[0], { run: signIn });
+ }),
+ );
+ $("kit-save").addEventListener("click", () => {
+ const a = document.createElement("a");
+ a.href = URL.createObjectURL(new Blob([JSON.stringify(kit, null, 1)], { type: "application/json" }));
+ a.download = "prism-id-recovery-kit.json";
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000);
+ });
+ $("kit-done").addEventListener("click", () => {
+ const next = afterKit;
+ kit = null;
+ afterKit = null;
+ run(next.run);
});
- const finish = async (data) => {
- const { keys, request } = await ceremony.ready;
- const delegation = { app: location.origin, nonce: request.nonce, sessionKey: request.sessionKey, expires: request.expires, assertion: data.assertion, records: data.records };
- try {
- const who = await verifySession(delegation, origins);
- const saved = { ...who, delegation, privateKey: keys.privateKey };
- await store("readwrite", (s) => s.put(saved, "current"));
- accountChannel.session = saved;
- close();
- panel.hidePopover();
- changed();
- say("Signed in");
- } catch (error) {
- close();
- begin("signin");
- frame.$("account-sub").textContent = error instanceof IdentityError ? `Sign-in was refused: ${error.message.toLowerCase()}.` : "Sign-in did not finish. Try again.";
- }
+ // ---- this device offers a link; the new one answers on the rendezvous topic.
+ const endLink = () => {
+ link?.stop?.();
+ link = null;
+ $("code").value = "";
+ $("confirm").hidden = true;
+ $("accept").hidden = true;
+ $("join-code").hidden = true;
};
+ $("link").addEventListener("click", () =>
+ run(async (Prism) => {
+ endLink();
+ held = await pull(Prism, held);
+ const { uri, pending } = await Prism.createLinkOffer(held, { now: Date.now() });
+ const topic = await Prism.rendezvousTopic(pending.offer.secret);
+ link = { pending, topic, request: null };
+ link.stop = bus(Prism).subscribe(topic, (bytes) => {
+ let request;
+ try {
+ request = parse(bytes);
+ } catch {
+ return;
+ }
+ if (request?.kind !== Prism.KIND.request || !link || link.request) return;
+ link.request = request;
+ $("confirm").hidden = false;
+ $("accept").hidden = false;
+ $("code").focus();
+ });
+ $("offer").textContent = uri;
+ $("offer").title = uri;
+ drawQr($("qr"), Prism.linkQr(uri));
+ show("offer");
+ }),
+ );
+ $("offer-copy").addEventListener("click", () => copy($("offer-copy"), $("offer").textContent));
+ $("accept").addEventListener("click", () =>
+ run(async (Prism) => {
+ if (!link?.request) return;
+ const accepted = await Prism.acceptLinkRequest(held, link.pending, link.request, { now: Date.now(), confirmCode: $("code").value.trim() });
+ await bus(Prism).publish(link.topic, json(accepted.response));
+ await keep(Prism, accepted.session);
+ endLink();
+ show("held");
+ panel.hidePopover();
+ say("Device added");
+ }),
+ );
- frame.accountWatch?.abort();
- frame.accountWatch = new AbortController();
- addEventListener(
- "message",
- async (event) => {
- if (!ceremony || event.origin !== origin || event.source !== (ceremony.iframe?.contentWindow ?? ceremony.popup)) return;
- const data = event.data ?? {};
- ceremony.answered = true;
- if (data.type === `${SPEC}/ready`) ceremony.iframe?.classList.add("ready");
- if (data.type === `${SPEC}/ready` && ceremony.slow) {
- ceremony.slow = false;
- paint();
+ $("join-go").addEventListener("click", () =>
+ run(async (Prism) => {
+ endLink();
+ const offer = Prism.parseLinkUri($("uri").value.trim());
+ if (offer.expires <= Date.now()) deny("offer", "That link has expired. Make a new one");
+ const device = await Prism.createDevice({ deviceClass: "browser", protection: "software" });
+ const topic = await Prism.rendezvousTopic(offer.secret);
+ const joined = new Promise((done, failed) => {
+ link = { topic };
+ link.stop = bus(Prism).subscribe(topic, (bytes) => {
+ let response;
+ try {
+ response = parse(bytes);
+ } catch {
+ return;
+ }
+ if (response?.kind !== Prism.KIND.response) return;
+ Prism.completeLink(device, offer, response).then(done, failed);
+ });
+ setTimeout(() => failed(new IdentityError("offer", "The other device did not answer. Make a new link and try again")), Math.max(0, offer.expires - Date.now()));
+ });
+ await bus(Prism).publish(topic, json(await Prism.requestLink(device, offer)));
+ $("join-code").textContent = `Type ${await Prism.linkCode(offer.secret, device.record)} on your other device.`;
+ $("join-code").hidden = false;
+ panel.classList.remove("busy");
+ try {
+ await keep(Prism, await joined);
+ } finally {
+ endLink();
}
- if (data.type === `${SPEC}/ready`) event.source.postMessage((await ceremony.ready).request, origin);
- else if (data.type === `${SPEC}/size` && ceremony.iframe) ceremony.iframe.style.height = `${Math.min(Math.max(Number(data.height) || 0, 48), 480)}px`;
- else if (data.type === `${SPEC}/busy`) button.classList.toggle("busy", Boolean(data.on));
- else if (data.type === `${SPEC}/session` && ceremony.mode === "signin") await finish(data);
- else if (data.type === `${SPEC}/added` && ceremony.mode === "add") {
- close();
- panel.hidePopover();
- say("Device added");
+ $("uri").value = "";
+ await signIn(Prism);
+ }),
+ );
+
+ // ---- recovery: the kit's recovery device binds this one, removes every
+ // other device and makes a new kit, which retires the old one.
+ $("kit-file").addEventListener("change", () =>
+ run(async (Prism) => {
+ const file = $("kit-file").files[0];
+ $("kit-file").value = "";
+ let saved;
+ try {
+ saved = JSON.parse(await file.text());
+ } catch {
+ deny("kit", "That is not a recovery kit");
}
- },
- { signal: frame.accountWatch.signal },
+ if (saved?.kind !== KIT || !Array.isArray(saved.records)) deny("kit", "That is not a recovery kit");
+ const device = await Prism.createDevice({ deviceClass: "browser", protection: "software" });
+ const recovered = await Prism.recoverPrism({ prism: saved.prism, records: saved.records, shares: [saved.share], device, rotateRecovery: ONE_PAPER_SHARE });
+ // The kit's log may be older than the id's: what the other devices
+ // shared since, and the id's public log, show a kit already used, by
+ // the newer recovery device that use made. Any app that hears the
+ // public log sees both recoveries; stitch is to order them (its
+ // docs/prism-id.md, Open).
+ const synced = await pull(Prism, recovered.session);
+ const log = await heard(Prism, synced);
+ const state = await Prism.resolvePrism(synced.prism, log);
+ const newer = state.active.filter((id) => state.roles[id] === "recovery" && id !== recovered.shares[0].recovery);
+ if (newer.length || !(await Prism.canSign(synced.prism, log, synced.device.id))) deny("kit", "That recovery kit was already used, and replaced by a newer one");
+ await keep(Prism, synced);
+ showKit(recovered.shares[0], { run: signIn });
+ }),
);
- // Only once the saved session is known, so a quick hover never starts a
- // sign-in for someone already signed in.
- const reach = () => loadSession().then(() => !accountChannel.session && begin("signin"));
+ // ---- the id's devices, from its log; Remove is Prism id's revokeDevice,
+ // which rotates the private boundary key.
+ const listDevices = async (Prism) => {
+ const state = await Prism.resolvePrism(held.prism, held.log);
+ $("device-list").replaceChildren(
+ ...state.active.map((id) => {
+ const item = document.createElement("li");
+ const record = state.devices[id];
+ const label = document.createElement("span");
+ const code = document.createElement("code");
+ code.textContent = id.slice(7, 15);
+ code.title = id;
+ label.append(`${KIND_LABEL[record.class] ?? "Device"} `, code, id === held.device.id ? " (this one)" : "");
+ item.append(label);
+ if (id !== held.device.id && state.roles[id] !== "recovery") {
+ const remove = document.createElement("button");
+ remove.type = "button";
+ remove.className = "text";
+ remove.textContent = "Remove";
+ remove.addEventListener("click", () =>
+ run(async (P) => {
+ await keep(P, await P.revokeDevice(await pull(P, held), id));
+ await listDevices(P);
+ }),
+ );
+ item.append(remove);
+ }
+ return item;
+ }),
+ );
+ };
+ $("devices").addEventListener("click", () =>
+ run(async (Prism) => {
+ held = await pull(Prism, held);
+ await saveDevice(held);
+ await listDevices(Prism);
+ show("devices");
+ }),
+ );
- // The dialog opens centred over the app (panels.css); opening it asks.
- panel.addEventListener("beforetoggle", (event) => {
- if (event.newState === "open") {
- paint();
- return void reach();
- }
- if (ceremony?.mode === "add") close();
+ $("continue").addEventListener("click", () => run(signIn));
+ $("join").addEventListener("click", () => (show("join"), $("uri").focus()));
+ $("recover").addEventListener("click", () => show("recover"));
+ $("back").addEventListener("click", () => {
+ endLink();
+ show(held ? "held" : "none");
});
-
- frame.$("account-add").addEventListener("click", () => begin("add"));
- frame.$("account-out").addEventListener("click", async () => {
+ $("out").addEventListener("click", async () => {
await store("readwrite", (s) => s.delete("current")).catch(() => {});
accountChannel.session = null;
- close();
panel.hidePopover();
changed();
say("Signed out");
});
- frame.$("account-copy").addEventListener("click", async () => {
- const copy = frame.$("account-copy");
+ const copy = async (button, text) => {
try {
- await navigator.clipboard.writeText(accountChannel.session?.account ?? "");
- copy.textContent = "Copied";
+ await navigator.clipboard.writeText(text);
+ button.textContent = "Copied";
} catch {
- copy.textContent = "Select it";
+ button.textContent = "Select it";
+ }
+ setTimeout(() => (button.textContent = "Copy"), 1600);
+ };
+ $("copy").addEventListener("click", () => copy($("copy"), held?.prism ?? ""));
+
+ const reach = async () => {
+ await loadSession();
+ if (!held) {
+ held = await loadDevice();
+ if (view === "none" && held) view = "held";
+ }
+ paint();
+ };
+ panel.addEventListener("beforetoggle", (event) => {
+ if (event.newState === "open") {
+ if (!["kit"].includes(view)) {
+ endLink();
+ view = held ? "held" : view === "removed" ? "removed" : "none";
+ }
+ reach();
}
- setTimeout(() => (copy.textContent = "Copy"), 1600);
});
- paint();
- loadSession().then(paint);
+ reach();
return { reach };
}
+// The theme panel's contents, which the frame puts in its empty panel.
export const THEME_PANEL = `
Theme
diff --git a/frame/publish.mjs b/frame/publish.mjs
index 369eff4..b582e82 100644
--- a/frame/publish.mjs
+++ b/frame/publish.mjs
@@ -10,6 +10,9 @@
// theme panel and the photos
// (frame/panels.mjs, frame/panels.css),
// whose hash the frame carries
+// //prism-id.mjs immutable: Prism id (identity/prism-id.mjs,
+// pinned to stitch), whose hash the
+// panels module carries
// /current.json the pointer: { spec, sha256, module, source }
// /backdrops/.jpg the immersive photos, and -thumb.jpg
//
@@ -45,9 +48,17 @@ const minified = async (source, what) => {
return Buffer.from(result.code, "utf8");
};
-// The panels module first: the frame carries its hash.
+// Prism id first: the panels module carries its hash.
+const prismBytes = await minified(await read("identity/prism-id.mjs"), "prism id");
+const prismSha = named(prismBytes);
+await mkdir(join(out, prismSha), { recursive: true });
+await writeFile(join(out, prismSha, "prism-id.mjs"), prismBytes);
+
+// The panels module next: the frame carries its hash.
const themeSource = await read("frame/panels.mjs");
-const themeBytes = await minified(bake(at(themeSource), '"/*PANELS_CSS*/"', minify(await read("frame/panels.css")), "frame/panels.mjs"), "panels");
+let themeModule = bake(at(themeSource), '"/*PANELS_CSS*/"', minify(await read("frame/panels.css")), "frame/panels.mjs");
+themeModule = bake(themeModule, '"/*PRISM_ID*/"', prismSha, "frame/panels.mjs");
+const themeBytes = await minified(themeModule, "panels");
const themeSha = named(themeBytes);
await mkdir(join(out, themeSha), { recursive: true });
await writeFile(join(out, themeSha, "prism-panels.mjs"), themeBytes);
@@ -75,4 +86,4 @@ for (const [, id] of themeSource.matchAll(/\bid: "([\w-]+)",\s*\n\s*image: "http
if (!photos) throw new Error("frame/panels.mjs names no built-in photo");
const pointer = { spec: "prism/frame/1", sha256, module: `${sha256}/prism-frame.mjs`, source: { repository: "UOR-Foundation/template", commit } };
await writeFile(join(out, "current.json"), JSON.stringify(pointer, null, 2) + "\n");
-console.log(`frame: ${sha256} (${bytes.length} bytes), panels ${themeSha} (${themeBytes.length} bytes), ${photos} photos -> ${out}/current.json`);
+console.log(`frame: ${sha256} (${bytes.length} bytes), panels ${themeSha} (${themeBytes.length} bytes), prism id ${prismSha} (${prismBytes.length} bytes), ${photos} photos -> ${out}/current.json`);
diff --git a/identity/PROTOCOL.md b/identity/PROTOCOL.md
index 39839e5..5774fe8 100644
--- a/identity/PROTOCOL.md
+++ b/identity/PROTOCOL.md
@@ -1,124 +1,103 @@
-# prism/identity/1
+# prism/identity/4
+
+A Prism id is stitch's Prism id ([afflom/stitch](https://github.com/afflom/stitch),
+`src/prism-id.js` and `docs/prism-id.md`). It is pinned by commit in
+[stitch.lock](stitch.lock) and copied, with the stitch modules it imports and
+the model decisions they call, into [prism-id.mjs](prism-id.mjs) by
+[stitch-sync.mjs](stitch-sync.mjs). This file says how the frame uses it.
+Stitch's documents are the contract for the id itself, and every
+authorization decision is taken by its `Stitch.PrismId` model. When stitch's
+Prism model is refined, re-pin:
+
+```sh
+node identity/stitch-sync.mjs # writes prism-id.mjs and stitch.lock
+npm run test:identity # the lock matches, every check refuses, the flow signs in
+```
-A Prism account is a passkey. Its private key never leaves the device's secure
-hardware (Secure Enclave, TPM, Android TEE or StrongBox). Everything else is
-public, content addressed and checkable by anyone, so no server is trusted to
-say who a user is.
+prism/identity/4 replaces identity/3 (a Prism id page at id.uor.foundation
+and a registry mailbox) and identity/1 and /2 (passkeys). Nothing here runs
+on a server of Prism's own. A session has the same shape as in identity/3.
## Parties
| Party | Where | Holds |
| --- | --- | --- |
-| Identity page | `https://id.uor.foundation` (rpId `id.uor.foundation`) | Nothing. It runs the WebAuthn ceremony and hands the result to the app. It serves no other content, because every page on the rpId's origin can ask a passkey to sign. |
-| Registry | `https://registry.uor.foundation`, routes under `/passkey/` | Public key records, indexed by credential. It verifies before it stores, and cannot forge: every record is checked again by whoever reads it. |
-| Frame | `` in every Prism app | Checks every signature in the browser and keeps the session. |
-
-For development the identity page runs on `http://localhost:` with rpId
-`localhost`, which WebAuthn treats as a secure context.
-
-## Encodings
-
-`b64u` is base64url without padding. `H(x)` is SHA-256. Strings are UTF-8.
-
-- **Key ID**: `b64u(H(spki))`, where `spki` is the credential public key as
- DER SubjectPublicKeyInfo (`AuthenticatorAttestationResponse.getPublicKey()`).
-- **Account ID**: the key ID of the account's first passkey. It never changes.
-- **Algorithms**: ES256 (`-7`, P-256) and RS256 (`-257`, for older Windows Hello).
-
-## Signed messages
-
-Every signature is a WebAuthn assertion: the authenticator signs
-`authenticatorData || H(clientDataJSON)`. The challenge inside `clientDataJSON`
-is the hash of the message below, so the signature covers the message. A
-verifier rebuilds the message, then checks, in order and failing closed:
-
-1. `clientData.type` is `webauthn.get`.
-2. `clientData.challenge` equals `b64u(H(message))`.
-3. `clientData.origin` is an identity origin the verifier accepts.
-4. `authenticatorData[0..32]` equals `H(rpId)` for that origin.
-5. Flags have user presence (`0x01`) and user verification (`0x04`).
-6. The signature verifies under the key's `spki` (ECDSA signatures are DER).
-
-| Purpose | Message |
-| --- | --- |
-| Session | `prism/identity/session/1\n\n\n\n` |
-| Bind a device | `prism/identity/bind/1\n\n` |
-| Revoke a device | `prism/identity/revoke/1\n\n` |
-
-`` is 32 random bytes in b64u, made by the app and used once.
-`` is the app's session public key, raw P-256 point in b64u.
-`` is a Unix time in milliseconds. A bind or revoke message names
-exactly one change, so replaying it repeats that change and nothing else.
-
-## Key record
-
-```json
-{
- "spec": "prism/identity/key/1",
- "key": "",
- "account": "",
- "credential": "",
- "alg": -7,
- "spki": "",
- "origin": "https://id.uor.foundation",
- "created": 1762516800000,
- "binding": null
-}
-```
-
-`binding` is null for an account's first key (then `key == account`).
-Otherwise it is the bind assertion made by a key already in the account:
-
-```json
-{ "credential": "", "clientDataJSON": "", "authenticatorData": "", "signature": "" }
-```
-
-A reader accepts a record only when `key == b64u(H(spki))` and either
-`key == account`, or the binding verifies as a bind message under a record that
-the reader has itself accepted for the same account. A chain longer than five
-bindings is refused.
-
-## Registry routes
-
-All bodies are JSON. Errors are `{"error": "", "message": ""}`.
-
-| Route | Does |
-| --- | --- |
-| `POST /passkey/challenge` | `{"challenge": "", "expires": }`. Single use, 120 s. |
-| `POST /passkey/register` | Registers a new passkey. Body: `spki`, `alg`, `credential`, `clientDataJSON`, `authenticatorData`, `attestationObject`, `transports`, and `binding` (null, or a bind assertion plus `account`). |
-| `GET /passkey/credential/{credential}` | The key record. `404` unknown, `410` revoked. |
-| `GET /passkey/account/{account}` | `{"account", "keys": [records], "revoked": [key IDs]}`. |
-| `POST /passkey/revoke` | Body: `account`, `key`, and a revoke assertion by a live key of the account. |
-
-`register` checks: `clientData.type` is `webauthn.create`; its challenge is one
-the registry issued and has not used (consumed on first use, pass or fail);
-origin is allowed; `rpIdHash`, UP, UV and AT flags; the attested credential ID
-equals `credential`; the attested COSE key is the same public key as `spki`;
-the credential is not already registered (first write wins); and the binding,
-when present, verifies under a live key of `account`. Error codes:
-`challenge`, `origin`, `rp`, `flags`, `credential`, `key`, `exists`,
-`binding`, `signature`, `revoked`, `rate`.
-
-Further codes: `request` (400, a malformed body), `account` (404, an unknown
-account), `store` (500, details only in the registry's log). An unknown
-credential is `credential` with 404. A bind or revoke assertion with the wrong
-type or challenge is `signature`.
-
-`revoke` takes `{account, key, assertion: {credential, clientDataJSON,
-authenticatorData, signature}}` and answers `{account, key, revoked: true,
-newly}`. A key bound before its binder was revoked stays valid, so
-`/passkey/account/` keeps revoked records in `keys` and names them in
-`revoked`; a reader builds a binding chain from that list. The key that signs
-a session must itself be live (`/passkey/credential/` answers 410).
-
-Writes are rate limited per client address. Reads are public with CORS `*`;
-writes allow only the identity origins.
-
-## Session
-
-On sign-in the frame makes a non-extractable P-256 key with WebCrypto, stored
-in the app origin's IndexedDB, and asks the passkey to sign a session message
-naming it. The signed session is the delegation: anyone can check that the
-account's passkey let this browser key act for it, on this app's origin, until
-`expires`. The private session key cannot be read out by script. No token is
-ever kept in `localStorage`. A session lasts 7 days; sign-out deletes it.
+| Frame | `` in every Prism app | This origin's device of the id (keys, keyring and log, in IndexedDB `prism-id`), and this app's session key with the id's signed session (IndexedDB `prism-identity`). It checks every signature itself. |
+| stitch's relay | The frame's `PRISM_RELAY` (`https://ntfy.sh`), with stitch's relay framing, through Prism id's `createRelayBus` | Messages under names hashed from secrets only holders know: sealed sync messages (`prism-sync:` topics) and link requests and answers (`prism-rendezvous:` topics). It holds them for the warm lifetime (30 minutes). |
+
+A page's `connect-src` must name the relay and its `wss:` origin. The page
+build reads `PRISM_RELAY` from the live frame. A page that does not admit the
+relay keeps the id on its device: creating, signing in and recovery work, but
+linking and sync do not.
+
+## Sign-in
+
+1. The frame takes in the sync messages the relay holds for every boundary
+ key it has, so a device removed elsewhere stops here
+ (`canSign` is false: the panel says "This device was removed" and forgets
+ the device).
+2. It makes a non-extractable P-256 session key and signs
+ `signAction(device, "prism/session/1", {sessionKey, expires}, {audience: location.origin})`.
+ `expires` is 7 days away; the most allowed is 8.
+3. It checks the result with `verifySession`, as anyone the app shows a
+ signature to does: the log resolves for the envelope's prism id, the
+ signer is an active device, the audience is this origin, the action is
+ fresh (`Stitch.PrismId.actionFresh`, `actionAllowed`). Only then does it
+ keep the session.
+
+A kept session is `{app, envelope, records}`. `frame.sign(bytes)` signs with
+the session key and returns the signature with it. Anyone can check it later
+with `verifySession(session, {fresh: 0})`, as of its signing and bounded by
+its expiry.
+
+## A new id
+
+`createPrism`, then `createRecovery(session, {threshold: 1, guardians: [{paper: true}]})`.
+The recovery kit is `{kind: "prism/recovery-kit/1", prism, share, records}`,
+with the paper share and the log, downloaded as JSON.
+
+## Linking
+
+Stitch's out-of-band link, over the relay:
+
+1. Signed-in device: `createLinkOffer`. The panel shows the `prism-link:`
+ URI and its QR code (`linkQr`), and subscribes to `rendezvousTopic(secret)`.
+2. New device: `parseLinkUri`, a new device, then `requestLink`, published on
+ the rendezvous topic. It shows `linkCode(secret, device)`.
+3. The person types those six digits into the first device, which calls
+ `acceptLinkRequest` with them as `confirmCode` and publishes the answer.
+ A wrong code is refused and the offer stays usable until it expires.
+4. New device: `completeLink`, then sign-in.
+
+## Recovery
+
+From a kit: `recoverPrism({prism, records, shares: [share], device, rotateRecovery: {threshold: 1, guardians: [{paper: true}]}})`
+binds this browser's new device and revokes every other device. It replaces
+the recovery device, so the new kit retires the old one. The frame then takes
+in what the relay holds. If that shows another active recovery device, the
+kit was already used and is refused.
+
+## Devices
+
+The panel lists the id's active devices from its log and removes one with
+`revokeDevice`, which rotates the private boundary key. It then shares the
+log under every key it holds, so devices that have not taken up the rotation
+still hear it.
+
+## Apps hear removals
+
+Every time a device shares (after creating, linking, removing or
+recovering), it also publishes the id's public log with `publishLog`, on a
+topic derived from the prism id alone. `verifySession` passes the relay to
+`verifyAction` (`{bus}`), which merges what that topic holds (`heardLog`), so
+a session from a device removed elsewhere is refused even when that device
+never synced. Sign-in and recovery check the same merged log.
+
+## Not yet (stitch's to define, its docs/prism-id.md "Open")
+
+- A used kit replayed against its own old log forks the recovery chain. Every
+ frame that hears the public log sees both recoveries and refuses the kit;
+ ordering them needs stitch's witnessed time.
+- The relay holds messages for 30 minutes, so an app hears a removal only
+ within 30 minutes of the last publish. A session signed before a removal
+ lasts until it expires (at most 8 days).
diff --git a/identity/README.md b/identity/README.md
index bbb8961..be5276a 100644
--- a/identity/README.md
+++ b/identity/README.md
@@ -1,64 +1,89 @@
-# Prism accounts
+# Prism ids
-The person icon at the right end of every Prism app's bar. One click opens the
-account panel; one more, and Face ID, Touch ID, Windows Hello or a phone signs
-the visitor in. No password exists anywhere. [PROTOCOL.md](PROTOCOL.md) is the
-contract; this file says why it is built this way and how to run it.
+The person icon at the right end of every Prism app's bar. One click and
+**Create a Prism id**, and the visitor is signed in. There is no password, no
+passkey prompt and no account server: the browser makes its own key, which
+never leaves it. One Prism id signs in to every Prism app, Foundry included.
+[PROTOCOL.md](PROTOCOL.md) is the contract. The id itself is stitch's Prism
+id, pinned in [stitch.lock](stitch.lock), and nothing here is deployed beyond
+the frame.
-## Why a passkey, and why this domain
+## One id, every app and device
-A passkey is the only credential a web page can reach that lives in the
-device's secure hardware: the Secure Enclave on Apple devices, the TPM under
-Windows Hello, the TEE or StrongBox on Android. The private key never leaves
-it, and the fingerprint or face never leaves the device at all.
+Each app keeps its own device of the id, in its own origin's storage. To use
+the same id in another app, or on a phone:
-A passkey belongs to one domain, its rpId, and every page on that domain can
-ask it to sign. So the rpId is `id.uor.foundation`, which serves this one
-page and nothing else. It is not `registry.uor.foundation`, which serves
-content others push, and not `uor.foundation`, which would let every
-subdomain ask. **The rpId is permanent**: changing it orphans every passkey.
+1. In an app already signed in, choose **Add a device or app**. Scan the QR code with a phone, or copy the link.
+2. In the new app, choose **Use my Prism id from another device or app** and paste it.
+3. The new app shows six digits. Type them into the first app.
+
+This is stitch's link offer. The link holds a one-time secret, good for five
+minutes. The six digits bind that secret to the device that answered, so
+someone who copied the link first gets different digits. The two devices meet
+on stitch's relay, under a name derived from that secret.
+
+## Losing every device never loses the id
+
+A new id's first step is its **recovery kit**: a file holding the paper share
+of the id's recovery device (stitch's threshold recovery, one share of one)
+and the id's log. On any browser, **Use a recovery kit** brings the id back.
+That browser becomes the id's device, every other device is removed, and a
+new kit replaces the old one.
+
+Recovery restores the id: signing in, as the same id, everywhere. It does not
+restore what an app kept only in a lost browser (its local projects, chats or
+databases). That lives with the app, not the id.
+
+Stitch lets only the recovery device replace itself, so a member cannot make
+a new kit. A kit is made when the id is created and again on each recovery.
+
+## Devices
+
+**Devices** lists the id's devices. **Remove** is stitch's `revokeDevice`,
+which rotates the id's private key; the id itself never changes. A removed
+device stops signing the next time it syncs. The recovery device has no
+Remove, because stitch lets no member revoke it.
## Who is trusted with what
| Part | If it were hostile, it could | It could not |
| --- | --- | --- |
-| Registry | Withhold a record, so a sign-in fails | Forge or swap a key: a record's name is its key's hash, and every binding is a passkey signature the frame checks |
-| Sign-in page | Refuse to help | Sign anything without the visitor's own biometric prompt, which names `id.uor.foundation` |
-| Another app | Ask the visitor to sign in to *it* | Use that session elsewhere: a session names the app origin it was signed for |
-| Script on the app's own page | Use the session while the page is open | Copy the session key out: it is a non-extractable WebCrypto key |
+| stitch's relay (ntfy) | Withhold or delay a sync message or a link answer, so a removal or a link does not arrive | Read a sync message (sealed in the id's private boundary) or forge any record (each is signed and checked by the reader). It sees hashed topic names, timing, padded sizes, and in a link answer the id's log (public keys and signatures) |
+| The app's page (its script) | Everything this origin's device can do: sign for this app, link or remove devices, read a recovery kit as it is made | Copy the device keys out: they are non-extractable WebCrypto keys |
+| Another app | Ask the visitor to sign in to *it* | Use this app's device or session: storage is per origin, and a session names the app origin it was signed for |
+| Anyone holding a recovery kit | Take the id over, from any browser | Use it once a newer kit replaced it, if they hear what the id's devices shared (see below) |
-Revocation is the registry withholding a record, so it takes effect at the
-next sign-in, not inside a session already signed (7 days at most).
+There is no biometric or OS prompt: a device's keys sign whenever its page
+asks, and the visitor's click is the only consent.
-## Adding a device
+A session lasts at most 8 days (the frame asks for 7). A removed device stops
+signing new sessions once it syncs, but a session it signed earlier stays
+valid until it expires. Every device also publishes the id's public log on
+the relay, and an app checking a session merges it, so a stolen browser that
+never syncs is refused once another device removed it and shared that.
-Synced passkeys (iCloud Keychain, Google Password Manager) already follow the
-visitor to their other devices. For any other device: open the panel, choose
-**Add another device**, make the passkey on the new device (a phone scans the
-code the browser shows), then confirm on this one. The registry stores the new
-key with that confirmation, and every app accepts either key for the account.
+The relay keeps a message for stitch's warm lifetime (30 minutes). A device
+away longer, or an app checking later, catches up from the next message a
+device shares. A used kit replayed against its own old log is refused once
+the newer recovery shows up in what the devices shared; stitch is to order
+the two recoveries.
## Run it
```sh
npm ci && npx playwright install chromium
-npm run test:identity # every refused check, then the whole flow in Chromium
-node identity/dev.mjs # the sign-in page on localhost:8790, a demo app on 127.0.0.1:8791
+npm run test:identity # the stitch copy matches its lock, every refused check, then the flow in Chromium
+node identity/dev.mjs # two demo apps, on 127.0.0.1:8791 and :8792
```
-`dev.mjs` stands in for the registry with an in-memory store that does not
-verify registrations; the frame's checks are the real ones.
+`test.mjs` puts an in-memory relay in place of the real one in the browser.
+`dev.mjs` run by hand uses the real relay.
-## Deploy
+## Follow stitch
-1. `node identity/publish.mjs out` writes the page with every file it loads
- pinned by hash, and `current.json` naming the page by its SHA-256.
-2. Serve `out/` as static files at `https://id.uor.foundation`, HTTPS only,
- with HSTS. Do not set `Cross-Origin-Opener-Policy: same-origin`: the
- popup fallback needs `window.opener`.
-3. Deploy the registry's `/passkey/` routes (UOR-Foundation/kappa-registry)
- with `https://id.uor.foundation` as the allowed identity origin.
+```sh
+node identity/stitch-sync.mjs # fetches that commit; add a local checkout path to read it instead
+```
-Ship the frame change only after steps 2 and 3 are live: every Prism app
-loads the frame from main on its next visit. Before then the panel says
-Prism accounts are not reachable, and never shows a broken page.
+This rewrites `prism-id.mjs` and `stitch.lock`. Copy `frame/` and `identity/`
+to Foundry and prism-devrel byte for byte, as with any frame change.
diff --git a/identity/dev.mjs b/identity/dev.mjs
index 5613542..d62096e 100644
--- a/identity/dev.mjs
+++ b/identity/dev.mjs
@@ -1,114 +1,74 @@
#!/usr/bin/env node
-// The whole account flow on one machine: the sign-in page on
-// http://localhost:8790 (rpId localhost), an in-memory stand-in for the
-// registry's /passkey/ routes on the same origin, and a demo app page on
-// http://127.0.0.1:8791 that mounts the frame. The stand-in stores and
-// serves records; it does not verify registrations, which is the real
-// registry's job (UOR-Foundation/kappa-registry). The frame verifies every
-// signature exactly as it does in production, so this exercises the real
-// client path. Used by identity/test.mjs; run it by hand to try the flow:
+// Prism ids on one machine: two demo apps, each its own origin
+// (http://127.0.0.1:8791 and http://127.0.0.1:8792), both mounting the frame
+// as frame/publish.mjs bakes it, so each keeps its own device of a visitor's
+// Prism id. Devices meet on stitch's relay (the frame's PRISM_RELAY), which
+// the apps' policy admits; identity/test.mjs stands a relay in for it in the
+// browser, and run by hand the real one is used. Used by identity/test.mjs;
+// run it by hand to try the flow:
// node identity/dev.mjs
-import { createHash, randomBytes } from "node:crypto";
+import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { createServer } from "node:http";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
const root = fileURLToPath(new URL("../", import.meta.url));
-const b64u = (bytes) => Buffer.from(bytes).toString("base64url");
-const types = { ".html": "text/html; charset=utf-8", ".mjs": "text/javascript", ".css": "text/css" };
// The frame as publish.mjs bakes it, without minifying: its panels module
-// beside it, named by its SHA-256, on the demo app's own origin.
+// and Prism id beside it, each named by its SHA-256, on the demo app's own
+// origin.
const PUBLISHED_HOST = "https://uor-foundation.github.io/template/frame/";
async function bakedFrame(host) {
const at = (text) => text.split(JSON.stringify(PUBLISHED_HOST)).join(JSON.stringify(host));
- const panels = at(await readFile(join(root, "frame/panels.mjs"), "utf8")).replace('"/*PANELS_CSS*/"', JSON.stringify(await readFile(join(root, "frame/panels.css"), "utf8")));
+ const prismId = await readFile(join(root, "identity/prism-id.mjs"), "utf8");
+ const prismSha = createHash("sha256").update(prismId).digest("hex");
+ const panels = at(await readFile(join(root, "frame/panels.mjs"), "utf8"))
+ .replace('"/*PANELS_CSS*/"', JSON.stringify(await readFile(join(root, "frame/panels.css"), "utf8")))
+ .replace('"/*PRISM_ID*/"', JSON.stringify(prismSha));
const sha = createHash("sha256").update(panels).digest("hex");
let module = at(await readFile(join(root, "frame/frame.mjs"), "utf8"));
module = module.replace('"/*CSS*/"', JSON.stringify(await readFile(join(root, "frame/frame.css"), "utf8")));
module = module.replace('"/*BRAND*/"', JSON.stringify(await readFile(join(root, "site/brand/hologram-warm.css"), "utf8")));
- return { frame: module.replace('"/*PANELS*/"', JSON.stringify(sha)), panels, sha };
+ return { frame: module.replace('"/*PANELS*/"', JSON.stringify(sha)), panels, sha, prismId, prismSha };
}
-export function start({ idPort = 8790, appPort = 8791 } = {}) {
- const accounts = `http://localhost:${idPort}`;
- const challenges = new Set();
- const records = new Map();
-
- const json = (response, status, body) => {
- response.writeHead(status, { "content-type": "application/json", "access-control-allow-origin": "*", "cache-control": "no-store" });
- response.end(JSON.stringify(body));
- };
- const body = (request) => new Promise((done) => {
- let text = "";
- request.on("data", (chunk) => (text += chunk));
- request.on("end", () => done(text ? JSON.parse(text) : {}));
- });
-
- const id = createServer(async (request, response) => {
- const path = new URL(request.url, accounts).pathname;
- if (request.method === "POST" && path === "/passkey/challenge") {
- const challenge = b64u(randomBytes(32));
- challenges.add(challenge);
- return json(response, 200, { challenge, expires: Date.now() + 120000 });
- }
- if (request.method === "POST" && path === "/passkey/register") {
- const r = await body(request);
- const client = JSON.parse(Buffer.from(r.clientDataJSON, "base64url"));
- if (!challenges.delete(client.challenge)) return json(response, 400, { error: "challenge", message: "The challenge is unknown or used." });
- if (records.has(r.credential)) return json(response, 409, { error: "exists", message: "The passkey is already registered." });
- const key = b64u(createHash("sha256").update(Buffer.from(r.spki, "base64url")).digest());
- const binding = r.binding ? { credential: r.binding.credential, clientDataJSON: r.binding.clientDataJSON, authenticatorData: r.binding.authenticatorData, signature: r.binding.signature } : null;
- const record = { spec: "prism/identity/key/1", key, account: r.binding?.account ?? key, credential: r.credential, alg: r.alg, spki: r.spki, origin: client.origin, created: Date.now(), binding };
- records.set(r.credential, record);
- return json(response, 201, record);
- }
- const credential = /^\/passkey\/credential\/([\w-]+)$/.exec(path)?.[1];
- if (request.method === "GET" && credential) {
- const record = records.get(credential);
- return record ? json(response, 200, record) : json(response, 404, { error: "unknown", message: "No passkey has that credential." });
- }
- const account = /^\/passkey\/account\/([\w-]+)$/.exec(path)?.[1];
- if (request.method === "GET" && account) {
- const keys = [...records.values()].filter((r) => r.account === account);
- return keys.length ? json(response, 200, { account, keys, revoked: [] }) : json(response, 404, { error: "account", message: "No account has that name." });
- }
- const file = { "/": "index.html", "/id.mjs": "id.mjs", "/id.css": "id.css", "/brand.css": "../site/brand/hologram-warm.css" }[path];
- if (!file) return json(response, 404, { error: "unknown", message: "Not found." });
- let text = await readFile(join(root, "identity", file), "utf8");
- if (file === "index.html") text = text.replace('content="https://registry.uor.foundation"', `content="${accounts}"`);
- response.writeHead(200, { "content-type": types[file.slice(file.lastIndexOf("."))] ?? "text/css", "cache-control": "no-store" });
- response.end(text);
- });
-
- const app = createServer(async (request, response) => {
- const path = new URL(request.url, "http://x").pathname;
- if (path === "/frame.mjs" || path === "/panels.mjs" || path.endsWith("/prism-panels.mjs")) {
- const baked = await bakedFrame(`http://127.0.0.1:${appPort}/frame/`);
- if (path.endsWith("/prism-panels.mjs") && path !== `/frame/${baked.sha}/prism-panels.mjs`) return json(response, 404, { error: "unknown", message: "Not found." });
+function app(port, name, relay) {
+ const origin = `http://127.0.0.1:${port}`;
+ return createServer(async (request, response) => {
+ const path = new URL(request.url, origin).pathname;
+ if (path === "/frame.mjs" || path.endsWith("/prism-panels.mjs") || path.endsWith("/prism-id.mjs")) {
+ const baked = await bakedFrame(`${origin}/frame/`);
+ const served = { "/frame.mjs": baked.frame, [`/frame/${baked.sha}/prism-panels.mjs`]: baked.panels, [`/frame/${baked.prismSha}/prism-id.mjs`]: baked.prismId }[path];
+ if (served === undefined) {
+ response.writeHead(404);
+ return response.end();
+ }
response.writeHead(200, { "content-type": "text/javascript", "cache-control": "no-store" });
- return response.end(path === "/frame.mjs" ? baked.frame : baked.panels);
+ return response.end(served);
}
response.writeHead(200, {
"content-type": "text/html; charset=utf-8",
- // /strict frames nothing, as a page whose policy predates accounts: the
- // frame must fall back to the sign-in window.
- "content-security-policy": `default-src 'self'; script-src 'self' blob:; style-src 'unsafe-inline'; frame-src ${path === "/strict" ? "'none'" : accounts}`,
+ // As a built page's policy: its own origin and the relay, nothing framed.
+ "content-security-policy": `default-src 'self'; script-src 'self' blob:; style-src 'unsafe-inline'; connect-src 'self' ${relay} ${relay.replace(/^https:/, "wss:")}; frame-src 'none'`,
});
- response.end(`Account demo
-`);
+ response.end(`${name}
+`);
});
+}
- return Promise.all([new Promise((done) => id.listen(idPort, done)), new Promise((done) => app.listen(appPort, "127.0.0.1", done))]).then(() => ({
- accounts,
- app: `http://127.0.0.1:${appPort}/`,
- records,
- close: () => Promise.all([new Promise((done) => id.close(done)), new Promise((done) => app.close(done))]),
- }));
+export async function start({ ports = [8791, 8792] } = {}) {
+ const PRISM_RELAY = /export const PRISM_RELAY = "([^"]+)"/.exec(await readFile(join(root, "frame/frame.mjs"), "utf8"))[1];
+ const servers = ports.map((port, i) => app(port, i ? "Second demo" : "Account demo", PRISM_RELAY));
+ await Promise.all(servers.map((server, i) => new Promise((done) => server.listen(ports[i], "127.0.0.1", done))));
+ return {
+ apps: ports.map((port) => `http://127.0.0.1:${port}/`),
+ relay: PRISM_RELAY,
+ close: () => Promise.all(servers.map((server) => new Promise((done) => server.close(done)))),
+ };
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
const running = await start();
- console.log(`sign-in page ${running.accounts}/\ndemo app ${running.app}`);
+ console.log(`demo apps ${running.apps.join(" and ")}, devices meet on ${running.relay}`);
}
diff --git a/identity/id.css b/identity/id.css
deleted file mode 100644
index c4d421e..0000000
--- a/identity/id.css
+++ /dev/null
@@ -1,44 +0,0 @@
-/* The sign-in page, drawn inside the frame's account panel (or alone, in a
- * popup). It inherits nothing from the app, so it brings the brand's tokens
- * (brand.css) and keeps a transparent ground: the panel behind it shows. */
-html { color-scheme: light; background: transparent; }
-html.dark { color-scheme: dark; }
-body {
- margin: 0;
- font-family: var(--font-sans);
- font-size: 1rem;
- line-height: 1.45;
- color: var(--foreground);
- background: transparent;
-}
-html.alone body { background: var(--background); min-height: 100vh; display: grid; place-items: center; }
-html.alone main { width: min(22rem, 100vw - 2rem); }
-main { display: grid; gap: 0.618rem; }
-button {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 0.5rem;
- min-height: 2.618rem;
- padding: 0 1rem;
- border: 1px solid transparent;
- border-radius: calc(var(--radius) - 2px);
- font: inherit;
- font-weight: 500;
- cursor: pointer;
- transition: background 150ms ease, opacity 150ms ease;
-}
-button svg { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
-button.primary { background: var(--primary); color: var(--primary-foreground); }
-button.primary:hover { background: color-mix(in oklab, var(--primary), var(--primary-foreground) 12%); }
-button.link { display: inline; min-height: 0; padding: 0; border: 0; background: none; color: var(--foreground); font-weight: 500; text-decoration: underline; text-decoration-color: var(--border); text-underline-offset: 0.2em; }
-button:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
-button:disabled { opacity: 0.6; cursor: default; }
-main.busy button { opacity: 0.6; pointer-events: none; }
-main.busy #go svg { animation: pulse 1.2s ease-in-out infinite; }
-@keyframes pulse { 50% { opacity: 0.35; } }
-.note { margin: 0; color: var(--muted-foreground); font-size: 0.8125rem; text-align: center; }
-.error { margin: 0; color: var(--destructive); font-size: 0.8125rem; text-align: center; }
-@media (pointer: coarse) { button:not(.link) { min-height: 3rem; } }
-@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }
-@media (forced-colors: active) { button { border-color: ButtonText; } }
diff --git a/identity/id.mjs b/identity/id.mjs
deleted file mode 100644
index de593ee..0000000
--- a/identity/id.mjs
+++ /dev/null
@@ -1,303 +0,0 @@
-// The Prism sign-in page (prism/identity/1, identity/PROTOCOL.md). It runs
-// the WebAuthn ceremony on the identity origin and hands the result to the
-// app that asked. It verifies nothing for the app: the frame checks every
-// signature itself, so this page can only fail to help, never lie.
-//
-// It runs in the frame's account panel as an iframe. Where a browser refuses
-// a passkey ceremony inside an iframe, it opens itself as a popup, and the
-// popup reports back through it. The app's origin is always the one the
-// browser gives the message, never one the message claims.
-
-const REGISTRY = document.querySelector('meta[name="prism-registry"]').content.replace(/\/$/, "");
-const RP = location.hostname;
-const SPEC = "prism/identity/1";
-const WEEK = 8 * 24 * 60 * 60 * 1000;
-
-const enc = new TextEncoder();
-const b64u = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
-const unb64u = (text) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
-const sha256 = async (text) => new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(text)));
-const $ = (id) => document.getElementById(id);
-
-const alone = window.parent === window;
-const popup = alone && Boolean(window.opener) && /(^#|&)popup(&|$)/.test(location.hash);
-const peer = alone ? window.opener : window.parent;
-const params = new URLSearchParams(location.hash.slice(1));
-if (params.get("theme") === "dark") document.documentElement.classList.add("dark");
-if (alone) document.documentElement.classList.add("alone");
-
-// The request: who asked (the browser says) and what the app's session will be.
-let request = null;
-let app = null;
-// A popup opened by this page's own iframe answers that iframe, which relays.
-let relayed = false;
-
-const valid = (r) =>
- r?.type === `${SPEC}/request` &&
- ["signin", "add"].includes(r.mode) &&
- /^[\w-]{43}$/.test(r.nonce) &&
- /^[\w-]{87}$/.test(r.sessionKey) &&
- Number.isSafeInteger(r.expires) &&
- r.expires > Date.now() &&
- r.expires <= Date.now() + WEEK &&
- (r.mode === "signin" || (/^[\w-]{43}$/.test(r.account) && /^[\w-]+$/.test(r.credential)));
-
-// Results go only to the app that asked; "ready" carries nothing and goes to whoever opened the page.
-const send = (message) => peer?.postMessage({ ...message, type: `${SPEC}/${message.type}` }, message.type === "ready" ? "*" : relayed ? location.origin : app);
-
-addEventListener("message", (event) => {
- if (event.source !== peer) return;
- const data = event.data;
- if (!valid(data)) return;
- // A popup this page's iframe opened takes the app's origin from that
- // iframe, which took it from the browser. Anyone else is the app.
- relayed = popup && event.origin === location.origin;
- const asking = relayed ? data.app : event.origin;
- if (typeof asking !== "string" || !/^https?:\/\/[^/]+$/.test(asking)) return;
- request = data;
- app = asking;
- paint();
-});
-
-// The popup's result, relayed by the iframe that opened it.
-let child = null;
-addEventListener("message", (event) => {
- if (!child || event.source !== child || event.origin !== location.origin) return;
- const type = String(event.data?.type ?? "");
- if (!type.startsWith(`${SPEC}/`) || type.endsWith("/ready") || type.endsWith("/size")) return;
- peer.postMessage(event.data, app);
- child.close();
-});
-
-// The passkey this device last signed in with: a hint, not a secret (a
-// credential ID names a key, it proves nothing). With it the browser asks
-// for that one passkey and skips its chooser. It is never taken as proof
-// that the device has no other: a remembered passkey that does not answer
-// is forgotten and the next tap asks for any, so a missing hint can never
-// send someone with an account to Create account. Inside an app's panel the
-// browser keeps this per app; in the sign-in window, for every app.
-const HINT = "prism-identity/last-credential";
-let remembered = null;
-try {
- const saved = localStorage.getItem(HINT);
- remembered = /^[\w-]{16,}$/.test(saved ?? "") ? saved : null;
-} catch {
- // No storage (a private window, blocked site data): every sign-in asks for any passkey.
-}
-function remember(credential) {
- remembered = credential;
- try {
- if (credential) localStorage.setItem(HINT, credential);
- else localStorage.removeItem(HINT);
- } catch {
- // Not kept; the next sign-in shows the chooser.
- }
-}
-
-// The device's own authenticator, by name, on the button itself, so the
-// visitor knows what is about to ask. Named only where one is set up;
-// elsewhere the browser offers a phone or a security key: "a passkey".
-const DEVICE = (() => {
- const ua = navigator.userAgent;
- if (/iPhone|iPad|iPod/.test(ua)) return "Face ID or Touch ID";
- if (/Android/.test(ua)) return "your screen lock";
- if (/Windows NT/.test(ua)) return "Windows Hello";
- if (/Macintosh/.test(ua)) return "Touch ID";
- return null;
-})();
-let device = null;
-if (DEVICE && window.PublicKeyCredential?.isUserVerifyingPlatformAuthenticatorAvailable) {
- PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable().then((available) => {
- device = available ? DEVICE : null;
- if (request) paint();
- }, () => {});
-}
-
-// One button. Continue asks the device for its Prism passkey (the one it
-// last used, when it remembers one); a device with none (the browser will
-// not say so before asking) turns the same button into Create account.
-// Adding a device is the same button, relabelled.
-let fresh = false;
-function paint() {
- const label = request.mode === "add" ? "Add device" : fresh ? "Create account" : `Continue with ${device ?? "a passkey"}`;
- $("go-label").textContent = label;
- $("fresh").hidden = !fresh || request.mode === "add";
- $("go").disabled = false;
- size();
-}
-
-function size() {
- if (!alone && app) send({ type: "size", height: Math.ceil(document.documentElement.getBoundingClientRect().height) });
-}
-new ResizeObserver(size).observe(document.body);
-
-function busy(on) {
- $("card").classList.toggle("busy", on);
- if (on && device) $("go-label").textContent = `Waiting for ${device}…`;
- else if (!on) paint();
- if (!alone && app) send({ type: "busy", on });
- if (on) $("error").hidden = true;
-}
-
-function fail(words) {
- $("error").textContent = words;
- $("error").hidden = false;
- size();
-}
-
-class RegistryError extends Error {}
-
-async function registry(path, body) {
- const response = await fetch(`${REGISTRY}${path}`, body === undefined ? { cache: "no-store" } : { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).catch(() => {
- throw new RegistryError("Accounts are unreachable right now. Try again soon.");
- });
- const data = await response.json().catch(() => ({}));
- if (!response.ok) throw new RegistryError(data.message || `The registry answered ${response.status}.`);
- return data;
-}
-
-// The record of a credential, and for a bound key every key of its account:
-// the frame checks the binding chain, so all of it travels with the
-// signature. A key bound before its binder was revoked stays valid, so the
-// account's list (which keeps revoked records) is what the chain is read
-// from. The passkey that signed must itself be live: the registry answers
-// 410 for a revoked one.
-async function chain(credential) {
- const record = await registry(`/passkey/credential/${credential}`);
- if (!record.binding) return [record];
- const { keys = [] } = await registry(`/passkey/account/${record.account}`);
- return [record, ...keys.filter((key) => key.credential !== credential)];
-}
-
-function assertion(credential) {
- const r = credential.response;
- return { credential: b64u(credential.rawId), clientDataJSON: b64u(r.clientDataJSON), authenticatorData: b64u(r.authenticatorData), signature: b64u(r.signature) };
-}
-
-async function sign(message, allow) {
- const credential = await navigator.credentials.get({
- publicKey: {
- challenge: await sha256(message),
- rpId: RP,
- userVerification: "required",
- timeout: 120000,
- allowCredentials: allow.map((id) => ({ type: "public-key", id: unb64u(id) })),
- },
- });
- return assertion(credential);
-}
-
-async function session(allow = []) {
- const { nonce, sessionKey, expires } = request;
- const signed = await sign(`prism/identity/session/1\n${app}\n${nonce}\n${sessionKey}\n${expires}`, allow);
- const records = await chain(signed.credential);
- remember(signed.credential);
- send({ type: "session", assertion: signed, records });
-}
-
-// A new passkey. A first one starts an account; another joins the account
-// whose passkey signs the binding.
-async function create() {
- const { challenge } = await registry("/passkey/challenge", {});
- const platform = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?.().catch(() => false);
- const adding = request.mode === "add";
- const credential = await navigator.credentials.create({
- publicKey: {
- challenge: unb64u(challenge),
- rp: { id: RP, name: "Prism" },
- user: { id: crypto.getRandomValues(new Uint8Array(32)), name: "Prism account", displayName: "Prism account" },
- pubKeyCredParams: [
- { type: "public-key", alg: -7 },
- { type: "public-key", alg: -257 },
- ],
- authenticatorSelection: {
- residentKey: "required",
- requireResidentKey: true,
- userVerification: "required",
- ...(platform && !adding ? { authenticatorAttachment: "platform" } : {}),
- },
- excludeCredentials: adding ? [{ type: "public-key", id: unb64u(request.credential) }] : [],
- hints: adding ? ["hybrid"] : [],
- attestation: "none",
- timeout: 120000,
- },
- });
- const r = credential.response;
- const spki = r.getPublicKey();
- const body = {
- spki: b64u(spki),
- alg: r.getPublicKeyAlgorithm(),
- credential: b64u(credential.rawId),
- clientDataJSON: b64u(r.clientDataJSON),
- authenticatorData: b64u(r.getAuthenticatorData()),
- attestationObject: b64u(r.attestationObject),
- transports: r.getTransports?.() ?? [],
- binding: null,
- };
- if (adding) {
- const key = b64u(await crypto.subtle.digest("SHA-256", spki));
- const bound = await sign(`prism/identity/bind/1\n${request.account}\n${key}`, [request.credential]);
- body.binding = { account: request.account, ...bound };
- }
- const record = await registry("/passkey/register", body);
- if (adding) return send({ type: "added", record });
- // A new account: the passkey now signs the app's session. Creating a
- // passkey signs nothing a reader could check, so this is a second prompt.
- await session([body.credential]);
-}
-
-// A browser that will not run a ceremony in an iframe runs it in a popup.
-function overflow() {
- child = open(`${location.pathname}#popup${document.documentElement.classList.contains("dark") ? "&theme=dark" : ""}`, "prism-identity", "popup,width=420,height=360");
- if (!child) return fail("Allow pop-ups, then try again.");
- const relay = (event) => {
- if (event.source !== child || event.data?.type !== `${SPEC}/ready`) return;
- removeEventListener("message", relay);
- child.postMessage({ ...request, app }, location.origin);
- };
- addEventListener("message", relay);
-}
-
-async function run(task) {
- if (!request) return;
- busy(true);
- try {
- await task();
- } catch (error) {
- // No passkey, or the visitor closed the prompt: the browser does not say
- // which. Either way, offer a new account, one tap away, and keep sign-in
- // a tap away too. Nothing else to read.
- if (error?.name === "NotAllowedError" || error?.name === "AbortError") {
- // The remembered passkey did not answer (removed, or the prompt was
- // closed): forget it, and the next tap asks for any passkey.
- if (request.mode === "signin" && !fresh && remembered) {
- remember(null);
- paint();
- return;
- }
- if (request.mode === "signin" && !fresh) {
- fresh = true;
- paint();
- }
- return;
- }
- if (error?.name === "SecurityError" && !alone) return overflow();
- if (error?.name === "InvalidStateError") return fail("This device is already added.");
- fail(error instanceof RegistryError ? error.message : "That did not work. Try again.");
- } finally {
- busy(false);
- }
-}
-
-$("go").addEventListener("click", () => run(() => (request.mode === "add" || fresh ? create() : session(remembered ? [remembered] : []))));
-$("again").addEventListener("click", () => {
- fresh = false;
- paint();
- run(() => session());
-});
-
-if (!window.PublicKeyCredential) {
- fail("This browser can't use passkeys.");
-} else {
- send({ type: "ready" });
-}
diff --git a/identity/index.html b/identity/index.html
deleted file mode 100644
index 0d68c4f..0000000
--- a/identity/index.html
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-
-
-
-
- Prism account
-
-
-
-
-
-
-
-
No passkey on this device yet.
-
-
-
-
diff --git a/identity/prism-id.mjs b/identity/prism-id.mjs
new file mode 100644
index 0000000..f8c7d42
--- /dev/null
+++ b/identity/prism-id.mjs
@@ -0,0 +1,2700 @@
+// GENERATED by identity/stitch-sync.mjs from afflom/stitch@7c0ccebfa00e5c09e135901be4c9fad149d1b420. DO NOT EDIT.
+// src/prism-id.js, the stitch modules it imports (src/layer1-uor/custody.js, src/layer1-uor/contracts.js, src/layer2-schedulers/policy.js, src/layer5-transport/relay-framing.js),
+// and the 39 model decisions they call (src/layer1-uor/generated-model.js); identity/stitch.lock pins them.
+// Change Prism id in stitch, then run node identity/stitch-sync.mjs .
+const stitch$layer1_uor_generated_model = (() => {
+const definitions = {"Stitch.Budget.reserveAllowed":{"module":"Stitch.Budget","name":"reserveAllowed","params":[{"name":"spent","type":{"kind":"Nat"}},{"name":"reserved","type":{"kind":"Nat"}},{"name":"cost","type":{"kind":"Nat"}},{"name":"limit","type":{"kind":"Nat"}},{"name":"now","type":{"kind":"Nat"}},{"name":"last","type":{"kind":"Nat"}},{"name":"end","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"last"},"right":{"k":"var","name":"now"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"var","name":"now"},"right":{"k":"var","name":"end"}},"right":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"var","name":"spent"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"reserved"},"right":{"k":"var","name":"cost"}}},"right":{"k":"var","name":"limit"}}}}},"Stitch.Budget.settlementAllowed":{"module":"Stitch.Budget","name":"settlementAllowed","params":[{"name":"reserved","type":{"kind":"Nat"}},{"name":"ceiling","type":{"kind":"Nat"}},{"name":"actual","type":{"kind":"Nat"}},{"name":"known","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"known"},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"actual"},"right":{"k":"var","name":"ceiling"}},"right":{"k":"binary","op":"<=?","left":{"k":"var","name":"ceiling"},"right":{"k":"var","name":"reserved"}}}}},"Stitch.PrismId.actionAllowed":{"module":"Stitch.PrismId","name":"actionAllowed","params":[{"name":"linked","type":{"kind":"Bool"}},{"name":"revoked","type":{"kind":"Bool"}},{"name":"delegate","type":{"kind":"Bool"}},{"name":"inScope","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"call","name":"deviceMaySign","args":[{"k":"var","name":"linked"},{"k":"var","name":"revoked"}]},"right":{"k":"call","name":"scopeAdmits","args":[{"k":"var","name":"delegate"},{"k":"var","name":"inScope"}]}}},"Stitch.PrismId.actionFresh":{"module":"Stitch.PrismId","name":"actionFresh","params":[{"name":"audienceMatches","type":{"kind":"Bool"}},{"name":"unseen","type":{"kind":"Bool"}},{"name":"issued","type":{"kind":"Nat"}},{"name":"now","type":{"kind":"Nat"}},{"name":"window","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"call","name":"actionGate","args":[{"k":"var","name":"audienceMatches"},{"k":"var","name":"unseen"},{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"now"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"issued"},"right":{"k":"var","name":"window"}}},"right":{"k":"binary","op":"<=?","left":{"k":"var","name":"issued"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"now"},"right":{"k":"var","name":"window"}}}}]}},"Stitch.PrismId.actionGate":{"module":"Stitch.PrismId","name":"actionGate","params":[{"name":"audienceMatches","type":{"kind":"Bool"}},{"name":"unseen","type":{"kind":"Bool"}},{"name":"inWindow","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"audienceMatches"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"unseen"},"right":{"k":"var","name":"inWindow"}}}},"Stitch.PrismId.attestationBinds":{"module":"Stitch.PrismId","name":"attestationBinds","params":[{"name":"verifiedHardware","type":{"kind":"Bool"}},{"name":"keyMatches","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"verifiedHardware"},"right":{"k":"var","name":"keyMatches"}}},"Stitch.PrismId.bindAllowed":{"module":"Stitch.PrismId","name":"bindAllowed","params":[{"name":"signerLinked","type":{"kind":"Bool"}},{"name":"signerRevoked","type":{"kind":"Bool"}},{"name":"signerDelegate","type":{"kind":"Bool"}},{"name":"signatureValid","type":{"kind":"Bool"}},{"name":"samePrism","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"call","name":"mayAdminister","args":[{"k":"var","name":"signerLinked"},{"k":"var","name":"signerRevoked"},{"k":"var","name":"signerDelegate"}]},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"signatureValid"},"right":{"k":"var","name":"samePrism"}}}},"Stitch.PrismId.boundaryKeyAdmitted":{"module":"Stitch.PrismId","name":"boundaryKeyAdmitted","params":[{"name":"keyEpoch","type":{"kind":"Nat"}},{"name":"requiredEpoch","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"<=?","left":{"k":"var","name":"requiredEpoch"},"right":{"k":"var","name":"keyEpoch"}}},"Stitch.PrismId.boundaryShared":{"module":"Stitch.PrismId","name":"boundaryShared","params":[{"name":"identities","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"<=?","left":{"k":"nat","value":"2"},"right":{"k":"var","name":"identities"}}},"Stitch.PrismId.boundaryVisibleTo":{"module":"Stitch.PrismId","name":"boundaryVisibleTo","params":[{"name":"member","type":{"kind":"Bool"}},{"name":"published","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"var","name":"published"},"right":{"k":"var","name":"member"}}},"Stitch.PrismId.deviceMaySign":{"module":"Stitch.PrismId","name":"deviceMaySign","params":[{"name":"linked","type":{"kind":"Bool"}},{"name":"revoked","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"linked"},"right":{"k":"not","value":{"k":"var","name":"revoked"}}}},"Stitch.PrismId.hostAdmitsDevice":{"module":"Stitch.PrismId","name":"hostAdmitsDevice","params":[{"name":"requiresHardwareKey","type":{"kind":"Bool"}},{"name":"attestedHardwareKey","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"requiresHardwareKey"}},"right":{"k":"var","name":"attestedHardwareKey"}}},"Stitch.PrismId.hybridSignatureAccepted":{"module":"Stitch.PrismId","name":"hybridSignatureAccepted","params":[{"name":"classicalValid","type":{"kind":"Bool"}},{"name":"pqAdvertised","type":{"kind":"Bool"}},{"name":"verifierHasPq","type":{"kind":"Bool"}},{"name":"pqValid","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"classicalValid"},"right":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"binary","op":"&&","left":{"k":"var","name":"pqAdvertised"},"right":{"k":"var","name":"verifierHasPq"}}},"right":{"k":"var","name":"pqValid"}}}},"Stitch.PrismId.hybridWrapRequired":{"module":"Stitch.PrismId","name":"hybridWrapRequired","params":[{"name":"recipientHasKem","type":{"kind":"Bool"}},{"name":"wrapHasKem","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"recipientHasKem"}},"right":{"k":"var","name":"wrapHasKem"}}},"Stitch.PrismId.linkGate":{"module":"Stitch.PrismId","name":"linkGate","params":[{"name":"userConfirmed","type":{"kind":"Bool"}},{"name":"alreadyUsed","type":{"kind":"Bool"}},{"name":"secretMatches","type":{"kind":"Bool"}},{"name":"fresh","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"userConfirmed"},"right":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"alreadyUsed"}},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"secretMatches"},"right":{"k":"var","name":"fresh"}}}}},"Stitch.PrismId.linkOfferAccepted":{"module":"Stitch.PrismId","name":"linkOfferAccepted","params":[{"name":"userConfirmed","type":{"kind":"Bool"}},{"name":"alreadyUsed","type":{"kind":"Bool"}},{"name":"secretMatches","type":{"kind":"Bool"}},{"name":"expires","type":{"kind":"Nat"}},{"name":"now","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"call","name":"linkGate","args":[{"k":"var","name":"userConfirmed"},{"k":"var","name":"alreadyUsed"},{"k":"var","name":"secretMatches"},{"k":"binary","op":"","left":{"k":"var","name":"now"},"right":{"k":"var","name":"expires"}}]}},"Stitch.PrismId.mayAdminister":{"module":"Stitch.PrismId","name":"mayAdminister","params":[{"name":"linked","type":{"kind":"Bool"}},{"name":"revoked","type":{"kind":"Bool"}},{"name":"delegate","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"call","name":"deviceMaySign","args":[{"k":"var","name":"linked"},{"k":"var","name":"revoked"}]},"right":{"k":"not","value":{"k":"var","name":"delegate"}}}},"Stitch.PrismId.mayShareBoundary":{"module":"Stitch.PrismId","name":"mayShareBoundary","params":[{"name":"shareable","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"var","name":"shareable"}},"Stitch.PrismId.presenceSatisfied":{"module":"Stitch.PrismId","name":"presenceSatisfied","params":[{"name":"required","type":{"kind":"Bool"}},{"name":"userPresent","type":{"kind":"Bool"}},{"name":"userVerified","type":{"kind":"Bool"}},{"name":"challengeMatches","type":{"kind":"Bool"}},{"name":"assertionValid","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"required"}},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"userPresent"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"userVerified"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"challengeMatches"},"right":{"k":"var","name":"assertionValid"}}}}}},"Stitch.PrismId.receivesPrivateBoundary":{"module":"Stitch.PrismId","name":"receivesPrivateBoundary","params":[{"name":"delegate","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"not","value":{"k":"var","name":"delegate"}}},"Stitch.PrismId.recoveryBindAllowed":{"module":"Stitch.PrismId","name":"recoveryBindAllowed","params":[{"name":"signerRecovery","type":{"kind":"Bool"}},{"name":"recoveryExists","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"var","name":"signerRecovery"},"right":{"k":"not","value":{"k":"var","name":"recoveryExists"}}}},"Stitch.PrismId.revocationCounts":{"module":"Stitch.PrismId","name":"revocationCounts","params":[{"name":"signerRecovery","type":{"kind":"Bool"}},{"name":"signerRevokedByRecovery","type":{"kind":"Bool"}},{"name":"targetRecovery","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"signerRevokedByRecovery"}},"right":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"targetRecovery"}},"right":{"k":"var","name":"signerRecovery"}}}},"Stitch.PrismId.scopeAdmits":{"module":"Stitch.PrismId","name":"scopeAdmits","params":[{"name":"delegate","type":{"kind":"Bool"}},{"name":"inScope","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"delegate"}},"right":{"k":"var","name":"inScope"}}},"Stitch.PrismId.thresholdMet":{"module":"Stitch.PrismId","name":"thresholdMet","params":[{"name":"threshold","type":{"kind":"Nat"}},{"name":"collected","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"nat","value":"1"},"right":{"k":"var","name":"threshold"}},"right":{"k":"binary","op":"<=?","left":{"k":"var","name":"threshold"},"right":{"k":"var","name":"collected"}}}},"Stitch.Relay.admissionAllowed":{"module":"Stitch.Relay","name":"admissionAllowed","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"capacity","type":{"kind":"Capacity"}},{"name":"bytes","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"nat","value":"0"},"right":{"k":"var","name":"bytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"bytes"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"entries"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"retainedBytes"},"right":{"k":"var","name":"bytes"}},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"retainedBytes"}},"right":{"k":"binary","op":"","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},"right":{"k":"project","value":{"k":"var","name":"capacity"},"field":"tombstones"}},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"tombstones"}}}}}}},"Stitch.Relay.admitCapacity":{"module":"Stitch.Relay","name":"admitCapacity","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"capacity","type":{"kind":"Capacity"}},{"name":"bytes","type":{"kind":"Nat"}}],"result":{"kind":"Capacity"},"body":{"k":"if","cond":{"k":"call","name":"admissionAllowed","args":[{"k":"var","name":"bounds"},{"k":"var","name":"capacity"},{"k":"var","name":"bytes"}]},"yes":{"k":"record","name":"Capacity","values":{"entries":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},"right":{"k":"nat","value":"1"}},"retainedBytes":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"retainedBytes"},"right":{"k":"var","name":"bytes"}},"tombstones":{"k":"project","value":{"k":"var","name":"capacity"},"field":"tombstones"}}},"no":{"k":"var","name":"capacity"}}},"Stitch.Relay.append":{"module":"Stitch.Relay","name":"append","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"state","type":{"kind":"Assembly"}},{"name":"frame","type":{"kind":"Frame"}},{"name":"now","type":{"kind":"Nat"}},{"name":"duplicate","type":{"kind":"Bool"}}],"result":{"kind":"Assembly"},"body":{"k":"if","cond":{"k":"call","name":"appendAllowed","args":[{"k":"var","name":"bounds"},{"k":"var","name":"state"},{"k":"var","name":"frame"},{"k":"var","name":"now"},{"k":"var","name":"duplicate"}]},"yes":{"k":"record","name":"Assembly","values":{"identity":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"receivedFrames":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"right":{"k":"nat","value":"1"}},"receivedBytes":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"right":{"k":"project","value":{"k":"var","name":"frame"},"field":"payloadBytes"}},"started":{"k":"project","value":{"k":"var","name":"state"},"field":"started"},"last":{"k":"var","name":"now"},"verifying":{"k":"bool","value":false}}},"no":{"k":"var","name":"state"}}},"Stitch.Relay.appendAllowed":{"module":"Stitch.Relay","name":"appendAllowed","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"state","type":{"kind":"Assembly"}},{"name":"frame","type":{"kind":"Frame"}},{"name":"now","type":{"kind":"Nat"}},{"name":"duplicate","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"duplicate"}},"right":{"k":"binary","op":"&&","left":{"k":"call","name":"assemblyCurrent","args":[{"k":"var","name":"bounds"},{"k":"var","name":"state"},{"k":"var","name":"now"}]},"right":{"k":"binary","op":"&&","left":{"k":"call","name":"sameIdentity","args":[{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},{"k":"project","value":{"k":"var","name":"frame"},"field":"identity"}]},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"right":{"k":"nat","value":"1"}},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"frames"}},"right":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"right":{"k":"project","value":{"k":"var","name":"frame"},"field":"payloadBytes"}},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"messageBytes"}}}}}}},"Stitch.Relay.assemblyCurrent":{"module":"Stitch.Relay","name":"assemblyCurrent","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"state","type":{"kind":"Assembly"}},{"name":"now","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"state"},"field":"last"},"right":{"k":"var","name":"now"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"var","name":"now"},"right":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"started"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"assemblyAge"}}},"right":{"k":"not","value":{"k":"project","value":{"k":"var","name":"state"},"field":"verifying"}}}}},"Stitch.Relay.beginVerification":{"module":"Stitch.Relay","name":"beginVerification","params":[{"name":"state","type":{"kind":"Assembly"}}],"result":{"kind":"Assembly"},"body":{"k":"record","name":"Assembly","values":{"identity":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"receivedFrames":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"receivedBytes":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"started":{"k":"project","value":{"k":"var","name":"state"},"field":"started"},"last":{"k":"project","value":{"k":"var","name":"state"},"field":"last"},"verifying":{"k":"call","name":"ready","args":[{"k":"var","name":"state"}]}}}},"Stitch.Relay.deliveryAllowed":{"module":"Stitch.Relay","name":"deliveryAllowed","params":[{"name":"state","type":{"kind":"Assembly"}},{"name":"digestVerified","type":{"kind":"Bool"}},{"name":"utf8Valid","type":{"kind":"Bool"}},{"name":"envelopeValid","type":{"kind":"Bool"}},{"name":"sessionCurrent","type":{"kind":"Bool"}},{"name":"consentCurrent","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"digestVerified"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"utf8Valid"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"envelopeValid"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"sessionCurrent"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"consentCurrent"},"right":{"k":"binary","op":"&&","left":{"k":"project","value":{"k":"var","name":"state"},"field":"verifying"},"right":{"k":"call","name":"ready","args":[{"k":"var","name":"state"}]}}}}}}}},"Stitch.Relay.effectAllowed":{"module":"Stitch.Relay","name":"effectAllowed","params":[{"name":"closed","type":{"kind":"Bool"}},{"name":"currentGeneration","type":{"kind":"Nat"}},{"name":"capturedGeneration","type":{"kind":"Nat"}},{"name":"sessionMatches","type":{"kind":"Bool"}},{"name":"consentCurrent","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"closed"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"var","name":"currentGeneration"},"right":{"k":"var","name":"capturedGeneration"}},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"sessionMatches"},"right":{"k":"var","name":"consentCurrent"}}}}},"Stitch.Relay.frameAllowed":{"module":"Stitch.Relay","name":"frameAllowed","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"frame","type":{"kind":"Frame"}},{"name":"channel","type":{"kind":"Bytes"}},{"name":"purpose","type":{"kind":"Bytes"}},{"name":"wallNow","type":{"kind":"Nat"}},{"name":"lifetime","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"let","name":"identity","type":{"kind":"Identity"},"value":{"k":"project","value":{"k":"var","name":"frame"},"field":"identity"},"body":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"channel"},{"k":"var","name":"channel"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"purpose"},{"k":"var","name":"purpose"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"nat","value":"0"},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"nat","value":"0"},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"frames"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"index"},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"wireBytes"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"wireBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"prim","operation":"multiply","args":[{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},{"k":"nat","value":"1"}],"type":{"kind":"Nat"}},{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}],"type":{"kind":"Nat"}},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"},"right":{"k":"prim","operation":"multiply","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}],"type":{"kind":"Nat"}}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"payloadBytes"},"right":{"k":"if","cond":{"k":"binary","op":"=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"index"},"right":{"k":"nat","value":"1"}},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"}},"yes":{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"},{"k":"prim","operation":"multiply","args":[{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},{"k":"nat","value":"1"}],"type":{"kind":"Nat"}},{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}],"type":{"kind":"Nat"}}],"type":{"kind":"Nat"}},"no":{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"created"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"wallNow"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"futureSkew"}}},"right":{"k":"binary","op":"","left":{"k":"var","name":"wallNow"},"right":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"created"},"right":{"k":"var","name":"lifetime"}}}}}}}}}}}}}}}}},"Stitch.Relay.limits":{"module":"Stitch.Relay","name":"limits","params":[],"result":{"kind":"Limits"},"body":{"k":"record","name":"Limits","values":{"wireBytes":{"k":"nat","value":"4096"},"chunkBytes":{"k":"nat","value":"2700"},"messageBytes":{"k":"nat","value":"524288"},"frames":{"k":"nat","value":"256"},"entries":{"k":"nat","value":"16"},"retainedBytes":{"k":"nat","value":"2097152"},"tombstones":{"k":"nat","value":"256"},"assemblyAge":{"k":"nat","value":"30000"},"futureSkew":{"k":"nat","value":"5000"},"requestTimeout":{"k":"nat","value":"30000"}}}},"Stitch.Relay.ready":{"module":"Stitch.Relay","name":"ready","params":[{"name":"state","type":{"kind":"Assembly"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"frames"}},"right":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"messageBytes"}}}},"Stitch.Relay.release":{"module":"Stitch.Relay","name":"release","params":[{"name":"capacity","type":{"kind":"Capacity"}},{"name":"bytes","type":{"kind":"Nat"}}],"result":{"kind":"Capacity"},"body":{"k":"record","name":"Capacity","values":{"entries":{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},{"k":"nat","value":"1"}],"type":{"kind":"Nat"}},"retainedBytes":{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"capacity"},"field":"retainedBytes"},{"k":"var","name":"bytes"}],"type":{"kind":"Nat"}},"tombstones":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"tombstones"},"right":{"k":"nat","value":"1"}}}}},"Stitch.Relay.sameIdentity":{"module":"Stitch.Relay","name":"sameIdentity","params":[{"name":"left","type":{"kind":"Identity"}},{"name":"right","type":{"kind":"Identity"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"channel"},{"k":"project","value":{"k":"var","name":"right"},"field":"channel"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"session"},{"k":"project","value":{"k":"var","name":"right"},"field":"session"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"digest"},{"k":"project","value":{"k":"var","name":"right"},"field":"digest"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"purpose"},{"k":"project","value":{"k":"var","name":"right"},"field":"purpose"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"left"},"field":"created"},"right":{"k":"project","value":{"k":"var","name":"right"},"field":"created"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"left"},"field":"messageBytes"},"right":{"k":"project","value":{"k":"var","name":"right"},"field":"messageBytes"}},"right":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"left"},"field":"frames"},"right":{"k":"project","value":{"k":"var","name":"right"},"field":"frames"}}}}}}}}},"Stitch.Relay.signalLifetime":{"module":"Stitch.Relay","name":"signalLifetime","params":[],"result":{"kind":"Nat"},"body":{"k":"nat","value":"60000"}},"Stitch.Relay.warmLifetime":{"module":"Stitch.Relay","name":"warmLifetime","params":[],"result":{"kind":"Nat"},"body":{"k":"nat","value":"1800000"}}};
+const types = {"Stitch.Relay.Assembly":{"kind":"structure","fields":[{"name":"identity","type":{"kind":"Identity"}},{"name":"receivedFrames","type":{"kind":"Nat"}},{"name":"receivedBytes","type":{"kind":"Nat"}},{"name":"started","type":{"kind":"Nat"}},{"name":"last","type":{"kind":"Nat"}},{"name":"verifying","type":{"kind":"Bool"}}]},"Stitch.Relay.Capacity":{"kind":"structure","fields":[{"name":"entries","type":{"kind":"Nat"}},{"name":"retainedBytes","type":{"kind":"Nat"}},{"name":"tombstones","type":{"kind":"Nat"}}]},"Stitch.Relay.Frame":{"kind":"structure","fields":[{"name":"identity","type":{"kind":"Identity"}},{"name":"index","type":{"kind":"Nat"}},{"name":"payloadBytes","type":{"kind":"Nat"}},{"name":"wireBytes","type":{"kind":"Nat"}}]},"Stitch.Relay.Identity":{"kind":"structure","fields":[{"name":"channel","type":{"kind":"Bytes"}},{"name":"session","type":{"kind":"Bytes"}},{"name":"digest","type":{"kind":"Bytes"}},{"name":"purpose","type":{"kind":"Bytes"}},{"name":"created","type":{"kind":"Nat"}},{"name":"messageBytes","type":{"kind":"Nat"}},{"name":"frames","type":{"kind":"Nat"}}]},"Stitch.Relay.Limits":{"kind":"structure","fields":[{"name":"wireBytes","type":{"kind":"Nat"}},{"name":"chunkBytes","type":{"kind":"Nat"}},{"name":"messageBytes","type":{"kind":"Nat"}},{"name":"frames","type":{"kind":"Nat"}},{"name":"entries","type":{"kind":"Nat"}},{"name":"retainedBytes","type":{"kind":"Nat"}},{"name":"tombstones","type":{"kind":"Nat"}},{"name":"assemblyAge","type":{"kind":"Nat"}},{"name":"futureSkew","type":{"kind":"Nat"}},{"name":"requestTimeout","type":{"kind":"Nat"}}]}};
+const qualify = (module, name) => name.includes('::') ? name.replace('::','.') : module+'.'+name;
+function natural(value) {
+ if(typeof value==='bigint'&&value>=0n)return value;
+ if(typeof value==='number'&&Number.isSafeInteger(value)&&value>=0)return BigInt(value);
+ throw new TypeError('model Nat must be a non-negative BigInt or safe integer');
+}
+function coerce(value,type,module) {
+ if(type.kind==='Nat')return natural(value);
+ if(type.kind==='Bool') {if(typeof value!=='boolean')throw new TypeError('model Bool required');return value;}
+ if(type.kind==='Bytes') {if(!(value instanceof Uint8Array))throw new TypeError('model Bytes required');return value.slice();}
+ if(type.kind==='String') {if(typeof value!=='string')throw new TypeError('model String required');return value;}
+ if(type.kind==='List') {if(!Array.isArray(value))throw new TypeError('model List required');return value.map(x=>coerce(x,type.element,module));}
+ const id=qualify(module,type.kind),shape=types[id];
+ if(!shape)throw new TypeError('unknown model type '+id);
+ if(shape.kind==='structure') {if(!value||typeof value!=='object'||Object.keys(value).sort().join(',')!==shape.fields.map(x=>x.name).sort().join(','))throw new TypeError('exact model record fields required for '+id);return Object.fromEntries(shape.fields.map(f=>[f.name,coerce(value[f.name],f.type,id.slice(0,id.lastIndexOf('.')))]));}
+ const constructor=shape.constructors.find(x=>x.name===value?.tag);
+ if(!constructor||!Array.isArray(value.fields)||value.fields.length!==constructor.fields.length)throw new TypeError('model constructor required for '+id);
+ return {tag:value.tag,fields:value.fields.map((v,i)=>coerce(v,constructor.fields[i],id.slice(0,id.lastIndexOf('.'))))};
+}
+const tailCall = Symbol("source-tail-call");
+function evaluate(ast,env,module,tail=false) {
+ switch(ast.k) {
+ case 'nat':return BigInt(ast.value);
+ case 'bool':case 'string':return ast.value;
+ case 'var':if(!Object.hasOwn(env,ast.name))throw Error('unbound model variable');return env[ast.name];
+ case 'if':return evaluate(evaluate(ast.cond,env,module)?ast.yes:ast.no,env,module,tail);
+ case 'not':return !evaluate(ast.value,env,module);
+ case 'project':return evaluate(ast.value,env,module)[ast.field];
+ case 'let':return evaluate(ast.body,{...env,[ast.name]:evaluate(ast.value,env,module)},module,tail);
+ case 'record':return Object.fromEntries(Object.entries(ast.values).map(([k,v])=>[k,evaluate(v,env,module)]));
+ case 'call': {const id=qualify(module,ast.name),args=ast.args.map(x=>evaluate(x,env,module));return tail?{[tailCall]:true,id,args}:invoke(id,args);}
+ case 'nil':return [];
+ case 'cons':return [evaluate(ast.head,env,module),...evaluate(ast.tail,env,module)];
+ case 'ctor':return {tag:ast.name.split('.').at(-1),fields:ast.args.map(x=>evaluate(x,env,module))};
+ case 'match': {
+ const value=evaluate(ast.value,env,module);let tag,fields;
+ if(Array.isArray(value)){tag=value.length?'cons':'nil';fields=value.length?[value[0],value.slice(1)]:[];}else if(typeof value==='bigint'){tag=value===0n?'zero':'succ';fields=value===0n?[]:[value-1n];}else if(typeof value==='boolean'){tag=value?'true':'false';fields=[];}else {tag=value.tag;fields=value.fields;}
+ const b=ast.branches.find(x=>x.constructor.split('.').at(-1)===tag);
+ if(!b||b.binders.length!==fields.length)throw Error('nonexhaustive model match');return evaluate(b.body,{...env,...Object.fromEntries(b.binders.map((n,i)=>[n,fields[i]]))},module,tail);
+ }
+ case 'binary': {
+ const left=evaluate(ast.left,env,module);
+ if(ast.op==='&&')return left&&evaluate(ast.right,env,module);
+ if(ast.op==='||')return left||evaluate(ast.right,env,module);
+ const right=evaluate(ast.right,env,module);
+ switch(ast.op){case '+':return left+right;case '=?':return left===right;case '<=?':return left<=right;case '':return leftevaluate(x,env,module));
+ switch(ast.operation){case 'subtract':return a[0]>=a[1]?a[0]-a[1]:0n;case 'multiply':return a[0]*a[1];case 'quotient':return a[1]===0n?a[2]:a[0]/a[1];case 'remainder':return a[1]===0n?a[2]:a[0]%a[1];case 'equal':return a[0].length===a[1].length&&a[0].every((x,i)=>x===a[1][i]);default:throw Error('unsupported model primitive');}
+ }
+ default:throw Error('unsupported model node '+ast.k);
+ }
+}
+function invoke(id,args) {for(;;){const d=definitions[id];if(!d||d.params.length!==args.length)throw Error('unknown model function/arity '+id);const result=evaluate(d.body,Object.fromEntries(d.params.map((p,i)=>[p.name,args[i]])),d.module,true);if(!result?.[tailCall])return result;id=result.id;args=result.args;}}
+const model=Object.freeze(Object.fromEntries(Object.entries(definitions).map(([id,d])=>[id,(...args)=>{if(args.length!==d.params.length)throw new TypeError('model arity '+id);return invoke(id,args.map((v,i)=>coerce(v,d.params[i].type,d.module)));}])));
+const budgetReserveAllowed = model["Stitch.Budget.reserveAllowed"];
+const budgetSettlementAllowed = model["Stitch.Budget.settlementAllowed"];
+
+return { model, budgetReserveAllowed, budgetSettlementAllowed };
+})();
+
+const stitch$layer1_uor_custody = (() => {
+/**
+ * Layer 1 object custody commitments. Browser-compatible, dependency-free WebCrypto.
+ *
+ * This is a reference realization, not a proof of browser or network behavior.
+ * Digests establish byte integrity under SHA-256's security assumptions; they do
+ * not establish authorization, confidentiality, availability, or retention.
+ *
+ * Hash frame (all lengths unsigned, big endian):
+ * UTF8("stitch/" + domain + "/v1\0") || uint64(payload.length) || payload
+ * Fragment payload: raw32(encodingDigest) || uint32(index) || fragmentBytes.
+ * Manifest payload: canonicalBytes(manifest without manifestDigest).
+ * Canonical JSON follows RFC 8785: sorted UTF-16 keys, ECMAScript finite
+ * binary64 serialization, unchanged Unicode strings, and UTF-8 output.
+ * Application schemas and explicit resource budgets remain separate contracts.
+ */
+
+const CUSTODY_LIMITS = Object.freeze({
+ maxObjectBytes: 16 * 1024 * 1024,
+ maxManifestBytes: 16 * 1024,
+ maxCanonicalBytes: 64 * 1024,
+ maxDepth: 16,
+ maxEntries: 4096,
+ maxStringLength: 4096,
+ maxRequests: 256,
+ maxCopies: 64,
+});
+
+class CustodyError extends Error {
+ constructor(code, message = code) {
+ super(message);
+ this.name = 'CustodyError';
+ this.code = code;
+ }
+}
+
+const fail = (code, message) => { throw new CustodyError(code, message); };
+const utf8 = new TextEncoder();
+const DIGEST = /^sha256:[0-9a-f]{64}$/;
+
+/** Snapshot caller-owned bytes before any asynchronous operation. */
+function copyBytes(value, maxBytes = CUSTODY_LIMITS.maxObjectBytes) {
+ if (!(value instanceof Uint8Array)) fail('InvalidBytes', 'Expected Uint8Array');
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || value.byteLength > maxBytes) {
+ fail('SizeLimit', 'Byte sequence exceeds its size limit');
+ }
+ return new Uint8Array(value);
+}
+
+function validString(value, maxLength = CUSTODY_LIMITS.maxStringLength) {
+ if (value.length > maxLength) fail('SizeLimit', 'String too long');
+ for (let i = 0; i < value.length; i++) {
+ const c = value.charCodeAt(i);
+ // RFC 7493 §2.1 (the JCS input domain) also excludes Unicode noncharacters.
+ if ((c >= 0xfdd0 && c <= 0xfdef) || c === 0xfffe || c === 0xffff) {
+ fail('InvalidCanonicalValue', 'Unicode noncharacter');
+ }
+ if (c >= 0xd800 && c <= 0xdbff) {
+ const next = value.charCodeAt(++i);
+ if (!(next >= 0xdc00 && next <= 0xdfff)) fail('InvalidCanonicalValue', 'Lone surrogate');
+ const point = 0x10000 + ((c - 0xd800) << 10) + next - 0xdc00;
+ if ((point & 0xffff) >= 0xfffe) fail('InvalidCanonicalValue', 'Unicode noncharacter');
+ } else if (c >= 0xdc00 && c <= 0xdfff) {
+ fail('InvalidCanonicalValue', 'Lone surrogate');
+ }
+ }
+}
+
+/**
+ * Canonical UTF-8 bytes. Rejects cycles, getters, symbols, sparse/extended arrays,
+ * nonfinite numbers, hidden properties, and non-JSON prototypes before coercion.
+ * Number serialization is the ECMAScript algorithm required by RFC 8785 §3.2.2.3.
+ * The caller must supply an already valid value; use parseCanonicalJson on wire JSON
+ * so duplicate properties are rejected before a normal JSON parser can erase them.
+ */
+function canonicalBytes(value, {
+ maxBytes = CUSTODY_LIMITS.maxCanonicalBytes,
+ maxDepth = CUSTODY_LIMITS.maxDepth,
+ maxEntries = CUSTODY_LIMITS.maxEntries,
+ maxStringLength = CUSTODY_LIMITS.maxStringLength,
+} = {}) {
+ for (const limit of [maxBytes, maxDepth, maxEntries, maxStringLength]) {
+ if (!Number.isSafeInteger(limit) || limit < 0) fail('SizeLimit', 'Invalid JSON resource bound');
+ }
+ const seen = new Set();
+ let entries = 0;
+ let outputLength = 0;
+ const append = value => {
+ outputLength += value.length;
+ if (outputLength > maxBytes) fail('SizeLimit', 'Canonical record too large');
+ return value;
+ };
+ function encode(v, depth) {
+ if (depth > maxDepth) fail('SizeLimit', 'Canonical record too deep');
+ if (++entries > maxEntries) fail('SizeLimit', 'Too many canonical values');
+ if (v === null) return append('null');
+ if (typeof v === 'boolean') return append(v ? 'true' : 'false');
+ if (typeof v === 'number') {
+ if (!Number.isFinite(v)) fail('InvalidCanonicalValue', 'Expected finite IEEE 754 number');
+ return append(JSON.stringify(v));
+ }
+ if (typeof v === 'string') {
+ validString(v, maxStringLength);
+ return append(JSON.stringify(v));
+ }
+ if (typeof v !== 'object' || seen.has(v)) fail('InvalidCanonicalValue', 'Non-JSON value or cycle');
+ const array = Array.isArray(v);
+ const proto = Object.getPrototypeOf(v);
+ if (array ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) {
+ fail('InvalidCanonicalValue', 'Expected a plain JSON value');
+ }
+ const keys = Reflect.ownKeys(v);
+ // Check count before enumerating or allocating any output for a large array.
+ if (keys.length > maxEntries + (array ? 1 : 0)) fail('SizeLimit', 'Too many keys');
+ if (keys.some(k => typeof k !== 'string')) fail('InvalidCanonicalValue', 'Symbol key');
+ const descriptors = Object.getOwnPropertyDescriptors(v);
+ for (const key of keys) {
+ const d = descriptors[key];
+ if (!Object.hasOwn(d, 'value') || (!d.enumerable && !(array && key === 'length'))) {
+ fail('InvalidCanonicalValue', 'Accessors and hidden fields are not canonical');
+ }
+ }
+ seen.add(v);
+ let result;
+ if (array) {
+ if (v.length > maxEntries || keys.length !== v.length + 1) {
+ fail('InvalidCanonicalValue', 'Sparse or extended array');
+ }
+ const items = [];
+ for (let i = 0; i < v.length; i++) {
+ if (!Object.hasOwn(descriptors, String(i))) fail('InvalidCanonicalValue', 'Sparse array');
+ items.push(encode(descriptors[String(i)].value, depth + 1));
+ }
+ result = append('[') + items.join(',') + append(']');
+ append(','.repeat(Math.max(0, items.length - 1)));
+ } else {
+ const items = [];
+ for (const key of keys.sort()) {
+ validString(key, maxStringLength);
+ const name = append(JSON.stringify(key));
+ items.push(name + append(':') + encode(descriptors[key].value, depth + 1));
+ }
+ result = append('{') + items.join(',') + append('}');
+ append(','.repeat(Math.max(0, items.length - 1)));
+ }
+ seen.delete(v);
+ return result;
+ }
+ const result = utf8.encode(encode(value, 0));
+ if (result.length > maxBytes) fail('SizeLimit', 'Canonical UTF-8 record too large');
+ return result;
+}
+
+/**
+ * Parse JSON without losing duplicate names, including escape-equivalent names.
+ * RFC 8785 §3.1 and §5 require validation before signature processing. This
+ * parser preserves strings without normalization, rejects nonfinite numbers and
+ * malformed UTF-8, and creates only data properties (including __proto__).
+ * Limits are deployment resource policies, not changes to the JCS data model.
+ */
+function parseCanonicalJson(input, {
+ maxBytes = CUSTODY_LIMITS.maxCanonicalBytes,
+ maxDepth = CUSTODY_LIMITS.maxDepth,
+ maxEntries = CUSTODY_LIMITS.maxEntries,
+ maxStringLength = CUSTODY_LIMITS.maxStringLength,
+} = {}) {
+ for (const value of [maxBytes, maxDepth, maxEntries, maxStringLength]) {
+ if (!Number.isSafeInteger(value) || value < 0) fail('SizeLimit', 'Invalid JSON resource bound');
+ }
+ let text;
+ if (input instanceof Uint8Array) {
+ if (input.byteLength > maxBytes) fail('SizeLimit', 'JSON input too large');
+ try { text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(input); }
+ catch { fail('InvalidCanonicalValue', 'Malformed JSON UTF-8'); }
+ } else if (typeof input === 'string') {
+ // Check code units before allocating UTF-8; its byte count is at least this.
+ if (input.length > maxBytes || utf8.encode(input).length > maxBytes) fail('SizeLimit', 'JSON input too large');
+ text = input;
+ } else fail('InvalidCanonicalValue', 'Expected JSON text or UTF-8 bytes');
+ let at = 0, entries = 0;
+ const invalid = () => fail('InvalidCanonicalValue', `Invalid JSON at offset ${at}`);
+ const ws = () => { while (at < text.length && /[\x20\t\r\n]/.test(text[at])) at++; };
+ function string() {
+ const start = at++;
+ while (at < text.length) {
+ const c = text.charCodeAt(at++);
+ if (c === 34) {
+ let value;
+ try { value = JSON.parse(text.slice(start, at)); } catch { invalid(); }
+ validString(value, maxStringLength);
+ return value;
+ }
+ if (c < 32) invalid();
+ if (c === 92) {
+ const escape = text[at++];
+ if (escape === 'u') {
+ if (!/^[0-9a-fA-F]{4}$/.test(text.slice(at, at + 4))) invalid();
+ at += 4;
+ } else if (!['"', '\\', '/', 'b', 'f', 'n', 'r', 't'].includes(escape)) invalid();
+ }
+ }
+ invalid();
+ }
+ const number = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
+ function value(depth) {
+ if (depth > maxDepth || ++entries > maxEntries) fail('SizeLimit', 'JSON structure exceeds resource bound');
+ ws();
+ const token = text[at];
+ if (token === '"') return string();
+ if (token === '{' || token === '[') {
+ at++; ws();
+ const array = token === '[', close = array ? ']' : '}', result = array ? [] : Object.create(null);
+ const names = new Set();
+ if (text[at] === close) { at++; return result; }
+ for (;;) {
+ ws();
+ if (array) result.push(value(depth + 1));
+ else {
+ if (text[at] !== '"') invalid();
+ const key = string();
+ if (names.has(key)) fail('InvalidCanonicalValue', 'Duplicate JSON property');
+ names.add(key); ws();
+ if (text[at++] !== ':') invalid();
+ result[key] = value(depth + 1);
+ }
+ ws();
+ if (text[at] === close) { at++; return result; }
+ if (text[at++] !== ',') invalid();
+ }
+ }
+ for (const [literal, parsed] of [['true', true], ['false', false], ['null', null]]) {
+ if (text.startsWith(literal, at)) { at += literal.length; return parsed; }
+ }
+ number.lastIndex = at;
+ const match = number.exec(text);
+ if (!match) invalid();
+ at = number.lastIndex;
+ const parsed = Number(match[0]);
+ if (!Number.isFinite(parsed)) fail('InvalidCanonicalValue', 'Expected finite IEEE 754 number');
+ return parsed;
+ }
+ const result = value(0);
+ ws();
+ if (at !== text.length) invalid();
+ return result;
+}
+
+function uint64(value) {
+ const bytes = new Uint8Array(8);
+ new DataView(bytes.buffer).setBigUint64(0, BigInt(value), false);
+ return bytes;
+}
+
+/** Domain-separated digest. Domain must be a short lowercase ASCII name. */
+async function sha256Bytes(bytes, domain) {
+ if (typeof domain !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(domain)) {
+ fail('InvalidSchema', 'Invalid digest domain');
+ }
+ const payload = copyBytes(bytes, CUSTODY_LIMITS.maxObjectBytes + 36);
+ if (!globalThis.crypto?.subtle) fail('CryptoUnavailable', 'WebCrypto requires a supported secure context');
+ const prefix = utf8.encode(`stitch/${domain}/v1\0`);
+ const framed = new Uint8Array(prefix.length + 8 + payload.length);
+ framed.set(prefix);
+ framed.set(uint64(payload.length), prefix.length);
+ framed.set(payload, prefix.length + 8);
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', framed));
+ return 'sha256:' + Array.from(digest, b => b.toString(16).padStart(2, '0')).join('');
+}
+
+function assertDigest(value) {
+ if (typeof value !== 'string' || !DIGEST.test(value)) fail('InvalidDigest', 'Expected full lowercase SHA-256 digest');
+ return value;
+}
+
+async function commitObject(bytes) {
+ const snapshot = copyBytes(bytes);
+ return Object.freeze({
+ digestAlgorithm: 'sha256',
+ contentDigest: await sha256Bytes(snapshot, 'object'),
+ byteLength: snapshot.length,
+ });
+}
+
+async function fragmentDigest(encodingDigest, index, bytes) {
+ assertDigest(encodingDigest);
+ if (!Number.isInteger(index) || index < 0 || index > 2) fail('InvalidSchema', 'Invalid fragment index');
+ const snapshot = copyBytes(bytes, Math.ceil(CUSTODY_LIMITS.maxObjectBytes / 2));
+ const payload = new Uint8Array(36 + snapshot.length);
+ for (let i = 0; i < 32; i++) payload[i] = parseInt(encodingDigest.slice(7 + i * 2, 9 + i * 2), 16);
+ new DataView(payload.buffer).setUint32(32, index, false);
+ payload.set(snapshot, 36);
+ return sha256Bytes(payload, 'fragment');
+}
+
+function exactKeys(value, expected, name = 'record') {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) fail('InvalidSchema', `${name} must be a record`);
+ const actual = Object.keys(value).sort();
+ const wanted = [...expected].sort();
+ if (actual.length !== wanted.length || actual.some((k, i) => k !== wanted[i])) {
+ fail('InvalidSchema', `${name} has missing or unknown fields`);
+ }
+}
+
+function deepFreeze(value) {
+ if (value && typeof value === 'object') {
+ for (const v of Object.values(value)) deepFreeze(v);
+ Object.freeze(value);
+ }
+ return value;
+}
+
+/** Snapshot strict records without executing accessors. */
+function snapshotRecord(record, maxBytes = CUSTODY_LIMITS.maxCanonicalBytes) {
+ const bytes = canonicalBytes(record);
+ if (bytes.length > maxBytes) fail('SizeLimit', 'Record exceeds its size limit');
+ return JSON.parse(new TextDecoder().decode(bytes));
+}
+
+function manifestBody(manifest) {
+ return { version: manifest.version, object: manifest.object, encoding: manifest.encoding, fragments: manifest.fragments };
+}
+
+/**
+ * Verify schema and complete manifest commitment; returns an immutable snapshot.
+ * This alone does not prove that its declared fragments encode its object.
+ * recoverObject establishes that relationship from actual fragment bytes.
+ */
+async function verifyManifest(manifest) {
+ const m = snapshotRecord(manifest, CUSTODY_LIMITS.maxManifestBytes);
+ exactKeys(m, ['version', 'object', 'encoding', 'fragments', 'manifestDigest'], 'manifest');
+ exactKeys(m.object, ['digestAlgorithm', 'contentDigest', 'byteLength'], 'object');
+ exactKeys(m.encoding, ['format', 'encodingDigest', 'byteLength', 'dependencies'], 'encoding');
+ exactKeys(m.fragments, ['scheme', 'threshold', 'count', 'byteLength', 'digests'], 'fragments');
+ if (m.version !== 1 || m.object.digestAlgorithm !== 'sha256' || m.encoding.format !== 'raw'
+ || m.fragments.scheme !== 'xor-2-of-3' || m.fragments.threshold !== 2 || m.fragments.count !== 3) {
+ fail('InvalidSchema', 'Unsupported custody version or encoding');
+ }
+ const length = m.object.byteLength;
+ if (!Number.isSafeInteger(length) || length < 0 || length > CUSTODY_LIMITS.maxObjectBytes) {
+ fail('SizeLimit', 'Invalid object length');
+ }
+ if (m.encoding.byteLength !== length || m.fragments.byteLength !== Math.ceil(length / 2)) {
+ fail('InvalidSchema', 'Inconsistent encoding or fragment lengths');
+ }
+ if (!Array.isArray(m.encoding.dependencies) || m.encoding.dependencies.length !== 0) {
+ fail('InvalidSchema', 'Raw encoding must be self-contained');
+ }
+ if (!Array.isArray(m.fragments.digests) || m.fragments.digests.length !== 3) {
+ fail('InvalidSchema', 'Expected exactly three fragment digests');
+ }
+ [m.object.contentDigest, m.encoding.encodingDigest, m.manifestDigest, ...m.fragments.digests].forEach(assertDigest);
+ const actual = await sha256Bytes(canonicalBytes(manifestBody(m)), 'manifest');
+ if (actual !== m.manifestDigest) fail('ManifestDigestMismatch', 'Manifest commitment does not match');
+ return deepFreeze(m);
+}
+
+/** Verify one fragment's full binding; does not establish coding consistency. */
+async function verifyFragment(manifest, fragment) {
+ // Read descriptors first so untrusted accessor fields are not executed.
+ if (!fragment || typeof fragment !== 'object' || Array.isArray(fragment)
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(fragment))) fail('InvalidSchema', 'Invalid fragment');
+ const descriptors = Object.getOwnPropertyDescriptors(fragment);
+ if (Reflect.ownKeys(fragment).length !== 2 || !descriptors.index?.enumerable || !descriptors.bytes?.enumerable
+ || !Object.hasOwn(descriptors.index, 'value') || !Object.hasOwn(descriptors.bytes, 'value')) {
+ fail('InvalidSchema', 'Fragment requires only index and bytes');
+ }
+ const index = descriptors.index.value;
+ if (!Number.isInteger(index) || index < 0 || index > 2) fail('InvalidSchema', 'Invalid fragment index');
+ const bytes = copyBytes(descriptors.bytes.value, Math.ceil(CUSTODY_LIMITS.maxObjectBytes / 2));
+ const m = await verifyManifest(manifest);
+ if (bytes.length !== m.fragments.byteLength) fail('InvalidSchema', 'Incorrect fragment length');
+ if (await fragmentDigest(m.encoding.encodingDigest, index, bytes) !== m.fragments.digests[index]) {
+ fail('FragmentDigestMismatch', 'Fragment is not committed by this manifest');
+ }
+ return { index, bytes };
+}
+
+return { CUSTODY_LIMITS, CustodyError, copyBytes, canonicalBytes, parseCanonicalJson, sha256Bytes, assertDigest, commitObject, fragmentDigest, exactKeys, deepFreeze, snapshotRecord, manifestBody, verifyManifest, verifyFragment };
+})();
+
+const stitch$layer1_uor_contracts = (() => {
+/** Shared runtime limits and closed-record validation. Limits are resource policy, not theorems. */
+class ContractError extends Error {
+ constructor(code, message = code) { super(message); this.name = 'ContractError'; this.code = code; }
+}
+const refuse = (code, message) => { throw new ContractError(code, message); };
+function record(value, keys) {
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value)) ||
+ Object.keys(value).sort().join('|') !== [...keys].sort().join('|')) refuse('invalid-record');
+ return value;
+}
+function natural(value, maximum = Number.MAX_SAFE_INTEGER) {
+ if (!Number.isSafeInteger(value) || value < 0 || value > maximum) refuse('invalid-integer');
+ return value;
+}
+function identifier(value) {
+ if (typeof value !== 'string' || !/^[a-zA-Z0-9._:-]{1,128}$/.test(value)) refuse('invalid-identifier');
+ return value;
+}
+function digest(value) {
+ if (typeof value !== 'string' || !/^sha256:[0-9a-f]{64}$/.test(value)) refuse('invalid-digest');
+ return value;
+}
+function hexValue(value, bits) {
+ if (typeof value !== 'string' || !/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(value) || value.length > 34 ||
+ BigInt(value) >= 1n << BigInt(bits)) refuse('invalid-ring-value');
+ return value;
+}
+
+return { ContractError, refuse, record, natural, identifier, digest, hexValue };
+})();
+
+const stitch$layer2_schedulers_policy = (() => {
+/** Conservative reservation ledger. Failed or ambiguous effects keep their reservation charged. */
+const { identifier, natural, record, refuse } = stitch$layer1_uor_contracts;
+const { snapshotRecord } = stitch$layer1_uor_custody;
+const { budgetReserveAllowed, budgetSettlementAllowed } = stitch$layer1_uor_generated_model;
+let runtimeEpoch = 0; // origin-local instance identity, never a distributed clock
+const kinds = ['refresh', 'place', 'repair', 'checkpoint', 'retrieve'];
+const measures = ['requests', 'transferBytes', 'storageBytes', 'computeSteps'];
+function cost(value) { record(value, measures); for (const k of measures) natural(value[k]); return value; }
+const zeroCost = () => Object.fromEntries(measures.map(k => [k, 0]));
+function createBudget({ epoch, startMs, endMs, limit }) {
+ identifier(epoch); natural(startMs); natural(endMs); cost(limit);
+ if (endMs <= startMs) refuse('invalid-epoch');
+ return { epoch, startMs, endMs, lastObservedMs: startMs, limit: { ...limit }, spent: zeroCost(), reservations: [] };
+}
+function validate(state) {
+ record(state, ['epoch', 'startMs', 'endMs', 'lastObservedMs', 'limit', 'spent', 'reservations']);
+ identifier(state.epoch); natural(state.startMs); natural(state.endMs); natural(state.lastObservedMs);
+ cost(state.limit); cost(state.spent);
+ if (state.endMs <= state.startMs || state.lastObservedMs < state.startMs || !Array.isArray(state.reservations)) refuse('invalid-budget');
+ const ids = new Set(); const totals = zeroCost();
+ for (const r of state.reservations) {
+ record(r, ['id', 'kind', 'cost', 'status']); identifier(r.id); cost(r.cost);
+ if (ids.has(r.id) || !kinds.includes(r.kind) || !['reserved', 'settled'].includes(r.status)) refuse('invalid-reservation');
+ ids.add(r.id);
+ for (const k of measures) totals[k] += r.cost[k];
+ }
+ for (const k of measures) {
+ natural(totals[k]);
+ if (totals[k] !== state.spent[k] || state.spent[k] > state.limit[k]) refuse('invalid-budget');
+ }
+}
+function reserveAction(state, { id, kind, cost: requested }, nowMs) {
+ requested = snapshotRecord(requested);
+ validate(state); identifier(id); natural(nowMs); cost(requested);
+ if (!kinds.includes(kind)) refuse('unsupported-action');
+ if (nowMs < state.lastObservedMs) refuse('clock-regression');
+ if (nowMs >= state.endMs) refuse('epoch-expired');
+ if (state.reservations.some(r => r.id === id)) refuse('duplicate-action');
+ const spent = zeroCost();
+ for (const k of measures) {
+ if (!budgetReserveAllowed(state.spent[k], 0, requested[k], state.limit[k], nowMs, state.lastObservedMs, state.endMs)) refuse('budget-exhausted');
+ spent[k] = state.spent[k] + requested[k];
+ }
+ return { ...structuredClone(state), lastObservedMs: nowMs, spent,
+ reservations: [...structuredClone(state.reservations), { id, kind, cost: { ...requested }, status: 'reserved' }] };
+}
+/** Only a completed, exact local accounting receipt can release unused reservation. */
+function settleAction(state, id, actualCost) {
+ actualCost = snapshotRecord(actualCost);
+ validate(state); identifier(id); cost(actualCost);
+ const reservation = state.reservations.find(r => r.id === id);
+ if (!reservation || reservation.status !== 'reserved') refuse('unknown-reservation');
+ const spent = { ...state.spent };
+ for (const k of measures) {
+ if (!budgetSettlementAllowed(reservation.cost[k], reservation.cost[k], actualCost[k], true)) refuse('reservation-exceeded');
+ spent[k] -= reservation.cost[k] - actualCost[k];
+ }
+ return { ...structuredClone(state), spent, reservations: state.reservations.map(r => r.id === id
+ ? { ...r, cost: { ...actualCost }, status: 'settled' } : structuredClone(r)) };
+}
+
+/**
+ * Local effect admission. Charges are cumulative ceilings in one explicit epoch,
+ * not measurements of TLS, ICE/STUN, browser memory, VM work, or host overhead.
+ * Failed/unknown effects stay charged. No automatic refund or epoch rollover.
+ */
+class ResourceAdmission {
+ #state;
+ #sequence = 0;
+ constructor({ clock = () => Math.floor(performance.now()), durationMs = 600000,
+ limit = { requests: 4096, transferBytes: 16 * 1024 * 1024,
+ storageBytes: 16 * 1024 * 1024, computeSteps: 1000000 }, maxActions = 16384 } = {}) {
+ natural(durationMs); natural(maxActions, 65536);
+ this.clock = clock;
+ this.maxActions = maxActions;
+ const startMs = clock(); natural(startMs);
+ natural(startMs + durationMs);
+ this.#state = createBudget({ epoch: `runtime-${++runtimeEpoch}`, startMs, endMs: startMs + durationMs, limit });
+ }
+ get state() { return structuredClone(this.#state); }
+ /** Read-only admission evidence for a correlated still-pending effect. */
+ reservationCurrent(id, epoch) {
+ const now = this.clock();
+ return Number.isSafeInteger(now) && now >= this.#state.lastObservedMs
+ && now < this.#state.endMs && this.#state.epoch === epoch
+ && this.#state.reservations.some(r => r.id === id && r.status === 'reserved');
+ }
+ reserve(kind, requested = {}) {
+ if (this.#sequence >= this.maxActions) refuse('action-capacity');
+ const amount = { ...zeroCost(), ...requested };
+ const id = `effect-${this.#sequence + 1}`;
+ const next = reserveAction(this.#state, { id, kind, cost: amount }, this.clock());
+ this.#state = next;
+ this.#sequence++;
+ return id;
+ }
+ run(kind, requested, effect) {
+ this.reserve(kind, requested);
+ return effect();
+ }
+}
+
+/** Exact UTF-8 application payload length, excluding lower-layer overhead. */
+const wireBytes = value => new TextEncoder().encode(typeof value === 'string' ? value : JSON.stringify(value)).length;
+function reserveNetwork(admission, kind, payload, destinations = 1) {
+ natural(destinations);
+ if (destinations) admission.reserve(kind, { requests: destinations, transferBytes: wireBytes(payload) * destinations });
+}
+
+return { zeroCost, createBudget, reserveAction, settleAction, ResourceAdmission, wireBytes, reserveNetwork };
+})();
+
+const stitch$layer5_transport_relay_framing = (() => {
+/** Stitch application framing over ntfy's bounded text-message API.
+ * No attachment URLs are followed. SHA-256 binds reconstructed bytes, not a
+ * publisher identity, availability, durable retention, or delivery to a peer.
+ */
+const { model } = stitch$layer1_uor_generated_model;
+const { parseCanonicalJson, sha256Bytes } = stitch$layer1_uor_custody;
+const { natural, record, refuse } = stitch$layer1_uor_contracts;
+const { wireBytes } = stitch$layer2_schedulers_policy;
+
+const call = (name, ...args) => model[`Stitch.Relay.${name}`](...args);
+const utf8 = new TextEncoder();
+const ascii = value => utf8.encode(value);
+const limits = call('limits');
+const RELAY_LIMITS = Object.freeze(Object.fromEntries(Object.entries(limits).map(([key, value]) => [key, Number(value)])));
+const RELAY_LIFETIMES = Object.freeze({ signal: Number(call('signalLifetime')), warm: Number(call('warmLifetime')) });
+const RELAY_EVENT_BYTES = 16 * 1024;
+const KEYS = ['v', 'p', 'c', 's', 'm', 't', 'b', 'n', 'i', 'x'];
+const JSON_LIMITS = Object.freeze({ maxBytes: RELAY_LIMITS.messageBytes, maxDepth: 32,
+ maxEntries: Math.floor(RELAY_LIMITS.messageBytes / 2) + 1, maxStringLength: RELAY_LIMITS.messageBytes });
+const hexDigest = value => typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value);
+const validPurpose = value => typeof value === 'string' && Object.hasOwn(RELAY_LIFETIMES, value);
+const purpose = value => { if (!validPurpose(value)) refuse('relay-purpose'); return value; };
+const objectEnvelope = value => value && typeof value === 'object' && !Array.isArray(value);
+
+const relayCapacity = (entries = 0, retainedBytes = 0, tombstones = 0) => ({ entries, retainedBytes, tombstones });
+const relayAdmissionAllowed = (capacity, bytes) => call('admissionAllowed', limits, capacity, bytes);
+const relayEffectAllowed = (node, capturedGeneration, sessionMatches, consentCurrent) =>
+ call('effectAllowed', node.closed, node.generation, capturedGeneration, sessionMatches, consentCurrent);
+
+function newRelaySession() {
+ if (!globalThis.crypto?.getRandomValues) refuse('relay-crypto-unavailable');
+ return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');
+}
+
+/** JSON is snapshotted before any await; a digest never binds a mutable object. */
+function snapshotRelayMessage(value) {
+ const raw = JSON.stringify(value);
+ if (typeof raw !== 'string') refuse('relay-envelope');
+ const bytes = utf8.encode(raw);
+ if (!bytes.length || bytes.length > RELAY_LIMITS.messageBytes) refuse('relay-message-limit');
+ if (!objectEnvelope(parseCanonicalJson(raw, JSON_LIMITS))) refuse('relay-envelope');
+ return Object.freeze({ raw, byteLength: bytes.length });
+}
+
+async function relayChannel(channelKey) {
+ if (typeof channelKey !== 'string') refuse('relay-channel');
+ // JSON escapes lone UTF-16 surrogates, preserving exact browser topic identity.
+ const raw = JSON.stringify(channelKey);
+ if (wireBytes(raw) > RELAY_LIMITS.messageBytes) refuse('relay-channel-limit');
+ return sha256Bytes(utf8.encode(raw), 'relay-channel');
+}
+
+function encodeBase64Url(bytes) {
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+function decodeBase64Url(value) {
+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1
+ || value.length > Math.ceil(RELAY_LIMITS.chunkBytes * 4 / 3)) refuse('relay-base64');
+ let binary;
+ try { binary = atob(value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - value.length % 4) % 4)); }
+ catch { refuse('relay-base64'); }
+ const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
+ // Reject nonzero pad bits, padding and alternate encodings (RFC4648 section3.5).
+ if (encodeBase64Url(bytes) !== value) refuse('relay-base64');
+ return bytes;
+}
+
+async function frameRelayMessage(snapshot, { channelKey, session, scope, createdAtMs = Date.now() }) {
+ purpose(scope); natural(createdAtMs);
+ if (!/^[0-9a-f]{32}$/.test(session)) refuse('relay-session');
+ const { raw } = snapshot;
+ const bytes = utf8.encode(raw);
+ if (typeof raw !== 'string' || bytes.length !== snapshot.byteLength
+ || !bytes.length || bytes.length > RELAY_LIMITS.messageBytes) refuse('relay-message-limit');
+ // The caller owns this immutable snapshot until framing completes.
+ const [channel, digest] = await Promise.all([relayChannel(channelKey), sha256Bytes(bytes, 'relay-message')]);
+ const count = Math.ceil(bytes.length / RELAY_LIMITS.chunkBytes);
+ if (count > RELAY_LIMITS.frames) refuse('relay-frame-limit');
+ const frames = [];
+ for (let index = 0; index < count; index++) {
+ const frame = { v: 'stitch/1', p: scope, c: channel, s: session, m: digest, t: createdAtMs,
+ b: bytes.length, n: count, i: index,
+ x: encodeBase64Url(bytes.subarray(index * RELAY_LIMITS.chunkBytes, (index + 1) * RELAY_LIMITS.chunkBytes)) };
+ const serialized = JSON.stringify(frame);
+ if (wireBytes(serialized) > RELAY_LIMITS.wireBytes) refuse('relay-wire-limit');
+ frames.push(serialized);
+ }
+ return { frames, digest, bytes: frames.reduce((sum, frame) => sum + wireBytes(frame), 0) };
+}
+
+const identity = frame => ({ channel: ascii(frame.c), session: ascii(frame.s), digest: ascii(frame.m), purpose: ascii(frame.p),
+ created: frame.t, messageBytes: frame.b, frames: frame.n });
+const frameState = (frame, payloadBytes, length) => ({ identity: identity(frame), index: frame.i, payloadBytes, wireBytes: length });
+const keyOf = frame => `${frame.p}:${frame.c}:${frame.s}:${frame.m}`;
+
+/** Bounded session-local assembler. Active payload buffers, pending inputs and
+ * completed/rejected tombstones all have independent, explicit ceilings.
+ * Cleanup uses the local monotonic clock, never a sender-controlled extension.
+ */
+class RelayReassembler {
+ #entries = new Map();
+ #tombstones = new Map();
+ #capacity = relayCapacity();
+ #pendingInputs = 0;
+ #lastNow = 0;
+ #generation = 0;
+ #disposed = false;
+ #timer = null;
+ constructor({ channelKey, scope, admission, clock = () => Math.floor(performance.now()), wallClock = Date.now,
+ current = () => true, consentCurrent = () => true, chargeIngress = true, automaticCleanup = true, verificationPool = new Map() } = {}) {
+ this.scope = purpose(scope); this.channelKey = channelKey;
+ this.channel = relayChannel(channelKey);
+ // A constructor's rejected promise must not become an unhandled rejection.
+ this.channel.catch(() => {});
+ this.admission = admission;
+ this.clock = clock; this.wallClock = wallClock;
+ this.current = current; this.consentCurrent = consentCurrent;
+ this.chargeIngress = chargeIngress; this.automaticCleanup = automaticCleanup;
+ this.verificationPool = verificationPool;
+ }
+ get state() {
+ this.#prune(this.#now());
+ return { entries: Number(this.#capacity.entries), retainedBytes: Number(this.#capacity.retainedBytes),
+ tombstones: this.#tombstones.size, pendingInputs: this.#pendingInputs, disposed: this.#disposed };
+ }
+ #now() {
+ const now = this.clock(); natural(now);
+ if (now < this.#lastNow) refuse('relay-clock-regression');
+ this.#lastNow = now; return now;
+ }
+ #schedule(now) {
+ if (this.#timer !== null) clearTimeout(this.#timer);
+ this.#timer = null;
+ if (!this.automaticCleanup || this.#disposed) return;
+ const deadlines = [...this.#entries.values()].filter(entry => !entry.cancelled).map(entry => Math.min(entry.started + RELAY_LIMITS.assemblyAge, entry.expires))
+ .concat([...this.#tombstones.values()]);
+ if (!deadlines.length) return;
+ this.#timer = setTimeout(() => {
+ this.#timer = null;
+ try { this.#prune(this.#now()); } catch { this.dispose(); }
+ }, Math.max(1, Math.min(...deadlines) - now));
+ this.#timer.unref?.();
+ }
+ #retire(key, entry, now) {
+ if (this.#entries.get(key) !== entry) return;
+ // A pending host digest still owns the immutable input buffer. Cancellation
+ // may fence delivery, but cannot release its resident-memory reservation.
+ if (entry.verificationPending) { entry.cancelled = true; this.#schedule(now); return; }
+ this.#entries.delete(key);
+ entry.buffer = null; entry.seen = null;
+ this.#capacity = call('release', this.#capacity, entry.header.b);
+ this.#tombstones.set(key, entry.expires);
+ this.#schedule(now);
+ }
+ #prune(now) {
+ for (const [key, entry] of this.#entries) {
+ if (now >= entry.started + RELAY_LIMITS.assemblyAge || now >= entry.expires) this.#retire(key, entry, now);
+ }
+ for (const [key, expires] of this.#tombstones) if (now >= expires) this.#tombstones.delete(key);
+ this.#capacity = { ...this.#capacity, tombstones: this.#tombstones.size };
+ this.#schedule(now);
+ }
+ dispose() {
+ this.#disposed = true; this.#generation++;
+ if (this.#timer !== null) clearTimeout(this.#timer);
+ this.#timer = null;
+ for (const [key, entry] of this.#entries) this.#retire(key, entry, this.#lastNow);
+ this.#tombstones.clear();
+ this.#capacity = { ...this.#capacity, tombstones: 0 };
+ }
+ /** Returns one complete verified logical envelope, or null. Refusals throw a
+ * bounded machine-readable error; a corrupt assembly is tombstoned, not retried.
+ */
+ async accept(raw) {
+ if (this.#disposed || !this.current() || !this.consentCurrent()) return null;
+ if (typeof raw !== 'string' || raw.length > RELAY_LIMITS.wireBytes) refuse('relay-wire-limit');
+ const length = wireBytes(raw);
+ if (length > RELAY_LIMITS.wireBytes) refuse('relay-wire-limit');
+ if (this.#pendingInputs >= RELAY_LIMITS.frames) refuse('relay-input-capacity');
+ this.admission?.reserve('retrieve', { computeSteps: 1, ...(this.chargeIngress ? { transferBytes: length } : {}) });
+ this.#pendingInputs++;
+ const generation = this.#generation;
+ try {
+ const frame = parseCanonicalJson(raw, { maxBytes: RELAY_LIMITS.wireBytes, maxDepth: 2, maxEntries: 16,
+ maxStringLength: RELAY_LIMITS.wireBytes });
+ record(frame, KEYS);
+ if (frame.v !== 'stitch/1' || frame.p !== this.scope || !hexDigest(frame.c) || !hexDigest(frame.m)
+ || typeof frame.s !== 'string' || !/^[0-9a-f]{32}$/.test(frame.s)) refuse('relay-frame');
+ for (const field of ['t', 'b', 'n', 'i']) natural(frame[field]);
+ // Reject count/length before decoding or allocating message-sized buffers.
+ if (!frame.b || frame.b > RELAY_LIMITS.messageBytes || !frame.n || frame.n > RELAY_LIMITS.frames
+ || frame.i >= frame.n) refuse('relay-frame-limit');
+ const chunk = decodeBase64Url(frame.x);
+ const state = frameState(frame, chunk.length, length);
+ const channel = await this.channel;
+ if (this.#disposed || generation !== this.#generation || !this.current() || !this.consentCurrent()) return null;
+ const now = this.#now(), wallNow = this.wallClock(); natural(wallNow);
+ this.#prune(now);
+ if (!call('frameAllowed', limits, state, ascii(channel), ascii(this.scope), wallNow, RELAY_LIFETIMES[this.scope])) refuse('relay-frame');
+ const key = keyOf(frame);
+ if (this.#tombstones.has(key)) return null;
+ let entry = this.#entries.get(key);
+ if (entry && !call('sameIdentity', entry.state.identity, state.identity)) {
+ this.#retire(key, entry, now); refuse('relay-mixed-message');
+ }
+ if (!entry) {
+ // Include verification work retained by older transport generations.
+ const older = [...this.verificationPool.values()].filter(item => item.owner !== this);
+ const capacity = relayCapacity(Number(this.#capacity.entries) + older.length,
+ Number(this.#capacity.retainedBytes) + older.reduce((sum, item) => sum + item.bytes, 0), this.#tombstones.size);
+ if (!relayAdmissionAllowed(capacity, frame.b)) refuse('relay-reassembly-capacity');
+ this.admission?.reserve('retrieve', { storageBytes: frame.b, computeSteps: frame.b + frame.n });
+ const expires = now + Math.min(RELAY_LIFETIMES[this.scope], Math.max(0, frame.t + RELAY_LIFETIMES[this.scope] - wallNow));
+ entry = { header: { b: frame.b }, cancelled: false, verificationPending: false, buffer: new Uint8Array(frame.b), seen: new Uint8Array(frame.n), started: now, expires,
+ state: { identity: state.identity, receivedFrames: 0, receivedBytes: 0, started: now, last: now, verifying: false } };
+ this.#entries.set(key, entry);
+ this.#capacity = call('admitCapacity', limits, this.#capacity, frame.b);
+ }
+ if (entry.cancelled) return null;
+ const offset = frame.i * RELAY_LIMITS.chunkBytes;
+ if (entry.seen[frame.i]) {
+ if (chunk.some((byte, index) => entry.buffer[offset + index] !== byte)) {
+ this.#retire(key, entry, now); refuse('relay-conflicting-duplicate');
+ }
+ return null;
+ }
+ if (!call('appendAllowed', limits, entry.state, state, now, false)) refuse('relay-assembly-state');
+ entry.buffer.set(chunk, offset); entry.seen[frame.i] = 1;
+ entry.state = call('append', limits, entry.state, state, now, false);
+ this.#schedule(now);
+ if (!call('ready', entry.state)) return null;
+ entry.state = call('beginVerification', entry.state);
+ const bytes = entry.buffer;
+ let result = null;
+ try {
+ const pendingBytes = [...this.verificationPool.values()].reduce((sum, item) => sum + item.bytes, 0);
+ if (!relayAdmissionAllowed(relayCapacity(this.verificationPool.size, pendingBytes), frame.b)) refuse('relay-verification-capacity');
+ entry.verificationPending = true;
+ this.verificationPool.set(entry, { owner: this, bytes: frame.b });
+ const digestVerified = await sha256Bytes(bytes, 'relay-message') === frame.m;
+ if (!digestVerified) refuse('relay-integrity');
+ const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
+ const envelope = parseCanonicalJson(decoded, JSON_LIMITS);
+ const envelopeValid = objectEnvelope(envelope) && typeof envelope.from === 'string' && envelope.from.length > 0 && envelope.from.length <= 128
+ && (this.scope !== 'signal' || envelope.channelKey === this.channelKey);
+ const stillCurrent = !entry.cancelled && !this.#disposed && generation === this.#generation && this.#entries.get(key) === entry && this.current();
+ const currentConsent = this.consentCurrent();
+ const finishedAt = this.#now();
+ if (finishedAt >= entry.started + RELAY_LIMITS.assemblyAge || finishedAt >= entry.expires) return null;
+ if (call('deliveryAllowed', entry.state, digestVerified, true, !!envelopeValid, stillCurrent, currentConsent)) result = envelope;
+ else if (!envelopeValid) refuse('relay-envelope');
+ return result;
+ } finally {
+ entry.verificationPending = false; this.verificationPool.delete(entry);
+ this.#retire(key, entry, this.#now());
+ }
+ } finally { this.#pendingInputs--; }
+ }
+}
+
+return { RELAY_LIMITS, RELAY_LIFETIMES, RELAY_EVENT_BYTES, relayCapacity, relayAdmissionAllowed, relayEffectAllowed, newRelaySession, snapshotRelayMessage, relayChannel, encodeBase64Url, decodeBase64Url, frameRelayMessage, RelayReassembler };
+})();
+
+/**
+ * Prism id: a login-free identity that comes into being in the browser.
+ *
+ * A prism is named by the kappa of its genesis record. Devices join it only
+ * through an out-of-band link offer (a QR code or any other channel the user
+ * already trusts). After that, linked devices keep each other in sync over the
+ * substrate message bus. Every authorization decision is taken by the
+ * Stitch.PrismId model in app/src/Stitch/PrismId.lex.tex.
+ *
+ * kappa = "sha256:" + lowercase hex SHA-256 of uor-addr canonical JSON:
+ * RFC 8785 shape, strings must already be NFC, integers only, object members
+ * ordered by the UTF-8 bytes of their names.
+ *
+ * Only P-256 ECDSA/ECDH, HKDF-SHA-256, HMAC-SHA-256, AES-256-GCM and SHA-256
+ * are required, so native, mobile (Secure Enclave, Android Keystore), TPM 2.0
+ * and secure-element devices can implement the same protocol. Where the
+ * platform has ML-KEM-768, every key wrap is hybrid (ECDH + ML-KEM); where it
+ * has ML-DSA-65, every record is also signed with ML-DSA. Actions a host marks
+ * as needing the person's approval carry a WebAuthn user-verified assertion.
+ * See docs/prism-id.md and docs/prism-id-threat-model.md.
+ */
+const { model } = stitch$layer1_uor_generated_model;
+const { RELAY_EVENT_BYTES, RELAY_LIFETIMES, RelayReassembler, frameRelayMessage, newRelaySession, relayChannel, snapshotRelayMessage } = stitch$layer5_transport_relay_framing;
+
+const subtle = globalThis.crypto.subtle;
+const encoder = new TextEncoder();
+const decoder = new TextDecoder('utf-8', { fatal: true });
+
+export const KIND = Object.freeze({
+ device: 'prism/device/1',
+ genesis: 'prism/genesis/1',
+ bind: 'prism/bind/1',
+ revoke: 'prism/revoke/1',
+ log: 'prism/log/1',
+ offer: 'prism/link-offer/1',
+ request: 'prism/link-request/1',
+ response: 'prism/link-response/1',
+ rendezvous: 'prism/rendezvous/1',
+ sync: 'prism/sync/1',
+ sealed: 'prism/sealed/1',
+ boundary: 'prism/boundary/1',
+ action: 'prism/action/1',
+ linkCode: 'prism/link-code/1',
+ keyring: 'prism/keyring/1',
+ recoverySecret: 'prism/recovery-secret/1',
+ recoveryShare: 'prism/recovery-share/1',
+ persona: 'prism/persona/1',
+ personaKey: 'prism/persona-key/1',
+ personaRecovery: 'prism/persona-recovery/1',
+ cover: 'prism/cover/1',
+ publicLog: 'prism/public-log/1'
+});
+
+/** Kinds of device that take part. Every one uses the same records and primitives. */
+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', 'threshold-shares']);
+/**
+ * member: full device of the prism. delegate: scoped device that never holds
+ * the private boundary. recovery: an offline authority whose key exists only as
+ * threshold shares held by guardians; it can link and revoke, never act at a host.
+ */
+export const ROLES = Object.freeze(['member', 'delegate', 'recovery']);
+
+export class PrismIdError extends Error {
+ constructor(code, message) { super(message); this.name = 'PrismIdError'; this.code = code; }
+}
+const refuse = (code, message) => { throw new PrismIdError(code, message); };
+
+// ---------------------------------------------------------------- canonical form
+
+function compareBytes(left, right) {
+ const n = Math.min(left.length, right.length);
+ for (let i = 0; i < n; i++) if (left[i] !== right[i]) return left[i] - right[i];
+ return left.length - right.length;
+}
+
+function canonicalString(text) {
+ if (!text.isWellFormed()) refuse('canonical', 'string is not well-formed Unicode');
+ if (text.normalize('NFC') !== text) refuse('canonical', 'string is not in NFC');
+ let out = '"';
+ for (const ch of text) {
+ const c = ch.codePointAt(0);
+ if (ch === '"') out += '\\"';
+ else if (ch === '\\') out += '\\\\';
+ else if (c === 8) out += '\\b';
+ else if (c === 9) out += '\\t';
+ else if (c === 10) out += '\\n';
+ else if (c === 12) out += '\\f';
+ else if (c === 13) out += '\\r';
+ else if (c < 32) out += '\\u00' + c.toString(16).padStart(2, '0');
+ else out += ch;
+ }
+ return out + '"';
+}
+
+/** uor-addr canonical JSON text of a JSON value. Refuses anything outside the subset. */
+export function canonicalJson(value) {
+ if (value === null) return 'null';
+ if (value === true) return 'true';
+ if (value === false) return 'false';
+ if (typeof value === 'number') {
+ if (!Number.isSafeInteger(value) || Object.is(value, -0)) refuse('canonical', 'number outside the integer subset');
+ return String(value);
+ }
+ if (typeof value === 'string') return canonicalString(value);
+ if (Array.isArray(value)) return '[' + value.map(canonicalJson).join(',') + ']';
+ if (typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
+ const members = Object.keys(value).map(key => {
+ if (value[key] === undefined) refuse('canonical', `member ${key} is undefined`);
+ return { key, bytes: encoder.encode(key) };
+ });
+ members.sort((a, b) => compareBytes(a.bytes, b.bytes));
+ return '{' + members.map(m => canonicalString(m.key) + ':' + canonicalJson(value[m.key])).join(',') + '}';
+ }
+ return refuse('canonical', `value of type ${typeof value} is not JSON`);
+}
+
+export const canonicalBytes = value => encoder.encode(canonicalJson(value));
+
+const hex = bytes => Array.from(new Uint8Array(bytes), b => b.toString(16).padStart(2, '0')).join('');
+
+/** kappa of a JSON value. */
+export async function kappa(value) {
+ return 'sha256:' + hex(await subtle.digest('SHA-256', canonicalBytes(value)));
+}
+
+export function isKappa(text) { return typeof text === 'string' && /^sha256:[0-9a-f]{64}$/.test(text); }
+
+export function toBase64Url(bytes) {
+ let s = '';
+ for (const b of new Uint8Array(bytes)) s += String.fromCharCode(b);
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+export function fromBase64Url(text) {
+ if (typeof text !== 'string' || !/^[A-Za-z0-9_-]*$/.test(text)) refuse('encoding', 'not base64url');
+ const s = atob(text.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - text.length % 4) % 4));
+ return Uint8Array.from(s, c => c.charCodeAt(0));
+}
+const random = n => globalThis.crypto.getRandomValues(new Uint8Array(n));
+
+
+// ---------------------------------------------------------------- devices
+
+const SIGN = { name: 'ECDSA', namedCurve: 'P-256' };
+const SIGN_HASH = { name: 'ECDSA', hash: 'SHA-256' };
+const AGREE = { name: 'ECDH', namedCurve: 'P-256' };
+const KEM = { name: 'ML-KEM-768' };
+const KEM_PUBLIC_BYTES = 1184;
+const PQSIGN = { name: 'ML-DSA-65' };
+const PQSIGN_PUBLIC_BYTES = 1952;
+const publicJwk = ({ kty, crv, x, y }) => ({ crv, kty, x, y });
+
+let kemSupport;
+/** Whether this platform offers ML-KEM-768 in WebCrypto. */
+export async function postQuantumAvailable() {
+ if (kemSupport === undefined) {
+ try { await subtle.generateKey(KEM, false, ['encapsulateBits', 'decapsulateBits']); kemSupport = true; }
+ catch { kemSupport = false; }
+ }
+ return kemSupport;
+}
+
+let pqSignSupport;
+/** Whether this platform offers ML-DSA-65 (FIPS 204) in WebCrypto. */
+export async function postQuantumSignaturesAvailable() {
+ if (pqSignSupport === undefined) {
+ try { await subtle.generateKey(PQSIGN, false, ['sign', 'verify']); pqSignSupport = true; }
+ catch { pqSignSupport = false; }
+ }
+ return pqSignSupport;
+}
+
+async function newKeys(extractable) {
+ const signing = await subtle.generateKey(SIGN, extractable, ['sign', 'verify']);
+ const agreement = await subtle.generateKey(AGREE, extractable, ['deriveBits']);
+ const kem = await postQuantumAvailable() ? await subtle.generateKey(KEM, extractable, ['encapsulateBits', 'decapsulateBits']) : null;
+ const pqsign = await postQuantumSignaturesAvailable() ? await subtle.generateKey(PQSIGN, extractable, ['sign', 'verify']) : null;
+ return { signing, agreement, kem, pqsign };
+}
+
+async function deviceFromKeys({ signing, agreement, kem, pqsign }, deviceClass, protection, presence) {
+ const record = {
+ kind: KIND.device,
+ class: deviceClass,
+ protection,
+ sign: publicJwk(await subtle.exportKey('jwk', signing.publicKey)),
+ agree: publicJwk(await subtle.exportKey('jwk', agreement.publicKey))
+ };
+ if (kem) record.kem = toBase64Url(await subtle.exportKey('raw-public', kem.publicKey));
+ if (pqsign) record.pqsign = toBase64Url(await subtle.exportKey('raw-public', pqsign.publicKey));
+ if (presence) record.presence = presence;
+ return Object.freeze({ id: await kappa(record), record, signingKey: signing.privateKey, agreementKey: agreement.privateKey,
+ kemKey: kem?.privateKey ?? null, pqSigningKey: pqsign?.privateKey ?? null });
+}
+
+/**
+ * A device holds non-extractable private keys: one signs prism records, one
+ * agrees keys for wrapping, and where the platform has it an ML-KEM-768 key
+ * makes every wrap to this device hybrid, and where it has ML-DSA-65 every
+ * record this device signs carries a second, post-quantum signature. Only its
+ * public record leaves the device. `deviceClass` and `protection` are claims
+ * the device makes about itself.
+ *
+ * `presence` binds a WebAuthn credential (a passkey) to the device:
+ * `{ rp, origin, key }` with the credential's P-256 public key as a JWK. A
+ * host can then require that an action carry an assertion the person made
+ * with user verification (see signAction). WebAuthn credentials are scoped to
+ * one relying party, so use one per persona.
+ */
+export async function createDevice({ deviceClass = 'browser', protection = 'software', presence } = {}) {
+ if (!DEVICE_CLASSES.includes(deviceClass) || deviceClass === 'recovery') refuse('device', `unknown device class ${deviceClass}`);
+ if (!KEY_PROTECTION.includes(protection) || protection === 'threshold-shares') refuse('device', `unknown key protection ${protection}`);
+ if (presence !== undefined) checkPresenceBinding(presence);
+ return deviceFromKeys(await newKeys(false), deviceClass, protection, presence === undefined ? undefined : { rp: presence.rp, origin: presence.origin, key: publicJwk(presence.key) });
+}
+
+const okKey = k => k && k.kty === 'EC' && k.crv === 'P-256' && typeof k.x === 'string' && typeof k.y === 'string' && Object.keys(k).length === 4;
+
+function checkPresenceBinding(presence) {
+ const key = presence?.key && publicJwk(presence.key);
+ if (!presence || typeof presence.rp !== 'string' || !presence.rp || typeof presence.origin !== 'string' || !presence.origin.startsWith('https://') || !okKey(key))
+ refuse('device', 'presence must name rp, an https origin and a P-256 credential key');
+}
+
+const OPTIONAL_DEVICE_FIELDS = Object.freeze({
+ kem: v => fromBase64Url(v).length === KEM_PUBLIC_BYTES,
+ pqsign: v => fromBase64Url(v).length === PQSIGN_PUBLIC_BYTES,
+ presence: v => { checkPresenceBinding(v); return Object.keys(v).length === 3 && Object.keys(v.key).length === 4; }
+});
+
+export function checkDeviceRecord(record) {
+ const ok = () => {
+ if (!record || typeof record !== 'object' || record.kind !== KIND.device || !DEVICE_CLASSES.includes(record.class) ||
+ !KEY_PROTECTION.includes(record.protection) || !okKey(record.sign) || !okKey(record.agree)) return false;
+ for (const key of Object.keys(record)) {
+ if (['kind', 'class', 'protection', 'sign', 'agree'].includes(key)) continue;
+ if (!OPTIONAL_DEVICE_FIELDS[key] || typeof record[key] !== (key === 'presence' ? 'object' : 'string') || !OPTIONAL_DEVICE_FIELDS[key](record[key])) return false;
+ }
+ return true;
+ };
+ let valid;
+ try { valid = ok(); } catch (error) { if (!(error instanceof PrismIdError)) throw error; valid = false; }
+ if (!valid) refuse('device', 'malformed device record');
+ return record;
+}
+
+async function signRecord(device, body) {
+ const bytes = canonicalBytes(body);
+ const envelope = { body, signer: device.id, signature: toBase64Url(await subtle.sign(SIGN_HASH, device.signingKey, bytes)) };
+ if (device.pqSigningKey) envelope.pqsignature = toBase64Url(await subtle.sign(PQSIGN, device.pqSigningKey, bytes));
+ return envelope;
+}
+
+/**
+ * Hybrid signature check (Stitch.PrismId.hybridSignatureAccepted). The P-256
+ * signature must always verify. When the signer advertises an ML-DSA-65 key
+ * and this verifier has ML-DSA, the ML-DSA signature must verify too, so
+ * stripping it is refused. A verifier without ML-DSA checks P-256 alone; a
+ * host that must resist a quantum forger refuses such verifiers with
+ * `{ requirePostQuantum: true }`.
+ */
+async function signatureValid(envelope, deviceRecord, { requirePostQuantum = false } = {}) {
+ try {
+ checkDeviceRecord(deviceRecord);
+ if (await kappa(deviceRecord) !== envelope.signer) return false;
+ const bytes = canonicalBytes(envelope.body);
+ const key = await subtle.importKey('jwk', { ...deviceRecord.sign, ext: true }, SIGN, false, ['verify']);
+ const classical = await subtle.verify(SIGN_HASH, key, fromBase64Url(envelope.signature), bytes);
+ const advertised = typeof deviceRecord.pqsign === 'string';
+ const verifierHasPq = await postQuantumSignaturesAvailable();
+ if (requirePostQuantum && !(advertised && verifierHasPq)) return false;
+ let pq = false;
+ if (advertised && verifierHasPq && typeof envelope.pqsignature === 'string') {
+ const pqKey = await subtle.importKey('raw-public', fromBase64Url(deviceRecord.pqsign), PQSIGN, false, ['verify']);
+ pq = await subtle.verify(PQSIGN, pqKey, fromBase64Url(envelope.pqsignature), bytes);
+ }
+ return model['Stitch.PrismId.hybridSignatureAccepted'](classical, advertised, verifierHasPq, pq);
+ } catch (error) {
+ if (error instanceof PrismIdError || error instanceof DOMException || error instanceof TypeError) return false;
+ throw error;
+ }
+}
+
+// ---------------------------------------------------------------- hybrid key wrapping
+
+/**
+ * Wrap bytes to a device record. ECDH with a fresh ephemeral key, plus
+ * ML-KEM-768 encapsulation whenever the recipient advertises a KEM key. A
+ * sender that cannot encapsulate refuses rather than downgrade
+ * (Stitch.PrismId.hybridWrapRequired).
+ */
+async function wrapTo(recipient, bytes, { salt, info, aad }) {
+ const ephemeral = await subtle.generateKey(AGREE, false, ['deriveBits']);
+ const peer = await subtle.importKey('jwk', { ...recipient.agree, ext: true }, AGREE, false, []);
+ const classical = new Uint8Array(await subtle.deriveBits({ name: 'ECDH', public: peer }, ephemeral.privateKey, 256));
+ let ikm = classical, kemCiphertext;
+ if (recipient.kem !== undefined) {
+ if (!await postQuantumAvailable()) refuse('post-quantum', 'the recipient requires a hybrid wrap and this platform has no ML-KEM');
+ const kemPublic = await subtle.importKey('raw-public', fromBase64Url(recipient.kem), KEM, false, ['encapsulateBits']);
+ const { sharedKey, ciphertext } = await subtle.encapsulateBits(KEM, kemPublic);
+ ikm = concat(classical, new Uint8Array(sharedKey));
+ kemCiphertext = toBase64Url(ciphertext);
+ }
+ const key = await hkdfAesKey(ikm, salt, info);
+ const wrap = { agree: publicJwk(await subtle.exportKey('jwk', ephemeral.publicKey)), ...await encryptWith(key, bytes, aad) };
+ if (kemCiphertext) wrap.kem = kemCiphertext;
+ return wrap;
+}
+
+async function unwrapFrom(device, wrap, { salt, info, aad }) {
+ if (!model['Stitch.PrismId.hybridWrapRequired'](device.record.kem !== undefined, typeof wrap.kem === 'string'))
+ refuse('post-quantum', 'a wrap to a post-quantum device must be hybrid');
+ const peer = await subtle.importKey('jwk', { ...wrap.agree, ext: true }, AGREE, false, []);
+ let ikm = new Uint8Array(await subtle.deriveBits({ name: 'ECDH', public: peer }, device.agreementKey, 256));
+ if (typeof wrap.kem === 'string') {
+ if (!device.kemKey) refuse('post-quantum', 'this device has no ML-KEM key');
+ ikm = concat(ikm, new Uint8Array(await subtle.decapsulateBits(KEM, device.kemKey, fromBase64Url(wrap.kem))));
+ }
+ return decryptWith(await hkdfAesKey(ikm, salt, info), wrap, aad);
+}
+
+function concat(...parts) {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let offset = 0;
+ for (const p of parts) { out.set(p, offset); offset += p.length; }
+ return out;
+}
+
+async function hkdfAesKey(ikm, salt, info) {
+ const material = await subtle.importKey('raw', ikm, 'HKDF', false, ['deriveKey']);
+ return subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt, info: encoder.encode(info) },
+ material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
+}
+
+async function encryptWith(key, bytes, aad) {
+ const iv = random(12);
+ const ciphertext = await subtle.encrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(aad) }, key, bytes);
+ return { iv: toBase64Url(iv), ciphertext: toBase64Url(ciphertext) };
+}
+async function decryptWith(key, box, aad) {
+ return new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv: fromBase64Url(box.iv), additionalData: encoder.encode(aad) }, key, fromBase64Url(box.ciphertext)));
+}
+
+// ---------------------------------------------------------------- boundary keys
+
+/**
+ * A boundary key is 32 random bytes. Sealing and topic keys are derived from
+ * it with HKDF and are never extractable. The bytes themselves are kept only
+ * on a sharing device (one that links members, rotates or sets up recovery);
+ * a hardened device keeps the derived keys alone (Stitch.PrismId.mayShareBoundary).
+ */
+async function boundaryFromRaw(raw, shareable) {
+ const material = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
+ const derive = (info, algorithm, usages) => subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(32), info: encoder.encode(info) }, material, algorithm, false, usages);
+ return Object.freeze({
+ seal: await derive('prism/boundary-seal/1', { name: 'AES-GCM', length: 256 }, ['encrypt', 'decrypt']),
+ topic: await derive('prism/boundary-topic/1', { name: 'HMAC', hash: 'SHA-256', length: 256 }, ['sign']),
+ raw: shareable ? Uint8Array.from(raw) : null
+ });
+}
+
+function requireShareable(session, what) {
+ if (!model['Stitch.PrismId.mayShareBoundary'](session.shareable === true)) refuse('hardened', `a hardened device cannot ${what}; use a sharing member`);
+}
+
+function keyringBytes(keyring) {
+ const keys = {};
+ for (const [id, entry] of keyring) {
+ if (!entry.raw) refuse('hardened', 'this keyring is hardened and cannot be shared');
+ keys[id] = toBase64Url(entry.raw);
+ }
+ return canonicalBytes({ kind: KIND.keyring, keys });
+}
+
+async function keyringFromBytes(bytes, shareable) {
+ const value = JSON.parse(decoder.decode(bytes));
+ if (value.kind !== KIND.keyring) refuse('keyring', 'malformed keyring');
+ const keyring = new Map();
+ for (const [id, raw] of Object.entries(value.keys)) keyring.set(id, await boundaryFromRaw(fromBase64Url(raw), shareable));
+ return keyring;
+}
+
+/**
+ * Make this device hold only non-extractable boundary keys. Script running in
+ * its origin can then use them while it runs but can never copy them out.
+ * A hardened device can still link delegates, revoke and sync; it cannot link
+ * members or set up recovery.
+ */
+export async function hardenSession(session) {
+ const keyring = new Map();
+ for (const [id, entry] of session.keyring) keyring.set(id, Object.freeze({ seal: entry.seal, topic: entry.topic, raw: null }));
+ return { ...session, keyring, shareable: false };
+}
+
+// ---------------------------------------------------------------- the prism log
+
+/** Records are kept by the kappa of their envelope, so merging is set union. */
+export async function addRecord(log, envelope) {
+ const next = new Map(log);
+ next.set(await kappa(envelope), envelope);
+ return next;
+}
+
+/** Commutative, associative and idempotent: union keyed by kappa. */
+export function mergeLogs(left, right) {
+ const next = new Map(left);
+ for (const [k, v] of right) next.set(k, v);
+ return next;
+}
+
+export async function logRoot(log) {
+ return kappa({ kind: KIND.log, records: [...log.keys()].sort() });
+}
+
+/** Admission bounds for logs and sync messages from peers, checked before any parsing or signature work. */
+export const MAX_LOG_RECORDS = 4096;
+export const MAX_SYNC_BYTES = 4 * 1024 * 1024;
+
+export async function logFromRecords(records) {
+ if (!Array.isArray(records)) refuse('log', 'records must be an array');
+ if (records.length > MAX_LOG_RECORDS) refuse('log', `log exceeds ${MAX_LOG_RECORDS} records`);
+ let log = new Map();
+ for (const r of records) log = await addRecord(log, r);
+ return log;
+}
+
+const byKey = ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0);
+const sameSet = (a, b) => a.size === b.size && [...a].every(x => b.has(x));
+
+function bindShape(body) {
+ return ROLES.includes(body.role) && Array.isArray(body.scope) && body.scope.every(x => typeof x === 'string') &&
+ (body.role === 'delegate' ? body.scope.length > 0 : body.scope.length === 0);
+}
+
+/**
+ * Resolve which devices may act for the prism, with what role and scope, and
+ * which boundary key is current.
+ *
+ * - A bind counts only when Stitch.PrismId.bindAllowed holds: the signer is a
+ * linked member or recovery device (not a delegate), its signature verifies,
+ * it names this prism, and the signer is not revoked unless a revocation kept
+ * that bind. A recovery-role bind also needs Stitch.PrismId.recoveryBindAllowed:
+ * while a recovery device exists, only a recovery device may add another.
+ * - Revocation wins over a concurrent bind: binds a revoked device made that
+ * the revoker did not list in `keep` are dropped.
+ * - Stitch.PrismId.revocationCounts: revocations by the recovery device come
+ * first; a device the recovery device revoked has no revocations that count;
+ * only a recovery device may revoke a recovery device. So a thief holding a
+ * member device cannot lock the person out: recovery revokes the thief and
+ * the thief's revocations stop counting.
+ * - Every rotating revocation carries a new boundary key (`epoch`, `wraps`).
+ * The current key is the one with the highest epoch; ties go to the smaller kappa.
+ */
+export async function resolvePrism(prism, log) {
+ const entries = [...log.entries()].sort(byKey);
+ // 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 = [];
+ for (const [id, e] of entries) {
+ const body = e?.body;
+ if (body?.prism !== prism) continue;
+ if (body.kind === KIND.bind && bindShape(body)) {
+ try { const r = checkDeviceRecord(body.device); const target = await kappa(r); devices.set(target, r); binds.push({ id, e, target }); }
+ catch (error) { if (!(error instanceof PrismIdError)) throw error; }
+ } else if (body.kind === KIND.revoke && typeof body.device === 'string' && Array.isArray(body.keep) &&
+ Number.isSafeInteger(body.epoch) && body.epoch > 0 && Array.isArray(body.wraps)) revokes.push({ id, e });
+ }
+ const verified = new Map();
+ const verify = async (id, e) => {
+ if (!verified.has(id)) verified.set(id, devices.has(e.signer) && await signatureValid(e, devices.get(e.signer)));
+ return verified.get(id);
+ };
+
+ let linked = new Set([genesis.signer]), roles = new Map([[genesis.signer, 'member']]), revocations = new Map();
+ for (let round = 0; round <= 2 * log.size + 2; round++) {
+ // Revocations by the recovery device first: they decide whose revocations count.
+ const revokedByRecovery = new Set();
+ for (const { id, e } of revokes) {
+ if (roles.get(e.signer) === 'recovery' && linked.has(e.signer) && await verify(id, e)) revokedByRecovery.add(e.body.device);
+ }
+ const nextRevocations = new Map();
+ for (const { id, e } of revokes) {
+ const signerRole = roles.get(e.signer);
+ if (!model['Stitch.PrismId.mayAdminister'](linked.has(e.signer), false, signerRole !== 'member' && signerRole !== 'recovery')) continue;
+ if (!model['Stitch.PrismId.revocationCounts'](signerRole === 'recovery', revokedByRecovery.has(e.signer) && signerRole !== 'recovery',
+ roles.get(e.body.device) === 'recovery')) continue;
+ if (!await verify(id, e)) continue;
+ const entry = nextRevocations.get(e.body.device) ?? { keep: new Set(), recoveryKeep: null, by: [] };
+ for (const k of e.body.keep) entry.keep.add(k);
+ if (signerRole === 'recovery') { entry.recoveryKeep ??= new Set(); for (const k of e.body.keep) entry.recoveryKeep.add(k); }
+ entry.by.push({ id, e });
+ nextRevocations.set(e.body.device, entry);
+ }
+ const nextLinked = new Set([genesis.signer]), nextRoles = new Map([[genesis.signer, 'member']]), scopes = new Map();
+ for (let grew = true; grew;) {
+ grew = false;
+ for (const { id, e, target } of binds) {
+ const current = nextRoles.get(target);
+ if (current === 'member' || current === 'recovery' || (current === 'delegate' && e.body.role === 'delegate')) continue;
+ // A member's revocation (with a keep list it chose) never drops a recovery bind; only recovery can.
+ const revocation = nextRevocations.get(e.signer);
+ const keep = e.body.role === 'recovery' ? revocation?.recoveryKeep : revocation?.keep;
+ const signerRevoked = e.body.role === 'recovery' ? !!keep && !keep.has(id) : revocation !== undefined && !keep.has(id);
+ const signerRole = nextRoles.get(e.signer);
+ let allowed = model['Stitch.PrismId.bindAllowed'](nextLinked.has(e.signer), signerRevoked,
+ signerRole !== 'member' && signerRole !== 'recovery', await verify(id, e), true);
+ if (allowed && e.body.role === 'recovery') {
+ const recoveryExists = [...nextRoles].some(([d, r]) => r === 'recovery' && d !== target && !nextRevocations.has(d));
+ allowed = model['Stitch.PrismId.recoveryBindAllowed'](signerRole === 'recovery', recoveryExists);
+ }
+ if (allowed) {
+ nextLinked.add(target); nextRoles.set(target, e.body.role);
+ if (e.body.role === 'delegate') scopes.set(target, [...e.body.scope].sort()); else scopes.delete(target);
+ grew = true;
+ }
+ }
+ }
+ const settled = sameSet(nextLinked, linked) && sameSet(new Set(nextRevocations.keys()), new Set(revocations.keys())) &&
+ [...nextRoles].every(([d, r]) => roles.get(d) === r) && nextRoles.size === roles.size;
+ linked = nextLinked; roles = nextRoles; revocations = nextRevocations;
+ if (settled) {
+ const active = [...linked].filter(d => model['Stitch.PrismId.deviceMaySign'](true, revocations.has(d))).sort();
+ const rekeys = [...revocations.values()].flatMap(r => r.by).filter(r => r.e.body.wraps.length > 0)
+ .sort((a, b) => b.e.body.epoch - a.e.body.epoch || (a.id < b.id ? -1 : 1));
+ const boundary = rekeys.length ? { epoch: rekeys[0].e.body.epoch, keyId: rekeys[0].id } : { epoch: 0, keyId: prism };
+ const maxEpoch = Math.max(0, ...[...revocations.values()].flatMap(r => r.by.map(b => b.e.body.epoch)));
+ return Object.freeze({
+ prism,
+ active,
+ revoked: [...revocations.keys()].sort(),
+ roles: Object.freeze(Object.fromEntries(active.map(d => [d, roles.get(d)]))),
+ scopes: Object.freeze(Object.fromEntries(active.filter(d => roles.get(d) === 'delegate').map(d => [d, scopes.get(d)]))),
+ devices: Object.freeze(Object.fromEntries(active.map(d => [d, devices.get(d)]))),
+ recovery: active.find(d => roles.get(d) === 'recovery') ?? null,
+ boundary: Object.freeze(boundary),
+ epoch: maxEpoch,
+ rekeys: rekeys.map(r => ({ keyId: r.id, epoch: r.e.body.epoch, wraps: r.e.body.wraps }))
+ });
+ }
+ }
+ return refuse('resolve', 'device linkage did not settle');
+}
+
+export async function canSign(prism, log, deviceId) {
+ const state = await resolvePrism(prism, log);
+ return model['Stitch.PrismId.deviceMaySign'](state.active.includes(deviceId) || state.revoked.includes(deviceId), state.revoked.includes(deviceId));
+}
+
+async function mayAdminister(session) {
+ const state = await resolvePrism(session.prism, session.log);
+ const id = session.device.id;
+ const role = state.roles[id];
+ if (!model['Stitch.PrismId.mayAdminister'](state.active.includes(id), state.revoked.includes(id), role !== 'member' && role !== 'recovery'))
+ refuse('unauthorized', 'this device may not administer the prism');
+ return state;
+}
+
+const boundaryRecipient = role => role === 'member' || role === 'recovery';
+const rekeyContext = (prism, id, epoch) => ({ salt: encoder.encode(prism), info: `prism/rekey-wrap/1 ${id}`, aad: `${prism} ${epoch}` });
+
+/** Take up any boundary keys wrapped to this device by revocations it has not yet absorbed. */
+async function absorbRekeys(session, state) {
+ const keyring = new Map(session.keyring);
+ for (const rekey of state.rekeys) {
+ if (keyring.has(rekey.keyId)) continue;
+ const wrap = rekey.wraps.find(w => w?.device === session.device.id);
+ if (!wrap) continue;
+ const raw = await unwrapFrom(session.device, wrap, rekeyContext(session.prism, wrap.device, rekey.epoch));
+ keyring.set(rekey.keyId, await boundaryFromRaw(raw, session.shareable === true));
+ raw.fill(0);
+ }
+ return keyring;
+}
+
+/** The boundary key this device must seal with. Refuses a stale key (Stitch.PrismId.boundaryKeyAdmitted). */
+export async function currentBoundary(session) {
+ const state = await resolvePrism(session.prism, session.log);
+ const epochOf = id => (id === session.prism ? 0 : state.rekeys.find(r => r.keyId === id)?.epoch);
+ const heldEpoch = Math.max(-1, ...[...session.keyring.keys()].map(epochOf).filter(Number.isSafeInteger));
+ if (heldEpoch < 0 || !model['Stitch.PrismId.boundaryKeyAdmitted'](heldEpoch, state.boundary.epoch) || !session.keyring.has(state.boundary.keyId))
+ refuse('stale-key', 'this device does not hold the current private boundary key');
+ return { keyId: state.boundary.keyId, epoch: state.boundary.epoch, entry: session.keyring.get(state.boundary.keyId) };
+}
+
+// ---------------------------------------------------------------- sessions
+
+function emptySession(prism, device, log) {
+ return { prism, device, keyring: new Map(), log, shareable: true, personas: new Map(), personaDevices: new Map() };
+}
+
+/**
+ * Create a prism on this device. No account, server or third party is involved.
+ * The private boundary key never leaves a member device unwrapped.
+ */
+export async function createPrism(deviceOptions) {
+ const device = await createDevice(deviceOptions);
+ const genesis = await signRecord(device, { kind: KIND.genesis, device: device.record, nonce: toBase64Url(random(16)) });
+ const prism = await kappa(genesis.body);
+ const session = emptySession(prism, device, await logFromRecords([genesis]));
+ session.keyring.set(prism, await boundaryFromRaw(random(32), true));
+ return session;
+}
+
+/**
+ * Revoke a device. By default the private boundary key rotates: a new key is
+ * wrapped to every remaining member and recovery device (hybrid where they
+ * advertise ML-KEM), never to the revoked device or to delegates. Binds the
+ * revoked device made that this device knows of are kept. Persona keys of the
+ * revoked device are revoked at every host this device can administer.
+ */
+export async function revokeDevice(session, deviceId, { rotate = true } = {}) {
+ const state = await mayAdminister(session);
+ const keep = [];
+ for (const [id, e] of session.log) if (e.body.kind === KIND.bind && e.signer === deviceId) keep.push(id);
+ const epoch = state.epoch + 1;
+ const wraps = [];
+ if (rotate) {
+ const raw = random(32);
+ for (const id of state.active) {
+ if (id === deviceId || !model['Stitch.PrismId.receivesPrivateBoundary'](!boundaryRecipient(state.roles[id]))) continue;
+ wraps.push({ device: id, ...await wrapTo(state.devices[id], raw, rekeyContext(session.prism, id, epoch)) });
+ }
+ raw.fill(0);
+ }
+ const envelope = await signRecord(session.device, { kind: KIND.revoke, prism: session.prism, device: deviceId, keep: keep.sort(), epoch, wraps });
+ const log = await addRecord(session.log, envelope);
+ let next = { ...session, log };
+ next.keyring = await absorbRekeys(next, await resolvePrism(session.prism, log));
+ next = await servicePersonas(next);
+ return next;
+}
+
+// ---------------------------------------------------------------- out-of-band linking
+
+const LINK_URI = 'prism-link:';
+
+async function hmacKey(raw, usages) {
+ return subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, usages);
+}
+
+/** Where the two devices meet on the bus. Only holders of the secret can derive it. */
+export async function rendezvousTopic(secret) {
+ return 'prism-rendezvous:' + (await kappa({ kind: KIND.rendezvous, secret })).slice(7);
+}
+
+/**
+ * Six-digit code both devices show before the link is accepted. It binds the
+ * secret to the joining device, so a device that read the QR code first shows
+ * a code that does not match the one on the device the person is holding.
+ */
+export async function linkCode(secret, deviceRecord) {
+ const digest = new Uint8Array(await subtle.digest('SHA-256', canonicalBytes({ kind: KIND.linkCode, secret, device: await kappa(deviceRecord) })));
+ return String(new DataView(digest.buffer).getUint32(0) % 1000000).padStart(6, '0');
+}
+
+/**
+ * Offer to link a new device. The returned URI is what the QR code (or NFC tag,
+ * USB/serial line, or typed text) carries. The pending half stays here and is
+ * used exactly once. A delegate offer names the actions the device may take.
+ * Only a sharing (not hardened) member can offer a member link.
+ */
+export async function createLinkOffer(session, { now, ttl = 300000, role = 'member', scope = [] }) {
+ await mayAdminister(session);
+ if (role === 'recovery' || !bindShape({ role, scope })) refuse('offer', 'a member has no scope; a delegate needs at least one action');
+ if (role === 'member') requireShareable(session, 'link a member');
+ const offer = { kind: KIND.offer, prism: session.prism, role, scope: [...scope].sort(), secret: toBase64Url(random(32)), expires: now + ttl };
+ return { offer, uri: LINK_URI + toBase64Url(canonicalBytes(offer)), pending: { offer, used: false } };
+}
+
+export function parseLinkUri(uri) {
+ if (typeof uri !== 'string' || !uri.startsWith(LINK_URI)) refuse('offer', 'not a prism link');
+ const offer = JSON.parse(decoder.decode(fromBase64Url(uri.slice(LINK_URI.length))));
+ if (offer.kind !== KIND.offer || !isKappa(offer.prism) || !Number.isSafeInteger(offer.expires) || !bindShape(offer) ||
+ offer.role === 'recovery' || typeof offer.secret !== 'string') refuse('offer', 'malformed link offer');
+ 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 });
+
+/** New device: answer an offer it read out of band. */
+export async function requestLink(device, offer) {
+ const key = await hmacKey(fromBase64Url(offer.secret), ['sign']);
+ const proof = await subtle.sign('HMAC', key, canonicalBytes(requestProofBody(offer.prism, device.record)));
+ return { kind: KIND.request, prism: offer.prism, device: device.record, proof: toBase64Url(proof) };
+}
+
+/**
+ * Existing member device: accept a link request. Refuses unless
+ * Stitch.PrismId.linkOfferAccepted holds: the person confirmed the matching
+ * six-digit code, the secret matches, the offer is unused and unexpired.
+ * A member receives the keyring, hybrid-wrapped when it advertises ML-KEM;
+ * a delegate receives no boundary key.
+ */
+export async function acceptLinkRequest(session, pending, request, { now, confirmCode }) {
+ await mayAdminister(session);
+ const { offer } = pending;
+ let secretMatches = false, userConfirmed = false;
+ if (request?.kind === KIND.request && request.prism === offer.prism) {
+ try {
+ checkDeviceRecord(request.device);
+ if (request.device.class === 'recovery') refuse('offer', 'a recovery device is never linked by offer');
+ const key = await hmacKey(fromBase64Url(offer.secret), ['verify']);
+ secretMatches = await subtle.verify('HMAC', key, fromBase64Url(request.proof), canonicalBytes(requestProofBody(request.prism, request.device)));
+ userConfirmed = typeof confirmCode === 'string' && confirmCode === await linkCode(offer.secret, request.device);
+ } catch (error) { if (!(error instanceof PrismIdError)) throw error; }
+ }
+ if (!model['Stitch.PrismId.linkOfferAccepted'](userConfirmed, pending.used, secretMatches, offer.expires, now)) refuse('offer', 'link request refused');
+ pending.used = true;
+ const bind = await signRecord(session.device, { kind: KIND.bind, prism: session.prism, device: request.device, role: offer.role, scope: offer.scope });
+ const log = await addRecord(session.log, bind);
+ let wrap = null;
+ if (model['Stitch.PrismId.receivesPrivateBoundary'](offer.role === 'delegate')) {
+ requireShareable(session, 'link a member');
+ wrap = await wrapTo(request.device, keyringBytes(session.keyring), linkContext(offer));
+ }
+ const response = { kind: KIND.response, prism: session.prism, records: [...log.values()], personas: personaRecords(session), wrap };
+ return { session: await servicePersonas({ ...session, log }), response };
+}
+
+/** New device: finish linking. Verifies that the prism now lists this device with the offered role. */
+export async function completeLink(device, offer, response) {
+ if (response?.kind !== KIND.response || response.prism !== offer.prism) refuse('response', 'response is for another prism');
+ const log = await logFromRecords(response.records);
+ const state = await resolvePrism(offer.prism, log);
+ if (!state.active.includes(device.id) || state.roles[device.id] !== offer.role) refuse('response', 'the prism did not bind this device');
+ const session = emptySession(offer.prism, device, log);
+ if (offer.role === 'member') {
+ if (!response.wrap) refuse('response', 'member link without the private boundary');
+ const bytes = await unwrapFrom(device, response.wrap, linkContext(offer));
+ session.keyring = await keyringFromBytes(bytes, true);
+ bytes.fill(0);
+ }
+ session.keyring = await absorbRekeys(session, state);
+ await mergePersonaRecords(session, response.personas);
+ return session;
+}
+
+// ---------------------------------------------------------------- threshold recovery
+
+/** GF(2^8) with the AES polynomial; Shamir secret sharing over it. */
+const GF_EXP = new Uint8Array(512), GF_LOG = new Uint8Array(256);
+{
+ let x = 1;
+ for (let i = 0; i < 255; i++) { GF_EXP[i] = x; GF_LOG[x] = i; x ^= (x << 1) ^ ((x & 0x80) ? 0x11b : 0); x &= 0xff; }
+ for (let i = 255; i < 512; i++) GF_EXP[i] = GF_EXP[i - 255];
+}
+const gfMul = (a, b) => (a && b ? GF_EXP[GF_LOG[a] + GF_LOG[b]] : 0);
+const gfDiv = (a, b) => (a ? GF_EXP[GF_LOG[a] + 255 - GF_LOG[b]] : 0);
+
+export function splitSecret(secret, threshold, count) {
+ if (!Number.isSafeInteger(threshold) || !Number.isSafeInteger(count) || threshold < 1 || threshold > count || count > 255)
+ refuse('recovery', 'threshold must be between 1 and the number of guardians (at most 255)');
+ const shares = Array.from({ length: count }, (_, i) => ({ index: i + 1, bytes: new Uint8Array(secret.length) }));
+ const coefficients = new Uint8Array(threshold);
+ for (let b = 0; b < secret.length; b++) {
+ coefficients[0] = secret[b];
+ globalThis.crypto.getRandomValues(coefficients.subarray(1));
+ for (const share of shares) {
+ let y = 0;
+ for (let c = threshold - 1; c >= 0; c--) y = gfMul(y, share.index) ^ coefficients[c];
+ share.bytes[b] = y;
+ }
+ }
+ coefficients.fill(0);
+ return shares;
+}
+
+export function combineShares(shares) {
+ const length = shares[0].bytes.length;
+ const out = new Uint8Array(length);
+ for (let b = 0; b < length; b++) {
+ let y = 0;
+ for (const i of shares) {
+ let basis = 1;
+ for (const j of shares) if (i !== j) basis = gfMul(basis, gfDiv(j.index, j.index ^ i.index));
+ y ^= gfMul(i.bytes[b], basis);
+ }
+ out[b] = y;
+ }
+ return out;
+}
+
+const shareContext = (prism, index) => ({ salt: encoder.encode(prism), info: 'prism/recovery-share/1', aad: `${prism} ${index}` });
+
+async function exportDeviceSecret(keys) {
+ const secret = {
+ sign: await subtle.exportKey('jwk', keys.signing.privateKey),
+ agree: await subtle.exportKey('jwk', keys.agreement.privateKey)
+ };
+ if (keys.kem) secret.kem = toBase64Url(await subtle.exportKey('pkcs8', keys.kem.privateKey));
+ if (keys.pqsign) secret.pqsign = toBase64Url(await subtle.exportKey('pkcs8', keys.pqsign.privateKey));
+ return secret;
+}
+
+async function importDeviceSecret(record, secret) {
+ const strip = ({ kty, crv, x, y, d }) => ({ kty, crv, x, y, d });
+ const signingKey = await subtle.importKey('jwk', strip(secret.sign), SIGN, false, ['sign']);
+ const agreementKey = await subtle.importKey('jwk', strip(secret.agree), AGREE, false, ['deriveBits']);
+ const kemKey = secret.kem ? await subtle.importKey('pkcs8', fromBase64Url(secret.kem), KEM, false, ['decapsulateBits']) : null;
+ const pqSigningKey = secret.pqsign ? await subtle.importKey('pkcs8', fromBase64Url(secret.pqsign), PQSIGN, false, ['sign']) : null;
+ return Object.freeze({ id: await kappa(record), record, signingKey, agreementKey, kemKey, pqSigningKey });
+}
+
+/**
+ * Set up threshold recovery. A recovery device is created whose private keys
+ * exist only as `threshold`-of-n shares, each sealed to one guardian: a device
+ * of another prism the person trusts (a shared boundary), a spare device of
+ * their own, or `{ paper: true }` for a share to print. The recovery device can
+ * link and revoke but never acts at a host. Needs a sharing member, or the
+ * current recovery device when rotating recovery.
+ */
+export async function createRecovery(session, { threshold, guardians }) {
+ const state = await mayAdminister(session);
+ requireShareable(session, 'set up recovery');
+ if (!Array.isArray(guardians) || guardians.length < 1) refuse('recovery', 'at least one guardian is required');
+ if (state.recovery && state.roles[session.device.id] !== 'recovery') refuse('recovery', 'recovery exists; only the recovery device may replace it');
+ const keys = await newKeys(true);
+ const device = await deviceFromKeys(keys, 'recovery', 'threshold-shares');
+ const bind = await signRecord(session.device, { kind: KIND.bind, prism: session.prism, device: device.record, role: 'recovery', scope: [] });
+ const log = await addRecord(session.log, bind);
+ const after = await resolvePrism(session.prism, log);
+ if (after.roles[device.id] !== 'recovery') refuse('recovery', 'the prism did not accept the recovery device');
+ const secret = canonicalBytes({ kind: KIND.recoverySecret, prism: session.prism, device: device.record, keys: await exportDeviceSecret(keys), keyring: JSON.parse(decoder.decode(keyringBytes(session.keyring))).keys });
+ const parts = splitSecret(secret, threshold, guardians.length);
+ secret.fill(0);
+ const shares = [];
+ for (const [i, guardian] of guardians.entries()) {
+ const part = parts[i];
+ const body = { kind: KIND.recoveryShare, prism: session.prism, recovery: device.id, threshold, index: part.index };
+ if (guardian?.paper === true) shares.push({ ...body, guardian: 'paper', share: toBase64Url(part.bytes) });
+ else {
+ checkDeviceRecord(guardian);
+ shares.push({ ...body, guardian: await kappa(guardian), wrap: await wrapTo(guardian, part.bytes, shareContext(session.prism, part.index)) });
+ }
+ part.bytes.fill(0);
+ }
+ return { session: { ...session, log }, recovery: device.id, shares };
+}
+
+/**
+ * Guardian: release a share to the person's new device. The guardian confirms
+ * out of band that the new device is really the person's (a call, a meeting),
+ * and compares the code from recoveryCode on both screens.
+ */
+export async function releaseShare(guardianDevice, share, newDeviceRecord) {
+ if (share.kind !== KIND.recoveryShare || share.guardian !== guardianDevice.id) refuse('recovery', 'this share is not held by this guardian');
+ const bytes = await unwrapFrom(guardianDevice, share.wrap, shareContext(share.prism, share.index));
+ checkDeviceRecord(newDeviceRecord);
+ const released = { kind: KIND.recoveryShare, prism: share.prism, recovery: share.recovery, threshold: share.threshold, index: share.index,
+ guardian: await kappa(newDeviceRecord), wrap: await wrapTo(newDeviceRecord, bytes, shareContext(share.prism, share.index)) };
+ bytes.fill(0);
+ return released;
+}
+
+/** Code the new device shows and the guardian compares before releasing a share. */
+export async function recoveryCode(prism, newDeviceRecord) {
+ return linkCode(toBase64Url(encoder.encode(prism)), newDeviceRecord);
+}
+
+/**
+ * Recover a prism on a new device from `threshold` shares. Refuses below the
+ * threshold (Stitch.PrismId.thresholdMet). The recovered recovery device binds
+ * the new device as a member and revokes every other device, which also stops
+ * any revocations a thief made from counting. Pass `rotateRecovery` with new
+ * guardians so the recovered secret is retired at once. Personas are carried
+ * over when their host-held logs are supplied.
+ */
+export async function recoverPrism({ prism, records, bus, shares, device, personas = {}, rotateRecovery }) {
+ let log = records === undefined ? null : await logFromRecords(records);
+ let state = log ? await resolvePrism(prism, log) : null;
+ if (!log && typeof bus?.retained !== 'function') refuse('recovery', 'give the prism log, or a bus that retains sync messages');
+ const recoveryId = state ? state.recovery : shares.find(s => s?.kind === KIND.recoveryShare && s.prism === prism)?.recovery;
+ if (!recoveryId) refuse('recovery', 'this prism has no active recovery device');
+ const parts = [];
+ for (const s of shares) {
+ if (s.kind !== KIND.recoveryShare || s.prism !== prism || s.recovery !== recoveryId) continue;
+ if (parts.some(p => p.index === s.index)) continue;
+ const bytes = s.guardian === 'paper' ? fromBase64Url(s.share) : await unwrapFrom(device, s.wrap, shareContext(prism, s.index));
+ parts.push({ index: s.index, threshold: s.threshold, bytes });
+ }
+ const threshold = parts[0]?.threshold ?? 0;
+ if (parts.some(p => p.threshold !== threshold) || !model['Stitch.PrismId.thresholdMet'](threshold, parts.length)) refuse('recovery', 'not enough shares');
+ const secretBytes = combineShares(parts.slice(0, threshold));
+ for (const p of parts) p.bytes.fill(0);
+ let secret;
+ try { secret = JSON.parse(decoder.decode(secretBytes)); } catch { refuse('recovery', 'the shares do not combine to a recovery secret'); }
+ secretBytes.fill(0);
+ if (secret.kind !== KIND.recoverySecret || secret.prism !== prism || await kappa(secret.device) !== recoveryId) refuse('recovery', 'the shares belong to another recovery device');
+ const recovery = await importDeviceSecret(secret.device, secret.keys);
+ const snapshot = new Map();
+ for (const [id, raw] of Object.entries(secret.keyring)) snapshot.set(id, await boundaryFromRaw(fromBase64Url(raw), true));
+ let carried = personas;
+ if (!log) {
+ const found = await collectFromBus(prism, bus, recovery, snapshot);
+ log = found.log;
+ carried = { ...found.personas, ...personas };
+ state = await resolvePrism(prism, log);
+ if (state.recovery !== recoveryId) refuse('recovery', 'the substrate holds no log in which this recovery device is active');
+ }
+ let custodian = emptySession(prism, recovery, log);
+ custodian.keyring = snapshot;
+ custodian.keyring = await absorbRekeys(custodian, state);
+ // Bind the new device, then revoke every other device; each revocation rotates the boundary.
+ const bind = await signRecord(recovery, { kind: KIND.bind, prism, device: device.record, role: 'member', scope: [] });
+ custodian.log = await addRecord(custodian.log, bind);
+ // Revoke from the recovery device every other device ever linked, including ones a thief revoked:
+ // once recovery revokes the thief, the thief's own revocations stop counting.
+ const done = new Set([recovery.id, device.id]);
+ for (let pending = [...state.active, ...state.revoked].filter(id => !done.has(id)); pending.length;) {
+ for (const id of pending) { done.add(id); custodian = await revokeDevice(custodian, id); }
+ const now = await resolvePrism(prism, custodian.log);
+ pending = now.active.filter(id => !done.has(id));
+ }
+ custodian = await recoverPersonas(custodian, recovery, device, secret, carried);
+ let result = { ...emptySession(prism, device, custodian.log), personas: custodian.personas, personaDevices: custodian.personaDevices };
+ result.keyring = await absorbRekeys(result, await resolvePrism(prism, custodian.log));
+ for (const [id, entry] of custodian.keyring) if (!result.keyring.has(id) && entry.raw) result.keyring.set(id, await boundaryFromRaw(entry.raw, true));
+ let newShares = null;
+ if (rotateRecovery) {
+ const rotated = await createRecovery({ ...custodian, keyring: result.keyring }, rotateRecovery);
+ custodian = await revokeDevice({ ...rotated.session, device: recovery, keyring: result.keyring }, recovery.id);
+ result = { ...result, log: custodian.log };
+ result.keyring = await absorbRekeys(result, await resolvePrism(prism, custodian.log));
+ newShares = rotated.shares;
+ }
+ return { session: result, shares: newShares };
+}
+
+/**
+ * Rebuild the prism log from sync messages the substrate retained, with no
+ * device and no other copy. The recovery device holds a snapshot of the
+ * keyring, and every rotation wraps the next boundary key to it, so it can
+ * open the retained messages on each sync topic in turn and follow the chain
+ * of rotations to the current key. Messages it cannot open are skipped.
+ */
+async function collectFromBus(prism, bus, device, keyring) {
+ const session = { ...emptySession(prism, device, new Map()), keyring: new Map(keyring) };
+ const personas = {};
+ const visited = new Set();
+ for (let pending = [...session.keyring.keys()]; pending.length; pending = [...session.keyring.keys()].filter(id => !visited.has(id))) {
+ for (const id of pending) {
+ visited.add(id);
+ for (const bytes of await bus.retained(await syncTopic(session, id))) {
+ try {
+ if (!(bytes instanceof Uint8Array) || bytes.length > MAX_SYNC_BYTES) continue;
+ const message = await openPrivate(session, JSON.parse(decoder.decode(bytes)));
+ if (message.kind !== KIND.sync || message.prism !== prism) continue;
+ const log = mergeLogs(session.log, await logFromRecords(message.records));
+ if (log.size > MAX_LOG_RECORDS) continue;
+ session.log = log;
+ for (const [pid, recs] of Object.entries(message.personas ?? {})) if (Array.isArray(recs)) personas[pid] = [...(personas[pid] ?? []), ...recs];
+ } catch (error) {
+ // A retained message this device cannot open or parse is not evidence of anything; skip it.
+ if (!(error instanceof PrismIdError || error instanceof SyntaxError || error instanceof DOMException || error instanceof TypeError)) throw error;
+ }
+ }
+ }
+ if (session.log.size) session.keyring = await absorbRekeys(session, await resolvePrism(prism, session.log));
+ }
+ if (!session.log.size) refuse('recovery', 'the substrate holds no sync message this recovery device can open');
+ return { log: session.log, personas };
+}
+
+// ---------------------------------------------------------------- personas: one unlinkable id per host
+
+/**
+ * A persona is a prism of its own, one per host (audience). Each device has its
+ * own non-extractable persona key for that host, so two hosts never see the
+ * same prism id or device key and cannot link the person. Persona logs follow
+ * the same rules (resolvePrism) as the main prism. The main prism records which
+ * persona belongs to which host inside the private boundary only: the main log
+ * travels sealed between member devices and is never given to a host.
+ *
+ * When the main prism has a recovery device, each persona also gets a persona
+ * recovery device whose private keys are wrapped to the main recovery device.
+ * No member keeps them, so a revoked member cannot hijack a persona.
+ */
+export async function ensurePersona(session, audience, { presence } = {}) {
+ if (typeof audience !== 'string' || !audience) refuse('persona', 'audience must name a host');
+ const state = await mayActForPersona(session);
+ const existing = choosePersona(session, audience);
+ if (existing) {
+ if (!session.personaDevices.has(audience)) {
+ const own = await createDevice({ deviceClass: session.device.record.class, protection: session.device.record.protection, presence });
+ const request = await signRecord(session.device, { kind: KIND.personaKey, prism: session.prism, audience, persona: existing.persona, device: own.record });
+ const personaDevices = new Map(session.personaDevices).set(audience, own);
+ return servicePersonas({ ...session, personaDevices, log: await addRecord(session.log, request) });
+ }
+ return session;
+ }
+ const own = await createDevice({ deviceClass: session.device.record.class, protection: session.device.record.protection, presence });
+ const genesis = await signRecord(own, { kind: KIND.genesis, device: own.record, nonce: toBase64Url(random(16)) });
+ const persona = await kappa(genesis.body);
+ let personaLog = await logFromRecords([genesis]);
+ let recoverySeal = null;
+ if (state.recovery) {
+ const keys = await newKeys(true);
+ const personaRecovery = await deviceFromKeys(keys, 'recovery', 'threshold-shares');
+ personaLog = await addRecord(personaLog, await signRecord(own, { kind: KIND.bind, prism: persona, device: personaRecovery.record, role: 'recovery', scope: [] }));
+ const secret = canonicalBytes({ kind: KIND.personaRecovery, persona, device: personaRecovery.record, keys: await exportDeviceSecret(keys) });
+ recoverySeal = { recovery: state.recovery, ...await wrapTo(state.devices[state.recovery], secret, { salt: encoder.encode(persona), info: 'prism/persona-recovery/1', aad: persona }) };
+ secret.fill(0);
+ }
+ const record = await signRecord(session.device, { kind: KIND.persona, prism: session.prism, audience, persona, recovery: recoverySeal });
+ const keyRecord = await signRecord(session.device, { kind: KIND.personaKey, prism: session.prism, audience, persona, device: own.record });
+ let log = await addRecord(session.log, record);
+ log = await addRecord(log, keyRecord);
+ const personas = new Map(session.personas).set(persona, personaLog);
+ const personaDevices = new Map(session.personaDevices).set(audience, own);
+ return servicePersonas({ ...session, log, personas, personaDevices });
+}
+
+async function mayActForPersona(session) {
+ const state = await resolvePrism(session.prism, session.log);
+ const id = session.device.id;
+ if (!model['Stitch.PrismId.deviceMaySign'](state.active.includes(id), state.revoked.includes(id))) refuse('unauthorized', 'this device may not act for the prism');
+ return state;
+}
+
+function personaEntries(session, kind) {
+ return [...session.log.entries()].filter(([, e]) => e.body.kind === kind && e.body.prism === session.prism);
+}
+
+function choosePersona(session, audience) {
+ const found = personaEntries(session, KIND.persona).filter(([, e]) => e.body.audience === audience).sort(byKey);
+ return found.length ? found[0][1].body : null;
+}
+
+/** What a host needs to verify this device's actions: the persona id and log for that host. */
+export async function personaFor(session, audience) {
+ const chosen = choosePersona(session, audience);
+ const own = session.personaDevices.get(audience);
+ if (!chosen || !own) refuse('persona', 'no persona for this host yet; call ensurePersona');
+ const log = session.personas.get(chosen.persona);
+ const state = await resolvePrism(chosen.persona, log);
+ if (!state.active.includes(own.id)) refuse('persona', 'this device is not yet bound in the persona; another member must sync first');
+ return { persona: chosen.persona, records: [...log.values()] };
+}
+
+/** Sign an action for a host under this device's persona there. */
+export async function signPersonaAction(session, audience, action, payload, { now, presence }) {
+ const { persona } = await personaFor(session, audience);
+ return signAction({ prism: persona, device: session.personaDevices.get(audience) }, action, payload, { now, audience, presence });
+}
+
+/**
+ * Keep every persona this device can administer in step with the main prism:
+ * bind persona keys requested by active main devices (with the same role and
+ * scope), and revoke persona keys of devices the main prism revoked.
+ */
+async function servicePersonas(session) {
+ if (!session.personas?.size) return session;
+ const state = await resolvePrism(session.prism, session.log);
+ const personas = new Map(session.personas);
+ for (const [audience, own] of session.personaDevices) {
+ const chosen = choosePersona(session, audience);
+ if (!chosen || !personas.has(chosen.persona)) continue;
+ let personaSession = { ...emptySession(chosen.persona, own, personas.get(chosen.persona)), shareable: false };
+ let personaState = await resolvePrism(chosen.persona, personaSession.log);
+ if (!personaState.active.includes(own.id) || !['member', 'recovery'].includes(personaState.roles[own.id])) continue;
+ for (const [, e] of personaEntries(session, KIND.personaKey)) {
+ if (e.body.persona !== chosen.persona) continue;
+ const target = await kappa(e.body.device);
+ const role = state.roles[e.signer];
+ if (state.revoked.includes(e.signer)) {
+ if (personaState.active.includes(target)) {
+ personaSession = await revokeDevice(personaSession, target, { rotate: false });
+ personaState = await resolvePrism(chosen.persona, personaSession.log);
+ }
+ } else if (role && role !== 'recovery' && !personaState.active.includes(target) && !personaState.revoked.includes(target)) {
+ const bind = await signRecord(own, { kind: KIND.bind, prism: chosen.persona, device: e.body.device, role, scope: role === 'delegate' ? state.scopes[e.signer] : [] });
+ personaSession.log = await addRecord(personaSession.log, bind);
+ personaState = await resolvePrism(chosen.persona, personaSession.log);
+ }
+ }
+ personas.set(chosen.persona, personaSession.log);
+ }
+ return { ...session, personas };
+}
+
+function personaRecords(session) {
+ return Object.fromEntries([...(session.personas ?? new Map())].map(([id, log]) => [id, [...log.values()]]));
+}
+
+async function mergePersonaRecords(session, incoming) {
+ if (!incoming || typeof incoming !== 'object') return;
+ const known = new Set(personaEntries(session, KIND.persona).map(([, e]) => e.body.persona));
+ for (const [id, records] of Object.entries(incoming)) {
+ if (!known.has(id)) continue;
+ const merged = mergeLogs(session.personas.get(id) ?? new Map(), await logFromRecords(records));
+ await resolvePrism(id, merged);
+ session.personas.set(id, merged);
+ }
+}
+
+async function recoverPersonas(custodian, recovery, device, secret, hostLogs) {
+ const personas = new Map(custodian.personas);
+ const personaDevices = new Map();
+ let log = custodian.log;
+ for (const [, e] of personaEntries(custodian, KIND.persona)) {
+ const { audience, persona, recovery: seal } = e.body;
+ if (!seal || seal.recovery !== recovery.id || !hostLogs[persona]) continue;
+ const bytes = await unwrapFrom(recovery, seal, { salt: encoder.encode(persona), info: 'prism/persona-recovery/1', aad: persona });
+ const sealed = JSON.parse(decoder.decode(bytes));
+ bytes.fill(0);
+ const personaRecovery = await importDeviceSecret(sealed.device, sealed.keys);
+ let personaSession = { ...emptySession(persona, personaRecovery, await logFromRecords(hostLogs[persona])), shareable: false };
+ const before = await resolvePrism(persona, personaSession.log);
+ if (!before.active.includes(personaRecovery.id)) continue;
+ const own = await createDevice({ deviceClass: device.record.class, protection: device.record.protection });
+ personaSession.log = await addRecord(personaSession.log, await signRecord(personaRecovery, { kind: KIND.bind, prism: persona, device: own.record, role: 'member', scope: [] }));
+ for (const id of before.active) if (id !== personaRecovery.id) personaSession = await revokeDevice(personaSession, id, { rotate: false });
+ log = await addRecord(log, await signRecord(device, { kind: KIND.personaKey, prism: custodian.prism, audience, persona, device: own.record }));
+ personas.set(persona, personaSession.log);
+ personaDevices.set(audience, own);
+ }
+ return { ...custodian, log, personas, personaDevices };
+}
+
+// ---------------------------------------------------------------- scoped actions and host admission
+
+/**
+ * Sign an action for a host (a foundry page, a native service, an embedded
+ * sink). `audience` names the host, so the envelope is useless anywhere else;
+ * a fresh nonce lets the host refuse replays. Prefer signPersonaAction, which
+ * shows the host only that host's persona.
+ *
+ * `presence(challenge)` asks the person to approve: in a browser it calls
+ * navigator.credentials.get with `challenge` and userVerification
+ * 'required', and returns `{ authenticatorData, clientDataJSON, signature }`
+ * as base64url. The challenge is the SHA-256 of the action body, so the
+ * assertion approves exactly this action. Script in the origin cannot make
+ * one without the person's gesture and verification.
+ */
+export async function signAction(session, action, payload, { now, audience, presence }) {
+ if (typeof action !== 'string' || !action) refuse('action', 'action must be a name');
+ if (typeof audience !== 'string' || !audience) refuse('action', 'action must name its audience');
+ const envelope = await signRecord(session.device, { kind: KIND.action, prism: session.prism, action, audience, payload, at: now, nonce: toBase64Url(random(16)) });
+ if (typeof presence === 'function') {
+ if (!session.device.record.presence) refuse('presence', 'this device has no passkey bound to it');
+ const assertion = await presence(await presenceChallenge(envelope.body));
+ envelope.presence = { authenticatorData: assertion.authenticatorData, clientDataJSON: assertion.clientDataJSON, signature: assertion.signature };
+ }
+ return envelope;
+}
+
+/** The WebAuthn challenge that approves an action: SHA-256 of its canonical body. */
+export async function presenceChallenge(body) {
+ return new Uint8Array(await subtle.digest('SHA-256', canonicalBytes(body)));
+}
+
+/** ECDSA signatures from WebAuthn are DER; WebCrypto verifies the raw r || s form. */
+function derToRaw(der) {
+ let i = 0;
+ const fail = () => refuse('presence', 'malformed assertion signature');
+ if (der[i++] !== 0x30) fail();
+ const total = der[i++];
+ if (total & 0x80 || total + 2 !== der.length) fail();
+ const integer = () => {
+ if (der[i++] !== 0x02) fail();
+ const length = der[i++];
+ if (length < 1 || length > 33 || i + length > der.length) fail();
+ let value = der.subarray(i, i + length);
+ i += length;
+ if (value.length === 33) { if (value[0] !== 0) fail(); value = value.subarray(1); }
+ const out = new Uint8Array(32);
+ out.set(value, 32 - value.length);
+ return out;
+ };
+ const r = integer(), s = integer();
+ if (i !== der.length) fail();
+ return concat(r, s);
+}
+
+const sameBytes = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
+
+/**
+ * Check a WebAuthn assertion against the passkey bound in the device record:
+ * type webauthn.get, the challenge for this action body, the bound origin and
+ * rp id, the user-present and user-verified flags, and the signature over
+ * authenticatorData || SHA-256(clientDataJSON).
+ */
+async function presenceEvidence(record, body, presence) {
+ const none = { userPresent: false, userVerified: false, challengeMatches: false, assertionValid: false };
+ const binding = record?.presence;
+ if (!binding || !presence || typeof presence !== 'object') return none;
+ try {
+ const authData = fromBase64Url(presence.authenticatorData);
+ const clientDataBytes = fromBase64Url(presence.clientDataJSON);
+ const clientData = JSON.parse(decoder.decode(clientDataBytes));
+ if (authData.length < 37) return none;
+ const rpHash = new Uint8Array(await subtle.digest('SHA-256', encoder.encode(binding.rp)));
+ const challengeMatches = clientData?.type === 'webauthn.get' && clientData.origin === binding.origin &&
+ clientData.challenge === toBase64Url(await presenceChallenge(body)) && sameBytes(authData.subarray(0, 32), rpHash);
+ const key = await subtle.importKey('jwk', { ...binding.key, ext: true }, SIGN, false, ['verify']);
+ const signed = concat(authData, new Uint8Array(await subtle.digest('SHA-256', clientDataBytes)));
+ const assertionValid = await subtle.verify(SIGN_HASH, key, derToRaw(fromBase64Url(presence.signature)), signed);
+ return { userPresent: (authData[32] & 0x01) !== 0, userVerified: (authData[32] & 0x04) !== 0, challengeMatches, assertionValid };
+ } catch (error) {
+ if (error instanceof PrismIdError || error instanceof SyntaxError || error instanceof DOMException || error instanceof TypeError) return none;
+ throw error;
+ }
+}
+
+/**
+ * Host side. Allowed only when Stitch.PrismId.actionFresh holds (this
+ * audience, nonce not seen, issued within `window` of now) and
+ * Stitch.PrismId.actionAllowed holds (an active member, or a delegate acting
+ * inside its scope; a recovery device never acts). `seen` is the host's replay
+ * set for the window. `prism` and `log` are the persona the device presented.
+ *
+ * `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. `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, 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' };
+ const state = await resolvePrism(prism, log);
+ const id = envelope.signer;
+ if (!state.devices[id] && !state.revoked.includes(id)) return { allowed: false, reason: 'unknown device' };
+ if (!state.devices[id] || !await signatureValid(envelope, state.devices[id], { requirePostQuantum })) return { allowed: false, reason: 'signature or revocation' };
+ const replayKey = `${id} ${body.nonce}`;
+ if (!model['Stitch.PrismId.actionFresh'](body.audience === audience, !seen.has(replayKey), body.at, now, window))
+ return { allowed: false, reason: 'audience, replay or time window' };
+ const required = requirePresence === true || (Array.isArray(requirePresence) && requirePresence.includes(body.action));
+ const evidence = required ? await presenceEvidence(state.devices[id], body, envelope.presence) : {};
+ if (!model['Stitch.PrismId.presenceSatisfied'](required, evidence.userPresent === true, evidence.userVerified === true,
+ evidence.challengeMatches === true, evidence.assertionValid === true)) return { allowed: false, reason: 'approval' };
+ const role = state.roles[id];
+ const scoped = role !== 'member';
+ const allowed = model['Stitch.PrismId.actionAllowed'](true, state.revoked.includes(id), scoped, role === 'delegate' && state.scopes[id].includes(body.action));
+ if (allowed) seen.add(replayKey);
+ return { allowed, reason: allowed ? 'ok' : 'scope', device: state.devices[id], role };
+}
+
+/**
+ * Host policy for a device. A host that requires hardware-held keys admits a
+ * device only when one of the host's own verifiers (Android key attestation,
+ * Apple App Attest, a TPM quote, a secure-element certificate chain, each with
+ * roots the host pins) confirms hardware protection of exactly this device's
+ * signing key (Stitch.PrismId.attestationBinds). The record's `protection`
+ * field is a claim, never evidence.
+ */
+export async function admitDevice(policy, deviceRecord, evidence, verifiers = {}) {
+ checkDeviceRecord(deviceRecord);
+ let attested = false;
+ if (policy?.requiresHardwareKey === true && evidence && typeof verifiers[evidence.format] === 'function') {
+ const result = await verifiers[evidence.format](evidence, deviceRecord);
+ const keyMatches = !!result?.key && result.key.x === deviceRecord.sign.x && result.key.y === deviceRecord.sign.y && result.key.crv === 'P-256';
+ attested = model['Stitch.PrismId.attestationBinds'](result?.hardware === true, keyMatches);
+ }
+ return hostAdmitsDevice(policy, { attestedHardwareKey: attested });
+}
+
+export function hostAdmitsDevice({ requiresHardwareKey = false } = {}, { attestedHardwareKey = false } = {}) {
+ return model['Stitch.PrismId.hostAdmitsDevice'](requiresHardwareKey === true, attestedHardwareKey === true);
+}
+
+// ---------------------------------------------------------------- boundaries and sealed content
+
+/**
+ * A boundary record. One identity: private. Two or more: shared, which is
+ * public to its members (Stitch.PrismId.boundaryShared). Published: public.
+ */
+export function describeBoundary({ members, published = false }) {
+ const unique = [...new Set(members)].sort();
+ if (!unique.length || !unique.every(isKappa)) refuse('boundary', 'members must be prism ids');
+ const shared = model['Stitch.PrismId.boundaryShared'](unique.length);
+ return { kind: KIND.boundary, members: unique, published, visibility: published ? 'public' : shared ? 'shared' : 'private' };
+}
+
+export function boundaryVisibleTo(boundary, prism) {
+ return model['Stitch.PrismId.boundaryVisibleTo'](boundary.members.includes(prism), boundary.published === true);
+}
+
+/**
+ * Sealed plaintext is padded (ISO/IEC 7816-4) to a power-of-two bucket of at
+ * least 1 KiB, so observers learn only the bucket, not the exact size.
+ */
+export function padToBucket(bytes, minimum = 1024) {
+ if (!Number.isSafeInteger(minimum) || minimum < 1024 || (minimum & (minimum - 1)) !== 0) refuse('padding', 'bucket must be a power of two of at least 1024');
+ let size = minimum;
+ while (size < bytes.length + 1) size *= 2;
+ const out = new Uint8Array(size);
+ out.set(bytes);
+ out[bytes.length] = 0x80;
+ return out;
+}
+
+export function unpad(bytes) {
+ let end = bytes.length - 1;
+ while (end >= 0 && bytes[end] === 0) end--;
+ if (end < 0 || bytes[end] !== 0x80) refuse('padding', 'malformed padding');
+ return bytes.subarray(0, end);
+}
+
+/** Seal a JSON value under the current private boundary key. The sealed object's kappa is its address. */
+export async function sealPrivate(session, value) {
+ const { keyId } = await currentBoundary(session);
+ return sealWith(session, keyId, value);
+}
+
+async function sealWith(session, keyId, value, { bucket = 1024 } = {}) {
+ const entry = session.keyring.get(keyId);
+ if (!entry) refuse('stale-key', 'this device does not hold that boundary key');
+ const padded = padToBucket(canonicalBytes(value), bucket);
+ const sealed = { kind: KIND.sealed, boundary: 'private', key: keyId, ...await encryptWith(entry.seal, padded, session.prism) };
+ return { address: await kappa(sealed), sealed, bucket: padded.length };
+}
+
+/** Open sealed content with whichever key it names, including keys from before a rotation. */
+export async function openPrivate(session, sealed) {
+ const entry = session.keyring.get(sealed?.key);
+ if (!entry) refuse('stale-key', 'this device does not hold that boundary key');
+ return JSON.parse(decoder.decode(unpad(await decryptWith(entry.seal, sealed, session.prism))));
+}
+
+// ---------------------------------------------------------------- substrate sync
+
+/** The sync topic for a boundary key. Only devices holding that key can derive it. */
+export async function syncTopic(session, keyId) {
+ const id = keyId ?? (await currentBoundary(session)).keyId;
+ const entry = session.keyring.get(id);
+ if (!entry) refuse('stale-key', 'this device does not hold that boundary key');
+ return 'prism-sync:' + hex(await subtle.sign('HMAC', entry.topic, canonicalBytes({ kind: KIND.sync, prism: session.prism })));
+}
+
+/**
+ * Publish this device's log and persona logs to its other member devices,
+ * sealed in the private boundary. After a rotation, publish once under the
+ * previous key so devices still listening there can take up the new key.
+ * Returns the padded bucket, so a cadence can keep every message that size.
+ */
+export async function publishSync(session, bus, { keyId, bucket } = {}) {
+ const id = keyId ?? (await currentBoundary(session)).keyId;
+ const sealed = await sealWith(session, id, { kind: KIND.sync, prism: session.prism, records: [...session.log.values()], personas: personaRecords(session) }, { bucket });
+ await bus.publish(await syncTopic(session, id), canonicalBytes(sealed.sealed));
+ return { bucket: sealed.bucket };
+}
+
+/** A cover message: sealed and padded like a sync message, ignored by receivers. */
+export async function publishCover(session, bus, { bucket = 1024 } = {}) {
+ const { keyId } = await currentBoundary(session);
+ const sealed = await sealWith(session, keyId, { kind: KIND.cover, prism: session.prism }, { bucket });
+ await bus.publish(await syncTopic(session, keyId), canonicalBytes(sealed.sealed));
+ return { bucket: sealed.bucket };
+}
+
+/**
+ * Constant-cadence sync. Call `tick` on a fixed timer: it publishes a pending
+ * 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, 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) {
+ 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);
+ }
+ };
+}
+
+/** Merge a sync message. Records that do not resolve for this prism are refused. */
+export async function receiveSync(session, bytes) {
+ if (!(bytes instanceof Uint8Array) || bytes.length > MAX_SYNC_BYTES) refuse('sync', `sync message exceeds ${MAX_SYNC_BYTES} bytes`);
+ const message = await openPrivate(session, JSON.parse(decoder.decode(bytes)));
+ if (message.kind === KIND.cover && message.prism === session.prism) return session;
+ if (message.kind !== KIND.sync || message.prism !== session.prism) refuse('sync', 'sync message for another prism');
+ const log = mergeLogs(session.log, await logFromRecords(message.records));
+ if (log.size > MAX_LOG_RECORDS) refuse('log', `log exceeds ${MAX_LOG_RECORDS} records`);
+ const state = await resolvePrism(session.prism, log);
+ const next = { ...session, log, personas: new Map(session.personas) };
+ next.keyring = await absorbRekeys(next, state);
+ await mergePersonaRecords(next, message.personas);
+ 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;
+
+/**
+ * The bus contract the substrate implements: publish bytes to a topic, deliver
+ * them to subscribers, and retain recent messages per topic so a device that
+ * was offline, or a recovering device with no copy of the log, can read them
+ * later (`retained`). This in-memory bus is for tests and single-page use.
+ */
+export function createMemoryBus() {
+ const subscribers = new Map();
+ const kept = new Map();
+ return {
+ async publish(topic, bytes) {
+ const list = kept.get(topic) ?? [];
+ list.push(new Uint8Array(bytes));
+ if (list.length > MAX_RETAINED) list.shift();
+ kept.set(topic, list);
+ for (const fn of [...(subscribers.get(topic) ?? [])]) await fn(new Uint8Array(bytes));
+ },
+ async retained(topic) {
+ return (kept.get(topic) ?? []).map(b => new Uint8Array(b));
+ },
+ subscribe(topic, fn) {
+ if (!subscribers.has(topic)) subscribers.set(topic, new Set());
+ subscribers.get(topic).add(fn);
+ return () => subscribers.get(topic)?.delete(fn);
+ }
+ };
+}
+
+// ---------------------------------------------------------------- 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;
+ }
+
+ /** `retained`: 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, retained: fetchTopic, close };
+}
diff --git a/identity/publish.mjs b/identity/publish.mjs
deleted file mode 100644
index 58b705f..0000000
--- a/identity/publish.mjs
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/usr/bin/env node
-// Builds the sign-in page for https://id.uor.foundation, content addressed
-// like the frame: index.html pins each file it loads by SHA-384 (subresource
-// integrity), so a changed byte never runs, and current.json names the page
-// by its own SHA-256 for anyone checking what the origin serves.
-// node identity/publish.mjs []
-// The origin serves as static files over HTTPS, with no other
-// content: every page on the rpId's origin can ask a passkey to sign.
-import { createHash } from "node:crypto";
-import { mkdir, readFile, writeFile } from "node:fs/promises";
-import { join } from "node:path";
-import { fileURLToPath } from "node:url";
-
-const root = fileURLToPath(new URL("../", import.meta.url));
-const [out = "identity-out", commit = process.env.GITHUB_SHA ?? null] = process.argv.slice(2);
-const files = { "id.mjs": "identity/id.mjs", "id.css": "identity/id.css", "brand.css": "site/brand/hologram-warm.css" };
-
-await mkdir(out, { recursive: true });
-let page = await readFile(join(root, "identity/index.html"), "utf8");
-for (const [name, source] of Object.entries(files)) {
- const bytes = await readFile(join(root, source));
- await writeFile(join(out, name), bytes);
- const integrity = `sha384-${createHash("sha384").update(bytes).digest("base64")}`;
- const tag = name.endsWith(".mjs") ? `src="${name}"` : `href="${name}"`;
- if (!page.includes(tag)) throw new Error(`identity/index.html does not load ${name}`);
- page = page.replace(tag, `${tag} integrity="${integrity}"`);
-}
-const bytes = Buffer.from(page, "utf8");
-const sha256 = createHash("sha256").update(bytes).digest("hex");
-await writeFile(join(out, "index.html"), bytes);
-await writeFile(join(out, "current.json"), JSON.stringify({ spec: "prism/identity-page/1", sha256, source: { repository: "UOR-Foundation/template", commit } }, null, 2) + "\n");
-console.log(`identity: ${sha256} -> ${out}/index.html`);
diff --git a/identity/stitch-sync.mjs b/identity/stitch-sync.mjs
new file mode 100644
index 0000000..7d2046d
--- /dev/null
+++ b/identity/stitch-sync.mjs
@@ -0,0 +1,176 @@
+#!/usr/bin/env node
+// Prism id comes from stitch (afflom/stitch), pinned by commit: the frame runs
+// stitch's Prism id and follows it as stitch's Prism model is refined. Stitch
+// is not a Foundry component yet, so nothing here edits it: this script copies it.
+//
+// identity/prism-id.mjs is generated, one self-contained module: stitch's
+// src/prism-id.js, the stitch modules it imports (the relay framing its
+// substrate bus uses, and what that imports), and the part of stitch's
+// generated model they call (every decision they name, what those call, and
+// the model's evaluator). The whole model is 1.2 MB; the part used is a few
+// KB, so the frame can carry it. Each imported module keeps its own scope.
+// identity/stitch.lock names the commit and the hash of every input and of
+// the output.
+//
+// node identity/stitch-sync.mjs fetch that commit, write both
+// node identity/stitch-sync.mjs read a local stitch checkout at it
+// node identity/stitch-sync.mjs --check the output is the one the lock names
+import { createHash } from "node:crypto";
+import { execFileSync } from "node:child_process";
+import { readFile, writeFile } from "node:fs/promises";
+import { join, posix } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = fileURLToPath(new URL("../", import.meta.url));
+const LOCK = join(root, "identity/stitch.lock");
+const OUT = join(root, "identity/prism-id.mjs");
+const REPOSITORY = "afflom/stitch";
+const ENTRY = "src/prism-id.js";
+const MODEL = "src/layer1-uor/generated-model.js";
+const sha256 = (text) => createHash("sha256").update(text).digest("hex");
+
+const [first, dir] = process.argv.slice(2);
+if (first === "--check") {
+ const lock = JSON.parse(await readFile(LOCK, "utf8"));
+ const actual = sha256(await readFile(OUT));
+ if (actual !== lock.output.sha256) {
+ console.error(`identity/prism-id.mjs is ${actual}, but identity/stitch.lock names ${lock.output.sha256}. Run node identity/stitch-sync.mjs ${lock.commit}.`);
+ process.exit(1);
+ }
+ console.log(`prism id: stitch ${lock.commit.slice(0, 12)}, output matches the lock`);
+ process.exit(0);
+}
+if (!/^[0-9a-f]{40}$/.test(first ?? "")) {
+ console.error("usage: node identity/stitch-sync.mjs <40-hex stitch commit> [] | --check");
+ process.exit(2);
+}
+const commit = first;
+
+async function source(path) {
+ if (dir) return execFileSync("git", ["-C", dir, "show", `${commit}:${path}`], { encoding: "utf8", maxBuffer: 64 << 20 });
+ const response = await fetch(`https://raw.githubusercontent.com/${REPOSITORY}/${commit}/${path}`);
+ if (!response.ok) throw new Error(`${REPOSITORY}@${commit}:${path} answered ${response.status}`);
+ return response.text();
+}
+
+// Every module prism-id.js reaches through its imports, dependencies first.
+const IMPORT = /^import\s*\{([^}]*)\}\s*from\s*'([^']+)';\n/gm;
+const sources = {};
+const order = [];
+async function load(path) {
+ if (path in sources) return;
+ sources[path] = null;
+ const text = await source(path);
+ sources[path] = text;
+ for (const [, , from] of text.matchAll(IMPORT)) {
+ const target = posix.join(posix.dirname(path), from);
+ if (target !== MODEL) await load(target);
+ }
+ order.push(path);
+}
+await load(ENTRY);
+const generated = await source(MODEL);
+sources[MODEL] = generated;
+
+// The generated model: `const definitions = {...};`, `const types = {...};`
+// (both JSON), then the digests and sources, then the evaluator from
+// `const qualify` to `export const model=`, then named bindings.
+const lines = generated.split("\n");
+const block = (head) => {
+ const start = lines.indexOf(`const ${head} = {`);
+ const end = lines.indexOf("};", start);
+ if (start < 0 || end < 0) throw new Error(`the generated model has no ${head} block`);
+ return JSON.parse(lines.slice(start, end + 1).join("\n").replace(`const ${head} = `, "").replace(/;$/, ""));
+};
+const definitions = block("definitions");
+const types = block("types");
+const evalStart = lines.findIndex((line) => line.startsWith("const qualify = "));
+const evalEnd = lines.findIndex((line) => line.startsWith("export const model="));
+if (evalStart < 0 || evalEnd < evalStart) throw new Error("the generated model's evaluator moved");
+const evaluator = lines.slice(evalStart, evalEnd + 1).join("\n");
+const bindings = Object.fromEntries([...generated.matchAll(/^export const (\w+) = model\["([\w.]+)"\];$/gm)].map(([, name, id]) => [name, id]));
+
+// Every decision the copied modules name, and everything those call:
+// model['Id'], call('name') for relay framing's Stitch.Relay, and the model's
+// named bindings a module imports.
+const qualify = (module, name) => (name.includes("::") ? name.replace("::", ".") : `${module}.${name}`);
+const used = new Set();
+const visit = (id) => {
+ if (used.has(id)) return;
+ const definition = definitions[id] ?? (() => { throw new Error(`stitch calls ${id}, which the model lacks`); })();
+ used.add(id);
+ const walk = (node) => {
+ if (!node || typeof node !== "object") return;
+ if (node.k === "call") visit(qualify(definition.module, node.name));
+ for (const value of Object.values(node)) walk(value);
+ };
+ walk(definition.body);
+};
+const named = new Set();
+for (const path of order) {
+ const text = sources[path];
+ for (const [, id] of text.matchAll(/model\['([\w.]+)'\]/g)) visit(id);
+ const prefix = /model\[`(Stitch\.\w+)\.\$\{name\}`\]/.exec(text)?.[1];
+ if (prefix) for (const [, name] of text.matchAll(/call\('(\w+)'/g)) visit(`${prefix}.${name}`);
+ for (const [, names, from] of text.matchAll(IMPORT)) {
+ if (posix.join(posix.dirname(path), from) !== MODEL) continue;
+ for (const name of names.split(",").map((n) => n.trim()).filter(Boolean)) {
+ if (name === "model") continue;
+ if (!bindings[name]) throw new Error(`${path} imports ${name}, which the model does not bind`);
+ named.add(name);
+ visit(bindings[name]);
+ }
+ }
+}
+const usedTypes = new Set();
+const typeOf = (module, type) => {
+ if (!type || ["Nat", "Bool", "Bytes", "String"].includes(type.kind)) return;
+ if (type.kind === "List") return typeOf(module, type.element);
+ const id = qualify(module, type.kind);
+ if (!types[id]) throw new Error(`the model lacks type ${id}`);
+ usedTypes.add(id);
+};
+for (const id of used) {
+ definitions[id].params.forEach((p) => typeOf(definitions[id].module, p.type));
+ typeOf(definitions[id].module, definitions[id].result);
+}
+const pick = (all, ids) => Object.fromEntries([...ids].sort().map((id) => [id, all[id]]));
+const modelModule = `const definitions = ${JSON.stringify(pick(definitions, used))};
+const types = ${JSON.stringify(pick(types, usedTypes))};
+${evaluator}
+${[...named].sort().map((name) => `export const ${name} = model["${bindings[name]}"];`).join("\n")}
+`;
+
+// Each module but prism-id.js keeps its own scope: its imports become reads
+// of the modules it names, its exports the object it returns. prism-id.js
+// stays the top level, so its exports are this module's.
+const scopeName = (path) => `stitch$${path.replace(/^src\//, "").replace(/\.js$/, "").replace(/[^\w]/g, "_")}`;
+const EXPORT = /^export (?:async function\*?|function\*?|class|const|let) (\w+)/gm;
+function rewrite(path, text) {
+ return text.replace(IMPORT, (_, names, from) => {
+ const fields = names.split(",").map((n) => n.trim()).filter(Boolean).map((n) => n.replace(/\s+as\s+/, ": "));
+ return `const { ${fields.join(", ")} } = ${scopeName(posix.join(posix.dirname(path), from))};\n`;
+ });
+}
+function scoped(path, text) {
+ if (/^export (?!(?:async function\*?|function\*?|class|const|let) \w)/m.test(text)) throw new Error(`${path} exports in a form this copy does not handle`);
+ const exported = [...text.matchAll(EXPORT)].map(([, name]) => name);
+ const body = rewrite(path, text).replace(/^export (?=(?:async function|function|class|const|let) )/gm, "");
+ return `const ${scopeName(path)} = (() => {\n${body}\nreturn { ${exported.join(", ")} };\n})();\n`;
+}
+const parts = [scoped(MODEL, modelModule), ...order.filter((p) => p !== ENTRY).map((p) => scoped(p, sources[p])), rewrite(ENTRY, sources[ENTRY])];
+const output = `// GENERATED by identity/stitch-sync.mjs from ${REPOSITORY}@${commit}. DO NOT EDIT.
+// src/prism-id.js, the stitch modules it imports (${order.filter((p) => p !== ENTRY).join(", ")}),
+// and the ${used.size} model decisions they call (${MODEL}); identity/stitch.lock pins them.
+// Change Prism id in stitch, then run node identity/stitch-sync.mjs .
+${parts.join("\n")}`;
+await writeFile(OUT, output);
+const lock = {
+ repository: REPOSITORY,
+ commit,
+ sources: Object.fromEntries([...order, MODEL].sort().map((path) => [path, sha256(sources[path])])),
+ decisions: [...used].sort(),
+ output: { path: "identity/prism-id.mjs", sha256: sha256(output) },
+};
+await writeFile(LOCK, JSON.stringify(lock, null, 2) + "\n");
+console.log(`prism id: stitch ${commit.slice(0, 12)}, ${order.length} modules, ${used.size} decisions, ${output.length} bytes -> identity/prism-id.mjs`);
diff --git a/identity/stitch.lock b/identity/stitch.lock
new file mode 100644
index 0000000..0c75c03
--- /dev/null
+++ b/identity/stitch.lock
@@ -0,0 +1,57 @@
+{
+ "repository": "afflom/stitch",
+ "commit": "7c0ccebfa00e5c09e135901be4c9fad149d1b420",
+ "sources": {
+ "src/layer1-uor/contracts.js": "94c67e0811f78029b251c55edbf365b2335040106b8125fa5298e59315d2c2d3",
+ "src/layer1-uor/custody.js": "597b34d6740b6b371e30af24ee18cd10f8c4142da38e616b9ec5e04d042ab74c",
+ "src/layer1-uor/generated-model.js": "fae51244e2b96601978233863e86aee96f35ef5a15ad4af4d3e687a9d770fb11",
+ "src/layer2-schedulers/policy.js": "8f2074f8fe07a7b1fda51896d78f11a797564afb64accebc7291261e5c00639f",
+ "src/layer5-transport/relay-framing.js": "35672c5720f5f1e5d009f1875a1c63de3a6badea2546d66baf73c77fb7c90ae0",
+ "src/prism-id.js": "eefc04c53d581308dee9033384050616849ef93996e8cb7858cd1435934b16d7"
+ },
+ "decisions": [
+ "Stitch.Budget.reserveAllowed",
+ "Stitch.Budget.settlementAllowed",
+ "Stitch.PrismId.actionAllowed",
+ "Stitch.PrismId.actionFresh",
+ "Stitch.PrismId.actionGate",
+ "Stitch.PrismId.attestationBinds",
+ "Stitch.PrismId.bindAllowed",
+ "Stitch.PrismId.boundaryKeyAdmitted",
+ "Stitch.PrismId.boundaryShared",
+ "Stitch.PrismId.boundaryVisibleTo",
+ "Stitch.PrismId.deviceMaySign",
+ "Stitch.PrismId.hostAdmitsDevice",
+ "Stitch.PrismId.hybridSignatureAccepted",
+ "Stitch.PrismId.hybridWrapRequired",
+ "Stitch.PrismId.linkGate",
+ "Stitch.PrismId.linkOfferAccepted",
+ "Stitch.PrismId.mayAdminister",
+ "Stitch.PrismId.mayShareBoundary",
+ "Stitch.PrismId.presenceSatisfied",
+ "Stitch.PrismId.receivesPrivateBoundary",
+ "Stitch.PrismId.recoveryBindAllowed",
+ "Stitch.PrismId.revocationCounts",
+ "Stitch.PrismId.scopeAdmits",
+ "Stitch.PrismId.thresholdMet",
+ "Stitch.Relay.admissionAllowed",
+ "Stitch.Relay.admitCapacity",
+ "Stitch.Relay.append",
+ "Stitch.Relay.appendAllowed",
+ "Stitch.Relay.assemblyCurrent",
+ "Stitch.Relay.beginVerification",
+ "Stitch.Relay.deliveryAllowed",
+ "Stitch.Relay.effectAllowed",
+ "Stitch.Relay.frameAllowed",
+ "Stitch.Relay.limits",
+ "Stitch.Relay.ready",
+ "Stitch.Relay.release",
+ "Stitch.Relay.sameIdentity",
+ "Stitch.Relay.signalLifetime",
+ "Stitch.Relay.warmLifetime"
+ ],
+ "output": {
+ "path": "identity/prism-id.mjs",
+ "sha256": "3035992b02efa243c87f1c6116e7e37e8a203fc4721d590c4158c762e8997995"
+ }
+}
diff --git a/identity/test.mjs b/identity/test.mjs
index 9c2f0bf..351815d 100644
--- a/identity/test.mjs
+++ b/identity/test.mjs
@@ -1,163 +1,167 @@
-// Prism accounts: the frame's checks, each refused case failing closed, and
-// the whole flow in Chromium with a virtual passkey authenticator.
+// Prism ids: the frame's checks, each refused case failing closed, and the
+// whole flow in Chromium across two apps (two origins): a new id with its
+// recovery kit, a session, a second app joining the same id by a link and a
+// six-digit code, a device removed, and every device lost and the id brought
+// back from the kit. Devices meet on stitch's relay, which a relay in memory
+// stands in for here, answering the browser as the relay does.
// node --test identity/test.mjs
import assert from "node:assert/strict";
-import { webcrypto as crypto } from "node:crypto";
+import { readFile } from "node:fs/promises";
import { after, before, describe, test } from "node:test";
-import { IdentityError, acceptRecord, originsOf, verifySession, verifySigned } from "../frame/panels.mjs";
+import { IdentityError, verifySession } from "../frame/panels.mjs";
+import * as Prism from "./prism-id.mjs";
import { start } from "./dev.mjs";
-const enc = new TextEncoder();
-const b64u = (bytes) => Buffer.from(bytes).toString("base64url");
-const sha = async (bytes) => new Uint8Array(await crypto.subtle.digest("SHA-256", typeof bytes === "string" ? enc.encode(bytes) : bytes));
-const ACCOUNTS = "https://id.uor.foundation";
-const ORIGINS = originsOf(ACCOUNTS);
+const APP = "https://app.example";
+const DAY = 864e5;
+const key = () => Buffer.from(crypto.getRandomValues(new Uint8Array(65))).toString("base64url");
-// WebCrypto's r||s as WebAuthn's DER.
-function der(raw) {
- const int = (bytes) => {
- let b = [...bytes];
- while (b.length > 1 && b[0] === 0) b.shift();
- if (b[0] & 0x80) b.unshift(0);
- return [0x02, b.length, ...b];
- };
- const body = [...int(raw.slice(0, 32)), ...int(raw.slice(32))];
- return new Uint8Array([0x30, body.length, ...body]);
-}
-
-async function passkey() {
- const keys = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);
- const spki = new Uint8Array(await crypto.subtle.exportKey("spki", keys.publicKey));
- const key = b64u(await sha(spki));
- return { keys, spki: b64u(spki), key, credential: b64u(crypto.getRandomValues(new Uint8Array(16))) };
-}
-
-async function assertion(pk, message, { origin = ACCOUNTS, rp = "id.uor.foundation", flags = 0x05, type = "webauthn.get" } = {}) {
- const clientDataJSON = enc.encode(JSON.stringify({ type, challenge: b64u(await sha(message)), origin, crossOrigin: true }));
- const authenticatorData = new Uint8Array([...(await sha(rp)), flags, 0, 0, 0, 0]);
- const raw = new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, pk.keys.privateKey, new Uint8Array([...authenticatorData, ...(await sha(clientDataJSON))])));
- return { credential: pk.credential, clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authenticatorData), signature: b64u(der(raw)) };
+// A session as the frame signs one.
+async function session(signer, { app = APP, action = "prism/session/1", expires = Date.now() + DAY, now = Date.now(), sessionKey = key() } = {}) {
+ const envelope = await Prism.signAction(signer, action, { sessionKey, expires }, { now, audience: app });
+ return { app, envelope, records: [...signer.log.values()] };
}
+const refuses = (code) => (error) => error instanceof IdentityError && error.code === code;
-const recordOf = (pk, account = pk.key, binding = null) => ({ spec: "prism/identity/key/1", key: pk.key, account, credential: pk.credential, alg: -7, spki: pk.spki, origin: ACCOUNTS, created: 0, binding });
-
-async function session(pk, records, overrides = {}) {
- const s = { app: "https://app.example", nonce: b64u(crypto.getRandomValues(new Uint8Array(32))), sessionKey: "k", expires: Date.now() + 60000, records, ...overrides };
- s.assertion = await assertion(pk, `prism/identity/session/1\n${s.app}\n${s.nonce}\n${s.sessionKey}\n${s.expires}`, overrides.signing);
- delete s.signing;
- return s;
+// Link a second device the way the panel does, without a relay.
+async function linked(id) {
+ const now = Date.now();
+ const { uri, pending } = await Prism.createLinkOffer(id, { now });
+ const offer = Prism.parseLinkUri(uri);
+ const device = await Prism.createDevice();
+ const request = await Prism.requestLink(device, offer);
+ const accepted = await Prism.acceptLinkRequest(id, pending, request, { now, confirmCode: await Prism.linkCode(offer.secret, device.record) });
+ return { first: accepted.session, second: await Prism.completeLink(device, offer, accepted.response) };
}
-const refuses = (code) => (error) => error instanceof IdentityError && error.code === code;
-
describe("the frame's checks", () => {
- test("a first passkey's session verifies and names its account", async () => {
- const pk = await passkey();
- const who = await verifySession(await session(pk, [recordOf(pk)]), ORIGINS);
- assert.equal(who.account, pk.key);
- });
-
- test("a session signed for another request is refused", async () => {
- const pk = await passkey();
- const s = await session(pk, [recordOf(pk)]);
- s.nonce = b64u(crypto.getRandomValues(new Uint8Array(32)));
- await assert.rejects(verifySession(s, ORIGINS), refuses("challenge"));
- });
-
- test("a signature made on another site is refused", async () => {
- const pk = await passkey();
- await assert.rejects(verifySession(await session(pk, [recordOf(pk)], { signing: { origin: "https://evil.example" } }), ORIGINS), refuses("origin"));
- });
-
- test("a passkey of another rpId is refused", async () => {
- const pk = await passkey();
- await assert.rejects(verifySession(await session(pk, [recordOf(pk)], { signing: { rp: "uor.foundation" } }), ORIGINS), refuses("rp"));
- });
-
- test("a device that did not verify its user is refused", async () => {
- const pk = await passkey();
- await assert.rejects(verifySession(await session(pk, [recordOf(pk)], { signing: { flags: 0x01 } }), ORIGINS), refuses("flags"));
- });
-
- test("a registration ceremony is not a sign-in", async () => {
- const pk = await passkey();
- await assert.rejects(verifySession(await session(pk, [recordOf(pk)], { signing: { type: "webauthn.create" } }), ORIGINS), refuses("type"));
+ test("a new id's session verifies and names the id", async () => {
+ const id = await Prism.createPrism();
+ const who = await verifySession(await session(id));
+ assert.equal(who.account, id.prism);
+ assert.equal(who.key, id.device.id);
+ assert.match(who.account, /^sha256:[0-9a-f]{64}$/);
});
- test("a signature by another key is refused", async () => {
- const pk = await passkey();
- const other = await passkey();
- const s = await session({ ...other, credential: pk.credential }, [recordOf(pk)]);
- await assert.rejects(verifySession(s, ORIGINS), refuses("signature"));
+ test("a session for another app is refused", async () => {
+ const id = await Prism.createPrism();
+ const s = await session(id, { app: "https://other.example" });
+ await assert.rejects(verifySession({ ...s, app: APP }), refuses("signature"));
});
- test("a record whose name is not its key's hash is refused", async () => {
- const pk = await passkey();
- const other = await passkey();
- const forged = { ...recordOf(pk), spki: other.spki };
- await assert.rejects(verifySession(await session(pk, [forged]), ORIGINS), refuses("key"));
+ test("a changed session key or expiry breaks the signature", async () => {
+ const id = await Prism.createPrism();
+ const s = await session(id);
+ const swapped = structuredClone(s);
+ swapped.envelope.body.payload.sessionKey = key();
+ await assert.rejects(verifySession(swapped), refuses("signature"));
+ const longer = structuredClone(s);
+ longer.envelope.body.payload.expires += DAY;
+ await assert.rejects(verifySession(longer), refuses("signature"));
});
- test("an expired session is refused", async () => {
- const pk = await passkey();
- const s = await session(pk, [recordOf(pk)]);
- await assert.rejects(verifySession(s, ORIGINS, s.expires + 1), refuses("expired"));
+ test("an expired, overlong or stale session is refused", async () => {
+ const id = await Prism.createPrism();
+ await assert.rejects(verifySession(await session(id, { expires: Date.now() - 1 })), refuses("expired"));
+ await assert.rejects(verifySession(await session(id, { expires: Date.now() + 9 * DAY })), refuses("expired"));
+ await assert.rejects(verifySession(await session(id, { now: Date.now() - 5 * 60000 })), refuses("signature"));
});
- test("a second device bound by the account's passkey signs for the account", async () => {
- const first = await passkey();
- const second = await passkey();
- const binding = await assertion(first, `prism/identity/bind/1\n${first.key}\n${second.key}`);
- const records = [recordOf(second, first.key, binding), recordOf(first)];
- const who = await verifySession(await session(second, records), ORIGINS);
- assert.equal(who.account, first.key);
+ test("a kept session checks later, as of its signing", async () => {
+ const id = await Prism.createPrism();
+ const s = await session(id, { now: Date.now() - 3 * DAY });
+ await assert.rejects(verifySession(s), refuses("signature"));
+ assert.equal((await verifySession(s, { fresh: 0 })).account, id.prism);
});
- test("a key bound by another account cannot join it", async () => {
- const victim = await passkey();
- const attacker = await passkey();
- const mine = await passkey();
- const binding = await assertion(attacker, `prism/identity/bind/1\n${victim.key}\n${mine.key}`);
- const records = [recordOf(mine, victim.key, binding), recordOf(attacker)];
- await assert.rejects(acceptRecord(mine.credential, records, ORIGINS), refuses("binding"));
+ test("an action that is not a session is refused", async () => {
+ const id = await Prism.createPrism();
+ await assert.rejects(verifySession(await session(id, { action: "prism/pay/1" })), refuses("action"));
});
- test("a binding signed for another key is refused", async () => {
- const first = await passkey();
- const second = await passkey();
- const binding = await assertion(first, `prism/identity/bind/1\n${first.key}\nsomeone-else`);
- await assert.rejects(acceptRecord(second.credential, [recordOf(second, first.key, binding), recordOf(first)], ORIGINS), refuses("challenge"));
+ test("a device removed from the id signs no session", async () => {
+ const { first, second } = await linked(await Prism.createPrism());
+ const removed = await Prism.revokeDevice(first, second.device.id);
+ const s = await session(second);
+ assert.equal((await verifySession(s)).account, first.prism);
+ await assert.rejects(verifySession({ ...s, records: [...removed.log.values()] }), refuses("signature"));
});
- test("an account's first key may not carry a binding", async () => {
- const pk = await passkey();
- await assert.rejects(verifySigned(recordOf(pk), await assertion(pk, "m"), "other", ORIGINS), refuses("challenge"));
- await assert.rejects(acceptRecord(pk.credential, [recordOf(pk, pk.key, await assertion(pk, "m"))], ORIGINS), refuses("binding"));
+ test("a device of another id cannot sign for this one", async () => {
+ const id = await Prism.createPrism();
+ const other = await Prism.createPrism();
+ const s = await session(other);
+ s.envelope.body.prism = id.prism;
+ await assert.rejects(verifySession({ ...s, records: [...id.log.values(), ...other.log.values()] }), refuses("signature"));
+ await assert.rejects(verifySession({ ...(await session(other)), records: [...id.log.values()] }), refuses("log"));
});
});
-describe("the flow in Chromium, with a virtual passkey", () => {
+// The relay in memory, as the browser sees ntfy: POST / keeps a
+// message, GET //json?poll=1 lists them, a WebSocket on //ws
+// hears new ones.
+function relayStandIn(origin) {
+ const topics = new Map();
+ const sockets = new Set();
+ const nameOf = (url) => new URL(url).pathname.split("/")[1];
+ return {
+ topics,
+ async attach(context) {
+ await context.route(`${origin}/**`, async (route) => {
+ const request = route.request();
+ const name = nameOf(request.url());
+ const headers = { "access-control-allow-origin": "*", "access-control-allow-headers": "*", "access-control-allow-methods": "GET, POST" };
+ if (request.method() === "OPTIONS") return route.fulfill({ status: 204, headers });
+ if (request.method() === "POST") {
+ const message = request.postData();
+ topics.set(name, [...(topics.get(name) ?? []), message]);
+ for (const socket of sockets) if (socket.name === name) socket.ws.send(JSON.stringify({ event: "message", message }));
+ return route.fulfill({ status: 200, headers, contentType: "application/json", body: "{}" });
+ }
+ const body = (topics.get(name) ?? []).map((message) => JSON.stringify({ event: "message", message })).join("\n");
+ return route.fulfill({ status: 200, headers, contentType: "application/x-ndjson", body });
+ });
+ await context.routeWebSocket(`${origin.replace(/^https:/, "wss:")}/**`, (ws) => {
+ const socket = { name: nameOf(ws.url().replace(/^wss:/, "https:")), ws };
+ sockets.add(socket);
+ ws.onClose(() => sockets.delete(socket));
+ });
+ },
+ };
+}
+
+describe("the flow in Chromium", () => {
let browser;
- let page;
let running;
- let cdp;
- let authenticator;
- // A Windows browser, whichever system runs the tests, so the page names its authenticator.
- const WINDOWS = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36";
+ let relay;
+ let context;
+ let first;
+ let second;
+ let firstId = null;
+ let kitPath = null;
+
+ const account = (p) => p.locator("prism-frame").evaluate((frame) => frame.account);
+ const newContext = async () => {
+ const made = await browser.newContext({ acceptDownloads: true });
+ await relay.attach(made);
+ return made;
+ };
+ const signOut = async (p) => {
+ await p.locator("#account").click();
+ await p.locator("#account-out").click();
+ await p.locator("#account:not(.signed-in)").waitFor({ timeout: 10000 });
+ };
before(async () => {
- running = await start({ idPort: 8792, appPort: 8793 });
+ running = await start({ ports: [8793, 8794] });
+ relay = relayStandIn(running.relay);
const { chromium } = await import("playwright");
- // One renderer for the page and its sign-in iframe, so one virtual
- // authenticator serves both.
- browser = await chromium.launch({ args: ["--disable-site-isolation-trials", "--disable-features=IsolateOrigins,site-per-process"] });
- page = await browser.newPage({ userAgent: WINDOWS });
- cdp = await page.context().newCDPSession(page);
- await cdp.send("WebAuthn.enable");
- ({ authenticatorId: authenticator } = await cdp.send("WebAuthn.addVirtualAuthenticator", {
- options: { protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },
- }));
- await page.goto(running.app);
+ browser = await chromium.launch();
+ context = await newContext();
+ first = await context.newPage();
+ second = await context.newPage();
+ await first.goto(running.apps[0]);
+ await second.goto(running.apps[1]);
});
after(async () => {
@@ -165,125 +169,148 @@ describe("the flow in Chromium, with a virtual passkey", () => {
await running?.close();
});
- const signIn = page2 => page2.locator("prism-frame").evaluate((frame) => frame.account);
- const ceremony = () => page.frameLocator("prism-frame >> iframe");
-
test("the icon sits after full screen and starts signed out", async () => {
- const order = await page.locator("prism-frame").evaluate((frame) => [...frame.shadowRoot.querySelector(".end").querySelectorAll("button")].map((b) => b.id));
+ const order = await first.locator("prism-frame").evaluate((frame) => [...frame.shadowRoot.querySelector(".end").querySelectorAll("button")].map((b) => b.id));
assert.deepEqual(order.slice(-2), ["fullscreen", "account"]);
- assert.equal(await page.locator("#account").getAttribute("aria-label"), "Sign in");
- assert.equal(await signIn(page), null);
- });
-
- test("a click the bar is redrawn under still opens the panel", async () => {
- // An app sets the frame's attributes as it loads, and each redraws the
- // bar; a click whose panel was still loading must open the new one.
- await page.locator("prism-frame").evaluate((frame) => {
- frame.shadowRoot.querySelector("#account").click();
- frame.setAttribute("purpose", "Redrawn while the panel loads.");
- });
- await page.locator("#account-panel:popover-open").waitFor({ timeout: 10000 });
- await page.keyboard.press("Escape");
- await page.locator("#account-panel:not(:popover-open)").waitFor({ timeout: 10000 });
+ assert.equal(await first.locator("#account").getAttribute("aria-label"), "Sign in");
+ assert.equal(await account(first), null);
});
- test("creating an account signs in, verified in the page", async () => {
- await page.locator("#account").click();
- // A centred dialog titled for what it does, its one button naming the
- // device's own authenticator.
- assert.equal(await page.locator("#account-title").textContent(), "Sign in");
- await ceremony().locator("#go-label", { hasText: "Continue with Windows Hello" }).waitFor({ timeout: 10000 });
- const box = await page.locator("#account-panel").boundingBox();
- const view = page.viewportSize();
- assert.ok(Math.abs(box.x + box.width / 2 - view.width / 2) <= 1, "the dialog is centred");
- // One button: a device with no passkey turns Sign in into Create account.
- await ceremony().locator("#go:enabled").click();
- await ceremony().locator("#go-label", { hasText: "Create account" }).waitFor({ timeout: 10000 });
- await ceremony().locator("#go:enabled").click();
- await page.locator("#account.signed-in").waitFor({ timeout: 10000 });
- const account = await signIn(page);
- assert.match(account.id, /^[\w-]{43}$/);
- assert.equal(running.records.size, 1);
- assert.equal(await page.locator("#account").getAttribute("aria-label"), "Prism account");
+ test("a new Prism id: no prompt, a recovery kit, then signed in", async () => {
+ await first.locator("#account").click();
+ assert.equal(await first.locator("#account-title").textContent(), "Sign in");
+ await first.locator("#account-create").click();
+ await first.locator("#account-kit-save").waitFor({ timeout: 10000 });
+ const [download] = await Promise.all([first.waitForEvent("download"), first.locator("#account-kit-save").click()]);
+ kitPath = await download.path();
+ const kit = JSON.parse(await readFile(kitPath, "utf8"));
+ assert.equal(kit.kind, "prism/recovery-kit/1");
+ assert.equal(kit.share.guardian, "paper");
+ await first.locator("#account-kit-done").click();
+ await first.locator("#account.signed-in").waitFor({ timeout: 10000 });
+ firstId = (await account(first)).id;
+ assert.equal(firstId, kit.prism);
+ assert.equal(await first.locator("#account").getAttribute("aria-label"), "Prism account");
});
- test("the session survives a reload and signs for the account", async () => {
- await page.reload();
- await page.locator("#account.signed-in").waitFor({ timeout: 10000 });
- const checked = await page.evaluate(async () => {
+ test("the session survives a reload and signs for the id", async () => {
+ await first.reload();
+ await first.locator("#account.signed-in").waitFor({ timeout: 10000 });
+ const checked = await first.evaluate(async () => {
const frame = document.querySelector("prism-frame");
- const { verifySession, originsOf } = await import("/panels.mjs");
const data = new TextEncoder().encode("hello");
const { signature, delegation } = await frame.sign(data);
- const who = await verifySession(delegation, originsOf(frame.getAttribute("accounts")));
- const raw = Uint8Array.from(atob(delegation.sessionKey.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
+ const raw = Uint8Array.from(atob(delegation.envelope.body.payload.sessionKey.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
const key = await crypto.subtle.importKey("raw", raw, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
const sig = Uint8Array.from(atob(signature.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
- return { same: who.account === frame.account.id, valid: await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, sig, data), app: delegation.app };
+ return { delegation, id: frame.account.id, valid: await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, sig, data) };
});
- assert.deepEqual(checked, { same: true, valid: true, app: new URL(running.app).origin });
+ assert.equal(checked.valid, true);
+ assert.equal(checked.delegation.app, new URL(running.apps[0]).origin);
+ assert.equal((await verifySession(checked.delegation, { fresh: 0 })).account, checked.id);
});
- test("sign out, then sign in again with the same passkey", async () => {
- const before = (await signIn(page)).id;
- await page.locator("#account").click();
- await page.locator("#account-out").click();
- await page.locator("#account:not(.signed-in)").waitFor({ timeout: 10000 });
- assert.equal(await signIn(page), null);
- await page.locator("#account").click();
- // This device signed in before: the page asks for that passkey only, no chooser.
- await ceremony().locator("#go-label", { hasText: "Continue with Windows Hello" }).waitFor({ timeout: 10000 });
- await ceremony().locator("#go:enabled").click();
- await page.locator("#account.signed-in").waitFor({ timeout: 10000 });
- assert.equal((await signIn(page)).id, before);
+ test("sign out, then sign in again: one click, same id", async () => {
+ await signOut(first);
+ await first.locator("#account").click();
+ await first.locator("#account-continue").click();
+ await first.locator("#account.signed-in").waitFor({ timeout: 10000 });
+ assert.equal((await account(first)).id, firstId);
});
- test("a page whose policy will not frame the sign-in page signs in through a window", async () => {
- const strict = await (await browser.newContext()).newPage();
- await strict.goto(new URL("strict", running.app).href);
- await strict.locator("#account").click();
- await strict.locator("#account-window:visible").waitFor({ timeout: 10000 });
- const [popup] = await Promise.all([strict.waitForEvent("popup"), strict.locator("#account-window").click()]);
- const cdp = await strict.context().newCDPSession(popup);
- await cdp.send("WebAuthn.enable");
- await cdp.send("WebAuthn.addVirtualAuthenticator", {
- options: { protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },
- });
- await popup.locator("#go:enabled").click();
- await popup.locator("#go-label", { hasText: "Create account" }).waitFor({ timeout: 10000 });
- await popup.locator("#go:enabled").click();
- await strict.locator("#account.signed-in").waitFor({ timeout: 10000 });
- assert.match((await signIn(strict)).id, /^[\w-]{43}$/);
- await strict.close();
- });
-
- test("the session key cannot be read out by script", async () => {
- const extractable = await page.evaluate(
- () =>
+ test("the session key and the device keys cannot be read out by script", async () => {
+ const keys = await first.evaluate(async () => {
+ const read = (name, store, id) =>
new Promise((done) => {
- const open = indexedDB.open("prism-identity");
+ const open = indexedDB.open(name);
open.onsuccess = () => {
- const get = open.result.transaction("session").objectStore("session").get("current");
- get.onsuccess = () => done(get.result.privateKey.extractable);
+ const get = open.result.transaction(store).objectStore(store).get(id);
+ get.onsuccess = () => done(get.result);
};
- }),
- );
- assert.equal(extractable, false);
+ });
+ const kept = await read("prism-identity", "session", "current");
+ const device = await read("prism-id", "prism", "self");
+ return [kept.privateKey.extractable, device.device.signingKey.extractable, device.device.agreementKey.extractable];
+ });
+ assert.deepEqual(keys, [false, false, false]);
+ });
+
+ test("another app joins the same id: a link, then the six-digit code", async () => {
+ await second.locator("#account").click();
+ await second.locator("#account-join").click();
+ // On the first app: a link offer.
+ await first.locator("#account").click();
+ await first.locator("#account-link").click();
+ await first.locator("#account-offer").waitFor({ timeout: 10000 });
+ const uri = await first.locator("#account-offer").textContent();
+ assert.match(await first.locator("#account-qr path").getAttribute("d"), /^M\d+ \d+h1v1h-1z/, "the offer shows its QR code");
+ assert.match(uri, /^prism-link:/);
+ await second.locator("#account-uri").fill(uri);
+ await second.locator("#account-join-go").click();
+ await second.locator("#account-join-code").waitFor({ timeout: 10000 });
+ const code = /(\d{6})/.exec(await second.locator("#account-join-code").textContent())[1];
+ await first.locator("#account-code").waitFor({ timeout: 10000 });
+ // A wrong code is refused, and the right one still works.
+ await first.locator("#account-code").fill(code === "000000" ? "111111" : "000000");
+ await first.locator("#account-accept").click();
+ await first.locator("#account-error", { hasText: "refused" }).waitFor({ timeout: 10000 });
+ await first.locator("#account-code").fill(code);
+ await first.locator("#account-accept").click();
+ await second.locator("#account.signed-in").waitFor({ timeout: 15000 });
+ assert.equal((await account(second)).id, firstId);
+ assert.notEqual((await account(second)).key, (await account(first)).key);
+ });
+
+ test("a removed app hears it on its next sign-in and signs nothing more", async () => {
+ await first.locator("#account").click();
+ await first.locator("#account-devices").click();
+ const rows = first.locator("#account-device-list li");
+ await rows.first().waitFor({ timeout: 10000 });
+ assert.equal(await rows.count(), 3);
+ assert.equal(await first.locator("#account-device-list li", { hasText: "(this one)" }).count(), 1);
+ assert.equal(await first.locator("#account-device-list li", { hasText: "Recovery kit" }).getByRole("button").count(), 0);
+ await first.locator("#account-device-list li", { hasText: "Browser" }).filter({ hasNotText: "(this one)" }).getByRole("button", { name: "Remove" }).click();
+ await first.locator("#account-device-list li").nth(2).waitFor({ state: "detached", timeout: 10000 });
+ await first.keyboard.press("Escape");
+
+ await signOut(second);
+ await second.locator("#account").click();
+ await second.locator("#account-continue").click();
+ await second.locator("#account-title", { hasText: "This device was removed" }).waitFor({ timeout: 10000 });
+ assert.equal(await account(second), null);
});
- test("a remembered passkey that is gone asks for any passkey, never straight to a new account", async () => {
- await page.locator("#account").click();
- await page.locator("#account-out").click();
- await page.locator("#account:not(.signed-in)").waitFor({ timeout: 10000 });
- await cdp.send("WebAuthn.clearCredentials", { authenticatorId: authenticator });
- await page.locator("#account").click();
- await ceremony().locator("#go-label", { hasText: "Continue with Windows Hello" }).waitFor({ timeout: 10000 });
- await ceremony().locator("#go:enabled").click();
- // The remembered passkey did not answer: forget it and keep Continue,
- // which next looks for any passkey. Only that failing says this device has none.
- await ceremony().locator("#card:not(.busy)").waitFor({ timeout: 10000 });
- assert.equal(await ceremony().locator("#go-label").textContent(), "Continue with Windows Hello");
- await ceremony().locator("#go:enabled").click();
- await ceremony().locator("#go-label", { hasText: "Create account" }).waitFor({ timeout: 10000 });
+ test("every device lost: the recovery kit brings the id back, and the kit is replaced", async () => {
+ const elsewhere = await newContext();
+ const fresh = await elsewhere.newPage();
+ await fresh.goto(running.apps[1]);
+ await fresh.locator("#account").click();
+ await fresh.locator("#account-recover").click();
+ await fresh.locator("#account-kit-file").setInputFiles(kitPath);
+ await fresh.locator("#account-kit-save").waitFor({ timeout: 15000 });
+ const [download] = await Promise.all([fresh.waitForEvent("download"), fresh.locator("#account-kit-save").click()]);
+ const newKit = JSON.parse(await readFile(await download.path(), "utf8"));
+ assert.equal(newKit.prism, firstId);
+ assert.notEqual(newKit.share.recovery, JSON.parse(await readFile(kitPath, "utf8")).share.recovery);
+ await fresh.locator("#account-kit-done").click();
+ await fresh.locator("#account.signed-in").waitFor({ timeout: 10000 });
+ assert.equal((await account(fresh)).id, firstId);
+
+ // Recovery removed every other device: the first app stops at its next sign-in.
+ await signOut(first);
+ await first.locator("#account").click();
+ await first.locator("#account-continue").click();
+ await first.locator("#account-title", { hasText: "This device was removed" }).waitFor({ timeout: 10000 });
+
+ // The old kit brings nothing back.
+ const third = await (await newContext()).newPage();
+ await third.goto(running.apps[0]);
+ await third.locator("#account").click();
+ await third.locator("#account-recover").click();
+ await third.locator("#account-kit-file").setInputFiles(kitPath);
+ await third.locator("#account-error", { hasText: "already used" }).waitFor({ timeout: 15000 });
+ assert.equal(await account(third), null);
+ await third.context().close();
+ await elsewhere.close();
});
});
diff --git a/package.json b/package.json
index 6685684..169cf02 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"type": "module",
"scripts": {
"test:try": "node --test try/test.mjs",
- "test:identity": "node --test identity/test.mjs"
+ "test:identity": "node identity/stitch-sync.mjs --check && node --test identity/test.mjs"
},
"devDependencies": {
"playwright": "1.62.1",
diff --git a/site/page.template.html b/site/page.template.html
index 61cb908..dd11d40 100644
--- a/site/page.template.html
+++ b/site/page.template.html
@@ -7,7 +7,7 @@
-
+
{{TITLE}}
@@ -35,7 +35,7 @@
-
+ holo://{{HOLO_NAME}}