/** * THE OWNER ALLOWS (ROUTES-AUDIT.md finding 8, coordinator 23 Nov 2026; behind the TOKEN-SCOPES switch). * * An assistant's token could act as the owner to the outside world: send mail from the owner's own domain, change where * an address forwards, and make a Google event that invites up to 200 guests (and has Google tell them all). With the * token-scopes switch on, a token reaches no device route at all; these three it may still ASK for: * * - the request is kept on the object as it came (`owner_ask_held`, never synced: a mail's words stay here); * - an `assistant_ask` row says what it would do, for the owner's phones (the unlock card's way: every app pulls it * with the unlock tables, and the card stands wherever the person is). LOCK TABLES 1: what it would do (the * addresses, subject, title, guests) and the answer the request got are sealed at arrival to the owner's arrival * key; only the kind, the asking token, the times, the state and the status stay clear, which is all the object * reads. With no arrival key handed yet an ask is refused (409 no_arrival_key), never written in the clear; * - the answer the token reads (`GET /v1/asks/<id>`) is kept on the object alone (`owner_ask_answer`, never synced) * for a day; * - the token is answered `202 owner_asked` with the ask's id, and reads `GET /v1/asks/<id>` for the outcome; * - the owner's own signed-in device answers: `POST /v1/asks/allow { ask_id }` runs the kept request as that device * would, once, and keeps its answer for the token; `POST /v1/asks/refuse { ask_id }` drops it; * - unanswered for ASK_MINUTES, it expires and the kept request goes. * * No token, no admin and no server-side path allows: only a device of the owner's own (unlockDevice's rule). Off, * nothing here runs: a token reaches these routes as before. */import { refuse } from"./http.ts";import { isSealedRow } from"./seal.ts";importtype { Store, StoredRow } from"./store.ts";importtype { Engine, Outcome } from"./engine.ts";exportconst ASK_TABLE = "assistant_ask";/** How long an ask waits for the owner. */exportconst ASK_MINUTES = 10;/** How much of a mail's text the card carries (it says the whole length too). */exportconst ASK_TEXT_CHARS = 4000;/** At most this many asks waiting at once on one database: an assistant cannot bury the phone in cards. */exportconst WAITING_MOST = 5;exportconst SCHEMA = `CREATE TABLE IF NOT EXISTS owner_ask_held (ask_id TEXT PRIMARY KEY, token_id TEXT NOT NULL, method TEXT NOT NULL, path TEXT NOT NULL, body TEXT NOT NULL);CREATE TABLE IF NOT EXISTS owner_ask_answer (ask_id TEXT PRIMARY KEY, token_id TEXT NOT NULL, answer TEXT NOT NULL, at INTEGER NOT NULL);`;/** How long the answer a token reads is kept after its ask was answered. */exportconst ANSWER_KEPT_MS = 24 * 60 * 60_000;/** The answer the asking token reads, kept on the object alone (the card's copy is sealed for the phone). */exportfunction keepAnswer(sql: SqlStorage, askId: string, tokenId: string, answer: string, nowMs: number): void { sql.exec("INSERT INTO owner_ask_answer (ask_id, token_id, answer, at) VALUES (?, ?, ?, ?) ON CONFLICT (ask_id) DO UPDATE SET answer = excluded.answer, at = excluded.at", askId, tokenId, answer, nowMs);}exporttypeAskKind = "mail_send" | "mail_forward" | "guests";/** What a kept request would do, said in the clear for the card: its kind and the few fields the owner decides on. */exportinterfaceAsked { kind: AskKind; fields: Record<string, unknown>;}const list = (v: unknown): string[] => (Array.isArray(v) ? v : typeof v === "string" ? [v] : []).map((x) => (typeof x === "string" ? x : typeof x === "object" && x && "email"in x ? String((x as { email: unknown }).email) : String(x))).filter((x) => x.trim() !== "");/** * Whether a token's request is one the owner must allow, and what it would do. `body` is the request's JSON (null when * it is not JSON). Anything else is not asked for: it is refused as every device route is. *//** The routes that act on the outside world (mail sent, a forward changed, an event's guests told): what `outward` covers. */exportfunction outwardRoute(method: string, path: string): boolean {return method === "POST" && (path === "/v1/mail/send" || path === "/v1/mail/addresses" || path === "/v1/google/events");}exportfunction askedOf(method: string, path: string, body: Record<string, unknown> | null): Asked | null {if (method !== "POST" || !body) returnnull;if (path === "/v1/mail/send") {// A send that names no sender or no one to send to is no card: it is refused as any device route is.if (!String(body.from ?? "").trim() || list(body.to).length === 0) returnnull;// AUDIT C 5: the card holds everything Allow sends (on Allow the kept request runs as it was sent): bcc, the text// (its head, and how long it is whole) and every attachment by name, type and size, never only from/to/subject.const text = typeof body.text === "string" ? body.text : "";const attachments = (Array.isArray(body.attachments) ? body.attachments : []).map((a) => {const f = (a ?? {}) asRecord<string, unknown>;const content = typeof f.content === "string" ? f.content.replace(/=+$/, "") : "";return`${String(f.name ?? "") || "unnamed"} (${String(f.mime ?? "") || "no type"}, ${Math.floor((content.length * 3) / 4)} bytes)`; });return { kind: "mail_send", fields: { from: String(body.from ?? ""), to: list(body.to), cc: list(body.cc), bcc: list(body.bcc), subject: String(body.subject ?? "").slice(0, 200), text: text.slice(0, ASK_TEXT_CHARS), text_chars: text.length, attachments }, }; }if (path === "/v1/mail/addresses" && Object.hasOwn(body, "forwardTo")) {return { kind: "mail_forward", fields: { address: String(body.address ?? "").toLowerCase(), forward_to: body.forwardTo === null || body.forwardTo === "" ? null : String(body.forwardTo) } }; }if (path === "/v1/google/events") {const event = (body.event ?? {}) asRecord<string, unknown>;const guests = list(event.attendees);if (body.op !== "delete" && guests.length > 0) {return { kind: "guests", fields: { title: String(event.summary ?? event.title ?? "").slice(0, 200), guests: guests.slice(0, 200), count: guests.length, notify: body.notify === "all" } }; } }returnnull;}const isoAfter = (ms: number): string => newDate(ms).toISOString();/** Waiting asks past their time leave waiting, their kept requests with them. */exportfunction sweep(sql: SqlStorage, store: Store, engine: Engine, nowMs: number, version: number, outcome: Outcome): void {const now = isoAfter(nowMs); sql.exec("DELETE FROM owner_ask_answer WHERE at < ?", nowMs - ANSWER_KEPT_MS);for (const r of [...store.scan(ASK_TABLE)]) {if (r.data.state === "waiting" && String(r.data.expires_at) <= now) settle(sql, engine, r, { state: "expired", answered_at: now }, version, outcome); }}/** An ask leaves waiting: its kept request goes, whatever the answer. */exportfunction settle(sql: SqlStorage, engine: Engine, row: StoredRow, patch: Record<string, unknown>, version: number, outcome: Outcome): void { sql.exec("DELETE FROM owner_ask_held WHERE ask_id = ?", row.id); engine.update(row, patch, version, outcome);}/** The ask a token makes: refused past WAITING_MOST waiting; the row the phones show, and the request kept. */exportfunction ask( sql: SqlStorage, store: Store, engine: Engine, token: { id: string; name: string }, request: { method: string; path: string; body: string }, asked: Asked, nowMs: number, version: number, outcome: Outcome, id: string,): StoredRow {const now = isoAfter(nowMs);const waiting = [...store.scan(ASK_TABLE)].filter((r) => r.data.state === "waiting" && String(r.data.expires_at) > now);if (waiting.length >= WAITING_MOST) refuse(429, "too_many_asks", `${WAITING_MOST} asks already wait for the owner: ask again once they are answered`); sql.exec("INSERT INTO owner_ask_held (ask_id, token_id, method, path, body) VALUES (?, ?, ?, ?, ?)", id, token.id, request.method, request.path, request.body);return engine.create( ASK_TABLE, { kind: asked.kind, ...asked.fields, token_id: token.id, client: token.name || "an assistant", asked_at: now, expires_at: isoAfter(nowMs + ASK_MINUTES * 60_000), state: "waiting" }, version, outcome,0, { id }, );}/** The kept request of a waiting ask, for Allow; refused by name when it is not waiting. */exportfunction held(sql: SqlStorage, store: Store, askId: string, nowMs: number): { row: StoredRow; method: string; path: string; body: string } {const row = store.get(ASK_TABLE, askId) ?? refuse(404, "no_such_ask", `no ask ${askId}`);if (row.data.state !== "waiting" || String(row.data.expires_at) <= isoAfter(nowMs)) refuse(409, "ask_not_waiting", "this ask was already answered, or its time ran out");const kept = sql.exec<{ method: string; path: string; body: string }>("SELECT method, path, body FROM owner_ask_held WHERE ask_id = ?", askId).toArray()[0] ?? refuse(409, "ask_not_waiting", "this ask's request is no longer kept");return { row, ...kept };}/** What the token that asked reads: the state, and once allowed the answer its request got. Another token is told nothing. */exportfunction readFor(sql: SqlStorage, store: Store, askId: string, tokenId: string): Record<string, unknown> {const row = store.get(ASK_TABLE, askId);if (!row || row.data.token_id !== tokenId) refuse(404, "no_such_ask", `no ask ${askId}`);const d = row.data;// An ask answered before LOCK TABLES 1 holds its answer on its open row, as the token read it then.let answer: unknown = sql.exec<{ answer: string }>("SELECT answer FROM owner_ask_answer WHERE ask_id = ? AND token_id = ?", askId, tokenId).toArray()[0]?.answer ?? (isSealedRow(d) ? null : (d.answer ?? null));if (typeof answer === "string") {try { answer = JSON.parse(answer); } catch { /* words, as the request answered them */ } }return { ask_id: row.id, kind: d.kind, state: d.state, expires_at: d.expires_at, answered_at: d.answered_at ?? null, status: d.status ?? null, answer };}