diff --git a/frame.lock b/frame.lock
index 3295c3d..a66a4a5 100644
--- a/frame.lock
+++ b/frame.lock
@@ -2,8 +2,8 @@
"spec": "prism/frame-lock/1",
"source": {
"repository": "UOR-Foundation/template",
- "commit": "d65a5ff543bf98fc4bbfb4a4e81789767529ab1d",
- "raw": "https://raw.githubusercontent.com/UOR-Foundation/template/d65a5ff543bf98fc4bbfb4a4e81789767529ab1d/"
+ "commit": "892f3ad6ad2b28b0f14e65a966c63b8722f9ef2b",
+ "raw": "https://raw.githubusercontent.com/UOR-Foundation/template/892f3ad6ad2b28b0f14e65a966c63b8722f9ef2b/"
},
"files": [
{
diff --git a/frame/frame.mjs b/frame/frame.mjs
index 7085b64..72eb8c4 100644
--- a/frame/frame.mjs
+++ b/frame/frame.mjs
@@ -765,7 +765,9 @@ class PrismFrame extends Element {
// the panel waits for them rather than open empty.
let ui = null;
const ready = (theme) => {
- if (ui) return;
+ // A render since this one (an attribute changed, as when Holo Search
+ // opens an app) drew a new panel, which its own render wires.
+ if (ui || !panel.isConnected) return;
frame.adoptPanels(theme);
panel.innerHTML = theme.THEME_PANEL;
frame.themed = true;
diff --git a/frame/panels.css b/frame/panels.css
index d60dca9..98005af 100644
--- a/frame/panels.css
+++ b/frame/panels.css
@@ -462,6 +462,8 @@
.account-in { display: grid; gap: 0.382rem; }
.account-id { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); margin-bottom: 0.618rem !important; padding: 0.618rem 1rem; border: var(--border-width) solid var(--border); border-radius: var(--radius-control); background: var(--background); }
.account-id code { font-family: var(--font-mono); color: var(--muted-foreground); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.account-qr { display: block; width: min(100%, 14rem); aspect-ratio: 1; margin: 0 auto 0.618rem; background: #fff; border-radius: var(--radius-control); }
+.account-qr path { fill: #000; }
.account-panel .text { padding: 0; border: 0; background: none; color: var(--foreground); font-weight: 500; text-decoration: underline; text-decoration-color: var(--border-strong); text-underline-offset: 0.2em; cursor: pointer; }
.account-panel .row { justify-content: flex-start; width: 100%; min-height: 2.618rem; padding: 0 1rem; border: 0; border-radius: var(--radius-control); background: none; color: var(--foreground); font-size: 1rem; text-align: start; cursor: pointer; }
.account-panel .row:hover { background: var(--accent); }
diff --git a/frame/panels.mjs b/frame/panels.mjs
index 9836a41..8fee36e 100644
--- a/frame/panels.mjs
+++ b/frame/panels.mjs
@@ -420,7 +420,8 @@ export async function verifySession(session, { now = Date.now(), fresh = 60000 }
const at = fresh ? now : body.at;
let verdict;
try {
- verdict = await Prism.verifyAction(body.prism, log, envelope, { audience: app, now: at, window: fresh || 1 });
+ // With the relay known, also hear removals the signing device did not present (the id's public log).
+ verdict = await Prism.verifyAction(body.prism, log, envelope, { audience: app, now: at, window: fresh || 1, ...(relay ? { bus: bus(Prism) } : {}) });
} catch (error) {
if (error instanceof Prism.PrismIdError) deny("log", `The log does not resolve: ${error.message}`);
throw error;
@@ -464,9 +465,11 @@ const relayAdmitted = (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.
+// key it holds, so a device that has not taken up a rotation still hears,
+// and publish its public records where apps hear removals.
async function share(Prism, held) {
for (const keyId of held.keyring.keys()) await Prism.publishSync(held, bus(Prism), { keyId }).catch(() => {});
+ await Prism.publishLog(held, bus(Prism)).catch(() => {});
}
// Take in what the other devices shared. A message that does not open or
// resolve is someone else's or stale: it is skipped, never trusted.
@@ -474,7 +477,7 @@ 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(() => [])) {
+ for (const bytes of await bus(Prism).retained(topic).catch(() => [])) {
try {
held = await Prism.receiveSync(held, bytes);
} catch (error) {
@@ -484,6 +487,8 @@ async function pull(Prism, held) {
}
return held;
}
+// The id's log as apps see it: this device's, with what the public log holds.
+const heard = (Prism, held) => Prism.heardLog(held.prism, held.log, bus(Prism)).catch(() => held.log);
// A 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
@@ -492,6 +497,16 @@ const KIT = "prism/recovery-kit/1";
const ONE_PAPER_SHARE = { threshold: 1, guardians: [{ paper: true }] };
const kitOf = (held, share) => ({ kind: KIT, prism: held.prism, share, records: [...held.log.values()] });
+// A QR code as one SVG path, with its four-module quiet zone.
+function drawQr(svg, { size, modules }) {
+ let d = "";
+ modules.forEach((row, y) => row.forEach((dark, x) => dark && (d += `M${x + 4} ${y + 4}h1v1h-1z`)));
+ svg.setAttribute("viewBox", `0 0 ${size + 8} ${size + 8}`);
+ const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
+ path.setAttribute("d", d);
+ svg.replaceChildren(path);
+}
+
const json = (value) => new TextEncoder().encode(JSON.stringify(value));
const parse = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
const short = (id) => `${id.slice(0, 15)}…${id.slice(-4)}`;
@@ -522,7 +537,8 @@ const ACCOUNT_PANEL = `
-
On the new device or app, open the person icon, choose Use my Prism id from another device or app, and paste this link. It works once, for five minutes.
+
On a phone, scan this code. On another app or computer, open the person icon, choose Use my Prism id from another device or app, and paste the link. It works once, for five minutes.
+
@@ -634,7 +650,7 @@ export function accounts(frame, core) {
const signIn = async (Prism) => {
held = await pull(Prism, held);
await saveDevice(held);
- if (!(await Prism.canSign(held.prism, held.log, held.device.id))) {
+ if (!(await Prism.canSign(held.prism, await heard(Prism, held), held.device.id))) {
await forgetDevice();
held = null;
return show("removed");
@@ -714,6 +730,7 @@ export function accounts(frame, core) {
});
$("offer").textContent = uri;
$("offer").title = uri;
+ drawQr($("qr"), Prism.linkQr(uri));
show("offer");
}),
);
@@ -782,13 +799,15 @@ export function accounts(frame, core) {
const device = await Prism.createDevice({ deviceClass: "browser", protection: "software" });
const recovered = await Prism.recoverPrism({ prism: saved.prism, records: saved.records, shares: [saved.share], device, rotateRecovery: ONE_PAPER_SHARE });
// The kit's log may be older than the id's: what the other devices
- // shared since shows a kit already used, by the newer recovery device
- // that use made. This refuses here; stitch is to make other devices
- // refuse it too (a used kit replayed against its own old log).
+ // shared since, and the id's public log, show a kit already used, by
+ // the newer recovery device that use made. Any app that hears the
+ // public log sees both recoveries; stitch is to order them (its
+ // docs/prism-id.md, Open).
const synced = await pull(Prism, recovered.session);
- const state = await Prism.resolvePrism(synced.prism, synced.log);
+ const log = await heard(Prism, synced);
+ const state = await Prism.resolvePrism(synced.prism, log);
const newer = state.active.filter((id) => state.roles[id] === "recovery" && id !== recovered.shares[0].recovery);
- if (newer.length || !(await Prism.canSign(synced.prism, synced.log, synced.device.id))) deny("kit", "That recovery kit was already used, and replaced by a newer one");
+ if (newer.length || !(await Prism.canSign(synced.prism, log, synced.device.id))) deny("kit", "That recovery kit was already used, and replaced by a newer one");
await keep(Prism, synced);
showKit(recovered.shares[0], { run: signIn });
}),
diff --git a/frame/unsplash/README.md b/frame/unsplash/README.md
index 0730ef3..58e1b7d 100644
--- a/frame/unsplash/README.md
+++ b/frame/unsplash/README.md
@@ -7,7 +7,7 @@ Unsplash key, so no page carries it; the frame (`frame/frame.mjs`,
| Route | What it does |
| --- | --- |
| `GET /search?q=&page=` | Nine landscape photos; with no words, Unsplash's wallpapers. Cached an hour. |
-| `GET /image?src=&w=[&h=]` | The photo's bytes, resized by Unsplash, cached a month. Any other host is refused. |
+| `GET /image?src=&w=[&h=][&q=<40-95>][&fm=jpg\|webp\|avif]` | The photo's bytes, resized by Unsplash, cached a month. Any other host is refused. Up to 5120 px; a width alone scales without ever enlarging past the original, a height too crops to the box. Quality defaults to 72 (60 for a box), format to jpg. |
| `POST /use?id=` | Unsplash's download event, sent when a visitor sets a photo. |
## Deploy
diff --git a/frame/unsplash/worker.mjs b/frame/unsplash/worker.mjs
index e73ff86..32dee99 100644
--- a/frame/unsplash/worker.mjs
+++ b/frame/unsplash/worker.mjs
@@ -7,7 +7,7 @@
// as data: images on any page. Nothing here is a secret but the key.
//
// GET /search?q=&page= nine landscape photos; no words: wallpapers
-// GET /image?src=&w=[&h=] the photo's bytes
+// GET /image?src=&w=[&h=][&q=<40-95>][&fm=jpg|webp|avif] the photo's bytes
// POST /use?id= Unsplash's download event, when one is chosen
//
// Deploy (frame/unsplash/README.md): wrangler secret put UNSPLASH_ACCESS_KEY,
@@ -24,6 +24,10 @@ const CORS = {
const json = (body, status = 200, headers = {}) =>
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json; charset=utf-8", ...CORS, ...headers } });
+// The widest side a photo is served at: a 5K screen's width, so any screen gets one image pixel per pixel.
+const MAX_SIDE = 5120;
+// The formats Unsplash renders; the caller picks one its browser decodes (jpg when it says nothing).
+const FORMATS = new Set(["jpg", "webp", "avif"]);
const clamp = (text, low, high, fallback) => Math.min(Math.max(Number.parseInt(text ?? "", 10) || fallback, low), high);
// What the frame needs of a photo, and nothing else: it stores this, so the
@@ -84,11 +88,15 @@ async function image(url) {
throw new Failure("src is not a URL", 400);
}
if (source.protocol !== "https:" || source.host !== IMAGES) throw new Failure("src is not an Unsplash image", 400);
- const width = clamp(url.searchParams.get("w"), 16, 2560, 2400);
- const height = url.searchParams.has("h") ? clamp(url.searchParams.get("h"), 16, 2560, 150) : null;
- source.searchParams.set("fm", "jpg");
- source.searchParams.set("fit", "crop");
- source.searchParams.set("q", height ? "60" : "72");
+ const width = clamp(url.searchParams.get("w"), 16, MAX_SIDE, 2400);
+ const height = url.searchParams.has("h") ? clamp(url.searchParams.get("h"), 16, MAX_SIDE, 150) : null;
+ const format = FORMATS.has(url.searchParams.get("fm")) ? url.searchParams.get("fm") : "jpg";
+ const quality = url.searchParams.has("q") ? clamp(url.searchParams.get("q"), 40, 95, 72) : height ? 60 : 72;
+ source.searchParams.set("fm", format);
+ // With a height the photo is cropped to the box (a thumbnail); with a width alone it is scaled, never past
+ // its own size, so asking for a screen wider than the original returns the original's every pixel.
+ source.searchParams.set("fit", height ? "crop" : "max");
+ source.searchParams.set("q", String(quality));
source.searchParams.set("w", String(width));
if (height) source.searchParams.set("h", String(height));
const response = await fetch(source, { cf: { cacheEverything: true, cacheTtl: 2592000 } });
diff --git a/identity/PROTOCOL.md b/identity/PROTOCOL.md
index 875fcf7..5774fe8 100644
--- a/identity/PROTOCOL.md
+++ b/identity/PROTOCOL.md
@@ -61,7 +61,7 @@ with the paper share and the log, downloaded as JSON.
Stitch's out-of-band link, over the relay:
1. Signed-in device: `createLinkOffer`. The panel shows the `prism-link:`
- URI and subscribes to `rendezvousTopic(secret)`.
+ URI and its QR code (`linkQr`), and subscribes to `rendezvousTopic(secret)`.
2. New device: `parseLinkUri`, a new device, then `requestLink`, published on
the rendezvous topic. It shows `linkCode(secret, device)`.
3. The person types those six digits into the first device, which calls
@@ -84,15 +84,20 @@ The panel lists the id's active devices from its log and removes one with
log under every key it holds, so devices that have not taken up the rotation
still hear it.
-## Not yet (stitch's to define)
-
-- A used kit replayed against its own old log: the device it makes is
- refused by the frame that finds the newer recovery, but a device holding
- only the old log accepts it. Stitch's recovery would need to make a
- replaced recovery device's binds void everywhere.
-- A host learns of a removal only from the log the signing device presents.
- A stolen device that never syncs can keep signing, and a session signed
- before a removal lasts until it expires (at most 8 days).
-- The relay holds messages for 30 minutes. A device away longer catches up
- from the next message another device shares.
-- A QR code for the link offer. Today the URI is copied and pasted.
+## Apps hear removals
+
+Every time a device shares (after creating, linking, removing or
+recovering), it also publishes the id's public log with `publishLog`, on a
+topic derived from the prism id alone. `verifySession` passes the relay to
+`verifyAction` (`{bus}`), which merges what that topic holds (`heardLog`), so
+a session from a device removed elsewhere is refused even when that device
+never synced. Sign-in and recovery check the same merged log.
+
+## Not yet (stitch's to define, its docs/prism-id.md "Open")
+
+- A used kit replayed against its own old log forks the recovery chain. Every
+ frame that hears the public log sees both recoveries and refuses the kit;
+ ordering them needs stitch's witnessed time.
+- The relay holds messages for 30 minutes, so an app hears a removal only
+ within 30 minutes of the last publish. A session signed before a removal
+ lasts until it expires (at most 8 days).
diff --git a/identity/README.md b/identity/README.md
index 9e3f4e1..be5276a 100644
--- a/identity/README.md
+++ b/identity/README.md
@@ -13,7 +13,7 @@ the frame.
Each app keeps its own device of the id, in its own origin's storage. To use
the same id in another app, or on a phone:
-1. In an app already signed in, choose **Add a device or app** and copy the link.
+1. In an app already signed in, choose **Add a device or app**. Scan the QR code with a phone, or copy the link.
2. In the new app, choose **Use my Prism id from another device or app** and paste it.
3. The new app shows six digits. Type them into the first app.
@@ -58,14 +58,15 @@ asks, and the visitor's click is the only consent.
A session lasts at most 8 days (the frame asks for 7). A removed device stops
signing new sessions once it syncs, but a session it signed earlier stays
-valid until it expires. An app hears of a removal only from the log the
-signing device presents, so a stolen browser that never syncs can keep
-signing until stitch defines how hosts hear revocations.
+valid until it expires. Every device also publishes the id's public log on
+the relay, and an app checking a session merges it, so a stolen browser that
+never syncs is refused once another device removed it and shared that.
The relay keeps a message for stitch's warm lifetime (30 minutes). A device
-away longer catches up from the next message another device shares. A used
-kit replayed against its own old log is refused here once the newer recovery
-shows up in what the devices shared; stitch is to make every device refuse it.
+away longer, or an app checking later, catches up from the next message a
+device shares. A used kit replayed against its own old log is refused once
+the newer recovery shows up in what the devices shared; stitch is to order
+the two recoveries.
## Run it
diff --git a/identity/prism-id.mjs b/identity/prism-id.mjs
index 74e6e3d..f8c7d42 100644
--- a/identity/prism-id.mjs
+++ b/identity/prism-id.mjs
@@ -1,9 +1,9 @@
-// GENERATED by identity/stitch-sync.mjs from afflom/stitch@e3efc6ee8b7de24db0e33dd17ea1413d02f82ae5. DO NOT EDIT.
+// GENERATED by identity/stitch-sync.mjs from afflom/stitch@7c0ccebfa00e5c09e135901be4c9fad149d1b420. DO NOT EDIT.
// src/prism-id.js, the stitch modules it imports (src/layer1-uor/custody.js, src/layer1-uor/contracts.js, src/layer2-schedulers/policy.js, src/layer5-transport/relay-framing.js),
-// and the 37 model decisions they call (src/layer1-uor/generated-model.js); identity/stitch.lock pins them.
+// and the 39 model decisions they call (src/layer1-uor/generated-model.js); identity/stitch.lock pins them.
// Change Prism id in stitch, then run node identity/stitch-sync.mjs .
const stitch$layer1_uor_generated_model = (() => {
-const definitions = {"Stitch.Budget.reserveAllowed":{"module":"Stitch.Budget","name":"reserveAllowed","params":[{"name":"spent","type":{"kind":"Nat"}},{"name":"reserved","type":{"kind":"Nat"}},{"name":"cost","type":{"kind":"Nat"}},{"name":"limit","type":{"kind":"Nat"}},{"name":"now","type":{"kind":"Nat"}},{"name":"last","type":{"kind":"Nat"}},{"name":"end","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"last"},"right":{"k":"var","name":"now"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"var","name":"now"},"right":{"k":"var","name":"end"}},"right":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"var","name":"spent"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"reserved"},"right":{"k":"var","name":"cost"}}},"right":{"k":"var","name":"limit"}}}}},"Stitch.Budget.settlementAllowed":{"module":"Stitch.Budget","name":"settlementAllowed","params":[{"name":"reserved","type":{"kind":"Nat"}},{"name":"ceiling","type":{"kind":"Nat"}},{"name":"actual","type":{"kind":"Nat"}},{"name":"known","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"known"},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"actual"},"right":{"k":"var","name":"ceiling"}},"right":{"k":"binary","op":"<=?","left":{"k":"var","name":"ceiling"},"right":{"k":"var","name":"reserved"}}}}},"Stitch.PrismId.actionAllowed":{"module":"Stitch.PrismId","name":"actionAllowed","params":[{"name":"linked","type":{"kind":"Bool"}},{"name":"revoked","type":{"kind":"Bool"}},{"name":"delegate","type":{"kind":"Bool"}},{"name":"inScope","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"call","name":"deviceMaySign","args":[{"k":"var","name":"linked"},{"k":"var","name":"revoked"}]},"right":{"k":"call","name":"scopeAdmits","args":[{"k":"var","name":"delegate"},{"k":"var","name":"inScope"}]}}},"Stitch.PrismId.actionFresh":{"module":"Stitch.PrismId","name":"actionFresh","params":[{"name":"audienceMatches","type":{"kind":"Bool"}},{"name":"unseen","type":{"kind":"Bool"}},{"name":"issued","type":{"kind":"Nat"}},{"name":"now","type":{"kind":"Nat"}},{"name":"window","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"call","name":"actionGate","args":[{"k":"var","name":"audienceMatches"},{"k":"var","name":"unseen"},{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"now"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"issued"},"right":{"k":"var","name":"window"}}},"right":{"k":"binary","op":"<=?","left":{"k":"var","name":"issued"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"now"},"right":{"k":"var","name":"window"}}}}]}},"Stitch.PrismId.actionGate":{"module":"Stitch.PrismId","name":"actionGate","params":[{"name":"audienceMatches","type":{"kind":"Bool"}},{"name":"unseen","type":{"kind":"Bool"}},{"name":"inWindow","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"audienceMatches"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"unseen"},"right":{"k":"var","name":"inWindow"}}}},"Stitch.PrismId.attestationBinds":{"module":"Stitch.PrismId","name":"attestationBinds","params":[{"name":"verifiedHardware","type":{"kind":"Bool"}},{"name":"keyMatches","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"verifiedHardware"},"right":{"k":"var","name":"keyMatches"}}},"Stitch.PrismId.bindAllowed":{"module":"Stitch.PrismId","name":"bindAllowed","params":[{"name":"signerLinked","type":{"kind":"Bool"}},{"name":"signerRevoked","type":{"kind":"Bool"}},{"name":"signerDelegate","type":{"kind":"Bool"}},{"name":"signatureValid","type":{"kind":"Bool"}},{"name":"samePrism","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"call","name":"mayAdminister","args":[{"k":"var","name":"signerLinked"},{"k":"var","name":"signerRevoked"},{"k":"var","name":"signerDelegate"}]},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"signatureValid"},"right":{"k":"var","name":"samePrism"}}}},"Stitch.PrismId.boundaryKeyAdmitted":{"module":"Stitch.PrismId","name":"boundaryKeyAdmitted","params":[{"name":"keyEpoch","type":{"kind":"Nat"}},{"name":"requiredEpoch","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"<=?","left":{"k":"var","name":"requiredEpoch"},"right":{"k":"var","name":"keyEpoch"}}},"Stitch.PrismId.boundaryShared":{"module":"Stitch.PrismId","name":"boundaryShared","params":[{"name":"identities","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"<=?","left":{"k":"nat","value":"2"},"right":{"k":"var","name":"identities"}}},"Stitch.PrismId.boundaryVisibleTo":{"module":"Stitch.PrismId","name":"boundaryVisibleTo","params":[{"name":"member","type":{"kind":"Bool"}},{"name":"published","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"var","name":"published"},"right":{"k":"var","name":"member"}}},"Stitch.PrismId.deviceMaySign":{"module":"Stitch.PrismId","name":"deviceMaySign","params":[{"name":"linked","type":{"kind":"Bool"}},{"name":"revoked","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"linked"},"right":{"k":"not","value":{"k":"var","name":"revoked"}}}},"Stitch.PrismId.hostAdmitsDevice":{"module":"Stitch.PrismId","name":"hostAdmitsDevice","params":[{"name":"requiresHardwareKey","type":{"kind":"Bool"}},{"name":"attestedHardwareKey","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"requiresHardwareKey"}},"right":{"k":"var","name":"attestedHardwareKey"}}},"Stitch.PrismId.hybridWrapRequired":{"module":"Stitch.PrismId","name":"hybridWrapRequired","params":[{"name":"recipientHasKem","type":{"kind":"Bool"}},{"name":"wrapHasKem","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"recipientHasKem"}},"right":{"k":"var","name":"wrapHasKem"}}},"Stitch.PrismId.linkGate":{"module":"Stitch.PrismId","name":"linkGate","params":[{"name":"userConfirmed","type":{"kind":"Bool"}},{"name":"alreadyUsed","type":{"kind":"Bool"}},{"name":"secretMatches","type":{"kind":"Bool"}},{"name":"fresh","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"userConfirmed"},"right":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"alreadyUsed"}},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"secretMatches"},"right":{"k":"var","name":"fresh"}}}}},"Stitch.PrismId.linkOfferAccepted":{"module":"Stitch.PrismId","name":"linkOfferAccepted","params":[{"name":"userConfirmed","type":{"kind":"Bool"}},{"name":"alreadyUsed","type":{"kind":"Bool"}},{"name":"secretMatches","type":{"kind":"Bool"}},{"name":"expires","type":{"kind":"Nat"}},{"name":"now","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"call","name":"linkGate","args":[{"k":"var","name":"userConfirmed"},{"k":"var","name":"alreadyUsed"},{"k":"var","name":"secretMatches"},{"k":"binary","op":"","left":{"k":"var","name":"now"},"right":{"k":"var","name":"expires"}}]}},"Stitch.PrismId.mayAdminister":{"module":"Stitch.PrismId","name":"mayAdminister","params":[{"name":"linked","type":{"kind":"Bool"}},{"name":"revoked","type":{"kind":"Bool"}},{"name":"delegate","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"call","name":"deviceMaySign","args":[{"k":"var","name":"linked"},{"k":"var","name":"revoked"}]},"right":{"k":"not","value":{"k":"var","name":"delegate"}}}},"Stitch.PrismId.mayShareBoundary":{"module":"Stitch.PrismId","name":"mayShareBoundary","params":[{"name":"shareable","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"var","name":"shareable"}},"Stitch.PrismId.receivesPrivateBoundary":{"module":"Stitch.PrismId","name":"receivesPrivateBoundary","params":[{"name":"delegate","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"not","value":{"k":"var","name":"delegate"}}},"Stitch.PrismId.recoveryBindAllowed":{"module":"Stitch.PrismId","name":"recoveryBindAllowed","params":[{"name":"signerRecovery","type":{"kind":"Bool"}},{"name":"recoveryExists","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"var","name":"signerRecovery"},"right":{"k":"not","value":{"k":"var","name":"recoveryExists"}}}},"Stitch.PrismId.revocationCounts":{"module":"Stitch.PrismId","name":"revocationCounts","params":[{"name":"signerRecovery","type":{"kind":"Bool"}},{"name":"signerRevokedByRecovery","type":{"kind":"Bool"}},{"name":"targetRecovery","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"signerRevokedByRecovery"}},"right":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"targetRecovery"}},"right":{"k":"var","name":"signerRecovery"}}}},"Stitch.PrismId.scopeAdmits":{"module":"Stitch.PrismId","name":"scopeAdmits","params":[{"name":"delegate","type":{"kind":"Bool"}},{"name":"inScope","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"delegate"}},"right":{"k":"var","name":"inScope"}}},"Stitch.PrismId.thresholdMet":{"module":"Stitch.PrismId","name":"thresholdMet","params":[{"name":"threshold","type":{"kind":"Nat"}},{"name":"collected","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"nat","value":"1"},"right":{"k":"var","name":"threshold"}},"right":{"k":"binary","op":"<=?","left":{"k":"var","name":"threshold"},"right":{"k":"var","name":"collected"}}}},"Stitch.Relay.admissionAllowed":{"module":"Stitch.Relay","name":"admissionAllowed","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"capacity","type":{"kind":"Capacity"}},{"name":"bytes","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"nat","value":"0"},"right":{"k":"var","name":"bytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"bytes"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"entries"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"retainedBytes"},"right":{"k":"var","name":"bytes"}},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"retainedBytes"}},"right":{"k":"binary","op":"","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},"right":{"k":"project","value":{"k":"var","name":"capacity"},"field":"tombstones"}},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"tombstones"}}}}}}},"Stitch.Relay.admitCapacity":{"module":"Stitch.Relay","name":"admitCapacity","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"capacity","type":{"kind":"Capacity"}},{"name":"bytes","type":{"kind":"Nat"}}],"result":{"kind":"Capacity"},"body":{"k":"if","cond":{"k":"call","name":"admissionAllowed","args":[{"k":"var","name":"bounds"},{"k":"var","name":"capacity"},{"k":"var","name":"bytes"}]},"yes":{"k":"record","name":"Capacity","values":{"entries":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},"right":{"k":"nat","value":"1"}},"retainedBytes":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"retainedBytes"},"right":{"k":"var","name":"bytes"}},"tombstones":{"k":"project","value":{"k":"var","name":"capacity"},"field":"tombstones"}}},"no":{"k":"var","name":"capacity"}}},"Stitch.Relay.append":{"module":"Stitch.Relay","name":"append","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"state","type":{"kind":"Assembly"}},{"name":"frame","type":{"kind":"Frame"}},{"name":"now","type":{"kind":"Nat"}},{"name":"duplicate","type":{"kind":"Bool"}}],"result":{"kind":"Assembly"},"body":{"k":"if","cond":{"k":"call","name":"appendAllowed","args":[{"k":"var","name":"bounds"},{"k":"var","name":"state"},{"k":"var","name":"frame"},{"k":"var","name":"now"},{"k":"var","name":"duplicate"}]},"yes":{"k":"record","name":"Assembly","values":{"identity":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"receivedFrames":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"right":{"k":"nat","value":"1"}},"receivedBytes":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"right":{"k":"project","value":{"k":"var","name":"frame"},"field":"payloadBytes"}},"started":{"k":"project","value":{"k":"var","name":"state"},"field":"started"},"last":{"k":"var","name":"now"},"verifying":{"k":"bool","value":false}}},"no":{"k":"var","name":"state"}}},"Stitch.Relay.appendAllowed":{"module":"Stitch.Relay","name":"appendAllowed","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"state","type":{"kind":"Assembly"}},{"name":"frame","type":{"kind":"Frame"}},{"name":"now","type":{"kind":"Nat"}},{"name":"duplicate","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"duplicate"}},"right":{"k":"binary","op":"&&","left":{"k":"call","name":"assemblyCurrent","args":[{"k":"var","name":"bounds"},{"k":"var","name":"state"},{"k":"var","name":"now"}]},"right":{"k":"binary","op":"&&","left":{"k":"call","name":"sameIdentity","args":[{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},{"k":"project","value":{"k":"var","name":"frame"},"field":"identity"}]},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"right":{"k":"nat","value":"1"}},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"frames"}},"right":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"right":{"k":"project","value":{"k":"var","name":"frame"},"field":"payloadBytes"}},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"messageBytes"}}}}}}},"Stitch.Relay.assemblyCurrent":{"module":"Stitch.Relay","name":"assemblyCurrent","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"state","type":{"kind":"Assembly"}},{"name":"now","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"state"},"field":"last"},"right":{"k":"var","name":"now"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"var","name":"now"},"right":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"started"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"assemblyAge"}}},"right":{"k":"not","value":{"k":"project","value":{"k":"var","name":"state"},"field":"verifying"}}}}},"Stitch.Relay.beginVerification":{"module":"Stitch.Relay","name":"beginVerification","params":[{"name":"state","type":{"kind":"Assembly"}}],"result":{"kind":"Assembly"},"body":{"k":"record","name":"Assembly","values":{"identity":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"receivedFrames":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"receivedBytes":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"started":{"k":"project","value":{"k":"var","name":"state"},"field":"started"},"last":{"k":"project","value":{"k":"var","name":"state"},"field":"last"},"verifying":{"k":"call","name":"ready","args":[{"k":"var","name":"state"}]}}}},"Stitch.Relay.deliveryAllowed":{"module":"Stitch.Relay","name":"deliveryAllowed","params":[{"name":"state","type":{"kind":"Assembly"}},{"name":"digestVerified","type":{"kind":"Bool"}},{"name":"utf8Valid","type":{"kind":"Bool"}},{"name":"envelopeValid","type":{"kind":"Bool"}},{"name":"sessionCurrent","type":{"kind":"Bool"}},{"name":"consentCurrent","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"digestVerified"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"utf8Valid"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"envelopeValid"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"sessionCurrent"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"consentCurrent"},"right":{"k":"binary","op":"&&","left":{"k":"project","value":{"k":"var","name":"state"},"field":"verifying"},"right":{"k":"call","name":"ready","args":[{"k":"var","name":"state"}]}}}}}}}},"Stitch.Relay.effectAllowed":{"module":"Stitch.Relay","name":"effectAllowed","params":[{"name":"closed","type":{"kind":"Bool"}},{"name":"currentGeneration","type":{"kind":"Nat"}},{"name":"capturedGeneration","type":{"kind":"Nat"}},{"name":"sessionMatches","type":{"kind":"Bool"}},{"name":"consentCurrent","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"closed"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"var","name":"currentGeneration"},"right":{"k":"var","name":"capturedGeneration"}},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"sessionMatches"},"right":{"k":"var","name":"consentCurrent"}}}}},"Stitch.Relay.frameAllowed":{"module":"Stitch.Relay","name":"frameAllowed","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"frame","type":{"kind":"Frame"}},{"name":"channel","type":{"kind":"Bytes"}},{"name":"purpose","type":{"kind":"Bytes"}},{"name":"wallNow","type":{"kind":"Nat"}},{"name":"lifetime","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"let","name":"identity","type":{"kind":"Identity"},"value":{"k":"project","value":{"k":"var","name":"frame"},"field":"identity"},"body":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"channel"},{"k":"var","name":"channel"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"purpose"},{"k":"var","name":"purpose"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"nat","value":"0"},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"nat","value":"0"},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"frames"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"index"},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"wireBytes"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"wireBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"prim","operation":"multiply","args":[{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},{"k":"nat","value":"1"}],"type":{"kind":"Nat"}},{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}],"type":{"kind":"Nat"}},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"},"right":{"k":"prim","operation":"multiply","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}],"type":{"kind":"Nat"}}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"payloadBytes"},"right":{"k":"if","cond":{"k":"binary","op":"=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"index"},"right":{"k":"nat","value":"1"}},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"}},"yes":{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"},{"k":"prim","operation":"multiply","args":[{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},{"k":"nat","value":"1"}],"type":{"kind":"Nat"}},{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}],"type":{"kind":"Nat"}}],"type":{"kind":"Nat"}},"no":{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"created"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"wallNow"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"futureSkew"}}},"right":{"k":"binary","op":"","left":{"k":"var","name":"wallNow"},"right":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"created"},"right":{"k":"var","name":"lifetime"}}}}}}}}}}}}}}}}},"Stitch.Relay.limits":{"module":"Stitch.Relay","name":"limits","params":[],"result":{"kind":"Limits"},"body":{"k":"record","name":"Limits","values":{"wireBytes":{"k":"nat","value":"4096"},"chunkBytes":{"k":"nat","value":"2700"},"messageBytes":{"k":"nat","value":"524288"},"frames":{"k":"nat","value":"256"},"entries":{"k":"nat","value":"16"},"retainedBytes":{"k":"nat","value":"2097152"},"tombstones":{"k":"nat","value":"256"},"assemblyAge":{"k":"nat","value":"30000"},"futureSkew":{"k":"nat","value":"5000"},"requestTimeout":{"k":"nat","value":"30000"}}}},"Stitch.Relay.ready":{"module":"Stitch.Relay","name":"ready","params":[{"name":"state","type":{"kind":"Assembly"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"frames"}},"right":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"messageBytes"}}}},"Stitch.Relay.release":{"module":"Stitch.Relay","name":"release","params":[{"name":"capacity","type":{"kind":"Capacity"}},{"name":"bytes","type":{"kind":"Nat"}}],"result":{"kind":"Capacity"},"body":{"k":"record","name":"Capacity","values":{"entries":{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},{"k":"nat","value":"1"}],"type":{"kind":"Nat"}},"retainedBytes":{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"capacity"},"field":"retainedBytes"},{"k":"var","name":"bytes"}],"type":{"kind":"Nat"}},"tombstones":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"tombstones"},"right":{"k":"nat","value":"1"}}}}},"Stitch.Relay.sameIdentity":{"module":"Stitch.Relay","name":"sameIdentity","params":[{"name":"left","type":{"kind":"Identity"}},{"name":"right","type":{"kind":"Identity"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"channel"},{"k":"project","value":{"k":"var","name":"right"},"field":"channel"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"session"},{"k":"project","value":{"k":"var","name":"right"},"field":"session"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"digest"},{"k":"project","value":{"k":"var","name":"right"},"field":"digest"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"purpose"},{"k":"project","value":{"k":"var","name":"right"},"field":"purpose"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"left"},"field":"created"},"right":{"k":"project","value":{"k":"var","name":"right"},"field":"created"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"left"},"field":"messageBytes"},"right":{"k":"project","value":{"k":"var","name":"right"},"field":"messageBytes"}},"right":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"left"},"field":"frames"},"right":{"k":"project","value":{"k":"var","name":"right"},"field":"frames"}}}}}}}}},"Stitch.Relay.signalLifetime":{"module":"Stitch.Relay","name":"signalLifetime","params":[],"result":{"kind":"Nat"},"body":{"k":"nat","value":"60000"}},"Stitch.Relay.warmLifetime":{"module":"Stitch.Relay","name":"warmLifetime","params":[],"result":{"kind":"Nat"},"body":{"k":"nat","value":"1800000"}}};
+const definitions = {"Stitch.Budget.reserveAllowed":{"module":"Stitch.Budget","name":"reserveAllowed","params":[{"name":"spent","type":{"kind":"Nat"}},{"name":"reserved","type":{"kind":"Nat"}},{"name":"cost","type":{"kind":"Nat"}},{"name":"limit","type":{"kind":"Nat"}},{"name":"now","type":{"kind":"Nat"}},{"name":"last","type":{"kind":"Nat"}},{"name":"end","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"last"},"right":{"k":"var","name":"now"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"var","name":"now"},"right":{"k":"var","name":"end"}},"right":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"var","name":"spent"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"reserved"},"right":{"k":"var","name":"cost"}}},"right":{"k":"var","name":"limit"}}}}},"Stitch.Budget.settlementAllowed":{"module":"Stitch.Budget","name":"settlementAllowed","params":[{"name":"reserved","type":{"kind":"Nat"}},{"name":"ceiling","type":{"kind":"Nat"}},{"name":"actual","type":{"kind":"Nat"}},{"name":"known","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"known"},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"actual"},"right":{"k":"var","name":"ceiling"}},"right":{"k":"binary","op":"<=?","left":{"k":"var","name":"ceiling"},"right":{"k":"var","name":"reserved"}}}}},"Stitch.PrismId.actionAllowed":{"module":"Stitch.PrismId","name":"actionAllowed","params":[{"name":"linked","type":{"kind":"Bool"}},{"name":"revoked","type":{"kind":"Bool"}},{"name":"delegate","type":{"kind":"Bool"}},{"name":"inScope","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"call","name":"deviceMaySign","args":[{"k":"var","name":"linked"},{"k":"var","name":"revoked"}]},"right":{"k":"call","name":"scopeAdmits","args":[{"k":"var","name":"delegate"},{"k":"var","name":"inScope"}]}}},"Stitch.PrismId.actionFresh":{"module":"Stitch.PrismId","name":"actionFresh","params":[{"name":"audienceMatches","type":{"kind":"Bool"}},{"name":"unseen","type":{"kind":"Bool"}},{"name":"issued","type":{"kind":"Nat"}},{"name":"now","type":{"kind":"Nat"}},{"name":"window","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"call","name":"actionGate","args":[{"k":"var","name":"audienceMatches"},{"k":"var","name":"unseen"},{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"now"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"issued"},"right":{"k":"var","name":"window"}}},"right":{"k":"binary","op":"<=?","left":{"k":"var","name":"issued"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"now"},"right":{"k":"var","name":"window"}}}}]}},"Stitch.PrismId.actionGate":{"module":"Stitch.PrismId","name":"actionGate","params":[{"name":"audienceMatches","type":{"kind":"Bool"}},{"name":"unseen","type":{"kind":"Bool"}},{"name":"inWindow","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"audienceMatches"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"unseen"},"right":{"k":"var","name":"inWindow"}}}},"Stitch.PrismId.attestationBinds":{"module":"Stitch.PrismId","name":"attestationBinds","params":[{"name":"verifiedHardware","type":{"kind":"Bool"}},{"name":"keyMatches","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"verifiedHardware"},"right":{"k":"var","name":"keyMatches"}}},"Stitch.PrismId.bindAllowed":{"module":"Stitch.PrismId","name":"bindAllowed","params":[{"name":"signerLinked","type":{"kind":"Bool"}},{"name":"signerRevoked","type":{"kind":"Bool"}},{"name":"signerDelegate","type":{"kind":"Bool"}},{"name":"signatureValid","type":{"kind":"Bool"}},{"name":"samePrism","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"call","name":"mayAdminister","args":[{"k":"var","name":"signerLinked"},{"k":"var","name":"signerRevoked"},{"k":"var","name":"signerDelegate"}]},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"signatureValid"},"right":{"k":"var","name":"samePrism"}}}},"Stitch.PrismId.boundaryKeyAdmitted":{"module":"Stitch.PrismId","name":"boundaryKeyAdmitted","params":[{"name":"keyEpoch","type":{"kind":"Nat"}},{"name":"requiredEpoch","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"<=?","left":{"k":"var","name":"requiredEpoch"},"right":{"k":"var","name":"keyEpoch"}}},"Stitch.PrismId.boundaryShared":{"module":"Stitch.PrismId","name":"boundaryShared","params":[{"name":"identities","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"<=?","left":{"k":"nat","value":"2"},"right":{"k":"var","name":"identities"}}},"Stitch.PrismId.boundaryVisibleTo":{"module":"Stitch.PrismId","name":"boundaryVisibleTo","params":[{"name":"member","type":{"kind":"Bool"}},{"name":"published","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"var","name":"published"},"right":{"k":"var","name":"member"}}},"Stitch.PrismId.deviceMaySign":{"module":"Stitch.PrismId","name":"deviceMaySign","params":[{"name":"linked","type":{"kind":"Bool"}},{"name":"revoked","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"linked"},"right":{"k":"not","value":{"k":"var","name":"revoked"}}}},"Stitch.PrismId.hostAdmitsDevice":{"module":"Stitch.PrismId","name":"hostAdmitsDevice","params":[{"name":"requiresHardwareKey","type":{"kind":"Bool"}},{"name":"attestedHardwareKey","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"requiresHardwareKey"}},"right":{"k":"var","name":"attestedHardwareKey"}}},"Stitch.PrismId.hybridSignatureAccepted":{"module":"Stitch.PrismId","name":"hybridSignatureAccepted","params":[{"name":"classicalValid","type":{"kind":"Bool"}},{"name":"pqAdvertised","type":{"kind":"Bool"}},{"name":"verifierHasPq","type":{"kind":"Bool"}},{"name":"pqValid","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"classicalValid"},"right":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"binary","op":"&&","left":{"k":"var","name":"pqAdvertised"},"right":{"k":"var","name":"verifierHasPq"}}},"right":{"k":"var","name":"pqValid"}}}},"Stitch.PrismId.hybridWrapRequired":{"module":"Stitch.PrismId","name":"hybridWrapRequired","params":[{"name":"recipientHasKem","type":{"kind":"Bool"}},{"name":"wrapHasKem","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"recipientHasKem"}},"right":{"k":"var","name":"wrapHasKem"}}},"Stitch.PrismId.linkGate":{"module":"Stitch.PrismId","name":"linkGate","params":[{"name":"userConfirmed","type":{"kind":"Bool"}},{"name":"alreadyUsed","type":{"kind":"Bool"}},{"name":"secretMatches","type":{"kind":"Bool"}},{"name":"fresh","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"userConfirmed"},"right":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"alreadyUsed"}},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"secretMatches"},"right":{"k":"var","name":"fresh"}}}}},"Stitch.PrismId.linkOfferAccepted":{"module":"Stitch.PrismId","name":"linkOfferAccepted","params":[{"name":"userConfirmed","type":{"kind":"Bool"}},{"name":"alreadyUsed","type":{"kind":"Bool"}},{"name":"secretMatches","type":{"kind":"Bool"}},{"name":"expires","type":{"kind":"Nat"}},{"name":"now","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"call","name":"linkGate","args":[{"k":"var","name":"userConfirmed"},{"k":"var","name":"alreadyUsed"},{"k":"var","name":"secretMatches"},{"k":"binary","op":"","left":{"k":"var","name":"now"},"right":{"k":"var","name":"expires"}}]}},"Stitch.PrismId.mayAdminister":{"module":"Stitch.PrismId","name":"mayAdminister","params":[{"name":"linked","type":{"kind":"Bool"}},{"name":"revoked","type":{"kind":"Bool"}},{"name":"delegate","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"call","name":"deviceMaySign","args":[{"k":"var","name":"linked"},{"k":"var","name":"revoked"}]},"right":{"k":"not","value":{"k":"var","name":"delegate"}}}},"Stitch.PrismId.mayShareBoundary":{"module":"Stitch.PrismId","name":"mayShareBoundary","params":[{"name":"shareable","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"var","name":"shareable"}},"Stitch.PrismId.presenceSatisfied":{"module":"Stitch.PrismId","name":"presenceSatisfied","params":[{"name":"required","type":{"kind":"Bool"}},{"name":"userPresent","type":{"kind":"Bool"}},{"name":"userVerified","type":{"kind":"Bool"}},{"name":"challengeMatches","type":{"kind":"Bool"}},{"name":"assertionValid","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"required"}},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"userPresent"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"userVerified"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"challengeMatches"},"right":{"k":"var","name":"assertionValid"}}}}}},"Stitch.PrismId.receivesPrivateBoundary":{"module":"Stitch.PrismId","name":"receivesPrivateBoundary","params":[{"name":"delegate","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"not","value":{"k":"var","name":"delegate"}}},"Stitch.PrismId.recoveryBindAllowed":{"module":"Stitch.PrismId","name":"recoveryBindAllowed","params":[{"name":"signerRecovery","type":{"kind":"Bool"}},{"name":"recoveryExists","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"var","name":"signerRecovery"},"right":{"k":"not","value":{"k":"var","name":"recoveryExists"}}}},"Stitch.PrismId.revocationCounts":{"module":"Stitch.PrismId","name":"revocationCounts","params":[{"name":"signerRecovery","type":{"kind":"Bool"}},{"name":"signerRevokedByRecovery","type":{"kind":"Bool"}},{"name":"targetRecovery","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"signerRevokedByRecovery"}},"right":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"targetRecovery"}},"right":{"k":"var","name":"signerRecovery"}}}},"Stitch.PrismId.scopeAdmits":{"module":"Stitch.PrismId","name":"scopeAdmits","params":[{"name":"delegate","type":{"kind":"Bool"}},{"name":"inScope","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"||","left":{"k":"not","value":{"k":"var","name":"delegate"}},"right":{"k":"var","name":"inScope"}}},"Stitch.PrismId.thresholdMet":{"module":"Stitch.PrismId","name":"thresholdMet","params":[{"name":"threshold","type":{"kind":"Nat"}},{"name":"collected","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"nat","value":"1"},"right":{"k":"var","name":"threshold"}},"right":{"k":"binary","op":"<=?","left":{"k":"var","name":"threshold"},"right":{"k":"var","name":"collected"}}}},"Stitch.Relay.admissionAllowed":{"module":"Stitch.Relay","name":"admissionAllowed","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"capacity","type":{"kind":"Capacity"}},{"name":"bytes","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"nat","value":"0"},"right":{"k":"var","name":"bytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"var","name":"bytes"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"entries"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"retainedBytes"},"right":{"k":"var","name":"bytes"}},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"retainedBytes"}},"right":{"k":"binary","op":"","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},"right":{"k":"project","value":{"k":"var","name":"capacity"},"field":"tombstones"}},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"tombstones"}}}}}}},"Stitch.Relay.admitCapacity":{"module":"Stitch.Relay","name":"admitCapacity","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"capacity","type":{"kind":"Capacity"}},{"name":"bytes","type":{"kind":"Nat"}}],"result":{"kind":"Capacity"},"body":{"k":"if","cond":{"k":"call","name":"admissionAllowed","args":[{"k":"var","name":"bounds"},{"k":"var","name":"capacity"},{"k":"var","name":"bytes"}]},"yes":{"k":"record","name":"Capacity","values":{"entries":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},"right":{"k":"nat","value":"1"}},"retainedBytes":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"retainedBytes"},"right":{"k":"var","name":"bytes"}},"tombstones":{"k":"project","value":{"k":"var","name":"capacity"},"field":"tombstones"}}},"no":{"k":"var","name":"capacity"}}},"Stitch.Relay.append":{"module":"Stitch.Relay","name":"append","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"state","type":{"kind":"Assembly"}},{"name":"frame","type":{"kind":"Frame"}},{"name":"now","type":{"kind":"Nat"}},{"name":"duplicate","type":{"kind":"Bool"}}],"result":{"kind":"Assembly"},"body":{"k":"if","cond":{"k":"call","name":"appendAllowed","args":[{"k":"var","name":"bounds"},{"k":"var","name":"state"},{"k":"var","name":"frame"},{"k":"var","name":"now"},{"k":"var","name":"duplicate"}]},"yes":{"k":"record","name":"Assembly","values":{"identity":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"receivedFrames":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"right":{"k":"nat","value":"1"}},"receivedBytes":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"right":{"k":"project","value":{"k":"var","name":"frame"},"field":"payloadBytes"}},"started":{"k":"project","value":{"k":"var","name":"state"},"field":"started"},"last":{"k":"var","name":"now"},"verifying":{"k":"bool","value":false}}},"no":{"k":"var","name":"state"}}},"Stitch.Relay.appendAllowed":{"module":"Stitch.Relay","name":"appendAllowed","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"state","type":{"kind":"Assembly"}},{"name":"frame","type":{"kind":"Frame"}},{"name":"now","type":{"kind":"Nat"}},{"name":"duplicate","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"duplicate"}},"right":{"k":"binary","op":"&&","left":{"k":"call","name":"assemblyCurrent","args":[{"k":"var","name":"bounds"},{"k":"var","name":"state"},{"k":"var","name":"now"}]},"right":{"k":"binary","op":"&&","left":{"k":"call","name":"sameIdentity","args":[{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},{"k":"project","value":{"k":"var","name":"frame"},"field":"identity"}]},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"right":{"k":"nat","value":"1"}},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"frames"}},"right":{"k":"binary","op":"<=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"right":{"k":"project","value":{"k":"var","name":"frame"},"field":"payloadBytes"}},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"messageBytes"}}}}}}},"Stitch.Relay.assemblyCurrent":{"module":"Stitch.Relay","name":"assemblyCurrent","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"state","type":{"kind":"Assembly"}},{"name":"now","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"state"},"field":"last"},"right":{"k":"var","name":"now"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"var","name":"now"},"right":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"state"},"field":"started"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"assemblyAge"}}},"right":{"k":"not","value":{"k":"project","value":{"k":"var","name":"state"},"field":"verifying"}}}}},"Stitch.Relay.beginVerification":{"module":"Stitch.Relay","name":"beginVerification","params":[{"name":"state","type":{"kind":"Assembly"}}],"result":{"kind":"Assembly"},"body":{"k":"record","name":"Assembly","values":{"identity":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"receivedFrames":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"receivedBytes":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"started":{"k":"project","value":{"k":"var","name":"state"},"field":"started"},"last":{"k":"project","value":{"k":"var","name":"state"},"field":"last"},"verifying":{"k":"call","name":"ready","args":[{"k":"var","name":"state"}]}}}},"Stitch.Relay.deliveryAllowed":{"module":"Stitch.Relay","name":"deliveryAllowed","params":[{"name":"state","type":{"kind":"Assembly"}},{"name":"digestVerified","type":{"kind":"Bool"}},{"name":"utf8Valid","type":{"kind":"Bool"}},{"name":"envelopeValid","type":{"kind":"Bool"}},{"name":"sessionCurrent","type":{"kind":"Bool"}},{"name":"consentCurrent","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"var","name":"digestVerified"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"utf8Valid"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"envelopeValid"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"sessionCurrent"},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"consentCurrent"},"right":{"k":"binary","op":"&&","left":{"k":"project","value":{"k":"var","name":"state"},"field":"verifying"},"right":{"k":"call","name":"ready","args":[{"k":"var","name":"state"}]}}}}}}}},"Stitch.Relay.effectAllowed":{"module":"Stitch.Relay","name":"effectAllowed","params":[{"name":"closed","type":{"kind":"Bool"}},{"name":"currentGeneration","type":{"kind":"Nat"}},{"name":"capturedGeneration","type":{"kind":"Nat"}},{"name":"sessionMatches","type":{"kind":"Bool"}},{"name":"consentCurrent","type":{"kind":"Bool"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"not","value":{"k":"var","name":"closed"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"var","name":"currentGeneration"},"right":{"k":"var","name":"capturedGeneration"}},"right":{"k":"binary","op":"&&","left":{"k":"var","name":"sessionMatches"},"right":{"k":"var","name":"consentCurrent"}}}}},"Stitch.Relay.frameAllowed":{"module":"Stitch.Relay","name":"frameAllowed","params":[{"name":"bounds","type":{"kind":"Limits"}},{"name":"frame","type":{"kind":"Frame"}},{"name":"channel","type":{"kind":"Bytes"}},{"name":"purpose","type":{"kind":"Bytes"}},{"name":"wallNow","type":{"kind":"Nat"}},{"name":"lifetime","type":{"kind":"Nat"}}],"result":{"kind":"Bool"},"body":{"k":"let","name":"identity","type":{"kind":"Identity"},"value":{"k":"project","value":{"k":"var","name":"frame"},"field":"identity"},"body":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"channel"},{"k":"var","name":"channel"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"purpose"},{"k":"var","name":"purpose"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"nat","value":"0"},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"nat","value":"0"},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"frames"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"index"},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"wireBytes"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"wireBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"","left":{"k":"prim","operation":"multiply","args":[{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},{"k":"nat","value":"1"}],"type":{"kind":"Nat"}},{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}],"type":{"kind":"Nat"}},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"},"right":{"k":"prim","operation":"multiply","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}],"type":{"kind":"Nat"}}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"payloadBytes"},"right":{"k":"if","cond":{"k":"binary","op":"=?","left":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"frame"},"field":"index"},"right":{"k":"nat","value":"1"}},"right":{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"}},"yes":{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"messageBytes"},{"k":"prim","operation":"multiply","args":[{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"identity"},"field":"frames"},{"k":"nat","value":"1"}],"type":{"kind":"Nat"}},{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}],"type":{"kind":"Nat"}}],"type":{"kind":"Nat"}},"no":{"k":"project","value":{"k":"var","name":"bounds"},"field":"chunkBytes"}}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"<=?","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"created"},"right":{"k":"binary","op":"+","left":{"k":"var","name":"wallNow"},"right":{"k":"project","value":{"k":"var","name":"bounds"},"field":"futureSkew"}}},"right":{"k":"binary","op":"","left":{"k":"var","name":"wallNow"},"right":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"identity"},"field":"created"},"right":{"k":"var","name":"lifetime"}}}}}}}}}}}}}}}}},"Stitch.Relay.limits":{"module":"Stitch.Relay","name":"limits","params":[],"result":{"kind":"Limits"},"body":{"k":"record","name":"Limits","values":{"wireBytes":{"k":"nat","value":"4096"},"chunkBytes":{"k":"nat","value":"2700"},"messageBytes":{"k":"nat","value":"524288"},"frames":{"k":"nat","value":"256"},"entries":{"k":"nat","value":"16"},"retainedBytes":{"k":"nat","value":"2097152"},"tombstones":{"k":"nat","value":"256"},"assemblyAge":{"k":"nat","value":"30000"},"futureSkew":{"k":"nat","value":"5000"},"requestTimeout":{"k":"nat","value":"30000"}}}},"Stitch.Relay.ready":{"module":"Stitch.Relay","name":"ready","params":[{"name":"state","type":{"kind":"Assembly"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedFrames"},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"frames"}},"right":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"state"},"field":"receivedBytes"},"right":{"k":"project","value":{"k":"project","value":{"k":"var","name":"state"},"field":"identity"},"field":"messageBytes"}}}},"Stitch.Relay.release":{"module":"Stitch.Relay","name":"release","params":[{"name":"capacity","type":{"kind":"Capacity"}},{"name":"bytes","type":{"kind":"Nat"}}],"result":{"kind":"Capacity"},"body":{"k":"record","name":"Capacity","values":{"entries":{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"capacity"},"field":"entries"},{"k":"nat","value":"1"}],"type":{"kind":"Nat"}},"retainedBytes":{"k":"prim","operation":"subtract","args":[{"k":"project","value":{"k":"var","name":"capacity"},"field":"retainedBytes"},{"k":"var","name":"bytes"}],"type":{"kind":"Nat"}},"tombstones":{"k":"binary","op":"+","left":{"k":"project","value":{"k":"var","name":"capacity"},"field":"tombstones"},"right":{"k":"nat","value":"1"}}}}},"Stitch.Relay.sameIdentity":{"module":"Stitch.Relay","name":"sameIdentity","params":[{"name":"left","type":{"kind":"Identity"}},{"name":"right","type":{"kind":"Identity"}}],"result":{"kind":"Bool"},"body":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"channel"},{"k":"project","value":{"k":"var","name":"right"},"field":"channel"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"session"},{"k":"project","value":{"k":"var","name":"right"},"field":"session"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"digest"},{"k":"project","value":{"k":"var","name":"right"},"field":"digest"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"prim","operation":"equal","args":[{"k":"project","value":{"k":"var","name":"left"},"field":"purpose"},{"k":"project","value":{"k":"var","name":"right"},"field":"purpose"}],"type":{"kind":"Bool"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"left"},"field":"created"},"right":{"k":"project","value":{"k":"var","name":"right"},"field":"created"}},"right":{"k":"binary","op":"&&","left":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"left"},"field":"messageBytes"},"right":{"k":"project","value":{"k":"var","name":"right"},"field":"messageBytes"}},"right":{"k":"binary","op":"=?","left":{"k":"project","value":{"k":"var","name":"left"},"field":"frames"},"right":{"k":"project","value":{"k":"var","name":"right"},"field":"frames"}}}}}}}}},"Stitch.Relay.signalLifetime":{"module":"Stitch.Relay","name":"signalLifetime","params":[],"result":{"kind":"Nat"},"body":{"k":"nat","value":"60000"}},"Stitch.Relay.warmLifetime":{"module":"Stitch.Relay","name":"warmLifetime","params":[],"result":{"kind":"Nat"},"body":{"k":"nat","value":"1800000"}}};
const types = {"Stitch.Relay.Assembly":{"kind":"structure","fields":[{"name":"identity","type":{"kind":"Identity"}},{"name":"receivedFrames","type":{"kind":"Nat"}},{"name":"receivedBytes","type":{"kind":"Nat"}},{"name":"started","type":{"kind":"Nat"}},{"name":"last","type":{"kind":"Nat"}},{"name":"verifying","type":{"kind":"Bool"}}]},"Stitch.Relay.Capacity":{"kind":"structure","fields":[{"name":"entries","type":{"kind":"Nat"}},{"name":"retainedBytes","type":{"kind":"Nat"}},{"name":"tombstones","type":{"kind":"Nat"}}]},"Stitch.Relay.Frame":{"kind":"structure","fields":[{"name":"identity","type":{"kind":"Identity"}},{"name":"index","type":{"kind":"Nat"}},{"name":"payloadBytes","type":{"kind":"Nat"}},{"name":"wireBytes","type":{"kind":"Nat"}}]},"Stitch.Relay.Identity":{"kind":"structure","fields":[{"name":"channel","type":{"kind":"Bytes"}},{"name":"session","type":{"kind":"Bytes"}},{"name":"digest","type":{"kind":"Bytes"}},{"name":"purpose","type":{"kind":"Bytes"}},{"name":"created","type":{"kind":"Nat"}},{"name":"messageBytes","type":{"kind":"Nat"}},{"name":"frames","type":{"kind":"Nat"}}]},"Stitch.Relay.Limits":{"kind":"structure","fields":[{"name":"wireBytes","type":{"kind":"Nat"}},{"name":"chunkBytes","type":{"kind":"Nat"}},{"name":"messageBytes","type":{"kind":"Nat"}},{"name":"frames","type":{"kind":"Nat"}},{"name":"entries","type":{"kind":"Nat"}},{"name":"retainedBytes","type":{"kind":"Nat"}},{"name":"tombstones","type":{"kind":"Nat"}},{"name":"assemblyAge","type":{"kind":"Nat"}},{"name":"futureSkew","type":{"kind":"Nat"}},{"name":"requestTimeout","type":{"kind":"Nat"}}]}};
const qualify = (module, name) => name.includes('::') ? name.replace('::','.') : module+'.'+name;
function natural(value) {
@@ -876,7 +876,9 @@ return { RELAY_LIMITS, RELAY_LIFETIMES, RELAY_EVENT_BYTES, relayCapacity, relayA
* Only P-256 ECDSA/ECDH, HKDF-SHA-256, HMAC-SHA-256, AES-256-GCM and SHA-256
* are required, so native, mobile (Secure Enclave, Android Keystore), TPM 2.0
* and secure-element devices can implement the same protocol. Where the
- * platform has ML-KEM-768, every key wrap is hybrid (ECDH + ML-KEM).
+ * platform has ML-KEM-768, every key wrap is hybrid (ECDH + ML-KEM); where it
+ * has ML-DSA-65, every record is also signed with ML-DSA. Actions a host marks
+ * as needing the person's approval carry a WebAuthn user-verified assertion.
* See docs/prism-id.md and docs/prism-id-threat-model.md.
*/
const { model } = stitch$layer1_uor_generated_model;
@@ -906,7 +908,9 @@ export const KIND = Object.freeze({
recoveryShare: 'prism/recovery-share/1',
persona: 'prism/persona/1',
personaKey: 'prism/persona-key/1',
- personaRecovery: 'prism/persona-recovery/1'
+ personaRecovery: 'prism/persona-recovery/1',
+ cover: 'prism/cover/1',
+ publicLog: 'prism/public-log/1'
});
/** Kinds of device that take part. Every one uses the same records and primitives. */
@@ -1005,6 +1009,8 @@ const SIGN_HASH = { name: 'ECDSA', hash: 'SHA-256' };
const AGREE = { name: 'ECDH', namedCurve: 'P-256' };
const KEM = { name: 'ML-KEM-768' };
const KEM_PUBLIC_BYTES = 1184;
+const PQSIGN = { name: 'ML-DSA-65' };
+const PQSIGN_PUBLIC_BYTES = 1952;
const publicJwk = ({ kty, crv, x, y }) => ({ crv, kty, x, y });
let kemSupport;
@@ -1017,14 +1023,25 @@ export async function postQuantumAvailable() {
return kemSupport;
}
+let pqSignSupport;
+/** Whether this platform offers ML-DSA-65 (FIPS 204) in WebCrypto. */
+export async function postQuantumSignaturesAvailable() {
+ if (pqSignSupport === undefined) {
+ try { await subtle.generateKey(PQSIGN, false, ['sign', 'verify']); pqSignSupport = true; }
+ catch { pqSignSupport = false; }
+ }
+ return pqSignSupport;
+}
+
async function newKeys(extractable) {
const signing = await subtle.generateKey(SIGN, extractable, ['sign', 'verify']);
const agreement = await subtle.generateKey(AGREE, extractable, ['deriveBits']);
const kem = await postQuantumAvailable() ? await subtle.generateKey(KEM, extractable, ['encapsulateBits', 'decapsulateBits']) : null;
- return { signing, agreement, kem };
+ const pqsign = await postQuantumSignaturesAvailable() ? await subtle.generateKey(PQSIGN, extractable, ['sign', 'verify']) : null;
+ return { signing, agreement, kem, pqsign };
}
-async function deviceFromKeys({ signing, agreement, kem }, deviceClass, protection) {
+async function deviceFromKeys({ signing, agreement, kem, pqsign }, deviceClass, protection, presence) {
const record = {
kind: KIND.device,
class: deviceClass,
@@ -1033,42 +1050,94 @@ async function deviceFromKeys({ signing, agreement, kem }, deviceClass, protecti
agree: publicJwk(await subtle.exportKey('jwk', agreement.publicKey))
};
if (kem) record.kem = toBase64Url(await subtle.exportKey('raw-public', kem.publicKey));
- return Object.freeze({ id: await kappa(record), record, signingKey: signing.privateKey, agreementKey: agreement.privateKey, kemKey: kem?.privateKey ?? null });
+ if (pqsign) record.pqsign = toBase64Url(await subtle.exportKey('raw-public', pqsign.publicKey));
+ if (presence) record.presence = presence;
+ return Object.freeze({ id: await kappa(record), record, signingKey: signing.privateKey, agreementKey: agreement.privateKey,
+ kemKey: kem?.privateKey ?? null, pqSigningKey: pqsign?.privateKey ?? null });
}
/**
* A device holds non-extractable private keys: one signs prism records, one
* agrees keys for wrapping, and where the platform has it an ML-KEM-768 key
- * makes every wrap to this device hybrid. Only its public record leaves the
- * device. `deviceClass` and `protection` are claims the device makes about itself.
+ * makes every wrap to this device hybrid, and where it has ML-DSA-65 every
+ * record this device signs carries a second, post-quantum signature. Only its
+ * public record leaves the device. `deviceClass` and `protection` are claims
+ * the device makes about itself.
+ *
+ * `presence` binds a WebAuthn credential (a passkey) to the device:
+ * `{ rp, origin, key }` with the credential's P-256 public key as a JWK. A
+ * host can then require that an action carry an assertion the person made
+ * with user verification (see signAction). WebAuthn credentials are scoped to
+ * one relying party, so use one per persona.
*/
-export async function createDevice({ deviceClass = 'browser', protection = 'software' } = {}) {
+export async function createDevice({ deviceClass = 'browser', protection = 'software', presence } = {}) {
if (!DEVICE_CLASSES.includes(deviceClass) || deviceClass === 'recovery') refuse('device', `unknown device class ${deviceClass}`);
if (!KEY_PROTECTION.includes(protection) || protection === 'threshold-shares') refuse('device', `unknown key protection ${protection}`);
- return deviceFromKeys(await newKeys(false), deviceClass, protection);
+ if (presence !== undefined) checkPresenceBinding(presence);
+ return deviceFromKeys(await newKeys(false), deviceClass, protection, presence === undefined ? undefined : { rp: presence.rp, origin: presence.origin, key: publicJwk(presence.key) });
}
const okKey = k => k && k.kty === 'EC' && k.crv === 'P-256' && typeof k.x === 'string' && typeof k.y === 'string' && Object.keys(k).length === 4;
+function checkPresenceBinding(presence) {
+ const key = presence?.key && publicJwk(presence.key);
+ if (!presence || typeof presence.rp !== 'string' || !presence.rp || typeof presence.origin !== 'string' || !presence.origin.startsWith('https://') || !okKey(key))
+ refuse('device', 'presence must name rp, an https origin and a P-256 credential key');
+}
+
+const OPTIONAL_DEVICE_FIELDS = Object.freeze({
+ kem: v => fromBase64Url(v).length === KEM_PUBLIC_BYTES,
+ pqsign: v => fromBase64Url(v).length === PQSIGN_PUBLIC_BYTES,
+ presence: v => { checkPresenceBinding(v); return Object.keys(v).length === 3 && Object.keys(v.key).length === 4; }
+});
+
export function checkDeviceRecord(record) {
- const keys = record ? Object.keys(record).length : 0;
- const kemOk = record?.kem === undefined ? keys === 5 : keys === 6 && fromBase64Url(record.kem).length === KEM_PUBLIC_BYTES;
- if (!record || record.kind !== KIND.device || !kemOk || !DEVICE_CLASSES.includes(record.class) ||
- !KEY_PROTECTION.includes(record.protection) || !okKey(record.sign) || !okKey(record.agree)) refuse('device', 'malformed device record');
+ const ok = () => {
+ if (!record || typeof record !== 'object' || record.kind !== KIND.device || !DEVICE_CLASSES.includes(record.class) ||
+ !KEY_PROTECTION.includes(record.protection) || !okKey(record.sign) || !okKey(record.agree)) return false;
+ for (const key of Object.keys(record)) {
+ if (['kind', 'class', 'protection', 'sign', 'agree'].includes(key)) continue;
+ if (!OPTIONAL_DEVICE_FIELDS[key] || typeof record[key] !== (key === 'presence' ? 'object' : 'string') || !OPTIONAL_DEVICE_FIELDS[key](record[key])) return false;
+ }
+ return true;
+ };
+ let valid;
+ try { valid = ok(); } catch (error) { if (!(error instanceof PrismIdError)) throw error; valid = false; }
+ if (!valid) refuse('device', 'malformed device record');
return record;
}
async function signRecord(device, body) {
- const signature = await subtle.sign(SIGN_HASH, device.signingKey, canonicalBytes(body));
- return { body, signer: device.id, signature: toBase64Url(signature) };
+ const bytes = canonicalBytes(body);
+ const envelope = { body, signer: device.id, signature: toBase64Url(await subtle.sign(SIGN_HASH, device.signingKey, bytes)) };
+ if (device.pqSigningKey) envelope.pqsignature = toBase64Url(await subtle.sign(PQSIGN, device.pqSigningKey, bytes));
+ return envelope;
}
-async function signatureValid(envelope, deviceRecord) {
+/**
+ * Hybrid signature check (Stitch.PrismId.hybridSignatureAccepted). The P-256
+ * signature must always verify. When the signer advertises an ML-DSA-65 key
+ * and this verifier has ML-DSA, the ML-DSA signature must verify too, so
+ * stripping it is refused. A verifier without ML-DSA checks P-256 alone; a
+ * host that must resist a quantum forger refuses such verifiers with
+ * `{ requirePostQuantum: true }`.
+ */
+async function signatureValid(envelope, deviceRecord, { requirePostQuantum = false } = {}) {
try {
checkDeviceRecord(deviceRecord);
if (await kappa(deviceRecord) !== envelope.signer) return false;
+ const bytes = canonicalBytes(envelope.body);
const key = await subtle.importKey('jwk', { ...deviceRecord.sign, ext: true }, SIGN, false, ['verify']);
- return await subtle.verify(SIGN_HASH, key, fromBase64Url(envelope.signature), canonicalBytes(envelope.body));
+ const classical = await subtle.verify(SIGN_HASH, key, fromBase64Url(envelope.signature), bytes);
+ const advertised = typeof deviceRecord.pqsign === 'string';
+ const verifierHasPq = await postQuantumSignaturesAvailable();
+ if (requirePostQuantum && !(advertised && verifierHasPq)) return false;
+ let pq = false;
+ if (advertised && verifierHasPq && typeof envelope.pqsignature === 'string') {
+ const pqKey = await subtle.importKey('raw-public', fromBase64Url(deviceRecord.pqsign), PQSIGN, false, ['verify']);
+ pq = await subtle.verify(PQSIGN, pqKey, fromBase64Url(envelope.pqsignature), bytes);
+ }
+ return model['Stitch.PrismId.hybridSignatureAccepted'](classical, advertised, verifierHasPq, pq);
} catch (error) {
if (error instanceof PrismIdError || error instanceof DOMException || error instanceof TypeError) return false;
throw error;
@@ -1478,6 +1547,218 @@ export function parseLinkUri(uri) {
return offer;
}
+/**
+ * The QR code for a link offer (ISO/IEC 18004: byte mode, error correction
+ * level M, the smallest version that holds it, the mask with the lowest
+ * penalty). Returns `{ size, modules }`, where `modules[y][x]` is true for a
+ * dark module; draw it with a quiet zone of four modules. A host renders it
+ * however it likes; the person scans it on the new device (TB2).
+ */
+export function linkQr(uri) {
+ parseLinkUri(uri);
+ return qrEncode(encoder.encode(uri));
+}
+
+// Error correction codewords per block and blocks, level M, versions 1 to 40.
+const QR_ECC_M = [0, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28];
+const QR_BLOCKS_M = [0, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49];
+const QR_MASKS = [
+ (x, y) => (x + y) % 2 === 0, (x, y) => y % 2 === 0, x => x % 3 === 0, (x, y) => (x + y) % 3 === 0,
+ (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0, (x, y) => x * y % 2 + x * y % 3 === 0,
+ (x, y) => (x * y % 2 + x * y % 3) % 2 === 0, (x, y) => ((x + y) % 2 + x * y % 3) % 2 === 0
+];
+const qrBit = (value, i) => ((value >>> i) & 1) !== 0;
+
+function qrRawModules(version) {
+ let n = (16 * version + 128) * version + 64;
+ if (version >= 2) {
+ const align = Math.floor(version / 7) + 2;
+ n -= (25 * align - 10) * align - 55;
+ if (version >= 7) n -= 36;
+ }
+ return n;
+}
+const qrDataCodewords = version => Math.floor(qrRawModules(version) / 8) - QR_ECC_M[version] * QR_BLOCKS_M[version];
+
+function qrGfMul(x, y) {
+ let z = 0;
+ for (let i = 7; i >= 0; i--) { z = (z << 1) ^ ((z >>> 7) * 0x11d); z ^= ((y >>> i) & 1) * x; }
+ return z;
+}
+
+function rsDivisor(degree) {
+ const out = new Array(degree).fill(0);
+ out[degree - 1] = 1;
+ let root = 1;
+ for (let i = 0; i < degree; i++) {
+ for (let j = 0; j < degree; j++) { out[j] = qrGfMul(out[j], root); if (j + 1 < degree) out[j] ^= out[j + 1]; }
+ root = qrGfMul(root, 2);
+ }
+ return out;
+}
+
+function rsRemainder(data, divisor) {
+ const out = divisor.map(() => 0);
+ for (const b of data) {
+ const factor = b ^ out.shift();
+ out.push(0);
+ divisor.forEach((c, i) => { out[i] ^= qrGfMul(c, factor); });
+ }
+ return out;
+}
+
+function qrEncode(bytes) {
+ let version = 1;
+ for (; ; version++) {
+ if (version > 40) refuse('offer', 'the link is too long for a QR code');
+ if (4 + (version < 10 ? 8 : 16) + 8 * bytes.length <= qrDataCodewords(version) * 8) break;
+ }
+ const capacity = qrDataCodewords(version) * 8;
+ const bits = [];
+ const put = (value, length) => { for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1); };
+ put(4, 4);
+ put(bytes.length, version < 10 ? 8 : 16);
+ for (const b of bytes) put(b, 8);
+ put(0, Math.min(4, capacity - bits.length));
+ put(0, (8 - bits.length % 8) % 8);
+ for (let pad = 0xec; bits.length < capacity; pad ^= 0xec ^ 0x11) put(pad, 8);
+ const data = [];
+ for (let i = 0; i < bits.length; i += 8) data.push(bits.slice(i, i + 8).reduce((a, b) => (a << 1) | b, 0));
+
+ // Split into blocks, add error correction, interleave.
+ const blocks = QR_BLOCKS_M[version], eccLength = QR_ECC_M[version];
+ const raw = Math.floor(qrRawModules(version) / 8);
+ const shortBlocks = blocks - raw % blocks, shortLength = Math.floor(raw / blocks);
+ const divisor = rsDivisor(eccLength), split = [];
+ for (let i = 0, k = 0; i < blocks; i++) {
+ const block = data.slice(k, k + shortLength - eccLength + (i < shortBlocks ? 0 : 1));
+ k += block.length;
+ const ecc = rsRemainder(block, divisor);
+ if (i < shortBlocks) block.push(0);
+ split.push(block.concat(ecc));
+ }
+ const codewords = [];
+ for (let i = 0; i < split[0].length; i++) {
+ for (let j = 0; j < split.length; j++) if (i !== shortLength - eccLength || j >= shortBlocks) codewords.push(split[j][i]);
+ }
+
+ const size = version * 4 + 17;
+ const modules = Array.from({ length: size }, () => new Array(size).fill(false));
+ const fixed = Array.from({ length: size }, () => new Array(size).fill(false));
+ const set = (x, y, dark) => { modules[y][x] = dark; fixed[y][x] = true; };
+ for (let i = 0; i < size; i++) { set(6, i, i % 2 === 0); set(i, 6, i % 2 === 0); }
+ for (const [cx, cy] of [[3, 3], [size - 4, 3], [3, size - 4]]) {
+ for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {
+ const x = cx + dx, y = cy + dy, d = Math.max(Math.abs(dx), Math.abs(dy));
+ if (x >= 0 && x < size && y >= 0 && y < size) set(x, y, d !== 2 && d !== 4);
+ }
+ }
+ const align = [];
+ if (version > 1) {
+ const count = Math.floor(version / 7) + 2;
+ const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2;
+ align.push(6);
+ for (let pos = size - 7; align.length < count; pos -= step) align.splice(1, 0, pos);
+ }
+ const last = align.length - 1;
+ align.forEach((ay, i) => align.forEach((ax, j) => {
+ if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return;
+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) set(ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
+ }));
+ const drawFormat = mask => {
+ const value = mask; // level M is 00
+ let rem = value;
+ for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
+ const f = ((value << 10) | rem) ^ 0x5412;
+ for (let i = 0; i <= 5; i++) set(8, i, qrBit(f, i));
+ set(8, 7, qrBit(f, 6)); set(8, 8, qrBit(f, 7)); set(7, 8, qrBit(f, 8));
+ for (let i = 9; i < 15; i++) set(14 - i, 8, qrBit(f, i));
+ for (let i = 0; i < 8; i++) set(size - 1 - i, 8, qrBit(f, i));
+ for (let i = 8; i < 15; i++) set(8, size - 15 + i, qrBit(f, i));
+ set(8, size - 8, true);
+ };
+ drawFormat(0);
+ if (version >= 7) {
+ let rem = version;
+ for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
+ const v = (version << 12) | rem;
+ for (let i = 0; i < 18; i++) {
+ const a = size - 11 + i % 3, b = Math.floor(i / 3);
+ set(a, b, qrBit(v, i)); set(b, a, qrBit(v, i));
+ }
+ }
+
+ // Codewords in the zigzag order, skipping function modules.
+ let i = 0;
+ for (let right = size - 1; right >= 1; right -= 2) {
+ if (right === 6) right = 5;
+ for (let vert = 0; vert < size; vert++) {
+ for (let j = 0; j < 2; j++) {
+ const x = right - j, upward = ((right + 1) & 2) === 0, y = upward ? size - 1 - vert : vert;
+ if (!fixed[y][x] && i < codewords.length * 8) { modules[y][x] = qrBit(codewords[i >>> 3], 7 - (i & 7)); i++; }
+ }
+ }
+ }
+
+ const applyMask = mask => {
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) if (!fixed[y][x] && QR_MASKS[mask](x, y)) modules[y][x] = !modules[y][x];
+ };
+ let best = 0, bestPenalty = Infinity;
+ for (let mask = 0; mask < 8; mask++) {
+ applyMask(mask);
+ drawFormat(mask);
+ const penalty = qrPenalty(modules, size);
+ if (penalty < bestPenalty) { best = mask; bestPenalty = penalty; }
+ applyMask(mask);
+ }
+ applyMask(best);
+ drawFormat(best);
+ return Object.freeze({ size, modules: modules.map(row => Object.freeze(row)) });
+}
+
+// The mask penalty of ISO/IEC 18004 section 7.8.3: runs, 2x2 blocks, finder-like patterns, dark balance.
+function qrPenalty(modules, size) {
+ let score = 0;
+ const addHistory = (run, history) => { if (history[0] === 0) run += size; history.pop(); history.unshift(run); };
+ const countPatterns = h => {
+ const n = h[1];
+ const core = n > 0 && h[2] === n && h[3] === n * 3 && h[4] === n && h[5] === n;
+ return (core && h[0] >= n * 4 && h[6] >= n ? 1 : 0) + (core && h[6] >= n * 4 && h[0] >= n ? 1 : 0);
+ };
+ for (const line of [i => modules[i], i => modules.map(row => row[i])]) {
+ for (let a = 0; a < size; a++) {
+ const row = line(a);
+ let color = false, run = 0;
+ const history = new Array(7).fill(0);
+ for (let b = 0; b < size; b++) {
+ if (row[b] === color) {
+ run++;
+ if (run === 5) score += 3; else if (run > 5) score++;
+ } else {
+ addHistory(run, history);
+ if (!color) score += countPatterns(history) * 40;
+ color = row[b];
+ run = 1;
+ }
+ }
+ if (color) { addHistory(run, history); run = 0; }
+ addHistory(run + size, history);
+ score += countPatterns(history) * 40;
+ }
+ }
+ let dark = 0;
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
+ if (modules[y][x]) dark++;
+ if (y < size - 1 && x < size - 1) {
+ const c = modules[y][x];
+ if (c === modules[y][x + 1] && c === modules[y + 1][x] && c === modules[y + 1][x + 1]) score += 3;
+ }
+ }
+ const total = size * size;
+ score += (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10;
+ return score;
+}
+
const requestProofBody = (prism, device) => ({ kind: KIND.request, prism, device });
const linkContext = offer => ({ salt: fromBase64Url(offer.secret), info: 'prism/link-wrap/1', aad: offer.prism });
@@ -1592,6 +1873,7 @@ async function exportDeviceSecret(keys) {
agree: await subtle.exportKey('jwk', keys.agreement.privateKey)
};
if (keys.kem) secret.kem = toBase64Url(await subtle.exportKey('pkcs8', keys.kem.privateKey));
+ if (keys.pqsign) secret.pqsign = toBase64Url(await subtle.exportKey('pkcs8', keys.pqsign.privateKey));
return secret;
}
@@ -1600,7 +1882,8 @@ async function importDeviceSecret(record, secret) {
const signingKey = await subtle.importKey('jwk', strip(secret.sign), SIGN, false, ['sign']);
const agreementKey = await subtle.importKey('jwk', strip(secret.agree), AGREE, false, ['deriveBits']);
const kemKey = secret.kem ? await subtle.importKey('pkcs8', fromBase64Url(secret.kem), KEM, false, ['decapsulateBits']) : null;
- return Object.freeze({ id: await kappa(record), record, signingKey, agreementKey, kemKey });
+ const pqSigningKey = secret.pqsign ? await subtle.importKey('pkcs8', fromBase64Url(secret.pqsign), PQSIGN, false, ['sign']) : null;
+ return Object.freeze({ id: await kappa(record), record, signingKey, agreementKey, kemKey, pqSigningKey });
}
/**
@@ -1667,13 +1950,15 @@ export async function recoveryCode(prism, newDeviceRecord) {
* guardians so the recovered secret is retired at once. Personas are carried
* over when their host-held logs are supplied.
*/
-export async function recoverPrism({ prism, records, shares, device, personas = {}, rotateRecovery }) {
- const log = await logFromRecords(records);
- const state = await resolvePrism(prism, log);
- if (!state.recovery) refuse('recovery', 'this prism has no active recovery device');
+export async function recoverPrism({ prism, records, bus, shares, device, personas = {}, rotateRecovery }) {
+ let log = records === undefined ? null : await logFromRecords(records);
+ let state = log ? await resolvePrism(prism, log) : null;
+ if (!log && typeof bus?.retained !== 'function') refuse('recovery', 'give the prism log, or a bus that retains sync messages');
+ const recoveryId = state ? state.recovery : shares.find(s => s?.kind === KIND.recoveryShare && s.prism === prism)?.recovery;
+ if (!recoveryId) refuse('recovery', 'this prism has no active recovery device');
const parts = [];
for (const s of shares) {
- if (s.kind !== KIND.recoveryShare || s.prism !== prism || s.recovery !== state.recovery) continue;
+ if (s.kind !== KIND.recoveryShare || s.prism !== prism || s.recovery !== recoveryId) continue;
if (parts.some(p => p.index === s.index)) continue;
const bytes = s.guardian === 'paper' ? fromBase64Url(s.share) : await unwrapFrom(device, s.wrap, shareContext(prism, s.index));
parts.push({ index: s.index, threshold: s.threshold, bytes });
@@ -1685,10 +1970,20 @@ export async function recoverPrism({ prism, records, shares, device, personas =
let secret;
try { secret = JSON.parse(decoder.decode(secretBytes)); } catch { refuse('recovery', 'the shares do not combine to a recovery secret'); }
secretBytes.fill(0);
- if (secret.kind !== KIND.recoverySecret || secret.prism !== prism || await kappa(secret.device) !== state.recovery) refuse('recovery', 'the shares belong to another recovery device');
+ if (secret.kind !== KIND.recoverySecret || secret.prism !== prism || await kappa(secret.device) !== recoveryId) refuse('recovery', 'the shares belong to another recovery device');
const recovery = await importDeviceSecret(secret.device, secret.keys);
+ const snapshot = new Map();
+ for (const [id, raw] of Object.entries(secret.keyring)) snapshot.set(id, await boundaryFromRaw(fromBase64Url(raw), true));
+ let carried = personas;
+ if (!log) {
+ const found = await collectFromBus(prism, bus, recovery, snapshot);
+ log = found.log;
+ carried = { ...found.personas, ...personas };
+ state = await resolvePrism(prism, log);
+ if (state.recovery !== recoveryId) refuse('recovery', 'the substrate holds no log in which this recovery device is active');
+ }
let custodian = emptySession(prism, recovery, log);
- for (const [id, raw] of Object.entries(secret.keyring)) custodian.keyring.set(id, await boundaryFromRaw(fromBase64Url(raw), true));
+ custodian.keyring = snapshot;
custodian.keyring = await absorbRekeys(custodian, state);
// Bind the new device, then revoke every other device; each revocation rotates the boundary.
const bind = await signRecord(recovery, { kind: KIND.bind, prism, device: device.record, role: 'member', scope: [] });
@@ -1701,7 +1996,7 @@ export async function recoverPrism({ prism, records, shares, device, personas =
const now = await resolvePrism(prism, custodian.log);
pending = now.active.filter(id => !done.has(id));
}
- custodian = await recoverPersonas(custodian, recovery, device, secret, personas);
+ custodian = await recoverPersonas(custodian, recovery, device, secret, carried);
let result = { ...emptySession(prism, device, custodian.log), personas: custodian.personas, personaDevices: custodian.personaDevices };
result.keyring = await absorbRekeys(result, await resolvePrism(prism, custodian.log));
for (const [id, entry] of custodian.keyring) if (!result.keyring.has(id) && entry.raw) result.keyring.set(id, await boundaryFromRaw(entry.raw, true));
@@ -1716,6 +2011,41 @@ export async function recoverPrism({ prism, records, shares, device, personas =
return { session: result, shares: newShares };
}
+/**
+ * Rebuild the prism log from sync messages the substrate retained, with no
+ * device and no other copy. The recovery device holds a snapshot of the
+ * keyring, and every rotation wraps the next boundary key to it, so it can
+ * open the retained messages on each sync topic in turn and follow the chain
+ * of rotations to the current key. Messages it cannot open are skipped.
+ */
+async function collectFromBus(prism, bus, device, keyring) {
+ const session = { ...emptySession(prism, device, new Map()), keyring: new Map(keyring) };
+ const personas = {};
+ const visited = new Set();
+ for (let pending = [...session.keyring.keys()]; pending.length; pending = [...session.keyring.keys()].filter(id => !visited.has(id))) {
+ for (const id of pending) {
+ visited.add(id);
+ for (const bytes of await bus.retained(await syncTopic(session, id))) {
+ try {
+ if (!(bytes instanceof Uint8Array) || bytes.length > MAX_SYNC_BYTES) continue;
+ const message = await openPrivate(session, JSON.parse(decoder.decode(bytes)));
+ if (message.kind !== KIND.sync || message.prism !== prism) continue;
+ const log = mergeLogs(session.log, await logFromRecords(message.records));
+ if (log.size > MAX_LOG_RECORDS) continue;
+ session.log = log;
+ for (const [pid, recs] of Object.entries(message.personas ?? {})) if (Array.isArray(recs)) personas[pid] = [...(personas[pid] ?? []), ...recs];
+ } catch (error) {
+ // A retained message this device cannot open or parse is not evidence of anything; skip it.
+ if (!(error instanceof PrismIdError || error instanceof SyntaxError || error instanceof DOMException || error instanceof TypeError)) throw error;
+ }
+ }
+ }
+ if (session.log.size) session.keyring = await absorbRekeys(session, await resolvePrism(prism, session.log));
+ }
+ if (!session.log.size) refuse('recovery', 'the substrate holds no sync message this recovery device can open');
+ return { log: session.log, personas };
+}
+
// ---------------------------------------------------------------- personas: one unlinkable id per host
/**
@@ -1730,20 +2060,20 @@ export async function recoverPrism({ prism, records, shares, device, personas =
* recovery device whose private keys are wrapped to the main recovery device.
* No member keeps them, so a revoked member cannot hijack a persona.
*/
-export async function ensurePersona(session, audience) {
+export async function ensurePersona(session, audience, { presence } = {}) {
if (typeof audience !== 'string' || !audience) refuse('persona', 'audience must name a host');
const state = await mayActForPersona(session);
const existing = choosePersona(session, audience);
if (existing) {
if (!session.personaDevices.has(audience)) {
- const own = await createDevice({ deviceClass: session.device.record.class, protection: session.device.record.protection });
+ const own = await createDevice({ deviceClass: session.device.record.class, protection: session.device.record.protection, presence });
const request = await signRecord(session.device, { kind: KIND.personaKey, prism: session.prism, audience, persona: existing.persona, device: own.record });
const personaDevices = new Map(session.personaDevices).set(audience, own);
return servicePersonas({ ...session, personaDevices, log: await addRecord(session.log, request) });
}
return session;
}
- const own = await createDevice({ deviceClass: session.device.record.class, protection: session.device.record.protection });
+ const own = await createDevice({ deviceClass: session.device.record.class, protection: session.device.record.protection, presence });
const genesis = await signRecord(own, { kind: KIND.genesis, device: own.record, nonce: toBase64Url(random(16)) });
const persona = await kappa(genesis.body);
let personaLog = await logFromRecords([genesis]);
@@ -1793,9 +2123,9 @@ export async function personaFor(session, audience) {
}
/** Sign an action for a host under this device's persona there. */
-export async function signPersonaAction(session, audience, action, payload, { now }) {
+export async function signPersonaAction(session, audience, action, payload, { now, presence }) {
const { persona } = await personaFor(session, audience);
- return signAction({ prism: persona, device: session.personaDevices.get(audience) }, action, payload, { now, audience });
+ return signAction({ prism: persona, device: session.personaDevices.get(audience) }, action, payload, { now, audience, presence });
}
/**
@@ -1879,11 +2209,82 @@ async function recoverPersonas(custodian, recovery, device, secret, hostLogs) {
* sink). `audience` names the host, so the envelope is useless anywhere else;
* a fresh nonce lets the host refuse replays. Prefer signPersonaAction, which
* shows the host only that host's persona.
+ *
+ * `presence(challenge)` asks the person to approve: in a browser it calls
+ * navigator.credentials.get with `challenge` and userVerification
+ * 'required', and returns `{ authenticatorData, clientDataJSON, signature }`
+ * as base64url. The challenge is the SHA-256 of the action body, so the
+ * assertion approves exactly this action. Script in the origin cannot make
+ * one without the person's gesture and verification.
*/
-export async function signAction(session, action, payload, { now, audience }) {
+export async function signAction(session, action, payload, { now, audience, presence }) {
if (typeof action !== 'string' || !action) refuse('action', 'action must be a name');
if (typeof audience !== 'string' || !audience) refuse('action', 'action must name its audience');
- return signRecord(session.device, { kind: KIND.action, prism: session.prism, action, audience, payload, at: now, nonce: toBase64Url(random(16)) });
+ const envelope = await signRecord(session.device, { kind: KIND.action, prism: session.prism, action, audience, payload, at: now, nonce: toBase64Url(random(16)) });
+ if (typeof presence === 'function') {
+ if (!session.device.record.presence) refuse('presence', 'this device has no passkey bound to it');
+ const assertion = await presence(await presenceChallenge(envelope.body));
+ envelope.presence = { authenticatorData: assertion.authenticatorData, clientDataJSON: assertion.clientDataJSON, signature: assertion.signature };
+ }
+ return envelope;
+}
+
+/** The WebAuthn challenge that approves an action: SHA-256 of its canonical body. */
+export async function presenceChallenge(body) {
+ return new Uint8Array(await subtle.digest('SHA-256', canonicalBytes(body)));
+}
+
+/** ECDSA signatures from WebAuthn are DER; WebCrypto verifies the raw r || s form. */
+function derToRaw(der) {
+ let i = 0;
+ const fail = () => refuse('presence', 'malformed assertion signature');
+ if (der[i++] !== 0x30) fail();
+ const total = der[i++];
+ if (total & 0x80 || total + 2 !== der.length) fail();
+ const integer = () => {
+ if (der[i++] !== 0x02) fail();
+ const length = der[i++];
+ if (length < 1 || length > 33 || i + length > der.length) fail();
+ let value = der.subarray(i, i + length);
+ i += length;
+ if (value.length === 33) { if (value[0] !== 0) fail(); value = value.subarray(1); }
+ const out = new Uint8Array(32);
+ out.set(value, 32 - value.length);
+ return out;
+ };
+ const r = integer(), s = integer();
+ if (i !== der.length) fail();
+ return concat(r, s);
+}
+
+const sameBytes = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
+
+/**
+ * Check a WebAuthn assertion against the passkey bound in the device record:
+ * type webauthn.get, the challenge for this action body, the bound origin and
+ * rp id, the user-present and user-verified flags, and the signature over
+ * authenticatorData || SHA-256(clientDataJSON).
+ */
+async function presenceEvidence(record, body, presence) {
+ const none = { userPresent: false, userVerified: false, challengeMatches: false, assertionValid: false };
+ const binding = record?.presence;
+ if (!binding || !presence || typeof presence !== 'object') return none;
+ try {
+ const authData = fromBase64Url(presence.authenticatorData);
+ const clientDataBytes = fromBase64Url(presence.clientDataJSON);
+ const clientData = JSON.parse(decoder.decode(clientDataBytes));
+ if (authData.length < 37) return none;
+ const rpHash = new Uint8Array(await subtle.digest('SHA-256', encoder.encode(binding.rp)));
+ const challengeMatches = clientData?.type === 'webauthn.get' && clientData.origin === binding.origin &&
+ clientData.challenge === toBase64Url(await presenceChallenge(body)) && sameBytes(authData.subarray(0, 32), rpHash);
+ const key = await subtle.importKey('jwk', { ...binding.key, ext: true }, SIGN, false, ['verify']);
+ const signed = concat(authData, new Uint8Array(await subtle.digest('SHA-256', clientDataBytes)));
+ const assertionValid = await subtle.verify(SIGN_HASH, key, derToRaw(fromBase64Url(presence.signature)), signed);
+ return { userPresent: (authData[32] & 0x01) !== 0, userVerified: (authData[32] & 0x04) !== 0, challengeMatches, assertionValid };
+ } catch (error) {
+ if (error instanceof PrismIdError || error instanceof SyntaxError || error instanceof DOMException || error instanceof TypeError) return none;
+ throw error;
+ }
}
/**
@@ -1892,18 +2293,30 @@ export async function signAction(session, action, payload, { now, audience }) {
* Stitch.PrismId.actionAllowed holds (an active member, or a delegate acting
* inside its scope; a recovery device never acts). `seen` is the host's replay
* set for the window. `prism` and `log` are the persona the device presented.
+ *
+ * `requirePresence` (true, or a list of action names) makes the host accept
+ * those actions only with the person's user-verified WebAuthn approval of
+ * exactly this action (Stitch.PrismId.presenceSatisfied). `requirePostQuantum`
+ * refuses an action whose ML-DSA signature this host cannot check. `bus`
+ * makes the host also merge what the prism's public topic retains (heardLog),
+ * so it hears revocations the signing device does not present.
*/
-export async function verifyAction(prism, log, envelope, { audience, now, window = 60000, seen = new Set() }) {
+export async function verifyAction(prism, log, envelope, { audience, now, window = 60000, seen = new Set(), requirePresence = false, requirePostQuantum = false, bus }) {
+ if (bus) log = await heardLog(prism, log, bus);
const body = envelope?.body;
if (body?.kind !== KIND.action || body.prism !== prism || !Number.isSafeInteger(body.at) || body.at < 0 || typeof body.nonce !== 'string')
return { allowed: false, reason: 'not an action of this prism' };
const state = await resolvePrism(prism, log);
const id = envelope.signer;
if (!state.devices[id] && !state.revoked.includes(id)) return { allowed: false, reason: 'unknown device' };
- if (!state.devices[id] || !await signatureValid(envelope, state.devices[id])) return { allowed: false, reason: 'signature or revocation' };
+ if (!state.devices[id] || !await signatureValid(envelope, state.devices[id], { requirePostQuantum })) return { allowed: false, reason: 'signature or revocation' };
const replayKey = `${id} ${body.nonce}`;
if (!model['Stitch.PrismId.actionFresh'](body.audience === audience, !seen.has(replayKey), body.at, now, window))
return { allowed: false, reason: 'audience, replay or time window' };
+ const required = requirePresence === true || (Array.isArray(requirePresence) && requirePresence.includes(body.action));
+ const evidence = required ? await presenceEvidence(state.devices[id], body, envelope.presence) : {};
+ if (!model['Stitch.PrismId.presenceSatisfied'](required, evidence.userPresent === true, evidence.userVerified === true,
+ evidence.challengeMatches === true, evidence.assertionValid === true)) return { allowed: false, reason: 'approval' };
const role = state.roles[id];
const scoped = role !== 'member';
const allowed = model['Stitch.PrismId.actionAllowed'](true, state.revoked.includes(id), scoped, role === 'delegate' && state.scopes[id].includes(body.action));
@@ -1955,8 +2368,9 @@ export function boundaryVisibleTo(boundary, prism) {
* Sealed plaintext is padded (ISO/IEC 7816-4) to a power-of-two bucket of at
* least 1 KiB, so observers learn only the bucket, not the exact size.
*/
-export function padToBucket(bytes) {
- let size = 1024;
+export function padToBucket(bytes, minimum = 1024) {
+ if (!Number.isSafeInteger(minimum) || minimum < 1024 || (minimum & (minimum - 1)) !== 0) refuse('padding', 'bucket must be a power of two of at least 1024');
+ let size = minimum;
while (size < bytes.length + 1) size *= 2;
const out = new Uint8Array(size);
out.set(bytes);
@@ -1977,11 +2391,12 @@ export async function sealPrivate(session, value) {
return sealWith(session, keyId, value);
}
-async function sealWith(session, keyId, value) {
+async function sealWith(session, keyId, value, { bucket = 1024 } = {}) {
const entry = session.keyring.get(keyId);
if (!entry) refuse('stale-key', 'this device does not hold that boundary key');
- const sealed = { kind: KIND.sealed, boundary: 'private', key: keyId, ...await encryptWith(entry.seal, padToBucket(canonicalBytes(value)), session.prism) };
- return { address: await kappa(sealed), sealed };
+ const padded = padToBucket(canonicalBytes(value), bucket);
+ const sealed = { kind: KIND.sealed, boundary: 'private', key: keyId, ...await encryptWith(entry.seal, padded, session.prism) };
+ return { address: await kappa(sealed), sealed, bucket: padded.length };
}
/** Open sealed content with whichever key it names, including keys from before a rotation. */
@@ -2005,17 +2420,60 @@ export async function syncTopic(session, keyId) {
* Publish this device's log and persona logs to its other member devices,
* sealed in the private boundary. After a rotation, publish once under the
* previous key so devices still listening there can take up the new key.
+ * Returns the padded bucket, so a cadence can keep every message that size.
*/
-export async function publishSync(session, bus, { keyId } = {}) {
+export async function publishSync(session, bus, { keyId, bucket } = {}) {
const id = keyId ?? (await currentBoundary(session)).keyId;
- const { sealed } = await sealWith(session, id, { kind: KIND.sync, prism: session.prism, records: [...session.log.values()], personas: personaRecords(session) });
- await bus.publish(await syncTopic(session, id), canonicalBytes(sealed));
+ const sealed = await sealWith(session, id, { kind: KIND.sync, prism: session.prism, records: [...session.log.values()], personas: personaRecords(session) }, { bucket });
+ await bus.publish(await syncTopic(session, id), canonicalBytes(sealed.sealed));
+ return { bucket: sealed.bucket };
+}
+
+/** A cover message: sealed and padded like a sync message, ignored by receivers. */
+export async function publishCover(session, bus, { bucket = 1024 } = {}) {
+ const { keyId } = await currentBoundary(session);
+ const sealed = await sealWith(session, keyId, { kind: KIND.cover, prism: session.prism }, { bucket });
+ await bus.publish(await syncTopic(session, keyId), canonicalBytes(sealed.sealed));
+ return { bucket: sealed.bucket };
+}
+
+/**
+ * Constant-cadence sync. Call `tick` on a fixed timer: it publishes a pending
+ * sync if there is one, otherwise a cover message, always padded to the same
+ * bucket. A relay then sees one message of one size per interval whether or
+ * not anything changed. The bucket only grows, when the log outgrows it.
+ *
+ * `refresh` keeps the substrate holding the prism: every `refresh` ticks a
+ * real sync goes out even with nothing pending, so a relay that keeps messages
+ * only for a while (the warm relay keeps them 30 minutes) always holds a
+ * recent one for offline devices and log-free recovery. Choose it so that
+ * `refresh` intervals are shorter than the relay's lifetime. Each real sync
+ * also publishes the public log (publishLog), so hosts hear revocations.
+ * Cover ticks publish nothing there; the public log holds no secret, but its
+ * timing shows which ticks were real.
+ */
+export function createSyncCadence({ bucket = 1024, refresh = Infinity } = {}) {
+ if (!(refresh === Infinity || (Number.isSafeInteger(refresh) && refresh > 0))) refuse('sync', 'refresh is a whole number of ticks');
+ let pending = false, size = bucket, since = 0;
+ return {
+ queue() { pending = true; },
+ get bucket() { return size; },
+ async tick(session, bus) {
+ since++;
+ const real = pending || since >= refresh;
+ const sent = real ? await publishSync(session, bus, { bucket: size }) : await publishCover(session, bus, { bucket: size });
+ if (real) { await publishLog(session, bus); since = 0; }
+ pending = false;
+ size = Math.max(size, sent.bucket);
+ }
+ };
}
/** Merge a sync message. Records that do not resolve for this prism are refused. */
export async function receiveSync(session, bytes) {
if (!(bytes instanceof Uint8Array) || bytes.length > MAX_SYNC_BYTES) refuse('sync', `sync message exceeds ${MAX_SYNC_BYTES} bytes`);
const message = await openPrivate(session, JSON.parse(decoder.decode(bytes)));
+ if (message.kind === KIND.cover && message.prism === session.prism) return session;
if (message.kind !== KIND.sync || message.prism !== session.prism) refuse('sync', 'sync message for another prism');
const log = mergeLogs(session.log, await logFromRecords(message.records));
if (log.size > MAX_LOG_RECORDS) refuse('log', `log exceeds ${MAX_LOG_RECORDS} records`);
@@ -2026,16 +2484,72 @@ export async function receiveSync(session, bytes) {
return servicePersonas(next);
}
+// ---------------------------------------------------------------- what hosts hear
+
/**
- * The bus contract the substrate implements: publish bytes to a topic and
- * deliver them to subscribers. This in-memory bus is for tests and single-page use.
+ * The public topic of a prism's log, derived from the prism id alone, so a
+ * host that knows the prism reads it with no secret. It carries only the
+ * signed public records (genesis, binds and revocations) a host already
+ * receives with every action. Publish a persona's own log under the persona,
+ * so hosts still cannot link personas; the main prism's log goes here only
+ * when the main prism is what hosts see.
+ */
+export async function logTopic(prism) {
+ if (!isKappa(prism)) refuse('log', 'not a prism id');
+ return 'prism-log:' + (await kappa({ kind: KIND.publicLog, prism })).slice(7);
+}
+
+/** Publish this prism's public log where hosts hear it: after every bind or revocation, and on the refresh cadence. */
+export async function publishLog(session, bus) {
+ await bus.publish(await logTopic(session.prism), canonicalBytes({ kind: KIND.publicLog, prism: session.prism, records: [...session.log.values()] }));
+}
+
+/**
+ * `log` merged with what the substrate retains on the prism's public topic,
+ * so a host hears a revocation the signing device never presents. Messages
+ * for another prism, over the bounds, or malformed are skipped. Every record
+ * is still checked by resolvePrism, so a forged one counts for nothing.
+ */
+export async function heardLog(prism, log, bus) {
+ let merged = log;
+ for (const bytes of await bus.retained(await logTopic(prism))) {
+ try {
+ if (!(bytes instanceof Uint8Array) || bytes.length > MAX_SYNC_BYTES) continue;
+ const message = JSON.parse(decoder.decode(bytes));
+ if (message?.kind !== KIND.publicLog || message.prism !== prism) continue;
+ const next = mergeLogs(merged, await logFromRecords(message.records));
+ if (next.size <= MAX_LOG_RECORDS) merged = next;
+ } catch (error) {
+ // A message that does not parse as this prism's log is not evidence of anything; skip it.
+ if (!(error instanceof PrismIdError || error instanceof SyntaxError || error instanceof TypeError)) throw error;
+ }
+ }
+ return merged;
+}
+
+/** How many messages per topic the in-memory bus retains. */
+export const MAX_RETAINED = 256;
+
+/**
+ * The bus contract the substrate implements: publish bytes to a topic, deliver
+ * them to subscribers, and retain recent messages per topic so a device that
+ * was offline, or a recovering device with no copy of the log, can read them
+ * later (`retained`). This in-memory bus is for tests and single-page use.
*/
export function createMemoryBus() {
const subscribers = new Map();
+ const kept = new Map();
return {
async publish(topic, bytes) {
+ const list = kept.get(topic) ?? [];
+ list.push(new Uint8Array(bytes));
+ if (list.length > MAX_RETAINED) list.shift();
+ kept.set(topic, list);
for (const fn of [...(subscribers.get(topic) ?? [])]) await fn(new Uint8Array(bytes));
},
+ async retained(topic) {
+ return (kept.get(topic) ?? []).map(b => new Uint8Array(b));
+ },
subscribe(topic, fn) {
if (!subscribers.has(topic)) subscribers.set(topic, new Set());
subscribers.get(topic).add(fn);
@@ -2122,7 +2636,7 @@ export function createRelayBus({
return true;
}
- /** The messages other buses left on the relay for a topic within the warm lifetime, oldest first. */
+ /** `retained`: the messages other buses left on the relay for a topic within the warm lifetime, oldest first. */
async function fetchTopic(topic) {
checkBusTopic(topic);
if (!relay || !fetchImpl) return [];
@@ -2182,5 +2696,5 @@ export function createRelayBus({
channels.clear();
}
- return { publish, subscribe, fetch: fetchTopic, close };
+ return { publish, subscribe, retained: fetchTopic, close };
}
diff --git a/identity/stitch.lock b/identity/stitch.lock
index 65db455..0c75c03 100644
--- a/identity/stitch.lock
+++ b/identity/stitch.lock
@@ -1,13 +1,13 @@
{
"repository": "afflom/stitch",
- "commit": "e3efc6ee8b7de24db0e33dd17ea1413d02f82ae5",
+ "commit": "7c0ccebfa00e5c09e135901be4c9fad149d1b420",
"sources": {
"src/layer1-uor/contracts.js": "94c67e0811f78029b251c55edbf365b2335040106b8125fa5298e59315d2c2d3",
"src/layer1-uor/custody.js": "597b34d6740b6b371e30af24ee18cd10f8c4142da38e616b9ec5e04d042ab74c",
- "src/layer1-uor/generated-model.js": "5e6f9974741e6079400d75bd1632ccd2334ad640fd1735554e0a6cf88fb805b7",
+ "src/layer1-uor/generated-model.js": "fae51244e2b96601978233863e86aee96f35ef5a15ad4af4d3e687a9d770fb11",
"src/layer2-schedulers/policy.js": "8f2074f8fe07a7b1fda51896d78f11a797564afb64accebc7291261e5c00639f",
"src/layer5-transport/relay-framing.js": "35672c5720f5f1e5d009f1875a1c63de3a6badea2546d66baf73c77fb7c90ae0",
- "src/prism-id.js": "556e725270602f5706a61d5682fe5fdb50aa699c174a19d5cd900db09b719b74"
+ "src/prism-id.js": "eefc04c53d581308dee9033384050616849ef93996e8cb7858cd1435934b16d7"
},
"decisions": [
"Stitch.Budget.reserveAllowed",
@@ -22,11 +22,13 @@
"Stitch.PrismId.boundaryVisibleTo",
"Stitch.PrismId.deviceMaySign",
"Stitch.PrismId.hostAdmitsDevice",
+ "Stitch.PrismId.hybridSignatureAccepted",
"Stitch.PrismId.hybridWrapRequired",
"Stitch.PrismId.linkGate",
"Stitch.PrismId.linkOfferAccepted",
"Stitch.PrismId.mayAdminister",
"Stitch.PrismId.mayShareBoundary",
+ "Stitch.PrismId.presenceSatisfied",
"Stitch.PrismId.receivesPrivateBoundary",
"Stitch.PrismId.recoveryBindAllowed",
"Stitch.PrismId.revocationCounts",
@@ -50,6 +52,6 @@
],
"output": {
"path": "identity/prism-id.mjs",
- "sha256": "262418eee8fcfbc3300b8c1a2f903662dee5a01b0467b522d37f6644bd0ef718"
+ "sha256": "3035992b02efa243c87f1c6116e7e37e8a203fc4721d590c4158c762e8997995"
}
}
diff --git a/identity/test.mjs b/identity/test.mjs
index e2aafd4..351815d 100644
--- a/identity/test.mjs
+++ b/identity/test.mjs
@@ -243,6 +243,7 @@ describe("the flow in Chromium", () => {
await first.locator("#account-link").click();
await first.locator("#account-offer").waitFor({ timeout: 10000 });
const uri = await first.locator("#account-offer").textContent();
+ assert.match(await first.locator("#account-qr path").getAttribute("d"), /^M\d+ \d+h1v1h-1z/, "the offer shows its QR code");
assert.match(uri, /^prism-link:/);
await second.locator("#account-uri").fill(uri);
await second.locator("#account-join-go").click();