From 8ea6d8f052ca65525ac89830f075ca765b37d11c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 22:14:18 +0000 Subject: [PATCH 1/5] Keep the Prism account through a lost device (prism/identity/2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Brings the frame and sign-in page in line with UOR-Foundation/template#73: recovery codes (a new account's first key is an Ed25519 recovery key, so no account depends on one device), "Lost your device? Use a recovery code" on any device, a Recovery code button for signed-in accounts, and key IDs named by κ (sha256:) with prism/identity/1 records still valid. The files are byte-identical to the template's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Asa3NdLCxdzL1iQw9rg5T --- frame/frame.mjs | 7 +- frame/panels.mjs | 59 +++++++++++-- identity/PROTOCOL.md | 76 ++++++++++++---- identity/README.md | 20 ++++- identity/dev.mjs | 25 ++++-- identity/id.css | 28 ++++++ identity/id.mjs | 201 ++++++++++++++++++++++++++++++++++++++----- identity/index.html | 15 ++++ identity/test.mjs | 126 +++++++++++++++++++++++++-- 9 files changed, 492 insertions(+), 65 deletions(-) diff --git a/frame/frame.mjs b/frame/frame.mjs index 74ad3d67..a7e5494d 100644 --- a/frame/frame.mjs +++ b/frame/frame.mjs @@ -346,9 +346,10 @@ 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 +// Prism accounts (prism/identity/2, identity/PROTOCOL.md). An account is a +// set of keys: passkeys, whose private keys stay in each device's secure +// hardware, and recovery codes its owner keeps, so losing a device never +// loses the account. Its name is the κ of its first 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"; diff --git a/frame/panels.mjs b/frame/panels.mjs index 61e1170a..d4cf8e18 100644 --- a/frame/panels.mjs +++ b/frame/panels.mjs @@ -342,11 +342,14 @@ export function panel(frame, core) { } // The theme panel's contents, which the frame puts in its empty panel. -// Prism accounts (prism/identity/1, identity/PROTOCOL.md): the checks the +// Prism accounts (prism/identity/2, 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; +// An account is a set of keys: passkeys on devices, and recovery keys its +// owner keeps as codes. Each added device and each recovery adds a binding; +// the bound only keeps this check finite. +const MAX_CHAIN = 32; const enc = new TextEncoder(); const b64u = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); const unb64u = (text) => { @@ -373,6 +376,23 @@ 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" } }, }; +// A recovery key: Ed25519, signing the protocol message itself. +const RECOVERY = -8; + +// A key's name, by its record's spec: key/2 names it by κ, the UORC address +// `sha256:` of its SPKI; key/1 (prism/identity/1) by base64url SHA-256. +const KEY_IDS = { + "prism/identity/key/2": async (spki) => `sha256:${[...(await digest(spki))].map((b) => b.toString(16).padStart(2, "0")).join("")}`, + "prism/identity/key/1": async (spki) => b64u(await digest(spki)), +}; + +// A recovery key's signature: no client or authenticator data, only an +// Ed25519 signature over the message, under the record's key. +async function verifyRecovery(record, signed, message) { + if (signed.clientDataJSON !== undefined || signed.authenticatorData !== undefined) deny("signature", "A recovery signature carries no sign-in data"); + const key = await crypto.subtle.importKey("spki", unb64u(record.spki), { name: "Ed25519" }, false, ["verify"]).catch(() => deny("key", "The public key does not parse")); + if (!(await crypto.subtle.verify({ name: "Ed25519" }, key, unb64u(signed.signature), enc.encode(message)))) deny("signature", "The signature does not verify"); +} // WebAuthn's ECDSA signatures are DER; WebCrypto's are the two 32-byte halves. function rawSignature(der) { @@ -397,6 +417,7 @@ function rawSignature(der) { // 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"); + if (record.alg === RECOVERY) return verifyRecovery(record, signed, message); let client; try { client = JSON.parse(new TextDecoder().decode(unb64u(signed.clientDataJSON))); @@ -422,8 +443,9 @@ export async function verifySigned(record, signed, message, origins) { // 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"); + const keyId = record && Object.hasOwn(KEY_IDS, record.spec) ? KEY_IDS[record.spec] : null; + if (!keyId) deny("record", "The passkey has no record"); + if ((await keyId(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; @@ -441,6 +463,8 @@ 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); + // A recovery code adds a device; only a device's passkey signs a session. + if (record.alg === RECOVERY) deny("algorithm", "A recovery code does not sign in by itself"); 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 }; } @@ -453,13 +477,14 @@ const ACCOUNT_PANEL = ` `; -// The account panel (prism/identity/1, identity/PROTOCOL.md): the sign-in +// The account panel (prism/identity/2, 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 @@ -519,6 +544,10 @@ export function accounts(frame, core) { frame.$("account-title").textContent = "Add a device"; frame.$("account-sub").textContent = "Your phone or another computer joins this account."; } + if (mode === "recovery") { + frame.$("account-title").textContent = "Recovery code"; + frame.$("account-sub").textContent = "A code that brings this account to any device, if you lose yours."; + } const saved = accountChannel.session; ceremony = { mode, @@ -530,7 +559,7 @@ export function accounts(frame, core) { 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 } : {}), + ...(mode === "signin" ? {} : { account: saved.account, credential: saved.credential }), }, })), }; @@ -542,8 +571,8 @@ export function accounts(frame, core) { 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.title = { add: "Add device", recovery: "Recovery code" }[mode] ?? "Sign in"; + iframe.allow = "publickey-credentials-get; publickey-credentials-create; clipboard-write"; iframe.referrerPolicy = "no-referrer"; box.replaceChildren(iframe); ceremony.iframe = iframe; @@ -611,6 +640,13 @@ export function accounts(frame, core) { if (!ceremony || event.origin !== origin || event.source !== (ceremony.iframe?.contentWindow ?? ceremony.popup)) return; const data = event.data ?? {}; ceremony.answered = true; + // A sign-in page from before recovery codes cannot make one: say so + // rather than show a button that would never answer. + if (data.type === `${SPEC}/ready` && ceremony.mode === "recovery" && !data.modes?.includes?.("recovery")) { + close(); + frame.$("account-sub").textContent = "Recovery codes are not available yet. Try again soon."; + return; + } if (data.type === `${SPEC}/ready`) ceremony.iframe?.classList.add("ready"); if (data.type === `${SPEC}/ready` && ceremony.slow) { ceremony.slow = false; @@ -624,6 +660,10 @@ export function accounts(frame, core) { close(); panel.hidePopover(); say("Device added"); + } else if (data.type === `${SPEC}/recovery` && ceremony.mode === "recovery") { + close(); + panel.hidePopover(); + say("Recovery code saved"); } }, { signal: frame.accountWatch.signal }, @@ -639,10 +679,11 @@ export function accounts(frame, core) { paint(); return void reach(); } - if (ceremony?.mode === "add") close(); + if (ceremony?.mode === "add" || ceremony?.mode === "recovery") close(); }); frame.$("account-add").addEventListener("click", () => begin("add")); + frame.$("account-recovery").addEventListener("click", () => begin("recovery")); frame.$("account-out").addEventListener("click", async () => { await store("readwrite", (s) => s.delete("current")).catch(() => {}); accountChannel.session = null; diff --git a/identity/PROTOCOL.md b/identity/PROTOCOL.md index 39839e5f..50bc6521 100644 --- a/identity/PROTOCOL.md +++ b/identity/PROTOCOL.md @@ -1,9 +1,15 @@ -# prism/identity/1 +# prism/identity/2 -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 +A Prism account is a set of keys: passkeys, whose private keys never leave +each device's secure hardware (Secure Enclave, TPM, Android TEE or StrongBox), +and recovery keys, whose private keys the owner keeps outside every device as +a recovery code. Losing a device never loses the account. Everything else is public, content addressed and checkable by anyone, so no server is trusted to -say who a user is. +say who a user is. One account signs in to every Prism app, Foundry included. + +prism/identity/2 extends prism/identity/1: keys are named by κ, recovery keys +exist, and an account's first key may be one. Every prism/identity/1 record, +signature and account stays valid. ## Parties @@ -20,14 +26,26 @@ For development the identity page runs on `http://localhost:` with rpId `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). +- **Key ID**: the κ of the key, `sha256:<64 lowercase hex>` of `H(spki)`, the + UORC object address of its DER SubjectPublicKeyInfo (for a passkey, + `AuthenticatorAttestationResponse.getPublicKey()`). Records of spec + `prism/identity/key/1` keep their prism/identity/1 key ID, `b64u(H(spki))`; + a reader picks the rule by the record's spec. +- **Account ID**: the key ID of the account's first key. It never changes, + and it outlives that key: revoking it, or losing its device, leaves the + account and every key bound into it. +- **Algorithms**: passkeys ES256 (`-7`, P-256) and RS256 (`-257`, for older + Windows Hello); recovery keys EdDSA (`-8`, Ed25519). ## Signed messages -Every signature is a WebAuthn assertion: the authenticator signs +A recovery key's signature is Ed25519 over the message's UTF-8 bytes, carried +as `{credential, signature}` with no `clientDataJSON` or `authenticatorData`; +a verifier checks it under the record's `spki` and refuses one that carries +either field. A recovery key signs bind and revoke messages, never a session: +only a device's passkey signs a session. + +Every passkey 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: @@ -54,7 +72,7 @@ exactly one change, so replaying it repeats that change and nothing else. ```json { - "spec": "prism/identity/key/1", + "spec": "prism/identity/key/2", "key": "", "account": "", "credential": "", @@ -67,16 +85,41 @@ exactly one change, so replaying it repeats that change and nothing else. ``` `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: +Otherwise it is the bind signature made by a key already in the account, a +passkey's assertion or a recovery key's signature: ```json { "credential": "", "clientDataJSON": "", "authenticatorData": "", "signature": "" } +{ "credential": "", "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. +A recovery key's record has `alg` `-8`, its `credential` is its raw 32-byte +public key in b64u (so the code alone finds its record), and its `origin` is +the identity origin it was made on. + +A reader accepts a record only when `key` is the key ID its spec names for +`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 32 bindings is refused; the bound only keeps a reader's work +finite. + +## Recovery codes + +A recovery code is a recovery key's 32-byte Ed25519 seed followed by the first +three bytes of `H(seed)`, in Crockford base32: 56 characters, written in +groups of four. A reader ignores spaces, hyphens and case, reads `I` and `L` +as `1` and `O` as `0`, and refuses a code whose check bytes differ. The +private key is the PKCS#8 encoding of the seed; the code is shown once, never +stored and never sent. + +The sign-in page makes a new account with a recovery key as its first key: +it creates the device's passkey, registers the recovery key alone (which +starts the account), binds the passkey to it with a recovery signature, shows +the code, and then asks the passkey to sign the app's session. A signed-in +account adds a recovery code by its passkey binding a new recovery key. On a +new device, the code finds its record, the device's new passkey is bound by +a recovery signature, and that passkey signs the session. A recovery key is +revoked like any key. ## Registry routes @@ -85,7 +128,8 @@ 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`). | +| `POST /passkey/register` | Registers a new passkey. Body: `spki`, `alg`, `credential`, `clientDataJSON`, `authenticatorData`, `attestationObject`, `transports`, and `binding` (null, or a bind signature plus `account`). | +| `POST /passkey/recovery` | Adds a recovery key. Body: `spki` alone, which starts an account with it as the first key and records the request's identity origin; or `spki`, `account` and `binding`, a bind signature by a live key of the account. Answers `{key, account, record}`. | | `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. | diff --git a/identity/README.md b/identity/README.md index bbb8961a..1ec78cd4 100644 --- a/identity/README.md +++ b/identity/README.md @@ -2,8 +2,20 @@ 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 visitor in. No password exists anywhere. One account signs in to every +Prism app, Foundry included. [PROTOCOL.md](PROTOCOL.md) is the contract; this +file says why it is built this way and how to run it. + +## Losing a device never loses the account + +A new account's first key is a recovery key, and the page shows its recovery +code once, before the first sign-in. The device's passkey joins the account +through it, so the account never depended on that device. On any new device, +**Lost your device? Use a recovery code** makes that device's passkey and +binds it with the code, and the visitor is signed in to the same account. A +signed-in visitor can make a fresh code from the panel at any time +(**Recovery code**); an account made before recovery codes existed gets its +first one there. ## Why a passkey, and why this domain @@ -57,7 +69,9 @@ verify registrations; the frame's checks are the real ones. 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. + with `https://id.uor.foundation` as the allowed identity origin. Recovery + codes need a registry with `POST /passkey/recovery`; deploy it before the + page. 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 diff --git a/identity/dev.mjs b/identity/dev.mjs index 5613542e..a0bc933e 100644 --- a/identity/dev.mjs +++ b/identity/dev.mjs @@ -16,6 +16,10 @@ import { fileURLToPath } from "node:url"; const root = fileURLToPath(new URL("../", import.meta.url)); const b64u = (bytes) => Buffer.from(bytes).toString("base64url"); +const kappa = (spki) => `sha256:${createHash("sha256").update(Buffer.from(spki, "base64url")).digest("hex")}`; +// The fields of an assertion the registry keeps: a passkey's carries client +// and authenticator data, a recovery key's only its signature. +const assertionOf = ({ credential, clientDataJSON, authenticatorData, signature }) => ({ credential, ...(clientDataJSON === undefined ? {} : { clientDataJSON, authenticatorData }), signature }); 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 @@ -58,18 +62,29 @@ export function start({ idPort = 8790, appPort = 8791 } = {}) { 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 }; + const key = kappa(r.spki); + const binding = r.binding ? assertionOf(r.binding) : null; + const record = { spec: "prism/identity/key/2", 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); + return json(response, 201, { key, account: record.account, record }); + } + // A recovery key: an account's first key, or bound into one. Its + // credential is its raw public key, the SPKI's last 32 bytes. + if (request.method === "POST" && path === "/passkey/recovery") { + const r = await body(request); + const key = kappa(r.spki); + const credential = b64u(Buffer.from(r.spki, "base64url").subarray(-32)); + if (records.has(credential)) return json(response, 409, { error: "exists", message: "The key is already registered." }); + const record = { spec: "prism/identity/key/2", key, account: r.account ?? key, credential, alg: -8, spki: r.spki, origin: accounts, created: Date.now(), binding: r.binding ? assertionOf(r.binding) : null }; + records.set(credential, record); + return json(response, 201, { key, account: record.account, 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]; + const account = /^\/passkey\/account\/(sha256:[0-9a-f]{64}|[\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." }); diff --git a/identity/id.css b/identity/id.css index c4d421e3..444efcc3 100644 --- a/identity/id.css +++ b/identity/id.css @@ -37,6 +37,34 @@ 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; } } +.stack { display: grid; gap: 0.5rem; } +.stack[hidden], [hidden] { display: none !important; } +.pair { display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem; } +.pair button { background: var(--secondary, transparent); color: var(--foreground); border-color: var(--border); } +input { + min-height: 2.618rem; + padding: 0 0.75rem; + border: 1px solid var(--border); + border-radius: calc(var(--radius) - 2px); + background: var(--background); + color: var(--foreground); + font: inherit; + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.875rem; +} +input:focus-visible { outline: 2px solid var(--ring); outline-offset: 1px; } +.code { + display: block; + padding: 0.618rem; + border: 1px dashed var(--border); + border-radius: calc(var(--radius) - 2px); + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.9375rem; + letter-spacing: 0.04em; + text-align: center; + word-spacing: 0.2em; + user-select: all; +} .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; } } diff --git a/identity/id.mjs b/identity/id.mjs index de593eeb..91fb7f8d 100644 --- a/identity/id.mjs +++ b/identity/id.mjs @@ -1,8 +1,14 @@ -// The Prism sign-in page (prism/identity/1, identity/PROTOCOL.md). It runs +// The Prism sign-in page (prism/identity/2, 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 also makes and reads recovery codes. A new account's first key is a +// recovery key (Ed25519) made here; the device's passkey joins it by a +// signature from that key, so the account never depended on the device. +// The code is the recovery key's private half: shown once, never stored, +// never sent. With it, any device signs in again by joining its own passkey. +// // 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 @@ -14,6 +20,10 @@ const SPEC = "prism/identity/1"; const WEEK = 8 * 24 * 60 * 60 * 1000; const enc = new TextEncoder(); +const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join(""); +// A key's name: its κ, the UORC address of its DER SubjectPublicKeyInfo. +const keyId = async (spki) => `sha256:${hex(await crypto.subtle.digest("SHA-256", spki))}`; +const ID = /^(sha256:[0-9a-f]{64}|[\w-]{43})$/; 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))); @@ -34,13 +44,13 @@ let relayed = false; const valid = (r) => r?.type === `${SPEC}/request` && - ["signin", "add"].includes(r.mode) && + ["signin", "add", "recovery"].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))); + (r.mode === "signin" || (ID.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); @@ -118,10 +128,14 @@ if (DEVICE && window.PublicKeyCredential?.isUserVerifyingPlatformAuthenticatorAv // not say so before asking) turns the same button into Create account. // Adding a device is the same button, relabelled. let fresh = false; +// The recovery code being shown, and what "I saved it" does next. +let kit = null; function paint() { - const label = request.mode === "add" ? "Add device" : fresh ? "Create account" : `Continue with ${device ?? "a passkey"}`; + const label = { add: "Add device", recovery: "Make a recovery code" }[request.mode] ?? (fresh ? "Create account" : `Continue with ${device ?? "a passkey"}`); $("go-label").textContent = label; - $("fresh").hidden = !fresh || request.mode === "add"; + $("fresh").hidden = !fresh || request.mode !== "signin"; + $("lost").hidden = request.mode !== "signin" || !$("recover").hidden || Boolean(kit); + $("go").hidden = Boolean(kit) || !$("recover").hidden; $("go").disabled = false; size(); } @@ -195,10 +209,68 @@ async function session(allow = []) { 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", {}); +// Recovery codes. The code is the recovery key's 32-byte Ed25519 seed and +// three check bytes (the start of its SHA-256), in Crockford base32: 56 +// characters, read in groups of four. The check bytes catch a mistyped code +// before anything is asked of the registry. +const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; +const PKCS8_ED25519 = Uint8Array.from([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20]); + +async function encodeCode(seed) { + const bytes = [...seed, ...new Uint8Array(await crypto.subtle.digest("SHA-256", seed)).slice(0, 3)]; + let bits = ""; + for (const byte of bytes) bits += byte.toString(2).padStart(8, "0"); + const chars = bits.match(/.{5}/g).map((five) => CROCKFORD[parseInt(five, 2)]); + return chars.join("").match(/.{4}/g).join(" "); +} + +class CodeError extends Error {} + +async function decodeCode(text) { + const clean = String(text).toUpperCase().replace(/[\s-]/g, "").replace(/[IL]/g, "1").replace(/O/g, "0"); + if (!/^[0-9A-HJKMNP-TV-Z]{56}$/.test(clean)) throw new CodeError("A recovery code is 56 letters and digits."); + const bits = [...clean].map((c) => CROCKFORD.indexOf(c).toString(2).padStart(5, "0")).join(""); + const bytes = Uint8Array.from(bits.match(/.{8}/g), (byte) => parseInt(byte, 2)); + const seed = bytes.slice(0, 32); + const check = new Uint8Array(await crypto.subtle.digest("SHA-256", seed)).slice(0, 3); + if (check.some((b, i) => b !== bytes[32 + i])) throw new CodeError("That code has a typo. Check it and try again."); + return seed; +} + +// A recovery key from its seed: the signing key, its SPKI, its κ and its +// credential (the raw public key, which finds its record). +async function recoveryKey(seed) { + const pkcs8 = new Uint8Array([...PKCS8_ED25519, ...seed]); + const extractable = await crypto.subtle.importKey("pkcs8", pkcs8, { name: "Ed25519" }, true, ["sign"]); + const { x } = await crypto.subtle.exportKey("jwk", extractable); + const publicKey = await crypto.subtle.importKey("jwk", { kty: "OKP", crv: "Ed25519", x }, { name: "Ed25519" }, true, ["verify"]); + const spki = new Uint8Array(await crypto.subtle.exportKey("spki", publicKey)); + const privateKey = await crypto.subtle.importKey("pkcs8", pkcs8, { name: "Ed25519" }, false, ["sign"]); + return { privateKey, spki, key: await keyId(spki), credential: x }; +} + +const newRecoveryKey = async () => { + const seed = crypto.getRandomValues(new Uint8Array(32)); + return { seed, ...(await recoveryKey(seed)) }; +}; + +// A recovery key's signature: Ed25519 over the protocol message itself. +async function signRecovery(recovery, message) { + return { credential: recovery.credential, signature: b64u(await crypto.subtle.sign({ name: "Ed25519" }, recovery.privateKey, enc.encode(message))) }; +} + +// Show the code until the visitor says it is saved; then `next` runs. +async function showKit(recovery, account, next) { + kit = { next, code: await encodeCode(recovery.seed), account }; + recovery.seed.fill(0); + $("kit-code").textContent = kit.code; + $("kit").hidden = false; + paint(); + $("kit-copy").focus(); +} + +// A new passkey for this device, made after `challenge`. +async function newPasskey(challenge, exclude) { const platform = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?.().catch(() => false); const adding = request.mode === "add"; const credential = await navigator.credentials.create({ @@ -216,7 +288,7 @@ async function create() { userVerification: "required", ...(platform && !adding ? { authenticatorAttachment: "platform" } : {}), }, - excludeCredentials: adding ? [{ type: "public-key", id: unb64u(request.credential) }] : [], + excludeCredentials: exclude ? [{ type: "public-key", id: unb64u(exclude) }] : [], hints: adding ? ["hybrid"] : [], attestation: "none", timeout: 120000, @@ -224,7 +296,7 @@ async function create() { }); const r = credential.response; const spki = r.getPublicKey(); - const body = { + return { spki: b64u(spki), alg: r.getPublicKeyAlgorithm(), credential: b64u(credential.rawId), @@ -233,17 +305,60 @@ async function create() { attestationObject: b64u(r.attestationObject), transports: r.getTransports?.() ?? [], binding: null, + key: await keyId(spki), }; - 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 }; +} + +// Register `passkey` into `account`, bound by `binding` (made over its key). +async function join(passkey, account, binding) { + const { key, ...body } = passkey; + return registry("/passkey/register", { ...body, binding: { account, ...binding } }); +} + +// A new passkey. Another device joins the account whose passkey signs the +// binding. A first one starts an account whose first key is a new recovery +// key, which binds the passkey with no prompt: the visitor saves the code, +// then the passkey signs the app's session (creating a passkey signs nothing +// a reader could check, so that is a second prompt). +async function create() { + const { challenge } = await registry("/passkey/challenge", {}); + if (request.mode === "add") { + const passkey = await newPasskey(challenge, request.credential); + const bound = await sign(`prism/identity/bind/1\n${request.account}\n${passkey.key}`, [request.credential]); + const record = await join(passkey, request.account, bound); + return send({ type: "added", record }); } - 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]); + const passkey = await newPasskey(challenge, null); + const recovery = await newRecoveryKey(); + const { account } = await registry("/passkey/recovery", { spki: b64u(recovery.spki) }); + await join(passkey, account, await signRecovery(recovery, `prism/identity/bind/1\n${account}\n${passkey.key}`)); + remember(passkey.credential); + await showKit(recovery, account, () => session([passkey.credential])); +} + +// A recovery code for a signed-in account: the passkey binds a new recovery +// key. Older codes keep working until a device revokes them. +async function makeRecovery() { + const recovery = await newRecoveryKey(); + const binding = await sign(`prism/identity/bind/1\n${request.account}\n${recovery.key}`, [request.credential]); + const { key } = await registry("/passkey/recovery", { account: request.account, spki: b64u(recovery.spki), binding }); + await showKit(recovery, request.account, () => send({ type: "recovery", key })); +} + +// Sign in with a recovery code: this device's new passkey joins the code's +// account, then signs the app's session. +async function recover(text) { + const recovery = await recoveryKey(await decodeCode(text)); + const record = await registry(`/passkey/credential/${recovery.credential}`).catch((error) => { + throw new RegistryError(/revoked/i.test(error.message) ? "That recovery code was replaced. Use the newest one." : /no key/i.test(error.message) ? "No account has that recovery code." : error.message); + }); + const { challenge } = await registry("/passkey/challenge", {}); + const passkey = await newPasskey(challenge, null); + await join(passkey, record.account, await signRecovery(recovery, `prism/identity/bind/1\n${record.account}\n${passkey.key}`)); + remember(passkey.credential); + $("code").value = ""; + $("recover").hidden = true; + await session([passkey.credential]); } // A browser that will not run a ceremony in an iframe runs it in a popup. @@ -267,6 +382,11 @@ async function run(task) { // 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") && (kit || !$("recover").hidden || request.mode === "recovery")) { + // A prompt closed during recovery or while a code is shown: nothing + // to infer about this device's passkeys. The same tap tries again. + return fail("That did not finish. Try again."); + } 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. @@ -283,13 +403,48 @@ async function run(task) { } 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."); + fail(error instanceof RegistryError || error instanceof CodeError ? error.message : "That did not work. Try again."); } finally { busy(false); } } -$("go").addEventListener("click", () => run(() => (request.mode === "add" || fresh ? create() : session(remembered ? [remembered] : [])))); +$("go").addEventListener("click", () => run(() => (request.mode === "recovery" ? makeRecovery() : request.mode === "add" || fresh ? create() : session(remembered ? [remembered] : [])))); +$("use-code").addEventListener("click", () => { + $("recover").hidden = false; + paint(); + $("code").focus(); +}); +$("recover-go").addEventListener("click", () => run(() => recover($("code").value))); +$("code").addEventListener("keydown", (event) => { + if (event.key === "Enter") run(() => recover($("code").value)); +}); +$("kit-copy").addEventListener("click", async () => { + try { + await navigator.clipboard.writeText(kit.code); + $("kit-copy").textContent = "Copied"; + } catch { + getSelection().selectAllChildren($("kit-code")); + $("kit-copy").textContent = "Selected"; + } + setTimeout(() => ($("kit-copy").textContent = "Copy"), 1600); +}); +$("kit-save").addEventListener("click", () => { + const text = `Prism account recovery code\n\n${kit.code}\n\nAccount ${kit.account}\n\nOn any device: open the person icon in a Prism app, choose "Lost your device? Use a recovery code" and enter this code.\nAnyone holding it can add a device to your account. Keep it offline.\n`; + const link = document.createElement("a"); + link.href = URL.createObjectURL(new Blob([text], { type: "text/plain" })); + link.download = "prism-recovery-code.txt"; + link.click(); + setTimeout(() => URL.revokeObjectURL(link.href), 1000); +}); +$("kit-done").addEventListener("click", () => { + const { next } = kit; + kit = null; + $("kit").hidden = true; + $("kit-code").textContent = ""; + paint(); + run(next); +}); $("again").addEventListener("click", () => { fresh = false; paint(); @@ -299,5 +454,5 @@ $("again").addEventListener("click", () => { if (!window.PublicKeyCredential) { fail("This browser can't use passkeys."); } else { - send({ type: "ready" }); + send({ type: "ready", modes: ["signin", "add", "recovery"] }); } diff --git a/identity/index.html b/identity/index.html index 0d68c4f9..522a3719 100644 --- a/identity/index.html +++ b/identity/index.html @@ -19,6 +19,21 @@ Sign in + + + diff --git a/identity/test.mjs b/identity/test.mjs index 9c2f0bf6..1a5c058f 100644 --- a/identity/test.mjs +++ b/identity/test.mjs @@ -25,13 +25,23 @@ function der(raw) { return new Uint8Array([0x30, body.length, ...body]); } +const kappa = async (spki) => `sha256:${Buffer.from(await sha(spki)).toString("hex")}`; + 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))) }; + return { keys, spki: b64u(spki), key: await kappa(spki), legacy: b64u(await sha(spki)), credential: b64u(crypto.getRandomValues(new Uint8Array(16))), alg: -7 }; +} + +// A recovery key, as the sign-in page makes one for a recovery code. +async function recoveryKey() { + const keys = await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]); + const spki = new Uint8Array(await crypto.subtle.exportKey("spki", keys.publicKey)); + return { keys, spki: b64u(spki), key: await kappa(spki), credential: b64u(spki.slice(-32)), alg: -8 }; } +const signRecovery = async (rk, message) => ({ credential: rk.credential, signature: b64u(await crypto.subtle.sign({ name: "Ed25519" }, rk.keys.privateKey, enc.encode(message))) }); + 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]); @@ -39,7 +49,7 @@ async function assertion(pk, message, { origin = ACCOUNTS, rp = "id.uor.foundati return { credential: pk.credential, clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authenticatorData), signature: b64u(der(raw)) }; } -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 }); +const recordOf = (pk, account = pk.key, binding = null) => ({ spec: "prism/identity/key/2", key: pk.key, account, credential: pk.credential, alg: pk.alg, 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 }; @@ -129,6 +139,54 @@ describe("the frame's checks", () => { await assert.rejects(acceptRecord(second.credential, [recordOf(second, first.key, binding), recordOf(first)], ORIGINS), refuses("challenge")); }); + test("an account made under prism/identity/1 still signs in", async () => { + const pk = await passkey(); + const legacy = { ...recordOf(pk), spec: "prism/identity/key/1", key: pk.legacy, account: pk.legacy }; + assert.equal((await verifySession(await session(pk, [legacy]), ORIGINS)).account, pk.legacy); + await assert.rejects(verifySession(await session(pk, [{ ...legacy, spec: "prism/identity/key/2" }]), ORIGINS), refuses("key")); + await assert.rejects(verifySession(await session(pk, [{ ...legacy, spec: "prism/identity/key/9" }]), ORIGINS), refuses("record")); + }); + + test("an account whose first key is a recovery key signs in with the passkey it bound", async () => { + const root = await recoveryKey(); + const device = await passkey(); + const binding = await signRecovery(root, `prism/identity/bind/1\n${root.key}\n${device.key}`); + const who = await verifySession(await session(device, [recordOf(device, root.key, binding), recordOf(root)]), ORIGINS); + assert.equal(who.account, root.key); + assert.match(who.account, /^sha256:[0-9a-f]{64}$/); + }); + + test("a recovery code brings a passkey-first account to a new device", async () => { + const lost = await passkey(); + const rk = await recoveryKey(); + const fresh = await passkey(); + const records = [ + recordOf(fresh, lost.key, await signRecovery(rk, `prism/identity/bind/1\n${lost.key}\n${fresh.key}`)), + recordOf(rk, lost.key, await assertion(lost, `prism/identity/bind/1\n${lost.key}\n${rk.key}`)), + recordOf(lost), + ]; + assert.equal((await verifySession(await session(fresh, records), ORIGINS)).account, lost.key); + }); + + test("a recovery key never signs a session itself", async () => { + const root = await recoveryKey(); + const s = { app: "https://app.example", nonce: b64u(crypto.getRandomValues(new Uint8Array(32))), sessionKey: "k", expires: Date.now() + 60000, records: [recordOf(root)] }; + s.assertion = await signRecovery(root, `prism/identity/session/1\n${s.app}\n${s.nonce}\n${s.sessionKey}\n${s.expires}`); + await assert.rejects(verifySession(s, ORIGINS), refuses("algorithm")); + }); + + test("a recovery signature is refused when forged, misdirected or dressed as a passkey's", async () => { + const root = await recoveryKey(); + const other = await recoveryKey(); + const device = await passkey(); + const message = `prism/identity/bind/1\n${root.key}\n${device.key}`; + const check = (binding) => acceptRecord(device.credential, [recordOf(device, root.key, binding), recordOf(root)], ORIGINS); + await assert.rejects(check({ ...(await signRecovery(other, message)), credential: root.credential }), refuses("signature")); + await assert.rejects(check(await signRecovery(root, `prism/identity/bind/1\n${root.key}\nsomeone-else`)), refuses("signature")); + await assert.rejects(check({ ...(await signRecovery(root, message)), clientDataJSON: "e30", authenticatorData: "" }), refuses("signature")); + await check(await signRecovery(root, message)); + }); + 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")); @@ -166,6 +224,7 @@ describe("the flow in Chromium, with a virtual passkey", () => { }); const signIn = page2 => page2.locator("prism-frame").evaluate((frame) => frame.account); + let recoveryCode = null; const ceremony = () => page.frameLocator("prism-frame >> iframe"); test("the icon sits after full screen and starts signed out", async () => { @@ -200,10 +259,15 @@ describe("the flow in Chromium, with a virtual passkey", () => { await ceremony().locator("#go:enabled").click(); await ceremony().locator("#go-label", { hasText: "Create account" }).waitFor({ timeout: 10000 }); await ceremony().locator("#go:enabled").click(); + // The account's first key is a recovery code, shown once; saving it signs in. + await ceremony().locator("#kit-code").waitFor({ timeout: 10000 }); + recoveryCode = await ceremony().locator("#kit-code").textContent(); + assert.match(recoveryCode, /^([0-9A-HJKMNP-TV-Z]{4} ){13}[0-9A-HJKMNP-TV-Z]{4}$/); + await ceremony().locator("#kit-done").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.match(account.id, /^sha256:[0-9a-f]{64}$/); + assert.equal(running.records.size, 2); assert.equal(await page.locator("#account").getAttribute("aria-label"), "Prism account"); }); @@ -252,8 +316,9 @@ describe("the flow in Chromium, with a virtual passkey", () => { await popup.locator("#go:enabled").click(); await popup.locator("#go-label", { hasText: "Create account" }).waitFor({ timeout: 10000 }); await popup.locator("#go:enabled").click(); + await popup.locator("#kit-done").click(); await strict.locator("#account.signed-in").waitFor({ timeout: 10000 }); - assert.match((await signIn(strict)).id, /^[\w-]{43}$/); + assert.match((await signIn(strict)).id, /^sha256:[0-9a-f]{64}$/); await strict.close(); }); @@ -286,4 +351,53 @@ describe("the flow in Chromium, with a virtual passkey", () => { await ceremony().locator("#go:enabled").click(); await ceremony().locator("#go-label", { hasText: "Create account" }).waitFor({ timeout: 10000 }); }); + + test("a lost device: the recovery code signs in on a new one, same account", async () => { + const fresh = await (await browser.newContext()).newPage({ userAgent: WINDOWS }); + const cdp2 = await fresh.context().newCDPSession(fresh); + await cdp2.send("WebAuthn.enable"); + await cdp2.send("WebAuthn.addVirtualAuthenticator", { + options: { protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true }, + }); + await fresh.goto(running.app); + await fresh.locator("#account").click(); + const box = fresh.frameLocator("prism-frame >> iframe"); + await box.locator("#use-code").click(); + await box.locator("#code").fill("0000 0000"); + await box.locator("#recover-go").click(); + await box.locator("#error", { hasText: "56 letters" }).waitFor({ timeout: 10000 }); + await box.locator("#code").fill(recoveryCode.toLowerCase()); + await box.locator("#recover-go").click(); + await fresh.locator("#account.signed-in").waitFor({ timeout: 10000 }); + const [first] = [...running.records.values()]; + assert.equal((await signIn(fresh)).id, first.account); + await fresh.close(); + }); + + test("a signed-in account makes a new recovery code", async () => { + const other = await (await browser.newContext()).newPage({ userAgent: WINDOWS }); + const cdp2 = await other.context().newCDPSession(other); + await cdp2.send("WebAuthn.enable"); + await cdp2.send("WebAuthn.addVirtualAuthenticator", { + options: { protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true }, + }); + await other.goto(running.app); + await other.locator("#account").click(); + const box = other.frameLocator("prism-frame >> iframe"); + await box.locator("#use-code").click(); + await box.locator("#code").fill(recoveryCode); + await box.locator("#recover-go").click(); + await other.locator("#account.signed-in").waitFor({ timeout: 10000 }); + const count = running.records.size; + await other.locator("#account").click(); + await other.locator("#account-recovery").click(); + await box.locator("#go-label", { hasText: "Make a recovery code" }).waitFor({ timeout: 10000 }); + await box.locator("#go:enabled").click(); + await box.locator("#kit-code").waitFor({ timeout: 10000 }); + assert.notEqual(await box.locator("#kit-code").textContent(), recoveryCode); + await box.locator("#kit-done").click(); + await other.locator("#account-panel:not(:popover-open)").waitFor({ timeout: 10000 }); + assert.equal(running.records.size, count + 1); + await other.close(); + }); }); From 0776d452f6e71cce1c6d767349ed1f5cdc75c482 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 22:52:56 +0000 Subject: [PATCH 2/5] Sign in with a stitch Prism id (prism/identity/3), synced from the template Byte-identical copies of UOR-Foundation/template frame/ and identity/: passkeys give way to stitch's Prism id (pinned in identity/stitch.lock), with no prompt, recovery codes and the same id in every Prism app. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Asa3NdLCxdzL1iQw9rg5T --- .github/workflows/try-page.yml | 2 +- frame/frame.css | 4 +- frame/frame.mjs | 40 +- frame/panels.css | 8 - frame/panels.mjs | 343 ++++--------- frame/publish.mjs | 17 +- identity/PROTOCOL.md | 248 ++++----- identity/README.md | 109 ++-- identity/dev.mjs | 107 ++-- identity/id.css | 31 +- identity/id.mjs | 638 +++++++++-------------- identity/index.html | 33 +- identity/prism-id.mjs | 900 +++++++++++++++++++++++++++++++++ identity/publish.mjs | 6 +- identity/stitch-sync.mjs | 121 +++++ identity/stitch.lock | 28 + identity/test.mjs | 474 ++++++----------- package.json | 2 +- 18 files changed, 1826 insertions(+), 1285 deletions(-) create mode 100644 identity/prism-id.mjs create mode 100644 identity/stitch-sync.mjs create mode 100644 identity/stitch.lock diff --git a/.github/workflows/try-page.yml b/.github/workflows/try-page.yml index 1f348645..65f578c7 100644 --- a/.github/workflows/try-page.yml +++ b/.github/workflows/try-page.yml @@ -64,7 +64,7 @@ jobs: fi - name: Verify, answer add 20 22 and replay 22/22 run: npm run test:try - - 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 the flow signs in run: npm run test:identity - name: Build the canonical frame every Prism app loads run: node frame/publish.mjs "$RUNNER_TEMP/frame" "$GITHUB_SHA" diff --git a/frame/frame.css b/frame/frame.css index db9cb45e..b233c1c3 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 a7e5494d..0f232087 100644 --- a/frame/frame.mjs +++ b/frame/frame.mjs @@ -25,11 +25,11 @@ // 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. +// accounts optional: the Prism id origin (https://id.uor.foundation) +// 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 +346,12 @@ function holoIndex() { const githubMark = ''; const starMark = ''; -// Prism accounts (prism/identity/2, identity/PROTOCOL.md). An account is a -// set of keys: passkeys, whose private keys stay in each device's secure -// hardware, and recovery codes its owner keeps, so losing a device never -// loses the account. Its name is the κ of its first 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. +// Prism ids (prism/identity/3, identity/PROTOCOL.md): stitch's Prism id, +// named by the κ of its genesis and held by devices whose keys never leave +// them, with recovery codes 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 runs the sign-in and checks every signature the Prism id page +// hands back, in the visitor's browser. const ACCOUNTS = "https://id.uor.foundation"; const SESSION_DAYS = 7; const b64u = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); @@ -374,7 +374,7 @@ 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. @@ -832,32 +832,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 + // pulse while the Prism id window is open, 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 9ea77de3..d3f279d2 100644 --- a/frame/panels.css +++ b/frame/panels.css @@ -466,14 +466,6 @@ .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; } @media (pointer: coarse) { .account-panel .row, #account-window { min-height: var(--touch); } diff --git a/frame/panels.mjs b/frame/panels.mjs index d4cf8e18..0a018299 100644 --- a/frame/panels.mjs +++ b/frame/panels.mjs @@ -341,22 +341,17 @@ 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/2, 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. -// An account is a set of keys: passkeys on devices, and recovery keys its -// owner keeps as codes. Each added device and each recovery adds a binding; -// the bound only keeps this check finite. -const MAX_CHAIN = 32; -const enc = new TextEncoder(); +// Prism ids (prism/identity/3, 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. The sign-in +// page signs one action for this app, "prism/session/1", letting a session +// key the frame made here act for the id on this origin until it expires. +// The frame trusts the page with nothing: it checks the action against the +// id's log with Prism id's own verifyAction, in the visitor's browser, as it +// checks the holo's bytes. 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) { @@ -369,127 +364,82 @@ 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" } }, -}; -// A recovery key: Ed25519, signing the protocol message itself. -const RECOVERY = -8; - -// A key's name, by its record's spec: key/2 names it by κ, the UORC address -// `sha256:` of its SPKI; key/1 (prism/identity/1) by base64url SHA-256. -const KEY_IDS = { - "prism/identity/key/2": async (spki) => `sha256:${[...(await digest(spki))].map((b) => b.toString(16).padStart(2, "0")).join("")}`, - "prism/identity/key/1": async (spki) => b64u(await digest(spki)), -}; - -// A recovery key's signature: no client or authenticator data, only an -// Ed25519 signature over the message, under the record's key. -async function verifyRecovery(record, signed, message) { - if (signed.clientDataJSON !== undefined || signed.authenticatorData !== undefined) deny("signature", "A recovery signature carries no sign-in data"); - const key = await crypto.subtle.importKey("spki", unb64u(record.spki), { name: "Ed25519" }, false, ["verify"]).catch(() => deny("key", "The public key does not parse")); - if (!(await crypto.subtle.verify({ name: "Ed25519" }, key, unb64u(signed.signature), enc.encode(message)))) deny("signature", "The signature does not verify"); -} - -// 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 +// only when a session is checked, 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"); - if (record.alg === RECOVERY) return verifyRecovery(record, signed, message); - 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 the frame that asked must receive it (Prism id's +// actionFresh); anyone checking a kept session later checks it as of its +// own signing, 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; } - 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"); -} - -// 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); - const keyId = record && Object.hasOwn(KEY_IDS, record.spec) ? KEY_IDS[record.spec] : null; - if (!keyId) deny("record", "The passkey has no record"); - if ((await keyId(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; + const at = fresh ? now : body.at; + let verdict; + try { + verdict = await Prism.verifyAction(body.prism, log, envelope, { audience: app, now: at, window: fresh || 1 }); + } catch (error) { + if (error instanceof Prism.PrismIdError) deny("log", `The log does not resolve: ${error.message}`); + 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; + if (!verdict.allowed) deny(verdict.reason === "scope" ? "scope" : "signature", `The session was refused (${verdict.reason})`); + return { account: body.prism, key: envelope.signer, sessionKey, expires }; } -// 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); - // A recovery code adds a device; only a device's passkey signs a session. - if (record.alg === RECOVERY) deny("algorithm", "A recovery code does not sign in by itself"); - 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 }; -} - - const ACCOUNT_PANEL = ` - + - - + `; -// The account panel (prism/identity/2, 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. +// The account panel: one button opens the Prism id page in a small window. +// It runs as its own first-party page, so this browser's Prism id device is +// the same one for every app (an iframe's storage is partitioned per site). +// The page answers this window only, through the browser's origin, and says +// nothing the frame takes on trust: verifySession checks every answer +// before a session is kept. export function accounts(frame, core) { const { SESSION_DAYS, store, accountChannel, loadSession } = core; frame.$("account-panel").innerHTML = ACCOUNT_PANEL; @@ -497,17 +447,10 @@ export function accounts(frame, core) { 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 SPEC = "prism/identity/3"; 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)); - const say = (words) => { frame.$("bar-status").textContent = words; setTimeout(() => (frame.$("bar-status").textContent = ""), 1600); @@ -516,10 +459,11 @@ export function accounts(frame, core) { 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."; + windowButton.hidden = Boolean(saved); + frame.$("account-title").textContent = saved ? "Prism id" : "Sign in"; + frame.$("account-sub").textContent = saved ? "Signed in on this device." : "One Prism id for every Prism app. No password."; if (saved) { - frame.$("account-id").textContent = `${saved.account.slice(0, 8)}…${saved.account.slice(-4)}`; + frame.$("account-id").textContent = `${saved.account.slice(0, 15)}…${saved.account.slice(-4)}`; frame.$("account-id").title = saved.account; } }; @@ -528,96 +472,40 @@ export function accounts(frame, core) { 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; + // One window at a time, each with its own session key, used once. + const begin = async (mode) => { close(); - paint(); - if (mode === "add") { - frame.$("account-title").textContent = "Add a device"; - frame.$("account-sub").textContent = "Your phone or another computer joins this account."; - } - if (mode === "recovery") { - frame.$("account-title").textContent = "Recovery code"; - frame.$("account-sub").textContent = "A code that brings this account to any device, if you lose yours."; - } - 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 === "signin" ? {} : { account: saved.account, credential: saved.credential }), - }, - })), - }; - if (!framed) { - windowButton.hidden = false; - return; - } - const iframe = document.createElement("iframe"); + const keys = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]); + const request = { type: `${SPEC}/request`, mode, sessionKey: b64u(await crypto.subtle.exportKey("raw", keys.publicKey)), expires: Date.now() + SESSION_DAYS * 864e5 }; const page = new URL(target); page.hash = `theme=${document.documentElement.classList.contains("dark") ? "dark" : "light"}`; - iframe.src = page.href; - iframe.title = { add: "Add device", recovery: "Recovery code" }[mode] ?? "Sign in"; - iframe.allow = "publickey-credentials-get; publickey-credentials-create; clipboard-write"; - iframe.referrerPolicy = "no-referrer"; - box.replaceChildren(iframe); - ceremony.iframe = iframe; + ceremony = { mode, keys, request, popup: open(page.href, "prism-id", "popup,width=420,height=560") }; + if (!ceremony.popup) { + ceremony = null; + return say("Allow pop-ups for this page to sign in"); + } + button.classList.add("busy"); 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 watch = setInterval(() => { + if (ceremony !== waiting) return clearInterval(watch); + if (waiting.popup.closed) { + clearInterval(watch); + close(); + } + }, 500); }; - 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"); - }); - 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 }; + const { keys, request } = ceremony; + const delegation = { app: location.origin, envelope: data.envelope, records: data.records }; try { - const who = await verifySession(delegation, origins); + if (data.envelope?.body?.payload?.sessionKey !== request.sessionKey || data.envelope?.body?.payload?.expires !== request.expires) deny("key", "The session is not the one this page asked for"); + const who = await verifySession(delegation); const saved = { ...who, delegation, privateKey: keys.privateKey }; await store("readwrite", (s) => s.put(saved, "current")); accountChannel.session = saved; @@ -627,7 +515,7 @@ export function accounts(frame, core) { say("Signed in"); } catch (error) { close(); - begin("signin"); + paint(); frame.$("account-sub").textContent = error instanceof IdentityError ? `Sign-in was refused: ${error.message.toLowerCase()}.` : "Sign-in did not finish. Try again."; } }; @@ -637,30 +525,11 @@ export function accounts(frame, core) { addEventListener( "message", async (event) => { - if (!ceremony || event.origin !== origin || event.source !== (ceremony.iframe?.contentWindow ?? ceremony.popup)) return; + if (!ceremony || event.origin !== origin || event.source !== ceremony.popup) return; const data = event.data ?? {}; - ceremony.answered = true; - // A sign-in page from before recovery codes cannot make one: say so - // rather than show a button that would never answer. - if (data.type === `${SPEC}/ready` && ceremony.mode === "recovery" && !data.modes?.includes?.("recovery")) { - close(); - frame.$("account-sub").textContent = "Recovery codes are not available yet. Try again soon."; - return; - } - if (data.type === `${SPEC}/ready`) ceremony.iframe?.classList.add("ready"); - if (data.type === `${SPEC}/ready` && ceremony.slow) { - ceremony.slow = false; - paint(); - } - 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)); + if (data.type === `${SPEC}/ready`) event.source.postMessage(ceremony.request, origin); 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"); - } else if (data.type === `${SPEC}/recovery` && ceremony.mode === "recovery") { + else if (data.type === `${SPEC}/recovery` && ceremony.mode === "recovery") { close(); panel.hidePopover(); say("Recovery code saved"); @@ -669,20 +538,15 @@ export function accounts(frame, core) { { signal: frame.accountWatch.signal }, ); - // 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 dialog opens centred over the app (panels.css); opening it asks. + const reach = () => loadSession(); panel.addEventListener("beforetoggle", (event) => { if (event.newState === "open") { paint(); - return void reach(); + reach().then(paint); } - if (ceremony?.mode === "add" || ceremony?.mode === "recovery") close(); }); - frame.$("account-add").addEventListener("click", () => begin("add")); + windowButton.addEventListener("click", () => begin("signin")); frame.$("account-recovery").addEventListener("click", () => begin("recovery")); frame.$("account-out").addEventListener("click", async () => { await store("readwrite", (s) => s.delete("current")).catch(() => {}); @@ -708,6 +572,7 @@ export function accounts(frame, core) { 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 369eff47..b582e82a 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 50bc6521..d82043f9 100644 --- a/identity/PROTOCOL.md +++ b/identity/PROTOCOL.md @@ -1,168 +1,92 @@ -# prism/identity/2 - -A Prism account is a set of keys: passkeys, whose private keys never leave -each device's secure hardware (Secure Enclave, TPM, Android TEE or StrongBox), -and recovery keys, whose private keys the owner keeps outside every device as -a recovery code. Losing a device never loses the account. Everything else is -public, content addressed and checkable by anyone, so no server is trusted to -say who a user is. One account signs in to every Prism app, Foundry included. +# prism/identity/3 + +A Prism id is stitch's Prism id ([afflom/stitch](https://github.com/afflom/stitch), +`src/prism-id.js` and `docs/prism-id.md`), pinned by commit in +[stitch.lock](stitch.lock) and copied, with the model decisions it calls, into +[prism-id.mjs](prism-id.mjs) by [stitch-sync.mjs](stitch-sync.mjs). This file +says how the frame and the Prism id page use 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 +``` -prism/identity/2 extends prism/identity/1: keys are named by κ, recovery keys -exist, and an account's first key may be one. Every prism/identity/1 record, -signature and account stays valid. +prism/identity/3 replaces prism/identity/2 (passkeys and recovery keys). +Nothing carries over: a passkey-era account is a fresh Prism id. + +## The id + +- **Prism id**: the κ (`sha256:` of uor-addr canonical JSON) of a + self-signed genesis record. It never changes. +- **Device**: non-extractable WebCrypto P-256 keys (one signs, one agrees + keys) made on the device with no prompt. Its id is the κ of its public + record. Devices are linked to the id by signed records in the id's log; + any member device can remove another, which rotates the private boundary + key. +- **Log**: the set of signed records (genesis, binds, revokes), merged by + set union. Anyone holding the log can resolve which devices may act. +- **Recovery code**: 56 Crockford base32 characters (a 32-byte seed and three + check bytes). It opens an escrow holding a recovery device of class + `recovery`: a member device kept outside every browser. With the code, a + new browser links its own device to the same id. Revoking the recovery + device retires the code. ## 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**: the κ of the key, `sha256:<64 lowercase hex>` of `H(spki)`, the - UORC object address of its DER SubjectPublicKeyInfo (for a passkey, - `AuthenticatorAttestationResponse.getPublicKey()`). Records of spec - `prism/identity/key/1` keep their prism/identity/1 key ID, `b64u(H(spki))`; - a reader picks the rule by the record's spec. -- **Account ID**: the key ID of the account's first key. It never changes, - and it outlives that key: revoking it, or losing its device, leaves the - account and every key bound into it. -- **Algorithms**: passkeys ES256 (`-7`, P-256) and RS256 (`-257`, for older - Windows Hello); recovery keys EdDSA (`-8`, Ed25519). - -## Signed messages - -A recovery key's signature is Ed25519 over the message's UTF-8 bytes, carried -as `{credential, signature}` with no `clientDataJSON` or `authenticatorData`; -a verifier checks it under the record's `spki` and refuses one that carries -either field. A recovery key signs bind and revoke messages, never a session: -only a device's passkey signs a session. - -Every passkey 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/2", - "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 signature made by a key already in the account, a -passkey's assertion or a recovery key's signature: - -```json -{ "credential": "", "clientDataJSON": "", "authenticatorData": "", "signature": "" } -{ "credential": "", "signature": "" } -``` - -A recovery key's record has `alg` `-8`, its `credential` is its raw 32-byte -public key in b64u (so the code alone finds its record), and its `origin` is -the identity origin it was made on. - -A reader accepts a record only when `key` is the key ID its spec names for -`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 32 bindings is refused; the bound only keeps a reader's work -finite. - -## Recovery codes - -A recovery code is a recovery key's 32-byte Ed25519 seed followed by the first -three bytes of `H(seed)`, in Crockford base32: 56 characters, written in -groups of four. A reader ignores spaces, hyphens and case, reads `I` and `L` -as `1` and `O` as `0`, and refuses a code whose check bytes differ. The -private key is the PKCS#8 encoding of the seed; the code is shown once, never -stored and never sent. - -The sign-in page makes a new account with a recovery key as its first key: -it creates the device's passkey, registers the recovery key alone (which -starts the account), binds the passkey to it with a recovery signature, shows -the code, and then asks the passkey to sign the app's session. A signed-in -account adds a recovery code by its passkey binding a new recovery key. On a -new device, the code finds its record, the device's new passkey is bound by -a recovery signature, and that passkey signs the session. A recovery key is -revoked like any key. - -## 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 signature plus `account`). | -| `POST /passkey/recovery` | Adds a recovery key. Body: `spki` alone, which starts an account with it as the first key and records the request's identity origin; or `spki`, `account` and `binding`, a bind signature by a live key of the account. Answers `{key, account, record}`. | -| `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. +| Prism id page | `https://id.uor.foundation` | This browser's device, keyring and log, in the origin's IndexedDB. It runs as its own window (first-party storage), so every app reaches the same device. It serves no other content. | +| Registry mailbox | `https://registry.uor.foundation/prism/topic/` | Opaque messages under names only holders can derive: recovery escrows (named by the code's locator) and sealed sync messages (named by a boundary key's sync topic). It reads none of them. | +| Frame | `` in every Prism app | This app's session key and the id's signed session. It checks every signature itself, with Prism id's `verifyAction`. | + +## Sign-in + +1. The frame makes a non-extractable P-256 session key and opens the Prism id + page as a window. The page posts `{type: "prism/identity/3/ready"}`. +2. The frame posts, to the page's origin only: + `{type: "prism/identity/3/request", mode: "signin" | "recovery", sessionKey, expires}` + (`sessionKey` is the raw public point in base64url; `expires` is at most + 8 days away). The page takes the app's origin from the browser, never + from the message. +3. The visitor continues (or creates an id, or uses a recovery code). The + page first takes in its other devices' sync messages, so a device removed + elsewhere stops here, then signs + `signAction(session, "prism/session/1", {sessionKey, expires}, {audience: })` + and posts `{type: "prism/identity/3/session", envelope, records}` to the + app's origin, then closes. +4. The frame checks that the payload is the key and expiry it asked for, + then `verifySession`: the log resolves for the envelope's prism id, the + signer is an active device, the audience is this origin, the nonce is + new and 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, and anyone can check it +later with `verifySession(session, {fresh: 0})`: as of its signing, bounded +by its expiry. + +`mode: "recovery"` makes a new recovery code on the device and answers +`{type: "prism/identity/3/recovery"}`; it signs nothing for the app. + +## Mailbox + +`POST /prism/topic/` with the message bytes keeps it; `GET` returns +`{topic, messages: [...]}`, newest last, or 404. A name is +`:<64 lowercase hex>` (`sha256:` for an escrow locator, +`prism-sync:` for a sync topic, `prism-rendezvous:` for linking). The +registry keeps the newest 64 distinct messages of a name, each at most +1 MiB. Readers skip any message that does not open or resolve. + +When the registry cannot keep an escrow, the page says so and the recovery +file (the code and its escrow, downloaded) recovers with no registry at all. + +## Not yet + +- Linking a second device by QR code (stitch's link offers over the + `prism-rendezvous:` mailbox). Today a recovery code adds a device. +- Removing a device from the page (stitch's `revokeDevice` works). +- A host learns of a removal only from the log the signing device presents; + a stolen device that never syncs can keep signing until stitch defines + how hosts hear revocations. diff --git a/identity/README.md b/identity/README.md index 1ec78cd4..8c478566 100644 --- a/identity/README.md +++ b/identity/README.md @@ -1,78 +1,67 @@ -# Prism accounts - -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. One account signs in to every -Prism app, Foundry included. [PROTOCOL.md](PROTOCOL.md) is the contract; this -file says why it is built this way and how to run it. - -## Losing a device never loses the account - -A new account's first key is a recovery key, and the page shows its recovery -code once, before the first sign-in. The device's passkey joins the account -through it, so the account never depended on that device. On any new device, -**Lost your device? Use a recovery code** makes that device's passkey and -binds it with the code, and the visitor is signed in to the same account. A -signed-in visitor can make a fresh code from the panel at any time -(**Recovery code**); an account made before recovery codes existed gets its -first one there. - -## Why a passkey, and why this domain - -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. - -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. +# Prism ids + +The person icon at the right end of every Prism app's bar. One click opens a +small Prism id window; one more, and the visitor is signed in. There is no +password and no passkey prompt: 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). + +## Losing a device never loses the id + +Creating a Prism id shows its recovery code once, before the first sign-in. +On any browser, **Use a recovery code** brings the same id there. A signed-in +visitor can make a fresh code from the panel at any time (**Recovery code**), +and every code keeps working until a device removes it. **Download** saves a +recovery file holding the code and its sealed escrow, which recovers even +when the registry cannot be reached. + +## Why a window, and why this domain + +A Prism id's device lives in `id.uor.foundation`'s storage. Inside another +site's iframe a browser partitions that storage per site, which would give +every app a different device, so the page runs as its own window, where its +storage is the same for every app. The origin serves this one page and +nothing else. ## 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` | +| Registry mailbox | Withhold an escrow or sync message | Read one, or forge one: names are derived from secrets, messages are sealed, and every record is signed and checked by the reader | +| Prism id page | Refuse to help | Sign for an app without the visitor continuing in its window, which names the app | | 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 | -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). +## Run it -## Adding a device +```sh +npm ci && npx playwright install chromium +npm run test:identity # the stitch copy matches its lock, every refused check, then the flow in Chromium +node identity/dev.mjs # the Prism id page on localhost:8790, a demo app on 127.0.0.1:8791 +``` -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. +`dev.mjs` stands in for the registry's mailbox with an in-memory one; the +frame's checks are the real ones. -## Run it +## Follow stitch ```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 +node identity/stitch-sync.mjs # fetches that commit; add a local checkout path to read it instead ``` -`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. +It rewrites `prism-id.mjs` and `stitch.lock`. Copy `frame/` and `identity/` +to Foundry and prism-devrel byte for byte, as with any frame change. ## Deploy -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. Recovery - codes need a registry with `POST /passkey/recovery`; deploy it before the - page. - -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. +1. Deploy the registry's `/prism/topic/` routes (UOR-Foundation/kappa-registry). +2. `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. Serve + `out/` as static files at `https://id.uor.foundation`, HTTPS only, with + HSTS. Do not set `Cross-Origin-Opener-Policy: same-origin`: the app needs + the window's `opener`. + +Ship the page before the frame: the frame opens the page's window. The page +works before the registry routes do (sign-in needs no registry; a new +recovery code then asks the visitor to download its recovery file). diff --git a/identity/dev.mjs b/identity/dev.mjs index a0bc933e..91261202 100644 --- a/identity/dev.mjs +++ b/identity/dev.mjs @@ -1,115 +1,88 @@ #!/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: +// The whole Prism id flow on one machine: the Prism id page on +// http://localhost:8790, an in-memory stand-in for the registry's Prism +// mailbox (/prism/topic/) on the same origin, and a demo app page on +// http://127.0.0.1:8791 that mounts the frame. The mailbox keeps and returns +// opaque messages, as the real one does (UOR-Foundation/kappa-registry); +// the frame verifies every session exactly as it does in production. 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 kappa = (spki) => `sha256:${createHash("sha256").update(Buffer.from(spki, "base64url")).digest("hex")}`; -// The fields of an assertion the registry keeps: a passkey's carries client -// and authenticator data, a recovery key's only its signature. -const assertionOf = ({ credential, clientDataJSON, authenticatorData, signature }) => ({ credential, ...(clientDataJSON === undefined ? {} : { clientDataJSON, authenticatorData }), signature }); 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(); + // The mailbox: the newest messages of each topic, as the registry keeps them. + const topics = new Map(); + const KEEP = 64; 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 bytesOf = (request) => new Promise((done) => { + const chunks = []; + request.on("data", (chunk) => chunks.push(chunk)); + request.on("end", () => done(Buffer.concat(chunks))); }); 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 }); + const topic = /^\/prism\/topic\/([a-z0-9-]+:[0-9a-f]{64})$/.exec(path)?.[1]; + if (topic && request.method === "POST") { + const message = (await bytesOf(request)).toString("base64url"); + const kept = (topics.get(topic) ?? []).filter((m) => m !== message); + topics.set(topic, [...kept, message].slice(-KEEP)); + return json(response, kept.length === topics.get(topic).length ? 200 : 201, { topic, messages: topics.get(topic).length }); } - 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 = kappa(r.spki); - const binding = r.binding ? assertionOf(r.binding) : null; - const record = { spec: "prism/identity/key/2", 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, { key, account: record.account, record }); + if (topic && request.method === "GET") { + return topics.has(topic) ? json(response, 200, { topic, messages: topics.get(topic) }) : json(response, 404, { error: "unknown", message: "No messages." }); } - // A recovery key: an account's first key, or bound into one. Its - // credential is its raw public key, the SPKI's last 32 bytes. - if (request.method === "POST" && path === "/passkey/recovery") { - const r = await body(request); - const key = kappa(r.spki); - const credential = b64u(Buffer.from(r.spki, "base64url").subarray(-32)); - if (records.has(credential)) return json(response, 409, { error: "exists", message: "The key is already registered." }); - const record = { spec: "prism/identity/key/2", key, account: r.account ?? key, credential, alg: -8, spki: r.spki, origin: accounts, created: Date.now(), binding: r.binding ? assertionOf(r.binding) : null }; - records.set(credential, record); - return json(response, 201, { key, account: record.account, 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\/(sha256:[0-9a-f]{64}|[\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]; + const file = { "/": "index.html", "/id.mjs": "id.mjs", "/prism-id.mjs": "prism-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}"`); + if (file === "index.html") text = text.replace('content="https://registry.uor.foundation"', `content="${accounts}"`).replace("connect-src https://registry.uor.foundation", "connect-src 'self'"); 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")) { + if (path === "/frame.mjs" || path.endsWith("/prism-panels.mjs") || path.endsWith("/prism-id.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." }); + 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) return json(response, 404, { error: "unknown", message: "Not found." }); 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}`, + // Frames nothing: the Prism id page opens as its own window. + "content-security-policy": "default-src 'self'; script-src 'self' blob:; style-src 'unsafe-inline'; frame-src 'none'", }); response.end(`Account demo `); @@ -118,7 +91,7 @@ export function start({ idPort = 8790, appPort = 8791 } = {}) { 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, + topics, close: () => Promise.all([new Promise((done) => id.close(done)), new Promise((done) => app.close(done))]), })); } diff --git a/identity/id.css b/identity/id.css index 444efcc3..fa9dbc33 100644 --- a/identity/id.css +++ b/identity/id.css @@ -1,7 +1,7 @@ -/* 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; } +/* The Prism id page: a small window an app's frame opens, or the page + * itself at https://id.uor.foundation. It brings the brand's tokens + * (brand.css). */ +html { color-scheme: light; } html.dark { color-scheme: dark; } body { margin: 0; @@ -9,19 +9,28 @@ body { font-size: 1rem; line-height: 1.45; color: var(--foreground); - background: transparent; + background: var(--background); + min-height: 100vh; + display: grid; + place-items: center; } -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; } +main { display: grid; gap: 0.618rem; width: min(22rem, 100vw - 2rem); padding: 1rem 0; } +h1 { margin: 0; font-size: 1.125rem; font-weight: 600; text-align: center; } +.id { margin: 0; display: flex; gap: 0.5rem; justify-content: center; align-items: baseline; } +.id code { font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.875rem; } +.warn { color: var(--foreground); } +.file { display: grid; gap: 0.25rem; } +.file input { min-height: 0; padding: 0.25rem; font-family: inherit; } button { display: inline-flex; + color: var(--foreground); + background: var(--secondary, transparent); align-items: center; justify-content: center; gap: 0.5rem; min-height: 2.618rem; padding: 0 1rem; - border: 1px solid transparent; + border: 1px solid var(--border); border-radius: calc(var(--radius) - 2px); font: inherit; font-weight: 500; @@ -29,13 +38,13 @@ button { 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 { background: var(--primary); color: var(--primary-foreground); border-color: transparent; } 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; } +main.busy { animation: pulse 1.2s ease-in-out infinite; } @keyframes pulse { 50% { opacity: 0.35; } } .stack { display: grid; gap: 0.5rem; } .stack[hidden], [hidden] { display: none !important; } diff --git a/identity/id.mjs b/identity/id.mjs index 91fb7f8d..87f030a1 100644 --- a/identity/id.mjs +++ b/identity/id.mjs @@ -1,424 +1,297 @@ -// The Prism sign-in page (prism/identity/2, 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. +// The Prism sign-in page (prism/identity/3, identity/PROTOCOL.md), on +// https://id.uor.foundation. It holds this browser's device of the visitor's +// Prism id: stitch's Prism id (afflom/stitch, pinned in identity/stitch.lock), +// whose device keys are non-extractable WebCrypto keys made here, with no +// prompt, no password and no passkey. Every app's frame opens this page as a +// small window, so the device lives in this origin's own storage and is the +// same for every app; the window asks once, the visitor continues, and the +// page signs a session for that app (Prism id's signAction) and closes. The +// frame checks the signature against the log itself (verifyAction), so this +// page can fail to help, never lie. // -// It also makes and reads recovery codes. A new account's first key is a -// recovery key (Ed25519) made here; the device's passkey joins it by a -// signature from that key, so the account never depended on the device. -// The code is the recovery key's private half: shown once, never stored, -// never sent. With it, any device signs in again by joining its own passkey. -// -// 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. +// A lost device never loses the id: a new id's first step is a recovery code +// (stitch's recovery device, sealed in an escrow only the code opens). On any +// browser, the code links that browser's own device to the same id. The +// escrow and the devices' sync messages sit in the registry's Prism mailbox, +// addressed by names only holders can derive; the registry reads none of it. + +import * as Prism from "./prism-id.mjs"; const REGISTRY = document.querySelector('meta[name="prism-registry"]').content.replace(/\/$/, ""); -const RP = location.hostname; -const SPEC = "prism/identity/1"; +const SPEC = "prism/identity/3"; +// The action a session is: this device lets an app's session key act for the +// id, on that app's origin, until it expires. +const ACTION = "prism/session/1"; const WEEK = 8 * 24 * 60 * 60 * 1000; - -const enc = new TextEncoder(); -const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join(""); -// A key's name: its κ, the UORC address of its DER SubjectPublicKeyInfo. -const keyId = async (spki) => `sha256:${hex(await crypto.subtle.digest("SHA-256", spki))}`; -const ID = /^(sha256:[0-9a-f]{64}|[\w-]{43})$/; -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 short = (id) => `${id.slice(0, 15)}…${id.slice(-4)}`; -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", "recovery"].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" || (ID.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. +const peer = window.opener; + +// ---------------------------------------------------------------- this browser's device + +// IndexedDB keeps CryptoKeys as they are: a non-extractable key stays one. +function db(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)); + }; + }); } -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. - } +async function load() { + const saved = await db("readonly", (s) => s.get("self")).catch(() => null); + if (!saved) return null; + return { prism: saved.prism, device: saved.device, keyring: saved.keyring, log: await Prism.logFromRecords(saved.records) }; } - -// 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(); - }, () => {}); +const save = (session) => db("readwrite", (s) => s.put({ prism: session.prism, device: session.device, keyring: session.keyring, records: [...session.log.values()] }, "self")); +const forget = () => db("readwrite", (s) => s.delete("self")); + +// ---------------------------------------------------------------- the registry's mailbox + +// POST /prism/topic/ keeps a message; GET returns the newest. A name is +// derived from a secret (a recovery code, a boundary key), so only holders +// find it, and every message is sealed, so the registry reads nothing. +class Unreachable extends Error {} +async function post(topic, bytes) { + const response = await fetch(`${REGISTRY}/prism/topic/${topic}`, { method: "POST", headers: { "content-type": "application/octet-stream" }, body: bytes }).catch(() => null); + if (!response?.ok) throw new Unreachable(`The registry did not keep it (${response?.status ?? "unreachable"}).`); } - -// 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; -// The recovery code being shown, and what "I saved it" does next. -let kit = null; -function paint() { - const label = { add: "Add device", recovery: "Make a recovery code" }[request.mode] ?? (fresh ? "Create account" : `Continue with ${device ?? "a passkey"}`); - $("go-label").textContent = label; - $("fresh").hidden = !fresh || request.mode !== "signin"; - $("lost").hidden = request.mode !== "signin" || !$("recover").hidden || Boolean(kit); - $("go").hidden = Boolean(kit) || !$("recover").hidden; - $("go").disabled = false; - size(); -} - -function size() { - if (!alone && app) send({ type: "size", height: Math.ceil(document.documentElement.getBoundingClientRect().height) }); +async function messages(topic) { + const response = await fetch(`${REGISTRY}/prism/topic/${topic}`, { cache: "no-store" }).catch(() => null); + if (response?.status === 404) return []; + if (!response?.ok) throw new Unreachable("Prism ids are unreachable right now. Try again soon."); + const { messages = [] } = await response.json(); + return messages.map((text) => Prism.fromBase64Url(text)); } -new ResizeObserver(size).observe(document.body); +const bus = { publish: (topic, bytes) => post(topic, bytes) }; -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; +// Share this device's log with the id's other devices, under every boundary +// key it holds, so a device that has not seen a rotation yet still hears. +async function share(session) { + for (const keyId of session.keyring.keys()) await Prism.publishSync(session, bus, { keyId }).catch(() => {}); } - -function fail(words) { - $("error").textContent = words; - $("error").hidden = false; - size(); +// 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(session) { + for (const keyId of [...session.keyring.keys()]) { + const topic = await Prism.syncTopic(session, keyId); + for (const bytes of await messages(topic).catch(() => [])) { + try { + session = await Prism.receiveSync(session, bytes); + } catch (error) { + if (!(error instanceof Prism.PrismIdError) && !(error instanceof DOMException) && !(error instanceof SyntaxError)) throw error; + } + } + } + return session; } -class RegistryError extends Error {} +// ---------------------------------------------------------------- recovery codes -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; -} +// A recovery file: the code and its escrow, for when the registry cannot be +// reached. It is as secret as the code. +const fileText = (code, escrow, prism) => + `Prism id recovery code\n\n${code}\n\nPrism id ${prism}\n\nOn any device: open the person icon in a Prism app (or https://id.uor.foundation), choose "Use a recovery code" and enter this code, or choose this file.\nAnyone holding it can add a device to your Prism id. Keep it offline.\n\nescrow ${JSON.stringify(escrow)}\n`; -// 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)]; +async function makeCode(session) { + const made = await Prism.createRecovery(session, { now: Date.now() }); + const kept = await post(made.escrow.locator, Prism.canonicalBytes(made.escrow)).then(() => true, () => false); + await save(made.session); + await share(made.session); + return { ...made, kept }; } -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) })), - }, +// The escrows a code may open: the one in a recovery file, or those in its mailbox. +async function escrowsFor(code, file) { + if (file) return [file.escrow]; + const locator = await Prism.recoveryLocator(await Prism.decodeCode(code)); + return (await messages(locator)).map((bytes) => { + try { + return JSON.parse(new TextDecoder().decode(bytes)); + } catch { + return null; + } }); - 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 }); -} - -// Recovery codes. The code is the recovery key's 32-byte Ed25519 seed and -// three check bytes (the start of its SHA-256), in Crockford base32: 56 -// characters, read in groups of four. The check bytes catch a mistyped code -// before anything is asked of the registry. -const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; -const PKCS8_ED25519 = Uint8Array.from([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20]); - -async function encodeCode(seed) { - const bytes = [...seed, ...new Uint8Array(await crypto.subtle.digest("SHA-256", seed)).slice(0, 3)]; - let bits = ""; - for (const byte of bytes) bits += byte.toString(2).padStart(8, "0"); - const chars = bits.match(/.{5}/g).map((five) => CROCKFORD[parseInt(five, 2)]); - return chars.join("").match(/.{4}/g).join(" "); -} - -class CodeError extends Error {} - -async function decodeCode(text) { - const clean = String(text).toUpperCase().replace(/[\s-]/g, "").replace(/[IL]/g, "1").replace(/O/g, "0"); - if (!/^[0-9A-HJKMNP-TV-Z]{56}$/.test(clean)) throw new CodeError("A recovery code is 56 letters and digits."); - const bits = [...clean].map((c) => CROCKFORD.indexOf(c).toString(2).padStart(5, "0")).join(""); - const bytes = Uint8Array.from(bits.match(/.{8}/g), (byte) => parseInt(byte, 2)); - const seed = bytes.slice(0, 32); - const check = new Uint8Array(await crypto.subtle.digest("SHA-256", seed)).slice(0, 3); - if (check.some((b, i) => b !== bytes[32 + i])) throw new CodeError("That code has a typo. Check it and try again."); - return seed; +async function recover(code, file) { + await Prism.decodeCode(code); + let opened = null; + let escrow = null; + for (const candidate of await escrowsFor(code, file)) { + try { + opened = await Prism.openRecovery(code, candidate); + escrow = candidate; + break; + } catch (error) { + if (!(error instanceof Prism.PrismIdError)) throw error; + } + } + if (!opened) throw new Prism.PrismIdError("escrow", file ? "That file does not open with that code." : "No Prism id has that recovery code here. If you saved a recovery file, choose it."); + const synced = await pull(opened); + const device = await Prism.createDevice({ deviceClass: "browser", protection: "software" }); + const joined = await Prism.recoverOnto(code, escrow, device, { now: Date.now(), log: synced.log }).catch((error) => { + if (error instanceof Prism.PrismIdError && error.code === "unauthorized") throw new Prism.PrismIdError("unauthorized", "That recovery code was removed from its Prism id."); + throw error; + }); + await save(joined); + await share(joined); + return joined; } -// A recovery key from its seed: the signing key, its SPKI, its κ and its -// credential (the raw public key, which finds its record). -async function recoveryKey(seed) { - const pkcs8 = new Uint8Array([...PKCS8_ED25519, ...seed]); - const extractable = await crypto.subtle.importKey("pkcs8", pkcs8, { name: "Ed25519" }, true, ["sign"]); - const { x } = await crypto.subtle.exportKey("jwk", extractable); - const publicKey = await crypto.subtle.importKey("jwk", { kty: "OKP", crv: "Ed25519", x }, { name: "Ed25519" }, true, ["verify"]); - const spki = new Uint8Array(await crypto.subtle.exportKey("spki", publicKey)); - const privateKey = await crypto.subtle.importKey("pkcs8", pkcs8, { name: "Ed25519" }, false, ["sign"]); - return { privateKey, spki, key: await keyId(spki), credential: x }; -} +// ---------------------------------------------------------------- the request -const newRecoveryKey = async () => { - const seed = crypto.getRandomValues(new Uint8Array(32)); - return { seed, ...(await recoveryKey(seed)) }; -}; +// Who asked (the browser says) and the app's session to sign. +let request = null; +let app = null; +const valid = (r) => + r?.type === `${SPEC}/request` && + ["signin", "recovery"].includes(r.mode) && + /^[\w-]{87}$/.test(r.sessionKey) && + Number.isSafeInteger(r.expires) && + r.expires > Date.now() && + r.expires <= Date.now() + WEEK; -// A recovery key's signature: Ed25519 over the protocol message itself. -async function signRecovery(recovery, message) { - return { credential: recovery.credential, signature: b64u(await crypto.subtle.sign({ name: "Ed25519" }, recovery.privateKey, enc.encode(message))) }; -} +// Results go only to the app that asked; "ready" carries nothing. +const send = (message) => peer?.postMessage({ ...message, type: `${SPEC}/${message.type}` }, message.type === "ready" ? "*" : app); -// Show the code until the visitor says it is saved; then `next` runs. -async function showKit(recovery, account, next) { - kit = { next, code: await encodeCode(recovery.seed), account }; - recovery.seed.fill(0); - $("kit-code").textContent = kit.code; - $("kit").hidden = false; +addEventListener("message", (event) => { + if (!peer || event.source !== peer || !valid(event.data)) return; + if (!/^https?:\/\/[^/]+$/.test(event.origin)) return; + request = event.data; + app = event.origin; paint(); - $("kit-copy").focus(); -} +}); -// A new passkey for this device, made after `challenge`. -async function newPasskey(challenge, exclude) { - 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: exclude ? [{ type: "public-key", id: unb64u(exclude) }] : [], - hints: adding ? ["hybrid"] : [], - attestation: "none", - timeout: 120000, - }, - }); - const r = credential.response; - const spki = r.getPublicKey(); - return { - 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, - key: await keyId(spki), - }; -} +// ---------------------------------------------------------------- the page -// Register `passkey` into `account`, bound by `binding` (made over its key). -async function join(passkey, account, binding) { - const { key, ...body } = passkey; - return registry("/passkey/register", { ...body, binding: { account, ...binding } }); -} +let held = null; +// The recovery code on screen, and what "I saved it" does next. +let kit = null; +let view = "loading"; -// A new passkey. Another device joins the account whose passkey signs the -// binding. A first one starts an account whose first key is a new recovery -// key, which binds the passkey with no prompt: the visitor saves the code, -// then the passkey signs the app's session (creating a passkey signs nothing -// a reader could check, so that is a second prompt). -async function create() { - const { challenge } = await registry("/passkey/challenge", {}); - if (request.mode === "add") { - const passkey = await newPasskey(challenge, request.credential); - const bound = await sign(`prism/identity/bind/1\n${request.account}\n${passkey.key}`, [request.credential]); - const record = await join(passkey, request.account, bound); - return send({ type: "added", record }); +function paint() { + const asking = Boolean(request); + const host = app ? new URL(app).host : ""; + for (const id of ["none", "held", "recover", "kit", "removed"]) $(id).hidden = view !== id; + $("title").textContent = { + loading: "Prism id", + none: asking ? `Sign in to ${host}` : "Prism id", + held: asking && request.mode === "signin" ? `Sign in to ${host}` : "Your Prism id", + recover: "Use a recovery code", + kit: "Your recovery code", + removed: "This device was removed", + }[view]; + if (held) { + $("id").textContent = short(held.prism); + $("id").title = held.prism; } - const passkey = await newPasskey(challenge, null); - const recovery = await newRecoveryKey(); - const { account } = await registry("/passkey/recovery", { spki: b64u(recovery.spki) }); - await join(passkey, account, await signRecovery(recovery, `prism/identity/bind/1\n${account}\n${passkey.key}`)); - remember(passkey.credential); - await showKit(recovery, account, () => session([passkey.credential])); + $("continue").hidden = !(asking && request.mode === "signin"); + $("make-code").hidden = asking && request.mode === "signin"; + $("make-code").classList.toggle("primary", asking && request.mode === "recovery"); } -// A recovery code for a signed-in account: the passkey binds a new recovery -// key. Older codes keep working until a device revokes them. -async function makeRecovery() { - const recovery = await newRecoveryKey(); - const binding = await sign(`prism/identity/bind/1\n${request.account}\n${recovery.key}`, [request.credential]); - const { key } = await registry("/passkey/recovery", { account: request.account, spki: b64u(recovery.spki), binding }); - await showKit(recovery, request.account, () => send({ type: "recovery", key })); -} - -// Sign in with a recovery code: this device's new passkey joins the code's -// account, then signs the app's session. -async function recover(text) { - const recovery = await recoveryKey(await decodeCode(text)); - const record = await registry(`/passkey/credential/${recovery.credential}`).catch((error) => { - throw new RegistryError(/revoked/i.test(error.message) ? "That recovery code was replaced. Use the newest one." : /no key/i.test(error.message) ? "No account has that recovery code." : error.message); - }); - const { challenge } = await registry("/passkey/challenge", {}); - const passkey = await newPasskey(challenge, null); - await join(passkey, record.account, await signRecovery(recovery, `prism/identity/bind/1\n${record.account}\n${passkey.key}`)); - remember(passkey.credential); - $("code").value = ""; - $("recover").hidden = true; - await session([passkey.credential]); +function busy(on) { + $("card").classList.toggle("busy", on); + if (on) $("error").hidden = true; } - -// 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); +function fail(words) { + $("error").textContent = words; + $("error").hidden = false; } - 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") && (kit || !$("recover").hidden || request.mode === "recovery")) { - // A prompt closed during recovery or while a code is shown: nothing - // to infer about this device's passkeys. The same tap tries again. - return fail("That did not finish. Try again."); - } - 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 instanceof CodeError ? error.message : "That did not work. Try again."); + fail(error instanceof Prism.PrismIdError || error instanceof Unreachable ? sentence(error.message) : "That did not work. Try again."); } finally { busy(false); } } +const sentence = (text) => (text ? text[0].toUpperCase() + text.slice(1) + (/[.!?]$/.test(text) ? "" : ".") : text); -$("go").addEventListener("click", () => run(() => (request.mode === "recovery" ? makeRecovery() : request.mode === "add" || fresh ? create() : session(remembered ? [remembered] : [])))); -$("use-code").addEventListener("click", () => { - $("recover").hidden = false; +function show(next) { + view = next; paint(); - $("code").focus(); -}); -$("recover-go").addEventListener("click", () => run(() => recover($("code").value))); -$("code").addEventListener("keydown", (event) => { - if (event.key === "Enter") run(() => recover($("code").value)); +} + +async function showKit(made, next) { + kit = { ...made, next }; + $("kit-code").textContent = made.code; + $("kit-kept").hidden = made.kept; + show("kit"); + $("kit-copy").focus(); +} + +// Sign the app's session: first take in what the other devices shared, so a +// device removed elsewhere stops here. +async function signIn() { + held = await pull(held); + await save(held); + if (!(await Prism.canSign(held.prism, held.log, held.device.id))) { + await forget(); + held = null; + return show("removed"); + } + const { sessionKey, expires } = request; + const envelope = await Prism.signAction(held, ACTION, { sessionKey, expires }, { now: Date.now(), audience: app }); + send({ type: "session", envelope, records: [...held.log.values()] }); + setTimeout(() => window.close(), 50); +} + +// After a new id or a recovery: sign in, if an app asked; otherwise show the id. +const after = () => (request?.mode === "signin" ? signIn() : request?.mode === "recovery" ? (send({ type: "recovery" }), setTimeout(() => window.close(), 50)) : show("held")); + +$("create").addEventListener("click", () => + run(async () => { + const made = await makeCode(await Prism.createPrism({ deviceClass: "browser", protection: "software" })); + held = made.session; + await showKit(made, after); + }), +); +$("continue").addEventListener("click", () => run(signIn)); +$("make-code").addEventListener("click", () => + run(async () => { + const made = await makeCode(await pull(held)); + held = made.session; + await showKit(made, after); + }), +); +for (const id of ["use-code", "removed-code"]) $(id).addEventListener("click", () => (show("recover"), $("code").focus())); +$("recover-back").addEventListener("click", () => show(held ? "held" : "none")); + +let file = null; +$("code-file").addEventListener("change", async () => { + const text = await $("code-file").files[0]?.text(); + const code = /(([0-9A-Z]{4} ){13}[0-9A-Z]{4})/.exec(text ?? "")?.[1]; + const escrow = /^escrow (.+)$/m.exec(text ?? "")?.[1]; + try { + file = { escrow: JSON.parse(escrow) }; + if (code) $("code").value = code; + } catch { + file = null; + fail("That is not a recovery file."); + } }); +const recoverNow = () => + run(async () => { + held = await recover($("code").value, file); + $("code").value = ""; + file = null; + await after(); + }); +$("recover-go").addEventListener("click", recoverNow); +$("code").addEventListener("keydown", (event) => event.key === "Enter" && recoverNow()); + $("kit-copy").addEventListener("click", async () => { try { await navigator.clipboard.writeText(kit.code); @@ -430,29 +303,24 @@ $("kit-copy").addEventListener("click", async () => { setTimeout(() => ($("kit-copy").textContent = "Copy"), 1600); }); $("kit-save").addEventListener("click", () => { - const text = `Prism account recovery code\n\n${kit.code}\n\nAccount ${kit.account}\n\nOn any device: open the person icon in a Prism app, choose "Lost your device? Use a recovery code" and enter this code.\nAnyone holding it can add a device to your account. Keep it offline.\n`; const link = document.createElement("a"); - link.href = URL.createObjectURL(new Blob([text], { type: "text/plain" })); - link.download = "prism-recovery-code.txt"; + link.href = URL.createObjectURL(new Blob([fileText(kit.code, kit.escrow, kit.session.prism)], { type: "text/plain" })); + link.download = "prism-id-recovery.txt"; link.click(); setTimeout(() => URL.revokeObjectURL(link.href), 1000); }); $("kit-done").addEventListener("click", () => { const { next } = kit; kit = null; - $("kit").hidden = true; $("kit-code").textContent = ""; - paint(); run(next); }); -$("again").addEventListener("click", () => { - fresh = false; - paint(); - run(() => session()); -}); +$("copy-id").addEventListener("click", () => navigator.clipboard?.writeText(held?.prism ?? "").catch(() => {})); -if (!window.PublicKeyCredential) { - fail("This browser can't use passkeys."); +if (!globalThis.indexedDB || !crypto?.subtle) { + fail("This browser can't keep a Prism id."); } else { - send({ type: "ready", modes: ["signin", "add", "recovery"] }); + held = await load(); + show(held ? "held" : "none"); + send({ type: "ready", modes: ["signin", "recovery"] }); } diff --git a/identity/index.html b/identity/index.html index 522a3719..2cf74610 100644 --- a/identity/index.html +++ b/identity/index.html @@ -5,29 +5,42 @@ - + - Prism account + Prism id +
- - - +

Prism id

+ + +