diff --git a/.github/workflows/try-page.yml b/.github/workflows/try-page.yml index 1f348645..4c930357 100644 --- a/.github/workflows/try-page.yml +++ b/.github/workflows/try-page.yml @@ -7,7 +7,7 @@ on: - "studio/**" - "v2/**" pull_request: - # Forge (studio/) is not read by the try page, the frame, the identity page or the try codespace: a pull + # Forge (studio/) is not read by the try page, the frame, Prism ids or the try codespace: a pull # request that changes only Forge or the v2/ prototypes does not wait for them. paths-ignore: - "studio/**" @@ -64,12 +64,10 @@ 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 two apps share one id run: npm run test:identity - name: Build the canonical frame every Prism app loads run: node frame/publish.mjs "$RUNNER_TEMP/frame" "$GITHUB_SHA" - - name: Build the sign-in page for id.uor.foundation, pinned by hash - run: node identity/publish.mjs "$RUNNER_TEMP/identity" "$GITHUB_SHA" deploy: name: publish the try page and the canonical frame diff --git a/bootstrap/frame-sync.mjs b/bootstrap/frame-sync.mjs index fa6a4259..bb3f4422 100644 --- a/bootstrap/frame-sync.mjs +++ b/bootstrap/frame-sync.mjs @@ -42,6 +42,7 @@ const FRAME = [ "bootstrap/precache.mjs", "bootstrap/register.mjs", "bootstrap/screens.mjs", + "bootstrap/weight.mjs", "bootstrap/worker-runtime.mjs", "lighthouserc.json", "site/app.mjs", diff --git a/bootstrap/page.mjs b/bootstrap/page.mjs index 6e00344c..e8811d15 100644 --- a/bootstrap/page.mjs +++ b/bootstrap/page.mjs @@ -104,10 +104,6 @@ const prismRegistry = new URL(`https://${DEFAULT_REGISTRY}/`); // a frame change reaches this app without rebuilding it. app.json may name // another frame host, for a test or a mirror. const frameHost = new URL(meta.frame ?? "https://uor-foundation.github.io/template/frame/"); -// Prism accounts: the sign-in page the frame's account panel shows. The -// page's policy frames that one origin and no other. app.json may name -// another, for a test. -const accounts = new URL(meta.accounts ?? "https://id.uor.foundation/"); const shareUrl = live.href; // The one speculation rule: the frame marks the pages a visitor is about to @@ -121,23 +117,26 @@ const speculationRules = JSON.stringify({ // with the page's, so the frame does not wait for a TLS handshake. const frameConnect = frameHost.origin !== live.origin ? `` : ""; -// The frame's Unsplash worker, which this page's connect-src must name for -// the theme panel's search: read from the live frame at build, after its -// SHA-256 is checked as the browser checks it. The frame itself is not -// written into the page: the page's own stand-in (prism-page.css) shows, -// drawn as the bar, until the module arrives, which keeps the first load -// inside the Lighthouse budget. -async function frameUnsplash() { +// The origins this page's connect-src must name for the frame: its Unsplash +// worker, for the theme panel's search, and stitch's relay (with its +// WebSocket origin), where a visitor's Prism id devices meet. Both are read +// from the live frame at build, after its SHA-256 is checked as the browser +// checks it. The frame itself is not written into the page: the page's own +// stand-in (prism-page.css) shows, drawn as the bar, until the module +// arrives, which keeps the first load inside the Lighthouse budget. +async function frameAllowed() { try { const pointer = await (await fetch(new URL("current.json", frameHost), { cache: "no-store" })).json(); if (!/^[0-9a-f]{64}$/.test(pointer.sha256 ?? "")) throw new Error("the frame pointer names no sha256"); const bytes = Buffer.from(await (await fetch(new URL(pointer.module, frameHost))).arrayBuffer()); if (hex(bytes) !== pointer.sha256) throw new Error(`the frame is ${hex(bytes)}, its pointer says ${pointer.sha256}`); const frame = await import(`data:text/javascript;base64,${bytes.toString("base64")}`); - return /^https:\/\/[a-z0-9.-]+$/.test(frame.UNSPLASH_ORIGIN ?? "") ? frame.UNSPLASH_ORIGIN : ""; + const origin = (value) => (/^https:\/\/[a-z0-9.-]+$/.test(value ?? "") ? value : ""); + const relay = origin(/^https:\/\/[a-z0-9.-]+/.exec(frame.PRISM_RELAY ?? "")?.[0]); + return { unsplash: origin(frame.UNSPLASH_ORIGIN), relay: relay ? `${relay} ${relay.replace(/^https:/, "wss:")}` : "" }; } catch (error) { - console.warn(`page: the frame could not be read at build (${error.message}); no Unsplash origin in connect-src`); - return ""; + console.warn(`page: the frame could not be read at build (${error.message}); no Unsplash or relay origin in connect-src`); + return { unsplash: "", relay: "" }; } } // The repository's GitHub stars at build, so the bar shows them from its @@ -166,7 +165,7 @@ async function githubStars() { } } const stars = await githubStars(); -const unsplashOrigin = await frameUnsplash(); +const frameOrigins = await frameAllowed(); // --------------------------------------------------------------------------- // The workspace and the spec, rendered here so the page says everything @@ -432,9 +431,8 @@ const fill = { HOLO_SEARCH_ORIGIN: holoSearch.origin, REGISTRY_ORIGIN: prismRegistry.origin, FRAME_ORIGIN: frameHost.origin, - ACCOUNTS: escape(accounts.href), - ACCOUNTS_ORIGIN: accounts.origin, - UNSPLASH_ORIGIN: unsplashOrigin, + UNSPLASH_ORIGIN: frameOrigins.unsplash, + PRISM_RELAY_ORIGINS: frameOrigins.relay, OG_IMAGE: escape(new URL("og.png", live).href), OG_ALT: escape(`${meta.name}: ${meta.purpose}`), NAME: escape(meta.name), diff --git a/bootstrap/weight.mjs b/bootstrap/weight.mjs new file mode 100644 index 00000000..836037f0 --- /dev/null +++ b/bootstrap/weight.mjs @@ -0,0 +1,150 @@ +#!/usr/bin/env node +// The weight gate (FR-03). Opens the assembled site as a first visitor on a +// phone, with no service worker, waits until the page has started (the +// canonical frame is running and the shield has replayed every example), +// then until the network is quiet, and counts every byte that came over the +// wire, the page's workers included. Measured at that state, the count is the +// same on every run: Lighthouse's resource summary was not, because the +// frame, the worker runtime and the holo wait for first paint and land in its +// trace only some of the time (72 KB one run, 152 KB the next, same build). +// +// The bytes are split two ways, each with its own budget: +// frame: what every Prism app carries and only the template changes (the +// canonical frame from its host, the fonts, the worker runtime and +// the frame-locked page modules); +// app: everything else, from the page itself to the holo and the app's +// own modules. +// A template change that grows the frame fails the template; an app that +// grows fails the app; neither can push the other over. +// node bootstrap/weight.mjs site +// Needs playwright with Chromium: npm install -g playwright && playwright install chromium +import { createServer } from "node:http"; +import { readFile, stat } from "node:fs/promises"; +import { extname, join, normalize } from "node:path"; +import { execSync } from "node:child_process"; +import { gzipSync } from "node:zlib"; +import { pathToFileURL } from "node:url"; + +export const BUDGET = { + frame: 100 * 1024, + app: 120 * 1024, + requests: 28, +}; + +// Site paths the template owns: what frame.lock pins under site/, the fonts, +// and the worker runtime bootstrap/worker-runtime.mjs writes. +export function frameOwned(lock) { + const files = new Set(lock.files.map((f) => f.path).filter((p) => p.startsWith("site/")).map((p) => p.slice("site/".length))); + return (path) => files.has(path) || path.startsWith("fonts/") || path.startsWith("worker-runtime/"); +} + +// requests: [{ url, bytes }] for one visit; site: the page's URL; owned: from +// frameOwned; frameHost: the frame's URL from app.json. +export function weigh(requests, { site, owned, frameHost }) { + const sum = { frame: 0, app: 0, requests: 0, lines: [] }; + const base = new URL(site); + const host = new URL(frameHost); + for (const { url, bytes } of requests) { + const u = new URL(url); + if (u.protocol === "blob:" || u.protocol === "data:") continue; + let part = "app"; + if (u.origin === host.origin && u.pathname.startsWith(host.pathname)) part = "frame"; + else if (u.origin === base.origin && u.pathname.startsWith(base.pathname) && owned(u.pathname.slice(base.pathname.length))) part = "frame"; + sum[part] += bytes; + sum.requests += 1; + sum.lines.push({ part, bytes, url }); + } + return sum; +} + +export function judge(sum, budget = BUDGET) { + const failures = []; + if (sum.frame > budget.frame) failures.push(`the frame's bytes are ${sum.frame}, over its budget of ${budget.frame}`); + if (sum.app > budget.app) failures.push(`the app's bytes are ${sum.app}, over its budget of ${budget.app}`); + if (sum.requests > budget.requests) failures.push(`${sum.requests} requests, over the budget of ${budget.requests}`); + return failures; +} + +// The page has started: the canonical frame is running and the shield has +// replayed every example (or named why it could not). +export function started() { + const frame = document.getElementById("frame"); + return Boolean(customElements.get("prism-frame")) + && /^(\d+\/\d+|error)$/.test(frame?.getAttribute("examples") ?? ""); +} + +// GitHub Pages compresses text and leaves woff2, png and the like as they are. +const types = { ".html": "text/html", ".css": "text/css", ".mjs": "text/javascript", ".js": "text/javascript", ".json": "application/json", ".webmanifest": "application/manifest+json", ".svg": "image/svg+xml", ".woff2": "font/woff2", ".png": "image/png", ".holo": "application/octet-stream", ".wasm": "application/wasm" }; +const compressed = new Set([".html", ".css", ".mjs", ".js", ".json", ".webmanifest", ".svg", ".holo", ".wasm"]); + +async function main() { + const site = process.argv[2] ?? "site"; + const playwright = await import("playwright").catch(() => + import(pathToFileURL(join(execSync("npm root -g").toString().trim(), "playwright", "index.mjs")).href)); + const { chromium } = playwright; + const owned = frameOwned(JSON.parse(await readFile("frame.lock", "utf8"))); + const app = JSON.parse(await readFile(join(site, "app.json"), "utf8")); + const frameHost = app.frame ?? "https://uor-foundation.github.io/template/frame/"; + + const server = createServer(async (request, response) => { + let path = decodeURIComponent(new URL(request.url, "http://x").pathname); + if (path.endsWith("/")) path += "index.html"; + const file = normalize(join(site, path)); + try { + await stat(file); + let body = await readFile(file); + const headers = { "content-type": types[extname(file)] ?? "application/octet-stream" }; + if (compressed.has(extname(file)) && /\bgzip\b/.test(request.headers["accept-encoding"] ?? "")) { + body = gzipSync(body, { level: 9 }); + headers["content-encoding"] = "gzip"; + } + response.writeHead(200, headers); + response.end(body); + } catch { + response.writeHead(404); + response.end(); + } + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const origin = `http://127.0.0.1:${server.address().port}/`; + + const browser = await chromium.launch(); + const runs = []; + try { + for (let run = 0; run < 2; run++) { + const context = await browser.newContext({ viewport: { width: 412, height: 823 }, isMobile: true, hasTouch: true, serviceWorkers: "block" }); + const page = await context.newPage(); + const requests = []; + const pending = []; + page.on("requestfinished", (request) => pending.push(request.sizes().then((s) => { + requests.push({ url: request.url(), bytes: s.responseBodySize + s.responseHeadersSize }); + }, () => {}))); + await page.goto(origin, { waitUntil: "load" }); + try { + await page.waitForFunction(started, null, { timeout: 30000 }); + } catch { + throw new Error(`the page never started: frame ${await page.evaluate(() => Boolean(customElements.get("prism-frame")))}, examples "${await page.locator("#frame").getAttribute("examples")}"`); + } + await page.waitForLoadState("networkidle"); + await Promise.all(pending); + runs.push(weigh(requests, { site: origin, owned, frameHost })); + await context.close(); + } + } finally { + await browser.close(); + server.close(); + } + + const [sum] = runs; + for (const line of sum.lines.sort((a, b) => b.bytes - a.bytes)) console.log(`${line.part.padEnd(5)} ${String(line.bytes).padStart(7)} ${line.url.replace(origin, "./")}`); + for (const r of runs) console.log(`weight: frame ${r.frame} of ${BUDGET.frame}, app ${r.app} of ${BUDGET.app}, ${r.requests} of ${BUDGET.requests} requests`); + const failures = runs.flatMap((r) => judge(r)); + // Both runs see the same requests, or the measure is not the page's. + if (runs[0].requests !== runs[1].requests) failures.push(`the runs saw ${runs[0].requests} and ${runs[1].requests} requests: the page had not settled`); + if (failures.length) { + for (const f of new Set(failures)) console.error(`FR-03: ${f}`); + process.exit(1); + } +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) await main(); diff --git a/frame.lock b/frame.lock index 322b5997..3295c3d6 100644 --- a/frame.lock +++ b/frame.lock @@ -2,13 +2,13 @@ "spec": "prism/frame-lock/1", "source": { "repository": "UOR-Foundation/template", - "commit": "0b7c323035b2bbb3729f4afad75820cac228cb09", - "raw": "https://raw.githubusercontent.com/UOR-Foundation/template/0b7c323035b2bbb3729f4afad75820cac228cb09/" + "commit": "d65a5ff543bf98fc4bbfb4a4e81789767529ab1d", + "raw": "https://raw.githubusercontent.com/UOR-Foundation/template/d65a5ff543bf98fc4bbfb4a4e81789767529ab1d/" }, "files": [ { "path": "bootstrap/frame-sync.mjs", - "sha256": "c82b0a057aeccd601ec817ea71d7211b10083d884a1267f8bdf310f11199062b" + "sha256": "5d874908a8f5813b6f7c1004ec0e73ec03584139bf7ac8ffabb2ad5c0eeee7af" }, { "path": "bootstrap/icons.py", @@ -20,7 +20,7 @@ }, { "path": "bootstrap/page.mjs", - "sha256": "2df4ef057d37e778b04f67e4f63d862c7da6a77c301d0862b2bb8681fc8ec9d4" + "sha256": "8eee238bce9206ca58fc9be5471c28c0bdab82e2350ed78f1972da2a1da6581f" }, { "path": "bootstrap/precache.mjs", @@ -34,13 +34,17 @@ "path": "bootstrap/screens.mjs", "sha256": "c9787ebf5ad8e8b649034ec3e43f8812ba51777ba59eb11f1f51ca084a395b67" }, + { + "path": "bootstrap/weight.mjs", + "sha256": "de432422e9931b4adf0f422a2030d7b38097a60a4d8fc9ed62fd20fe0c468373" + }, { "path": "bootstrap/worker-runtime.mjs", "sha256": "0f9fbb6ec4db48fb7f7c4b779a0494e95d5411e868b36e1e163e5173fcc34557" }, { "path": "lighthouserc.json", - "sha256": "0145d04da93193801b0d8736ceba7e0df94b9b15f183b07a16e6feda16d72082" + "sha256": "85aa0f6219cb8396b34f5b461c1d4d7b149e4cc1674cbd2f0100c5b5e16636d9" }, { "path": "site/app.mjs", @@ -52,7 +56,7 @@ }, { "path": "site/page.template.html", - "sha256": "d7df0bc4d5190ca38ee768bdbd54cbc665ede811608de846068c8a92bd02c14d" + "sha256": "b48b9d18e23e959c9e96b4bec58e2e7d80b7b977e981d8a7b0fd369293819b08" }, { "path": "site/prism-page.css", @@ -68,7 +72,7 @@ }, { "path": "site/sw.js", - "sha256": "b4d4eb5c8314f5abed013ea9d172e7352dbdfa5aa2b503901df364ebcfbf11f7" + "sha256": "baf0fbd7da2fa0b33124951bbd1218aa6658c342340fb24415c636f220c9ea74" }, { "path": "site/theme.js", 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 74ad3d67..7085b641 100644 --- a/frame/frame.mjs +++ b/frame/frame.mjs @@ -7,7 +7,7 @@ // // The contract (prism/frame/1): // +// verdict verdict-label fingerprint proof proof-url examples> // … optional: shown in the bar, e.g. "Update available" // // name the app's name ("Luhn check") @@ -25,11 +25,10 @@ // proof-url optional: the proof's attestation // examples optional: "passed/total" once the page has replayed the holo's // examples, "running" while it does, "error" when it could not -// accounts optional: the Prism accounts origin (https://id.uor.foundation) -// The element's account is the visitor's Prism account (null when signed -// out); sign(bytes) signs with this browser's session key and returns the -// signature with the passkey's delegation; "accountchange" fires on sign-in -// and sign-out. identity/PROTOCOL.md is the account contract. +// The element's account is the visitor's Prism id (null when signed out); +// sign(bytes) signs with this browser's session key and returns the +// signature with the id's delegation; "accountchange" fires on sign-in and +// sign-out. identity/PROTOCOL.md is the account contract. // The shield sums the three: green only when the bytes are authentic and // every example gives its proved answer; its panel shows each check, as a // browser shows a page's security. @@ -346,12 +345,14 @@ function holoIndex() { const githubMark = ''; const starMark = ''; -// Prism accounts (prism/identity/1, identity/PROTOCOL.md). An account is a -// passkey: its private key stays in the device's secure hardware, and the -// account's name is the hash of its public key. The frame keeps the session -// and signs with it; the panels module runs the sign-in and checks every -// signature the sign-in page hands back, in the visitor's browser. -const ACCOUNTS = "https://id.uor.foundation"; +// Prism ids (prism/identity/4, identity/PROTOCOL.md): stitch's Prism id, +// named by the κ of its genesis and held by devices whose keys never leave +// them, with a recovery kit its owner keeps, so losing a device never loses +// the id. The frame keeps this app's session and signs with it; the panels +// module holds this origin's device and runs the sign-in, in the visitor's +// browser. Devices of one id meet on stitch's relay, which the page build +// reads from here into the page's connect-src (with its WebSocket origin). +export const PRISM_RELAY = "https://ntfy.sh"; const SESSION_DAYS = 7; const b64u = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); // The session, in this app's IndexedDB: the browser key cannot be read out @@ -373,11 +374,11 @@ function store(mode, work) { const accountChannel = { session: null, loaded: null }; function loadSession() { return (accountChannel.loaded ??= store("readonly", (s) => s.get("current")) - .then((saved) => (accountChannel.session = saved && saved.delegation.expires > Date.now() ? saved : null)) + .then((saved) => (accountChannel.session = saved?.delegation?.envelope && saved.expires > Date.now() ? saved : null)) .catch(() => null)); } // What the account panel, in the panels module, borrows from the frame. -const ACCOUNT_CORE = { SESSION_DAYS, b64u, store, accountChannel, loadSession }; +const ACCOUNT_CORE = { SESSION_DAYS, b64u, store, accountChannel, loadSession, PRISM_RELAY }; // Everything the markup needs, from the attributes (get), the page's title // and its address: one function, for the element and for the shell. @@ -400,7 +401,6 @@ function modelOf(get, title, base) { ...starsOf(Number(get("stars"))), card: get("card") ?? new URL("og.png", url).href, identity: get("identity") ?? "#identity-title", - accounts: get("accounts") ?? ACCOUNTS, host: (url.host + url.pathname).replace(/\/$/, ""), x: `https://x.com/intent/post?${query({ text, url: url.href })}`, linkedin: `https://www.linkedin.com/sharing/share-offsite/?${query({ url: url.href })}`, @@ -448,7 +448,7 @@ export function shell(attributes, base) { // there is none, to write the shell. const Element = globalThis.HTMLElement ?? class {}; class PrismFrame extends Element { - static observedAttributes = ["name", "address", "live", "repo", "home", "purpose", "card", "identity", "verdict", "verdict-label", "fingerprint", "proof", "proof-url", "examples", "stars", "accounts"]; + static observedAttributes = ["name", "address", "live", "repo", "home", "purpose", "card", "identity", "verdict", "verdict-label", "fingerprint", "proof", "proof-url", "examples", "stars"]; constructor() { super(); @@ -831,32 +831,32 @@ class PrismFrame extends Element { // The visitor's Prism account, for the app: null when signed out. get account() { const saved = accountChannel.session; - return saved ? { id: saved.account, key: saved.key, expires: saved.delegation.expires } : null; + return saved ? { id: saved.account, key: saved.key, expires: saved.expires } : null; } // Signs bytes with this browser's session key. The delegation proves the - // account's passkey let that key act for it here; verifySession checks it. + // Prism id let that key act for it here; verifySession checks it. async sign(data) { const saved = accountChannel.session; - if (!saved || saved.delegation.expires <= Date.now()) throw Object.assign(new Error("No one is signed in"), { name: "IdentityError", code: "signed-out" }); + if (!saved || saved.expires <= Date.now()) throw Object.assign(new Error("No one is signed in"), { name: "IdentityError", code: "signed-out" }); const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, saved.privateKey, data); return { signature: b64u(signature), delegation: saved.delegation }; } - // The account icon, after full screen: a line drawing signed out, a soft - // pulse while a passkey is asked, filled once signed in. Its panel and the + // The account icon, after full screen: a line drawing signed out, filled + // once signed in. Its panel and the // sign-in itself come with the panels module (accounts() there), fetched // when the visitor reaches for the icon, so an app's first load carries - // none of it. Where passkeys cannot work (no secure context, no WebAuthn, - // no IndexedDB, no popover) the icon is not shown, so it never offers - // what would fail. + // none of it. Where a Prism id cannot work (no secure context, no + // WebCrypto, no IndexedDB, no popover) the icon is not shown, so it never + // offers what would fail. accountPanel() { const button = this.$("account"); const panel = this.$("account-panel"); this.accountWatch?.abort(); this.accountReady = null; let wired = false; - if (typeof panel.showPopover !== "function" || !window.isSecureContext || !window.PublicKeyCredential || !globalThis.indexedDB) { + if (typeof panel.showPopover !== "function" || !window.isSecureContext || !globalThis.crypto?.subtle || !globalThis.indexedDB) { button.hidden = true; return; } diff --git a/frame/panels.css b/frame/panels.css index 9ea77de3..d60dca90 100644 --- a/frame/panels.css +++ b/frame/panels.css @@ -466,17 +466,21 @@ .account-panel .row { justify-content: flex-start; width: 100%; min-height: 2.618rem; padding: 0 1rem; border: 0; border-radius: var(--radius-control); background: none; color: var(--foreground); font-size: 1rem; text-align: start; cursor: pointer; } .account-panel .row:hover { background: var(--accent); } .account-panel .row:focus-visible, .account-panel .text:focus-visible, .account-close:focus-visible { outline: var(--ring-width) solid var(--ring); outline-offset: var(--ring-offset); } -.account-ceremony:empty { display: none; } -/* The iframe's colour scheme matches the page inside it; a mismatch would - * make the browser paint it an opaque ground over the dialog. */ -.account-ceremony iframe { display: block; width: 100%; height: 2.618rem; border: 0; color-scheme: light; } -:host([dark]) .account-ceremony iframe { color-scheme: dark; } -/* Shown only once the sign-in page has answered, so a page that fails to - * load never shows the browser's error page in the dialog. */ -.account-ceremony iframe:not(.ready) { visibility: hidden; height: 0 !important; } -#account-window { width: 100%; min-height: 2.618rem; font-size: 1rem; } +.account-panel .primary { width: 100%; min-height: 2.618rem; font-size: 1rem; } +.account-panel .account-in > p { margin-bottom: 0.618rem; color: var(--muted-foreground); } +.account-panel .account-in > p b { color: var(--foreground); font-weight: 600; } +.account-panel input:not([type="file"]) { width: 100%; min-height: 2.618rem; padding: 0 1rem; border: var(--border-width) solid var(--border); border-radius: var(--radius-control); background: var(--background); color: var(--foreground); font: inherit; font-size: 1rem; } +.account-panel #account-code { margin-top: 0.382rem; font-family: var(--font-mono); letter-spacing: 0.2em; } +.account-panel label { display: grid; color: var(--muted-foreground); } +.account-panel input:focus-visible { outline: var(--ring-width) solid var(--ring); outline-offset: var(--ring-offset); } +.account-code { margin-top: 0.618rem !important; color: var(--foreground); font-size: 1rem; } +.account-devices { display: grid; gap: 0.382rem; margin: 0; padding: 0; list-style: none; } +.account-devices li { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); min-height: 2.618rem; padding: 0 1rem; border: var(--border-width) solid var(--border); border-radius: var(--radius-control); } +.account-devices code { font-family: var(--font-mono); color: var(--muted-foreground); } +.account-error { margin-top: 1rem !important; color: var(--destructive, #c2410c); } +.account-panel.busy > :not(.account-close) { opacity: 0.618; pointer-events: none; } @media (pointer: coarse) { - .account-panel .row, #account-window { min-height: var(--touch); } + .account-panel .row, .account-panel .primary, .account-panel input:not([type="file"]) { min-height: var(--touch); } .account-close { top: 0.618rem; right: 0.618rem; width: var(--touch); height: var(--touch); min-height: var(--touch); } } @media (prefers-reduced-transparency: reduce) { .account-panel::backdrop { -webkit-backdrop-filter: none; backdrop-filter: none; background: rgb(0 0 0 / 0.618); } } diff --git a/frame/panels.mjs b/frame/panels.mjs index 61e1170a..9836a414 100644 --- a/frame/panels.mjs +++ b/frame/panels.mjs @@ -341,19 +341,23 @@ export function panel(frame, core) { return { open: () => query || home() }; } -// The theme panel's contents, which the frame puts in its empty panel. -// Prism accounts (prism/identity/1, identity/PROTOCOL.md): the checks the -// sign-in page's answer must pass. The page is trusted with nothing; every -// signature is checked here, in the visitor's browser, as the frame checks -// the holo's bytes. A failed check is an IdentityError naming which one. -const MAX_CHAIN = 5; -const enc = new TextEncoder(); +// Prism ids (prism/identity/4, identity/PROTOCOL.md). A visitor's Prism id +// is stitch's Prism id (afflom/stitch, pinned in identity/stitch.lock): the +// κ of its genesis, held by devices whose keys never leave them. Each app's +// origin keeps its own device of the id, made here with no prompt; another +// device or app joins the same id by stitch's link offer, confirmed with a +// six-digit code, and a recovery kit brings it back after every device is +// lost. Devices meet on stitch's substrate (its relay), so nothing here +// needs a server of Prism's own. +// +// Signing in is the device signing one action for this app, +// "prism/session/1", which lets a session key made here act for the id on +// this origin until it expires. verifySession checks that action against the +// id's log with Prism id's own verifyAction, here and for anyone the app +// shows a signature to. A failed check is an IdentityError naming which. +const SESSION_ACTION = "prism/session/1"; +const MAX_SESSION_MS = 8 * 24 * 60 * 60 * 1000; const b64u = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -const unb64u = (text) => { - if (typeof text !== "string" || !/^[\w-]*$/.test(text)) throw new IdentityError("encoding", "A value is not base64url"); - return Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0)); -}; -const digest = async (bytes) => new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); export class IdentityError extends Error { constructor(code, message) { @@ -366,307 +370,518 @@ const deny = (code, message) => { throw new IdentityError(code, message); }; -// The origins whose signatures count, each with its WebAuthn rpId. -export const originsOf = (accounts) => ({ [new URL(accounts).origin]: new URL(accounts).hostname }); - -const ALGORITHMS = { - [-7]: { key: { name: "ECDSA", namedCurve: "P-256" }, verify: { name: "ECDSA", hash: "SHA-256" } }, - [-257]: { key: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, verify: { name: "RSASSA-PKCS1-v1_5" } }, -}; - -// WebAuthn's ECDSA signatures are DER; WebCrypto's are the two 32-byte halves. -function rawSignature(der) { - let at = 2; - const integer = () => { - if (der[at++] !== 0x02) deny("signature", "The signature is not DER"); - const length = der[at++]; - let value = der.slice(at, (at += length)); - while (value.length > 32 && value[0] === 0) value = value.slice(1); - if (value.length > 32 || at > der.length) deny("signature", "The signature is not DER"); - const out = new Uint8Array(32); - out.set(value, 32 - value.length); - return out; - }; - if (der[0] !== 0x30 || der[1] !== der.length - 2) deny("signature", "The signature is not DER"); - const r = integer(); - const s = integer(); - return new Uint8Array([...r, ...s]); -} +// Prism id itself (identity/prism-id.mjs), published beside the frame and +// named by its SHA-256, which frame/publish.mjs writes here. It is fetched +// when the visitor reaches for the account icon, and checked as the frame +// checks this module. Unpublished (tests, a checkout), it is read from the +// repository. +const PRISM_ID = "/*PRISM_ID*/"; +let prismModule = null; +export const prismId = () => + (prismModule ??= (async () => { + if (!/^[0-9a-f]{64}$/.test(PRISM_ID)) return import("../identity/prism-id.mjs"); + const bytes = await (await fetch(new URL(`${PRISM_ID}/prism-id.mjs`, FRAME_HOST))).arrayBuffer(); + const hex = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (b) => b.toString(16).padStart(2, "0")).join(""); + if (hex !== PRISM_ID) throw new Error("Prism id is not the module this frame names"); + const url = URL.createObjectURL(new Blob([bytes], { type: "text/javascript" })); + try { + return await import(url); + } finally { + URL.revokeObjectURL(url); + } + })().catch((error) => { + prismModule = null; + throw error; + })); -// One WebAuthn assertion: the passkey of record signed message. The six -// checks of PROTOCOL.md, in its order, failing closed. -export async function verifySigned(record, signed, message, origins) { - if (signed?.credential !== record.credential) deny("credential", "The signature is from another passkey"); - let client; +// A session: { app, envelope, records }. The envelope is the id's +// "prism/session/1" action for `app`, naming the session key and its expiry; +// records are the id's log as the signing device knew it. `fresh` is the +// window in which it must be checked after signing (Prism id's actionFresh); +// anyone checking a kept session later checks it as of its own signing +// (fresh: 0), and its expiry bounds it. +export async function verifySession(session, { now = Date.now(), fresh = 60000 } = {}) { + const Prism = await prismId(); + const { app, envelope, records } = session ?? {}; + const body = envelope?.body; + if (typeof app !== "string" || !/^https?:\/\/[^/]+$/.test(app)) deny("app", "The session names no app"); + if (body?.action !== SESSION_ACTION) deny("action", "The signature is not a session"); + const { sessionKey, expires } = body.payload ?? {}; + if (typeof sessionKey !== "string" || !/^[\w-]{87}$/.test(sessionKey)) deny("key", "The session key is malformed"); + if (!Number.isSafeInteger(expires) || expires <= now) deny("expired", "The session has expired"); + if (expires > body.at + MAX_SESSION_MS) deny("expired", "The session lasts too long"); + let log; try { - client = JSON.parse(new TextDecoder().decode(unb64u(signed.clientDataJSON))); - } catch { - deny("client", "The signed client data is not JSON"); + log = await Prism.logFromRecords(records); + } catch (error) { + if (error instanceof Prism.PrismIdError) deny("log", "The log does not parse"); + throw error; + } + const at = fresh ? now : body.at; + let verdict; + try { + 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 (client.type !== "webauthn.get") deny("type", "The signature is not a sign-in"); - if (client.challenge !== b64u(await digest(enc.encode(message)))) deny("challenge", "The signature is for another request"); - const rp = Object.hasOwn(origins, client.origin) ? origins[client.origin] : null; - if (!rp) deny("origin", "The signature was made on another site"); - const data = unb64u(signed.authenticatorData); - if (data.length < 37 || b64u(data.slice(0, 32)) !== b64u(await digest(enc.encode(rp)))) deny("rp", "The passkey belongs to another site"); - if ((data[32] & 0x05) !== 0x05) deny("flags", "The device did not verify its user"); - const algorithm = ALGORITHMS[record.alg] ?? deny("algorithm", "The passkey's algorithm is not ES256 or RS256"); - const key = await crypto.subtle.importKey("spki", unb64u(record.spki), algorithm.key, false, ["verify"]).catch(() => deny("key", "The public key does not parse")); - let signature = unb64u(signed.signature); - if (record.alg === -7) signature = rawSignature(signature); - const body = new Uint8Array([...data, ...(await digest(unb64u(signed.clientDataJSON)))]); - if (!(await crypto.subtle.verify(algorithm.verify, key, signature, body))) deny("signature", "The signature does not verify"); + if (!verdict.allowed) deny(verdict.reason === "scope" ? "scope" : "signature", `The session was refused (${verdict.reason})`); + return { account: body.prism, key: envelope.signer, sessionKey, expires }; } -// A key record, accepted only when its name is its key's hash and it is the -// account's first key or bound to it by a key already accepted. -export async function acceptRecord(credential, records, origins, depth = 0) { - const record = records.find((r) => r?.credential === credential); - if (!record || record.spec !== "prism/identity/key/1") deny("record", "The passkey has no record"); - if (b64u(await digest(unb64u(record.spki))) !== record.key) deny("key", "The record's name is not its key's hash"); - if (record.key === record.account) { - if (record.binding) deny("binding", "An account's first key has no binding"); - return record; - } - 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; +// ---------------------------------------------------------------- this origin's device + +// The device and its view of the id, in this origin's IndexedDB. IndexedDB +// keeps CryptoKeys as they are: a non-extractable key stays one. +function deviceStore(mode, work) { + return new Promise((done, fail) => { + const open = indexedDB.open("prism-id", 1); + open.onupgradeneeded = () => open.result.createObjectStore("prism"); + open.onerror = () => fail(open.error); + open.onsuccess = () => { + const tx = open.result.transaction("prism", mode); + const request = work(tx.objectStore("prism")); + tx.oncomplete = () => (open.result.close(), done(request?.result)); + tx.onerror = () => (open.result.close(), fail(tx.error)); + }; + }); } +export const loadDevice = () => deviceStore("readonly", (s) => s.get("self")).catch(() => null); +const saveDevice = (held) => deviceStore("readwrite", (s) => s.put(held, "self")); +const forgetDevice = () => deviceStore("readwrite", (s) => s.delete("self")); -// A session: the account's passkey let one browser key act for it, on one -// app's origin, until it expires. Anyone holding the session can check it. -export async function verifySession(session, origins, now = Date.now()) { - const { app, nonce, sessionKey, expires, assertion, records } = session ?? {}; - if (!Number.isSafeInteger(expires) || expires <= now) deny("expired", "The session has expired"); - const record = await acceptRecord(assertion?.credential, records ?? [], origins); - await verifySigned(record, assertion, `prism/identity/session/1\n${app}\n${nonce}\n${sessionKey}\n${expires}`, origins); - return { account: record.account, key: record.key, credential: record.credential, expires }; +// The bus to the id's other devices: stitch's relay (the frame's +// PRISM_RELAY), which the page's connect-src must name; the page build reads +// it from the frame. A page that does not admit it keeps the id on this +// device: sign-in and recovery work, linking and syncing wait. +let relay = null; +let relayBus = null; +const relayAdmitted = (origin) => { + const policy = [...document.querySelectorAll('meta[http-equiv="Content-Security-Policy" i]')].map((meta) => meta.content).join(";"); + const connect = /(?:^|;)\s*connect-src([^;]*)/.exec(policy)?.[1] ?? /(?:^|;)\s*default-src([^;]*)/.exec(policy)?.[1]; + return connect === undefined || connect.includes(origin); +}; +const bus = (Prism) => (relayBus ??= Prism.createRelayBus({ relay: relay && relayAdmitted(new URL(relay).origin) ? relay : null })); + +// Share this device's log with the id's other devices, under every boundary +// key it holds, so a device that has not taken up a rotation still hears. +async function share(Prism, held) { + for (const keyId of held.keyring.keys()) await Prism.publishSync(held, bus(Prism), { keyId }).catch(() => {}); +} +// Take in what the other devices shared. A message that does not open or +// resolve is someone else's or stale: it is skipped, never trusted. +async function pull(Prism, held) { + for (const keyId of [...held.keyring.keys()]) { + const topic = await Prism.syncTopic(held, keyId).catch(() => null); + if (!topic) continue; + for (const bytes of await bus(Prism).fetch(topic).catch(() => [])) { + try { + held = await Prism.receiveSync(held, bytes); + } catch (error) { + if (!(error instanceof Prism.PrismIdError) && !(error instanceof DOMException) && !(error instanceof SyntaxError)) throw error; + } + } + } + return held; } +// A recovery kit: the paper share of the id's recovery device (stitch's +// threshold recovery, one share of one) and the id's log. It is as secret as +// the id: whoever holds it can take the id over. +const KIT = "prism/recovery-kit/1"; +const ONE_PAPER_SHARE = { threshold: 1, guardians: [{ paper: true }] }; +const kitOf = (held, share) => ({ kind: KIT, prism: held.prism, share, records: [...held.log.values()] }); + +const json = (value) => new TextEncoder().encode(JSON.stringify(value)); +const parse = (bytes) => JSON.parse(new TextDecoder().decode(bytes)); +const short = (id) => `${id.slice(0, 15)}…${id.slice(-4)}`; +const sentence = (text) => (text ? text[0].toUpperCase() + text.slice(1) + (/[.!?]$/.test(text) ? "" : ".") : text); +const KIND_LABEL = { browser: "Browser", native: "App", mobile: "Phone", embedded: "Device", recovery: "Recovery kit" }; const ACCOUNT_PANEL = `

Sign in

-

One account for every Prism app. No password.

-