Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions frame.lock
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
{
Expand Down
4 changes: 3 additions & 1 deletion frame/frame.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 2 additions & 0 deletions frame/panels.css
Original file line number Diff line number Diff line change
Expand Up @@ -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); }
Expand Down
39 changes: 29 additions & 10 deletions frame/panels.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -464,17 +465,19 @@ 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.
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) {
Expand All @@ -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
Expand All @@ -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)}`;
Expand Down Expand Up @@ -522,7 +537,8 @@ const ACCOUNT_PANEL = `
<button id="account-kit-done" class="row" type="button">I saved it</button>
</div>
<div id="account-view-offer" class="account-in" hidden>
<p>On the new device or app, open the person icon, choose <b>Use my Prism id from another device or app</b>, and paste this link. It works once, for five minutes.</p>
<p>On a phone, scan this code. On another app or computer, open the person icon, choose <b>Use my Prism id from another device or app</b>, and paste the link. It works once, for five minutes.</p>
<svg id="account-qr" class="account-qr" role="img" aria-label="QR code of the link"></svg>
<p class="account-id"><code id="account-offer"></code><button id="account-offer-copy" class="text" type="button">Copy</button></p>
<label id="account-confirm" hidden>Type the code the new device shows <input id="account-code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" pattern="[0-9]{6}" /></label>
<button id="account-accept" class="primary" type="button" hidden>Add it</button>
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -714,6 +730,7 @@ export function accounts(frame, core) {
});
$("offer").textContent = uri;
$("offer").title = uri;
drawQr($("qr"), Prism.linkQr(uri));
show("offer");
}),
);
Expand Down Expand Up @@ -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 });
}),
Expand Down
2 changes: 1 addition & 1 deletion frame/unsplash/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Unsplash key, so no page carries it; the frame (`frame/frame.mjs`,
| Route | What it does |
| --- | --- |
| `GET /search?q=<words>&page=<n>` | Nine landscape photos; with no words, Unsplash's wallpapers. Cached an hour. |
| `GET /image?src=<images.unsplash.com URL>&w=<px>[&h=<px>]` | The photo's bytes, resized by Unsplash, cached a month. Any other host is refused. |
| `GET /image?src=<images.unsplash.com URL>&w=<px>[&h=<px>][&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=<photo id>` | Unsplash's download event, sent when a visitor sets a photo. |

## Deploy
Expand Down
20 changes: 14 additions & 6 deletions frame/unsplash/worker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
// as data: images on any page. Nothing here is a secret but the key.
//
// GET /search?q=<words>&page=<n> nine landscape photos; no words: wallpapers
// GET /image?src=<images.unsplash.com URL>&w=<px>[&h=<px>] the photo's bytes
// GET /image?src=<images.unsplash.com URL>&w=<px>[&h=<px>][&q=<40-95>][&fm=jpg|webp|avif] the photo's bytes
// POST /use?id=<photo id> Unsplash's download event, when one is chosen
//
// Deploy (frame/unsplash/README.md): wrangler secret put UNSPLASH_ACCESS_KEY,
Expand All @@ -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
Expand Down Expand Up @@ -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 } });
Expand Down
31 changes: 18 additions & 13 deletions identity/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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).
15 changes: 8 additions & 7 deletions identity/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down
614 changes: 564 additions & 50 deletions identity/prism-id.mjs

Large diffs are not rendered by default.

10 changes: 6 additions & 4 deletions identity/stitch.lock
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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",
Expand All @@ -50,6 +52,6 @@
],
"output": {
"path": "identity/prism-id.mjs",
"sha256": "262418eee8fcfbc3300b8c1a2f903662dee5a01b0467b522d37f6644bd0ef718"
"sha256": "3035992b02efa243c87f1c6116e7e37e8a203fc4721d590c4158c762e8997995"
}
}
1 change: 1 addition & 0 deletions identity/test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading