/** * The phone's half of a sealed Send, played by a test (ruling R5, lane * e2e-share): the sender's phone lays the payload from its own plain copy * through the one rule (`send.contents`, the same WASM the phone's Rust is), * seals it to the receiver's sharing key and posts only the box and its * outside; the receiver's phone opens the box, plans the landing over its own * copy (`send.keep`), asks its object to copy the bytes, and writes the rows. * * The box here is AES-256-GCM under a key only the receiving "phone" (this * test's memory) holds, bound to `send:`, the shape cotton-core's `p1:` * gives (the curve itself is proven in Rust, seal::share). What matters to * these tests is that the objects never hold a key that opens it. */ import { env, runInDurableObject } from "cloudflare:test"; import type { Business } from "../src/business.ts"; import { tryPlan } from "../src/rules/index.ts"; import type { Store } from "../src/store.ts"; type Body = Record; type Inside = { store: Store }; export interface SendPhone { slug: string; db: string; number: string; ask(method: string, path: string, body?: unknown): Promise<{ status: number; body: T }>; } /** Each person's sharing secret, as a phone keeps it: their public half (as posted) → the key that opens what is sealed to it. */ const secrets = new Map(); function b64url(bytes: Uint8Array): string { let s = ""; for (const b of bytes) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function unb64url(text: string): Uint8Array { const b64 = text.replace(/-/g, "+").replace(/_/g, "/"); return Uint8Array.from(atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4)), (c) => c.charCodeAt(0)); } /** A phone posts its person's sharing key; the secret stays in the phone. */ export async function postSharingKey(p: SendPhone): Promise { const raw = crypto.getRandomValues(new Uint8Array(32)); raw[31] = raw[31]! & 0x7f; const key = b64url(raw); secrets.set(key, (await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"])) as CryptoKey); const posted = await p.ask("POST", "/v1/send/key", { key }); if (posted.status !== 200) throw new Error(`key not posted: ${JSON.stringify(posted.body)}`); return key; } async function seal(to: string, id: string, payload: unknown): Promise { // A made-up key (a person who is not one's own, or not on Cotton) opens for nobody: the box is sealed under a key no one keeps. const key = secrets.get(to) ?? ((await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt"])) as CryptoKey); const nonce = crypto.getRandomValues(new Uint8Array(12)); const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: new TextEncoder().encode(`send:${id}`) }, key, new TextEncoder().encode(JSON.stringify(payload)))); const body = new Uint8Array(12 + ct.length); body.set(nonce); body.set(ct, 12); return `p1:${b64url(body)}`; } /** The phone opens a box sealed to its person's sharing key. */ export async function openBox(key: string, id: string, box: string): Promise { const secret = secrets.get(key); if (!secret) throw new Error("this phone holds no such sharing key"); const body = unb64url(box.slice(3)); const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: body.slice(0, 12), additionalData: new TextEncoder().encode(`send:${id}`) }, secret, body.slice(12)); return JSON.parse(new TextDecoder().decode(plain)) as Payload; } export interface Payload { id: string; title: string; root: { table: string; id: string }; from: { number: string; name?: string }; records: { table: string; id: string; data: Body; role: string }[]; files: { key: string; bytes: number; folder?: boolean }[]; bytes: number; } interface Landing { creates: { table: string; id: string; data: Body }[]; copies: { from: string; to: string; bytes: number; folder?: boolean }[]; held: { table: string; sent: string; id: string }[]; bytes: number; root: { table: string; id: string }; } function inObject(slug: string, fn: (b: Inside) => T): Promise { return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance: Business) => fn(instance as unknown as Inside)); } /** The tables as the phone's rule reads them: the phone's copy is plain, so no table reads as sealed to it. */ function shapes(store: Store): Body { const out: Body = {}; for (const raw of store.definitions("table")) { const columns = Array.isArray(raw.columns) ? (raw.columns as Body[]) : []; out[String(raw.id)] = { columns: columns.map((c) => ({ key: String(c.key), type: String(c.type), ...(typeof c.link_to === "string" ? { link_to: c.link_to } : {}), computed: c.computed !== undefined && c.computed !== null })), ...(raw.send ? { send: raw.send } : {}), sealed: false, }; } return out; } function reads(store: Store, weighed: Map | null, asked: Map) { return (question: string, args: Body): unknown => { if (question === "send.row") return store.get(String(args.table), String(args.id))?.data ?? null; if (question === "send.linked") return store.list(String(args.table), { column: String(args.column), equals: args.id }).map((r) => ({ ...r.data, id: r.id })); if (question === "send.find") { const [first, ...rest] = Object.entries(args.equals as Body); if (!first) return []; return store .list(String(args.table), { column: first[0], equals: first[1] }) .filter((r) => rest.every(([k, v]) => r.data[k] === v)) .map((r) => r.id); } if (question === "send.weigh") { const at = `${args.folder === true ? "d" : "f"}:${String(args.key)}`; if (!weighed) { asked.set(at, { key: String(args.key), folder: args.folder === true }); return 0; } return weighed.get(at) ?? null; } throw new Error(`no answer for ${question}`); }; } /** What the sender's phone lays for one record, or the rule's refusal. */ export async function contents(from: SendPhone, table: string, record: string, id: string = crypto.randomUUID().replace(/-/g, "")): Promise<{ ok: Payload } | { error: string; code: string }> { const input = (store: Store) => ({ id, table, record, from: { number: from.number, name: "Test Sender" }, made_at: new Date().toISOString(), source_database: from.db, tables: shapes(store) }); const asked = new Map(); const first = await inObject(from.slug, (b) => tryPlan("send.contents", input(b.store), reads(b.store, null, asked))); if ("error" in first || !asked.size) return first; const weighed = await from.ask<{ files: { key: string; folder: boolean; bytes: number | null }[] }>("POST", "/v1/send/weigh", { files: [...asked.values()] }); const weights = new Map(weighed.body.files.map((f) => [`${f.folder ? "d" : "f"}:${f.key}`, f.bytes])); return inObject(from.slug, (b) => tryPlan("send.contents", input(b.store), reads(b.store, weights, new Map()))); } /** The sender's phone sends one record: the receiver's sharing key asked, the payload laid and sealed, the box posted. */ export async function sendSealed(from: SendPhone, to: SendPhone, table: string, record: string): Promise<{ status: number; body: Body; payload?: Payload }> { const key = await from.ask<{ key: string }>("GET", `/v1/send/key?number=${encodeURIComponent(to.number)}`); if (key.status !== 200) return key as { status: number; body: Body }; const id = crypto.randomUUID().replace(/-/g, ""); const made = await contents(from, table, record, id); if ("error" in made) return { status: 400, body: { error: made } }; const box = await seal(key.body.key, id, made.ok); const sent = await from.ask("POST", "/v1/send/make", { id, to: to.number, box, table, files: made.ok.files.map((f) => ({ key: f.key, ...(f.folder ? { folder: true } : {}) })) }); return { ...sent, payload: made.ok }; } /** The receiver's phone plans a landing over its own copy. */ export function landing(p: SendPhone, payload: Payload): Promise<{ ok: Landing } | { error: string; code: string }> { return inObject(p.slug, (b) => tryPlan("send.keep", { payload, tables: shapes(b.store), database: p.db, sent_by: null, sent_at: new Date().toISOString() }, reads(b.store, null, new Map()))); } /** What the receiver already holds of a send, as its card says. */ export function held(p: SendPhone, payload: Payload): Promise { return inObject(p.slug, (b) => { const out = tryPlan("send.held", { payload, tables: shapes(b.store), database: p.db, sent_by: null, sent_at: new Date().toISOString() }, reads(b.store, null, new Map())); return "ok" in out ? out.ok : []; }); } /** The rows a landing makes, written by the receiver's phone (its sync seals them under its own key); what it already holds is not made again. */ export function writeRows(p: SendPhone, plan: Landing): Promise { return inObject(p.slug, (b) => { for (const c of plan.creates) if (!b.store.get(c.table, c.id)) b.store.insert(c.table, c.id, c.data, null, b.store.bump()); }); } /** The receiver's phone keeps an offer: opens it, plans, asks the copies, and writes the rows once kept. */ export async function keepSealed(p: SendPhone, key: string, item: Body, tell = false): Promise<{ status: number; body: Body; plan?: Landing }> { const payload = await openBox(key, String(item.id), String(item.box)); const planned = await landing(p, payload); if ("error" in planned) return { status: 400, body: { error: planned } }; const kept = await p.ask("POST", "/v1/send/keep", { id: item.id, tell, copies: planned.ok.copies, root: planned.ok.root }); if (kept.status === 200 && kept.body.state === "kept") await writeRows(p, planned.ok); return { ...kept, plan: planned.ok }; }