/** * Shared lists (ruling R5, 16 Nov 2026): a list two or more * people see and edit, sealed on their phones to the list's own key * (cotton-core `seal::shared_list`). The list lives on its founder's object; * every other member reaches it through their own object, which asks the * founder's by RPC naming its owner's number. * * The objects hold only what the phones post: the membership (each member's * public sharing key and each epoch's `w1:` wraps of the list key) and the * items as `g1:<epoch>:` text. They never hold a key that opens one. * * - Only a member now reads or writes the list. A member's write seals an * item at the CURRENT epoch; an item at another epoch is refused. * - A member changes the membership by posting the whole state again: adding * someone keeps the epoch; removing someone moves it on, and every item * must then be sealed again at the new epoch (the remover's phone did it), * so nothing the object holds after is open to the one removed. * - The founder's object tells each member's object which lists they are in, * and a removed member's that they are out. */import { directory } from"../directory.ts";importtype { Env } from"../env.ts";import { json, readJson, refuse } from"../http.ts";import { numberOf } from"../calling/calls.ts";import { isPersonOf, ownKeys } from"./send.ts";exportconst SCHEMA = `CREATE TABLE IF NOT EXISTS shared_list (id TEXT PRIMARY KEY, state TEXT NOT NULL, at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS shared_in (owner TEXT NOT NULL, id TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (owner, id));`;exportinterfaceSharedHost { sql: SqlStorage; env: Env; slug: string; ownerPhone: string | null;}const LIST_ID = /^[A-Za-z0-9_-]{4,64}$/;const ITEM_ID = /^[A-Za-z0-9_-]{1,64}$/;const KEY = /^[A-Za-z0-9_-]{43}$/;const MAX_ITEMS = 2000;const MAX_ITEM = 16_384;/** A list's state as the phones lay it (cotton-core `SharedList`), checked for shape only: the object reads no value. */interfaceState { membership: { set_id: string; epoch: number; members: Record<string, string>; wraps: Record<string, Record<string, string>> }; items: Record<string, string>;}function stateOf(raw: unknown, id: string): State {const s = raw asState;const bad = (why: string): never => refuse(400, "bad_list", `the list's state: ${why}`);if (!s || typeof s !== "object" || !s.membership || typeof s.items !== "object" || s.items === null) bad("membership and items");const m = s.membership;if (m.set_id !== id) bad("it names another list");if (!Number.isInteger(m.epoch) || m.epoch < 1) bad("an epoch from 1");const members = Object.entries(m.members ?? {});if (!members.length) bad("at least one member");for (const [number, key] of members) {try {if (numberOf(number) !== number) bad("a member is named by their number"); } catch { bad("a member is named by their number"); }if (typeof key !== "string" || !KEY.test(key)) bad("a member's sharing key"); }const current = m.wraps?.[String(m.epoch)] ?? {};for (const [number] of members) if (typeof current[number] !== "string" || !current[number]!.startsWith("w1:")) bad("every member's wrap of the current key");for (const wraps ofObject.values(m.wraps ?? {})) for (const w ofObject.values(wraps)) if (typeof w !== "string" || !w.startsWith("w1:")) bad("a wrap");const items = Object.entries(s.items);if (items.length > MAX_ITEMS) bad(`at most ${MAX_ITEMS} items`);for (const [item, sealed] of items) {if (!ITEM_ID.test(item)) bad("an item's id");if (typeof sealed !== "string" || !sealed.startsWith("g1:") || sealed.length > MAX_ITEM) bad("an item is sealed text"); }return s;}function epochOf(sealed: string): number {returnNumber(sealed.split(":")[1]);}function load(sql: SqlStorage, id: string): State | null {const row = sql.exec<{ state: string }>("SELECT state FROM shared_list WHERE id = ?", id).toArray()[0];return row ? (JSON.parse(row.state) asState) : null;}function save(sql: SqlStorage, id: string, state: State): void { sql.exec("INSERT INTO shared_list (id, state, at) VALUES (?, ?, ?) ON CONFLICT (id) DO UPDATE SET state = excluded.state, at = excluded.at", id, JSON.stringify(state), newDate().toISOString());}function listId(raw: unknown): string {returntypeof raw === "string" && LIST_ID.test(raw) ? raw : refuse(400, "bad_list", "id: the list's id");}function peer(env: Env, slug: string) {return env.BUSINESS.get(env.BUSINESS.idFromName(slug), { locationHint: "apac" }) as unknown asShared;}/** The RPC surface another object calls (business.ts forwards each). */exportinterfaceShared { sharedRead(from: string, id: string, key: string | null): Promise<State | null>; sharedPut(from: string, id: string, item: string, sealed: string | null): Promise<boolean>; sharedState(from: string, id: string, state: unknown): Promise<boolean>; sharedJoined(from: string, id: string, joined: boolean): Promise<void>;}/** The founder's object, by the founder's number. */asyncfunction founder(host: SharedHost, owner: string): Promise<Shared> {const slug = await directory(host.env).lookup(owner);if (!slug) refuse(404, "no_list", "That list is not there.");return peer(host.env, slug);}// ── on the founder's object ────────────────────────────────────────────/** * The list, to one of its members now, whose sharing key is the one the list holds for them (AUDIT FIX B1, B-2: a slot * whose key someone else put there reads nothing); nothing to anyone else (not even whether it exists). */exportfunction readAsked(host: SharedHost, from: string, id: string, key: string | null): State | null {const state = load(host.sql, id);return state && key !== null && Object.hasOwn(state.membership.members, from) && state.membership.members[from] === key ? state : null;}/** An item written or taken by one of its members now, sealed at the current epoch. */exportfunction putAsked(host: SharedHost, from: string, id: string, item: string, sealed: string | null): boolean {const state = load(host.sql, id);if (!state || !Object.hasOwn(state.membership.members, from) || !ITEM_ID.test(item)) returnfalse;if (sealed === null) {delete state.items[item]; } else {if (typeof sealed !== "string" || !sealed.startsWith("g1:") || sealed.length > MAX_ITEM || epochOf(sealed) !== state.membership.epoch) returnfalse;if (!Object.hasOwn(state.items, item) && Object.keys(state.items).length >= MAX_ITEMS) returnfalse; state.items[item] = sealed; } save(host.sql, id, state);returntrue;}/** * The membership changed by one of its members now: an add keeps the epoch, a removal moves it on with every item * sealed again. Who may change what (AUDIT FIX B1, B-2): only the founder adds, and only their own people; a member who * stays keeps the key the list holds for them (a post changes no one's key but the poster's own); only the founder * removes others, and a member removes only themselves. */exportasyncfunction stateAsked(host: SharedHost, from: string, id: string, raw: unknown): Promise<boolean> {const was = load(host.sql, id);if (!was || !Object.hasOwn(was.membership.members, from)) returnfalse;let next: State;try { next = stateOf(raw, id); } catch {returnfalse; }const founderPosts = from === host.ownerPhone;const before = was.membership.members;const after = next.membership.members;const added = Object.keys(after).filter((n) => !Object.hasOwn(before, n));if (added.length && !founderPosts) returnfalse;for (const number of added) if (!(await isPersonOf(host.sql, number))) returnfalse;if (Object.keys(after).some((n) => n !== from && Object.hasOwn(before, n) && after[n] !== before[n])) returnfalse;const removed = Object.keys(before).filter((n) => !Object.hasOwn(after, n));if (!founderPosts && removed.some((n) => n !== from)) returnfalse;const epoch = next.membership.epoch;if (removed.length ? epoch <= was.membership.epoch : epoch !== was.membership.epoch) returnfalse;if (removed.length && Object.values(next.items).some((sealed) => epochOf(sealed) !== epoch)) returnfalse;if (!Object.hasOwn(next.membership.members, host.ownerPhone ?? "")) returnfalse; save(host.sql, id, next);await tell(host, id, was, next);returntrue;}/** Each member's object told it is in, each removed one's that it is out. */asyncfunction tell(host: SharedHost, id: string, was: State | null, next: State): Promise<void> {const owner = host.ownerPhone!;const before = newSet(Object.keys(was?.membership.members ?? {}));const now = newSet(Object.keys(next.membership.members));const changes: [string, boolean][] = [...[...now].filter((n) => !before.has(n)).map((n): [string, boolean] => [n, true]), ...[...before].filter((n) => !now.has(n)).map((n): [string, boolean] => [n, false])];for (const [number, joined] of changes) {if (number === owner) continue;try {const slug = await directory(host.env).lookup(number);if (slug && slug !== host.slug) await peer(host.env, slug).sharedJoined(owner, id, joined); } catch {// A member whose object does not answer finds the list when they ask for it by name. } }}// ── on a member's object ───────────────────────────────────────────────/** The founder's object says this person is in (or out of) one of their lists. */exportasyncfunction joinedIn(host: SharedHost, from: string, id: string, joined: boolean): Promise<void> {if (!LIST_ID.test(id)) return;if (!joined) { host.sql.exec("DELETE FROM shared_in WHERE owner = ? AND id = ?", from, id);return; }// Only one of this person's people puts them on a list.if (!(await isPersonOf(host.sql, from))) return; host.sql.exec("INSERT OR IGNORE INTO shared_in (owner, id, at) VALUES (?, ?, ?)", from, id, newDate().toISOString());}// ── the phone's routes ─────────────────────────────────────────────────/** * `GET /v1/shared/lists`: the lists this person founded and those they are in. * `POST /v1/shared/lists {id, state}`: a list founded here (the founder among its members, each other member one of this person's people). * `GET /v1/shared/list?owner&id`: a list, read where it lives. * `POST /v1/shared/list/item {owner, id, item, sealed|null}`: an item written or taken. * `POST /v1/shared/list/state {owner, id, state}`: the membership changed. */exportasyncfunction route(host: SharedHost, deviceId: string | null, request: Request, url: URL): Promise<Response | null> {const path = url.pathname;if (!path.startsWith("/v1/shared/")) returnnull;if (!deviceId) refuse(401, "sign_in", "a shared list is read from a signed-in phone");const me = host.ownerPhone ?? refuse(409, "no_owner", "this object has no number to share from");const method = request.method;if (method === "GET" && path === "/v1/shared/lists") {const founded = host.sql.exec<{ id: string }>("SELECT id FROM shared_list ORDER BY at DESC").toArray().map((r) => ({ owner: me, id: r.id }));const joined = host.sql.exec<{ owner: string; id: string }>("SELECT owner, id FROM shared_in ORDER BY at DESC").toArray().map((r) => ({ owner: r.owner, id: r.id }));return json({ me, lists: [...founded, ...joined] }); }if (method === "POST" && path === "/v1/shared/lists") {const body = await readJson(request);const id = listId(body.id);if (load(host.sql, id)) refuse(409, "list_exists", "a list with this id is here already");const state = stateOf(body.state, id);if (state.membership.epoch !== 1 || !Object.hasOwn(state.membership.members, me)) refuse(400, "bad_list", "a new list is founded at epoch 1 with its founder among its members");for (const number ofObject.keys(state.membership.members)) {if (number !== me && !(await isPersonOf(host.sql, number))) refuse(403, "not_your_person", "A list is shared only with your people: someone you both accepted on Cotton."); } save(host.sql, id, state);await tell(host, id, null, state);return json({ ok: true, owner: me, id }); }const owner = url.searchParams.get("owner") ?? (method === "POST" ? null : me);if (method === "GET" && path === "/v1/shared/list") {const id = listId(url.searchParams.get("id"));const at = numberOf(owner ?? me);const key = ownKeys(host.sql).share;const state = at === me ? readAsked(host, me, id, key) : await (await founder(host, at)).sharedRead(me, id, key);return state ? json({ me, owner: at, id, state }) : refuse(404, "no_list", "That list is not there."); }if (method === "POST" && (path === "/v1/shared/list/item" || path === "/v1/shared/list/state")) {const body = await readJson(request);const id = listId(body.id);const at = numberOf(typeof body.owner === "string" ? body.owner : me);let ok: boolean;if (path === "/v1/shared/list/item") {const item = typeof body.item === "string" ? body.item : refuse(400, "bad_item", "item: the item's id");const sealed = body.sealed === null ? null : typeof body.sealed === "string" ? body.sealed : refuse(400, "bad_item", "sealed: the item sealed in the list, or null to take it"); ok = at === me ? putAsked(host, me, id, item, sealed) : await (await founder(host, at)).sharedPut(me, id, item, sealed); } else { ok = at === me ? await stateAsked(host, me, id, body.state) : await (await founder(host, at)).sharedState(me, id, body.state); }return ok ? json({ ok: true }) : refuse(403, "not_on_list", "Only someone on this list changes it, and only as the list now stands."); }returnnull;}