diff --git a/CONFORMANCE.md b/CONFORMANCE.md index f8d2704..23ed7ba 100644 --- a/CONFORMANCE.md +++ b/CONFORMANCE.md @@ -31,6 +31,7 @@ model does not sanction. | `FR-01` | `build` | With a working worker, the page loads and verifies the archive only in that worker before using its identities or guest | | `FR-02` | `build` | A returning browser whose worker kept an earlier deploy serves this deploy from the navigation that brings its page | | `FR-03` | `build` | A first visit's bytes are counted once the page has started, the frame's and the app's each within its own budget | +| `FR-04` | `build` | An app's workspace key opens only on a device of the Prism ID that made it, follows the ID when it joins or is recovered, and stays locked on a removed device | ## Cited authorities diff --git a/TEMPLATE-VERIFICATION.md b/TEMPLATE-VERIFICATION.md index cf6517d..ddf53a7 100644 --- a/TEMPLATE-VERIFICATION.md +++ b/TEMPLATE-VERIFICATION.md @@ -417,6 +417,34 @@ and end up with a second account. | `npm run test:identity`, "a click the bar is redrawn under still opens the panel" | the frame before this fix, which opened the panel it was clicked on even after the bar was redrawn (found on holo-search: a first click right after load did nothing) | rejected: `not ok 2`, waiting for `#account-panel:popover-open`; fixed, 21 of 21 pass | | same test, after the account panel became a centred dialog and the button reads "Continue with Windows Hello" | the same branch removed again | rejected: the button read `Create account` where `Continue with Windows Hello` was required; restored, 21 of 21 pass | +## An app's workspace key (FR-04) + +An app that keeps a visitor's work in the browser asks the frame for a +workspace key, `frame.workspaceKey()`: 32 random bytes the frame seals under +the Prism ID's private boundary key (Prism ID's `sealPrivate`) and keeps in +this origin's `prism-id` store, under `workspace`. Only a device of the ID that +made it opens it. Joining an ID from another device, or recovering one from a +kit, reseals it for that ID in the same IndexedDB write that keeps the device +(`carryWorkspace`), so work made before the join is not lost. A removed device +makes a new ID and carries nothing, so the work it kept stays locked: the key +answers `removed`, and `{ replace: true }` starts a new one. After a removal +rotates the boundary key, a member device reseals the key under the new key, +which the removed device does not hold. While an app holds its key, the ID card +reads "Your ID and your work, sealed on your devices". + +`frame_fr_04` (`crates/conformance/tests/frame.rs`) runs `openWorkspace` and +`carryWorkspace` in Node; `npm run test:identity` carries them across two apps +in Chromium (try-page.yml). + +| Gate | Planted defect | Result | +| --- | --- | --- | +| `frame_fr_04` | `openWorkspace` no longer refuses a key kept by another ID (`if (false && kept.prism !== held.prism)`) | rejected: `AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal`, the other ID was answered `stale-key` where `removed` was required; restored, passes | +| `npm run test:identity`, "another app joins the same id" | joining keeps the device without carrying the workspace key (`await keep(Prism, next)`) | rejected: `not ok 5`, the joined app's key answered `removed`; restored, 16 of 16 pass | + +The template's ratchet held: the three popovers in `frame/panels.css` now share +one surface and title rule, and the panel's relay messages parse in one place, +so this change shrinks the counted lines. + ## The workspace page The standard page became the workspace: a header row, the app's surface diff --git a/crates/conformance/tests/frame.rs b/crates/conformance/tests/frame.rs index 2c05219..9f65896 100644 --- a/crates/conformance/tests/frame.rs +++ b/crates/conformance/tests/frame.rs @@ -1,66 +1,75 @@ -//! Executes the production frame regression under Node's isolated VM loader. +//! Executes the production frame regressions under Node. use std::path::PathBuf; use std::process::Command; -#[test] -fn frame_fr_01() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .ancestors() - .nth(2) - .expect("crates/conformance is two below the root") - .to_path_buf(); +/// Runs a Node regression from the repository root and fails with its output unless it passes. +fn node(id: &str, args: &[&str]) { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."); let result = Command::new("node") - .arg("site/worker-gate.mjs") + .args(args) .current_dir(root) .output() - .expect("Node executes the production frame regression"); + .expect("Node runs"); + let (out, err) = ( + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr), + ); assert!( result.status.success(), - "FR-01: {}\n{}", - String::from_utf8_lossy(&result.stdout), - String::from_utf8_lossy(&result.stderr) + "{id}: {out} +{err}" ); } +/// `FR-01`: With a working worker, the page loads and verifies the archive only in that worker before using its identities or guest +#[test] +fn frame_fr_01() { + node("FR-01", &["site/worker-gate.mjs"]); +} + /// `FR-02`: A returning browser whose worker kept an earlier deploy serves this deploy from the navigation that brings its page #[test] fn frame_fr_02() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .ancestors() - .nth(2) - .expect("crates/conformance is two below the root") - .to_path_buf(); - let result = Command::new("node") - .arg("site/sw-gate.mjs") - .current_dir(root) - .output() - .expect("Node executes the production service worker regression"); - assert!( - result.status.success(), - "FR-02: {}\n{}", - String::from_utf8_lossy(&result.stdout), - String::from_utf8_lossy(&result.stderr) - ); + node("FR-02", &["site/sw-gate.mjs"]); } /// `FR-03`: A first visit's bytes are counted once the page has started, the frame's and the app's each within its own budget #[test] fn frame_fr_03() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .ancestors() - .nth(2) - .expect("crates/conformance is two below the root") - .to_path_buf(); - let result = Command::new("node") - .arg("bootstrap/weight-gate.mjs") - .current_dir(root) - .output() - .expect("Node executes the weight gate's regression"); - assert!( - result.status.success(), - "FR-03: {}\n{}", - String::from_utf8_lossy(&result.stdout), - String::from_utf8_lossy(&result.stderr) - ); + node("FR-03", &["bootstrap/weight-gate.mjs"]); +} + +/// `FR-04`: An app's workspace key opens only on a device of the Prism ID that made it, follows the ID when it joins or is recovered, and stays locked on a removed device +/// +/// The decisions run here; the frame's panel carries them across two apps in Chromium in +/// `identity/test.mjs` (try-page.yml). +#[test] +fn frame_fr_04() { + node("FR-04", &["--input-type=module", "-e", WORKSPACE]); } + +const WORKSPACE: &str = r#" +import assert from "node:assert/strict"; +import * as Prism from "./identity/prism-id.mjs"; +import { carryWorkspace, openWorkspace } from "./frame/panels.mjs"; +const id = await Prism.createPrism(); +const made = await openWorkspace(Prism, id, null); +assert.equal(made.key.length, 32); +const again = await openWorkspace(Prism, id, made.record); +assert.deepEqual([again.key, again.record], [made.key, null]); +const other = await Prism.createPrism(); +await assert.rejects(openWorkspace(Prism, other, made.record), { code: "removed" }); +assert.notDeepEqual((await openWorkspace(Prism, other, null)).key, made.key); +const carried = await carryWorkspace(Prism, made.record, id, other); +assert.deepEqual((await openWorkspace(Prism, other, carried)).key, made.key); +assert.equal(await carryWorkspace(Prism, made.record, other, id), null); +const { uri, pending } = await Prism.createLinkOffer(id, { now: Date.now() }); +const offer = Prism.parseLinkUri(uri); +const device = await Prism.createDevice(); +const accepted = await Prism.acceptLinkRequest(id, pending, await Prism.requestLink(device, offer), { now: Date.now(), confirmCode: await Prism.linkCode(offer.secret, device.record) }); +const second = await Prism.completeLink(device, offer, accepted.response); +const rotated = await openWorkspace(Prism, await Prism.revokeDevice(accepted.session, second.device.id), made.record); +assert.deepEqual(rotated.key, made.key); +await assert.rejects(openWorkspace(Prism, second, rotated.record)); +"#; diff --git a/features/suites/frame.feature b/features/suites/frame.feature index b482d1b..6a20da1 100644 --- a/features/suites/frame.feature +++ b/features/suites/frame.feature @@ -49,3 +49,12 @@ Feature: frame And everything else counts as the app's And the frame's bytes, the app's bytes and the requests are each held to their own budget And a blob or data URL is not counted again + + @FR-04 @build + Scenario: An app's workspace key opens only on a device of the Prism ID that made it, follows the ID when it joins or is recovered, and stays locked on a removed device + Given a Prism ID made on this device and the frame's openWorkspace and carryWorkspace + When an app asks for its workspace key, again, from another ID, after joining another ID, and after a removal rotated the ID's key + Then the first request makes 32 random bytes sealed under the ID's private boundary key, and the next opens the same bytes without sealing again + And another ID is refused as removed, and asking for a new key replaces the one it cannot open + And joining or recovering an ID reseals the key for that ID in the same write that keeps the device + And after a rotation a member device reseals the key under the new boundary key, which the removed device cannot open diff --git a/frame/frame.mjs b/frame/frame.mjs index 09178e9..e13aacf 100644 --- a/frame/frame.mjs +++ b/frame/frame.mjs @@ -131,12 +131,14 @@ const firstMove = () => // which publish.mjs writes here. // It is fetched after the first move, checked against that hash as the page // checks the frame, and imported; a failure is tried again the next time. +// Unpublished (a checkout, or an app that bundles its locked copy of the +// frame), it is imported from beside this file, as panels.mjs imports Prism id. const PANELS = "/*PANELS*/"; let panelsModule = null; let panelsSheet = null; const loadPanels = () => (panelsModule ??= (async () => { - if (!/^[0-9a-f]{64}$/.test(PANELS)) throw new Error("this frame was published without its panels"); + if (!/^[0-9a-f]{64}$/.test(PANELS)) return import("./panels.mjs"); const bytes = await (await fetch(new URL(`${PANELS}/prism-panels.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 !== PANELS) throw new Error("the panels module is not the one this frame names"); @@ -846,6 +848,13 @@ class PrismFrame extends Element { return { signature: b64u(signature), delegation: saved.delegation }; } + // This app's workspace key: 32 bytes only a device of the visitor's Prism + // id opens (panels.mjs, openWorkspace). { replace: true } starts a new one. + workspaceKey(options) { + if (!this.accountsReady) return Promise.reject(Object.assign(new Error("A Prism ID cannot work here"), { name: "IdentityError", code: "unsupported" })); + return this.accountsReady().then((accounts) => accounts.workspace(options)); + } + // The Prism id icon, after full screen: a line drawing until the id is // ready, filled once it is. The id is made, and this app's session signed, // with nothing to click and nothing in the way, by the panels module @@ -857,7 +866,7 @@ class PrismFrame extends Element { const button = this.$("account"); const panel = this.$("account-panel"); this.accountWatch?.abort(); - this.accountReady = null; + this.accountReady = this.accountsReady = null; let wired = false; if (typeof panel.showPopover !== "function" || !window.isSecureContext || !globalThis.crypto?.subtle || !globalThis.indexedDB) { button.hidden = true; @@ -891,6 +900,7 @@ class PrismFrame extends Element { } return this.accountReady; }; + this.accountsReady = ready; const reach = () => ready().then((accounts) => accounts.reach(), () => {}); for (const type of ["pointerenter", "focus", "touchstart"]) button.addEventListener(type, reach, { passive: true }); // First use: the visitor's first touch, click or key anywhere makes the id. diff --git a/frame/panels.css b/frame/panels.css index a596c64..02e0587 100644 --- a/frame/panels.css +++ b/frame/panels.css @@ -2,37 +2,37 @@ * suggestions and the theme (its modes, the Unsplash search and the photos). * Loaded with frame/panels.mjs after the visitor's first move, never with the * page; a panel opened before then waits for them. */ -/* The theme panel: three modes side by side, then three photos to set - * behind the page, then the photographer's credit. It opens under the theme - * button (the script sets --theme-top and --theme-right) as share does. */ -.theme-panel { +/* The popovers' common surface and titles. */ +.theme-panel, .trust-panel, .share-panel { position: fixed; - inset: var(--theme-top, 3rem) var(--theme-right, 1rem) auto auto; - width: min(20rem, 100vw - 2rem); - max-height: calc(100vh - var(--theme-top, 3rem) - 1rem); margin: 0; - padding: var(--space-3); overflow: auto; border: var(--border-width) solid var(--border); border-radius: var(--radius); background: var(--popover); color: var(--popover-foreground); box-shadow: var(--shadow-overlay); + transition: opacity var(--duration) var(--ease), transform var(--duration) var(--ease), overlay var(--duration) allow-discrete, display var(--duration) allow-discrete; +} +.theme-panel:not(:popover-open), .trust-panel:not(:popover-open), .share-panel:not(:popover-open) { opacity: 0; transform: translateY(-0.25rem) scale(0.98); } +:host([dark]) :is(.theme-panel, .trust-panel, .share-panel, .account-panel) { box-shadow: none; border-color: var(--border-strong); } +/* The theme panel: three modes side by side, then three photos to set + * behind the page, then the photographer's credit. It opens under the theme + * button (the script sets --theme-top and --theme-right) as share does. */ +.theme-panel { + inset: var(--theme-top, 3rem) var(--theme-right, 1rem) auto auto; + width: min(20rem, 100vw - 2rem); + max-height: calc(100vh - var(--theme-top, 3rem) - 1rem); + padding: var(--space-3); font-size: var(--text-14); scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; transform-origin: top right; - transition: opacity var(--duration) var(--ease), transform var(--duration) var(--ease), overlay var(--duration) allow-discrete, display var(--duration) allow-discrete; } -.theme-panel:not(:popover-open) { opacity: 0; transform: translateY(-0.25rem) scale(0.98); } -:host([dark]) .theme-panel { box-shadow: none; border-color: var(--border-strong); } +.theme-title, .share-title, .trust-title { font-family: var(--font-display); font-weight: 600; font-size: var(--text-16); letter-spacing: var(--tracking-display); } .theme-title { margin: 0 0 var(--space-3); padding: 0 var(--space-1); - font-family: var(--font-display); - font-weight: 600; - font-size: var(--text-16); - letter-spacing: var(--tracking-display); } /* The modes: one slim segmented switch, as a system setting draws it. The * mode in use is a raised chip inside a sunken track; small, fine icons. */ @@ -243,25 +243,14 @@ * opens under the shield (the script sets --trust-top and --trust-left), * lifts in over one beat and closes on Escape or a click outside. */ .trust-panel { - position: fixed; inset: var(--trust-top, 3rem) auto auto var(--trust-left, 1rem); width: min(22rem, 100vw - 2rem); max-height: calc(100vh - var(--trust-top, 3rem) - 1rem); - margin: 0; padding: var(--space-2); - overflow: auto; - border: var(--border-width) solid var(--border); - border-radius: var(--radius); - background: var(--popover); - color: var(--popover-foreground); - box-shadow: var(--shadow-overlay); font-size: var(--text-14); line-height: 1.45; transform-origin: top left; - transition: opacity var(--duration) var(--ease), transform var(--duration) var(--ease), overlay var(--duration) allow-discrete, display var(--duration) allow-discrete; } -.trust-panel:not(:popover-open) { opacity: 0; transform: translateY(-0.25rem) scale(0.98); } -:host([dark]) .trust-panel { box-shadow: none; border-color: var(--border-strong); } .trust-panel p { margin: 0; } .trust-head { @@ -272,7 +261,6 @@ border-bottom: var(--border-width) solid var(--border); } .trust-words { min-width: 0; } -.trust-title { font-family: var(--font-display); font-size: var(--text-16); font-weight: 600; letter-spacing: var(--tracking-display); } .check { display: flex; gap: var(--space-3); padding: var(--space-2); } .check .mark { flex: none; display: grid; place-items: center; width: 1.25rem; height: 1.3125rem; } .check .mark svg { width: 1rem; height: 1rem; fill: none; stroke: currentColor; stroke-width: 1.75; } @@ -327,29 +315,14 @@ * a click outside, and gives focus back to the button. Light ground: the * overlay shadow; dark ground: no shadow, a stronger hairline. */ .share-panel { - position: fixed; inset: var(--share-top, 4rem) var(--share-right, 1rem) auto auto; width: min(23rem, 100vw - 2rem); max-height: calc(100vh - var(--share-top, 4rem) - 1rem); - margin: 0; padding: var(--space-4); - overflow: auto; - border: var(--border-width) solid var(--border); - border-radius: var(--radius); - background: var(--popover); - color: var(--popover-foreground); - box-shadow: var(--shadow-overlay); transform-origin: top right; - transition: opacity var(--duration) var(--ease), transform var(--duration) var(--ease), overlay var(--duration) allow-discrete, display var(--duration) allow-discrete; } -.share-panel:not(:popover-open) { opacity: 0; transform: translateY(-0.25rem) scale(0.98); } -:host([dark]) .share-panel { box-shadow: none; border-color: var(--border-strong); } .share-title { margin: 0 0 var(--space-3); - font-family: var(--font-display); - font-weight: 600; - font-size: var(--text-16); - letter-spacing: var(--tracking-display); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -420,7 +393,6 @@ -webkit-backdrop-filter: blur(1rem); backdrop-filter: blur(1rem); } -:host([dark]) .account-panel { box-shadow: none; border-color: var(--border-strong); } .account-panel p, .account-panel h2 { margin: 0; } .account-close { position: absolute; top: 1rem; right: 1rem; display: grid; place-items: center; width: 2rem; height: 2rem; min-height: 0; padding: 0; border: 0; border-radius: var(--radius-control); background: none; color: var(--muted-foreground); cursor: pointer; } .account-close:hover { background: var(--accent); color: var(--foreground); } diff --git a/frame/panels.mjs b/frame/panels.mjs index 18ebfa5..00b4d57 100644 --- a/frame/panels.mjs +++ b/frame/panels.mjs @@ -450,7 +450,7 @@ function deviceStore(mode, work) { }); } export const loadDevice = () => deviceStore("readonly", (s) => s.get("self")).catch(() => null); -const saveDevice = (held) => deviceStore("readwrite", (s) => s.put(held, "self")); +const saveDevice = (held, workspace) => deviceStore("readwrite", (s) => (workspace && s.put(workspace, "workspace"), s.put(held, "self"))); const forgetDevice = () => deviceStore("readwrite", (s) => s.delete("self")); const loadKit = () => deviceStore("readonly", (s) => s.get("kit")).catch(() => null); const saveKit = (kit) => deviceStore("readwrite", (s) => s.put(kit, "kit")); @@ -461,6 +461,21 @@ const saveGuarding = (list) => deviceStore("readwrite", (s) => s.put(list, "guar // The recovery device this device gave a guardian, so the panel stops offering one. const loadGuarded = () => deviceStore("readonly", (s) => s.get("guarded")).catch(() => null); const saveGuarded = (recovery) => deviceStore("readwrite", (s) => s.put(recovery, "guarded")); +// An app's workspace key: 32 random bytes sealed under the id's private +// boundary key, so only a device of the id that made it opens it. The app +// seals its own records with the key; the frame keeps only the sealed key. +const loadWorkspace = () => deviceStore("readonly", (s) => s.get("workspace")).catch(() => null); +export async function openWorkspace(Prism, held, kept) { + if (kept && kept.prism !== held.prism) deny("removed", "This device was removed from the Prism ID that keeps this work"); + const value = kept ? await Prism.openPrivate(held, kept.sealed) : { key: Prism.toBase64Url(crypto.getRandomValues(new Uint8Array(32))) }; + const boundary = await Prism.currentBoundary(held).catch(() => (kept ? null : deny("stale-key", "This device is waiting for your Prism ID's newest key"))); + const record = boundary && kept?.sealed.key !== boundary.keyId ? { prism: held.prism, sealed: (await Prism.sealPrivate(held, value)).sealed } : null; + return { key: Prism.fromBase64Url(value.key), record }; +} +// Joining or recovering an id carries what the id this browser had kept; a +// removed device makes a new id and carries nothing, so its work stays locked. +export const carryWorkspace = async (Prism, kept, from, to) => + kept && from && kept.prism === from.prism ? { prism: to.prism, sealed: (await Prism.sealPrivate(to, await Prism.openPrivate(from, kept.sealed))).sealed } : null; // 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 @@ -542,12 +557,7 @@ function awaitOn(Prism, topic, kind, accept = () => true, ms = WAIT_MS) { const stop = () => (clearTimeout(timer), unsubscribe()); const found = new Promise((done, failed) => { unsubscribe = bus(Prism).subscribe(topic, (bytes) => { - let message; - try { - message = parse(bytes); - } catch { - return; - } + const message = parse(bytes); if (message?.kind === kind && accept(message)) done(message); }); timer = setTimeout(() => failed(new IdentityError("wait", "The other device did not answer in time. Try again")), ms); @@ -566,7 +576,14 @@ function drawQr(svg, { size, modules }) { } const json = (value) => new TextEncoder().encode(JSON.stringify(value)); -const parse = (bytes) => JSON.parse(new TextDecoder().decode(bytes)); +// A relay message as JSON, or null when it is not. +const parse = (bytes) => { + try { + return JSON.parse(new TextDecoder().decode(bytes)); + } catch { + return null; + } +}; 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" }; @@ -583,7 +600,7 @@ const ACCOUNT_PANEL = `
${glyph(LOCK)}Held only on your devices${glyph(LOCK)}Devices
${row("devices", LAPTOP, "Your devices", "See where your ID is, or remove a device")} @@ -644,7 +661,6 @@ const ACCOUNT_PANEL = ` const TITLES = { held: ["Prism ID", "Every Prism app knows you by this ID. There is no password to remember and no account to make."], - kit: ["Prism ID", "Every Prism app knows you by this ID. There is no password to remember and no account to make."], offer: ["Add a device", ""], join: ["Use an ID you already have", ""], recover: ["Recover with a kit", ""], @@ -668,6 +684,7 @@ export function accounts(frame, core) { let link = null; let guarding = []; let guarded = false; + let working = false; const say = (words) => { frame.$("bar-status").textContent = words; @@ -680,7 +697,7 @@ export function accounts(frame, core) { function paint() { core.paint(); for (const name of ["held", "offer", "join", "recover", "devices", "guard", "guardian", "help"]) $(`view-${name}`).hidden = name !== view; - const [title, sub] = TITLES[view === "held" && kit ? "kit" : view]; + const [title, sub] = TITLES[view]; $("title").textContent = title; $("sub").textContent = sub; $("sub").hidden = !sub; @@ -692,6 +709,7 @@ export function accounts(frame, core) { $("back").hidden = view === "held"; $("id").textContent = held ? short(held.prism) : "Making your Prism ID"; $("id").title = held?.prism ?? ""; + $("held").textContent = working ? "Your ID and your work, sealed on your devices" : "Held only on your devices"; } const show = (next) => { view = next; @@ -721,9 +739,9 @@ export function accounts(frame, core) { frame.$("account").classList.remove("busy"); } }; - const keep = async (Prism, next) => { + const keep = async (Prism, next, workspace) => { held = next; - await saveDevice(held); + await saveDevice(held, workspace); await share(Prism, held); }; @@ -816,12 +834,8 @@ export function accounts(frame, core) { const endLink = () => { link?.stop?.(); link = null; - $("ask").hidden = true; - $("help-check").hidden = true; + for (const id of ["ask", "help-check", "confirm", "accept", "join-code"]) $(id).hidden = true; $("code").value = ""; - $("confirm").hidden = true; - $("accept").hidden = true; - $("join-code").hidden = true; }; $("link").addEventListener("click", () => run(async (Prism) => { @@ -831,16 +845,10 @@ export function accounts(frame, core) { const topic = await Prism.rendezvousTopic(pending.offer.secret); link = { pending, topic, request: null }; link.stop = bus(Prism).subscribe(topic, (bytes) => { - let request; - try { - request = parse(bytes); - } catch { - return; - } + const request = parse(bytes); if (request?.kind !== Prism.KIND.request || !link || link.request) return; link.request = request; - $("confirm").hidden = false; - $("accept").hidden = false; + $("confirm").hidden = $("accept").hidden = false; $("code").focus(); }); $("offer").textContent = uri; @@ -873,12 +881,7 @@ export function accounts(frame, core) { const joined = new Promise((done, failed) => { link = { topic }; link.stop = bus(Prism).subscribe(topic, (bytes) => { - let response; - try { - response = parse(bytes); - } catch { - return; - } + const response = parse(bytes); if (response?.kind !== Prism.KIND.response) return; Prism.completeLink(device, offer, response).then(done, failed); }); @@ -889,7 +892,8 @@ export function accounts(frame, core) { $("join-code").hidden = false; panel.classList.remove("busy"); try { - await keep(Prism, await joined); + const next = await joined; + await keep(Prism, next, await carryWorkspace(Prism, await loadWorkspace(), held, next)); } finally { endLink(); } @@ -944,7 +948,7 @@ export function accounts(frame, core) { const state = await Prism.resolvePrism(synced.prism, log).catch((error) => (error?.code === "fork" ? used() : Promise.reject(error))); const newer = state.active.filter((id) => state.roles[id] === "recovery" && id !== recovered.shares[0].recovery); if (newer.length || !(await Prism.canSign(synced.prism, log, synced.device.id))) used(); - await keep(Prism, synced); + await keep(Prism, synced, await carryWorkspace(Prism, await loadWorkspace(), held, synced)); await holdKit(recovered.shares[0]); await store("readwrite", (s) => s.delete("current")).catch(() => {}); accountChannel.session = null; @@ -1131,8 +1135,19 @@ export function accounts(frame, core) { } }); + // { replace: true } starts a new key, for an app whose device was removed. + const workspace = async ({ replace = false } = {}) => { + const Prism = await prismId(); + await quietly(); + if (!held) deny("unsupported", "There is no Prism ID here yet"); + const { key, record } = await openWorkspace(Prism, held, replace ? null : await loadWorkspace()); + if (record) await saveDevice(held, record); + working = true; + paint(); + return key; + }; reach(); - return { reach }; + return { reach, workspace }; } // The theme panel's contents, which the frame puts in its empty panel. diff --git a/identity/PROTOCOL.md b/identity/PROTOCOL.md index e5b0d24..674b7c3 100644 --- a/identity/PROTOCOL.md +++ b/identity/PROTOCOL.md @@ -136,6 +136,18 @@ topic derived from the prism id alone. `verifySession` passes the relay to a session from a device removed elsewhere is refused even when that device never synced. Making the session and recovery check the same merged log. +## An app's workspace key + +`frame.workspaceKey()` answers 32 bytes an app seals its own records with. The +frame makes them at random on first use, seals them with `sealPrivate` and +keeps `{prism, sealed}` in this origin's `prism-id` store under `workspace`; +the app never stores the key. A later call opens it with `openPrivate`, and +reseals it when the id's boundary key has rotated. Joining an id or recovering +one carries the key from the id this browser had (`carryWorkspace`), in the +same write that keeps the device. A key kept by another id is refused as +`removed`: this device was removed and made a new id. `{replace: true}` makes a +new key, for an app that starts again. + ## Not yet (stitch's to define, its docs/prism-id.md "Open") - Whoever holds a used paper kit (no guardian) can still sign a second diff --git a/identity/README.md b/identity/README.md index c32fbea..7ee0989 100644 --- a/identity/README.md +++ b/identity/README.md @@ -48,6 +48,13 @@ share once. A lost or copied kit alone then brings nothing back. Add the guardian before saving the first kit, and no kit that works alone ever leaves the browser. +## Your work, sealed to your id + +An app can keep a visitor's work sealed to their id: the frame hands it a +key that only the id's devices open, and carries it when this app joins the +id from another device or recovers it. A device removed from the id cannot +open the work it kept. See PROTOCOL.md, "An app's workspace key". + ## Devices **Devices** lists the id's devices. **Remove** is stitch's `revokeDevice`, diff --git a/identity/test.mjs b/identity/test.mjs index 74df6f6..62d68e0 100644 --- a/identity/test.mjs +++ b/identity/test.mjs @@ -146,6 +146,9 @@ describe("the flow in Chromium", () => { let kitPath = null; const account = (p) => p.locator("prism-frame").evaluate((frame) => frame.account); + // The app's workspace key as bytes, or the refusal's code (FR-04). + const workspaceKey = (p, options) => p.locator("prism-frame").evaluate((frame, o) => frame.workspaceKey(o).then((key) => [...key], (error) => error.code), options); + let secondKey = null; const ready = (p) => p.locator("#account.signed-in").waitFor({ timeout: 15000 }); const newContext = async () => { const made = await browser.newContext({ acceptDownloads: true }); @@ -186,7 +189,11 @@ describe("the flow in Chromium", () => { assert.equal(relay.requests, asked); assert.equal(await first.locator("#account-panel").evaluate((panel) => panel.matches(":popover-open")), false); firstId = (await account(first)).id; + const key = await workspaceKey(first); + assert.equal(key.length, 32); + assert.deepEqual(await workspaceKey(first), key); await first.locator("#account").click(); + assert.equal(await first.locator("#account-held").textContent(), "Your ID and your work, sealed on your devices"); assert.equal(await first.locator("#account-title").textContent(), "Prism ID"); assert.equal(await first.getByText(/sign in/i).count(), 0); assert.equal(relay.requests, asked); @@ -236,6 +243,7 @@ describe("the flow in Chromium", () => { }); test("another app joins the same id: a link, then the six-digit code", async () => { + secondKey = await workspaceKey(second); await second.locator("#account").click(); await second.locator("#account-join").click(); // On the first app: a link offer. @@ -258,6 +266,8 @@ describe("the flow in Chromium", () => { await first.locator("#account-accept").click(); await second.waitForFunction((id) => document.querySelector("prism-frame").account?.id === id, firstId, { timeout: 15000 }); assert.notEqual((await account(second)).key, (await account(first)).key); + // The work the second app kept under the id it had now opens under the joined id. + assert.deepEqual(await workspaceKey(second), secondKey); }); test("a removed app hears it on its next load and stops signing for the id", async () => { @@ -275,6 +285,9 @@ describe("the flow in Chromium", () => { await second.reload(); await second.mouse.click(5, 200); await second.waitForFunction((id) => { const a = document.querySelector("prism-frame").account; return a && a.id !== id; }, firstId, { timeout: 15000 }); + // A removed device keeps its work locked, and may start again with a new key. + assert.equal(await workspaceKey(second), "removed"); + assert.notDeepEqual(await workspaceKey(second, { replace: true }), secondKey); }); test("every device lost: the recovery kit brings the id back, and the kit is replaced", async () => { diff --git a/model/ids.toml b/model/ids.toml index 67c4e95..dab14b9 100644 --- a/model/ids.toml +++ b/model/ids.toml @@ -54,3 +54,9 @@ id = "FR-03" level = "build" suite = "frame" statement = "A first visit's bytes are counted once the page has started, the frame's and the app's each within its own budget" + +[[id]] +id = "FR-04" +level = "build" +suite = "frame" +statement = "An app's workspace key opens only on a device of the Prism ID that made it, follows the ID when it joins or is recovered, and stays locked on a removed device"