/** * The unlock window on the Worker (sealing plan §3 and * ruling R4). * * An assistant's owner token asks to read sealed tables (`request_unlock`, or * a read that reaches one: `window_needed`). The object mints a one-use X25519 * pair, keeps the private half sealed under the Worker secret `WINDOW_KEY` in * its own table, and writes an `unlock_request` row with the public half. The * owner allows it on the phone, which wraps the table keys of every version * (and the blind keys) to that public half, signs the unlock statement with * the person key, and posts `unlock_allow`. The object checks the signature, * opens the wrap, deletes the private half at once (a replayed grant opens * nothing), stamps `ends_at` on its own clock, and keeps the opened keys * sealed under `WINDOW_KEY` in `window_secret` and in memory. * * While `now < ends_at`, nothing ended it and the token is not revoked, that * one token's reads of the granted tables open rows. The guard is checked on * every call; the alarm only cleans up. The window ends at `ends_at` (timer), * on the phone (`unlock_end`), when the assistant ends it (`end_unlock`), when * the token is revoked, or when `WINDOW_KEY` no longer opens what it kept * (key_lost); each deletes `window_secret` and drops the keys from memory. * * HOW LONG. The person picks when allowing: 15 minutes, 1 hour, 1 day, or * until they turn it off (`minutes` 15, 60, 1440 or 0, [DURATIONS]). The * request may suggest one; the person's pick wins. A standing grant (0) ends * only by the person (phone), the assistant, revoking the connection, or key * loss; its `ends_at` is [STANDING_ENDS]. * * WHO. Any assistant connection may ASK, a lane's and the coordinator's too * (plan Q8 lifted by the owner, 15 Nov 2026). Only the person's own signed-in * device ALLOWS, with the person key's signature: no token, no admin, no * server-side way opens a window. A window binds to the assistant's * CONNECTION, not its access token: an OAuth refresh mints a new token in the * same connection (`mcp_token.connection_id`), and the window stands; a pasted * token is its own connection. * * THE LOG. Every read or write answered inside a window writes an * `assistant_read` row (which assistant, tables, tool, how many rows, when): * clear, like the grant row it hangs from (it names no value a person typed). * * NO FALLBACK TO CLEAR. A missing `WINDOW_KEY` refuses every request by name * (`window_unavailable`); a row that does not open is answered parked by * name, never blank. * * The internal tables are the object's own SQLite tables, never in `rows`, * never synced, never journalled. */ import type { Engine, Outcome } from "./engine.ts"; import { closed } from "./agent_statement.ts"; import { refuse, sha256Hex } from "./http.ts"; import type { McpCaller } from "./mcp/context.ts"; import { askerOf } from "./tokens.ts"; import type { Store, StoredRow } from "./store.ts"; import { fromBase64Url, toBase64Url } from "./vault.ts"; export const SCHEMA = ` CREATE TABLE IF NOT EXISTS window_request_key (request_id TEXT PRIMARY KEY, priv TEXT NOT NULL); CREATE TABLE IF NOT EXISTS window_secret (grant_id TEXT PRIMARY KEY, token_id TEXT NOT NULL, tables TEXT NOT NULL, blob TEXT NOT NULL, ends_at TEXT NOT NULL); CREATE INDEX IF NOT EXISTS window_secret_token ON window_secret (token_id); `; /** The connection column, on an object made before windows bound to connections: a window kept then is its token's own connection. */ export function migrate(sql: SqlStorage): void { const columns = [...sql.exec("PRAGMA table_info(window_secret)")].map((c) => c.name); if (!columns.includes("connection_id")) { sql.exec("ALTER TABLE window_secret ADD COLUMN connection_id TEXT NOT NULL DEFAULT ''"); sql.exec("UPDATE window_secret SET connection_id = token_id"); } sql.exec("CREATE INDEX IF NOT EXISTS window_secret_connection ON window_secret (connection_id)"); } export const REQUEST_TABLE = "unlock_request"; export const GRANT_TABLE = "unlock_grant"; export const READ_TABLE = "assistant_read"; /** The window's own tables: only the object's unlock code writes them, never a device's direct write nor an MCP write. */ export const WINDOW_TABLES: ReadonlySet = new Set([REQUEST_TABLE, GRANT_TABLE, READ_TABLE]); export const UNLOCK_CONTEXT = "cotton-unlock-v1"; /** What the person may pick: 15 minutes, 1 hour, 1 day, or until they turn it off (0). */ export const DURATIONS: readonly number[] = [15, 60, 1440, 0]; export const STANDING = 0; /** A standing grant's ends_at: later than any clock. */ export const STANDING_ENDS = "9999-12-31T23:59:59.999Z"; /** What a request suggests when it says nothing. */ export const DEFAULT_MINUTES = 15; /** Is this one of the four durations? */ export function isDuration(minutes: unknown): minutes is number { return typeof minutes === "number" && DURATIONS.includes(minutes); } const DURATION_SAID = "minutes is 15, 60 or 1440, or 0 for until the owner turns it off"; export const REQUEST_TTL_MS = 10 * 60_000; /** Requests an object takes in an hour, across every token (plan §3.3, card spam). */ export const REQUESTS_PER_HOUR = 6; const REASON_LENGTH = 200; const WRAP_PREFIX = "w1:"; const WRAP_INFO = "cotton-vault-wrap-v1"; /** A PKCS#8 X25519 private key is this prefix and the 32 secret bytes (RFC 8410). */ const X25519_PKCS8 = Uint8Array.from([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20]); export type EndedBy = "timer" | "phone" | "assistant" | "token_revoked" | "key_lost"; /** The connection a token belongs to: its `connection_id` (an OAuth connection, kept across refreshes), else the token itself. */ export function connectionOf(store: Store, tokenId: string): string { const said = store.get("mcp_token", tokenId)?.data.connection_id; return typeof said === "string" && said ? said : tokenId; } /** The keys one window holds for one table: TK by version, and BK. */ export interface TableKeys { table: string; /** The window these keys are of. */ grant_id: string; /** Until the owner turns it off. */ standing: boolean; tk: ReadonlyMap; bk: Uint8Array; /** TFR(table): the root of the files this table's rows keep that a window opens (a message's kept chat pictures), when the grant handed it. */ files?: Uint8Array; ends_at: string; } /** A window's opened bundle (seal-core grant.rs `GrantBundle`). */ export interface Bundle { request_id: string; token_id: string; keys: Map>; blind: Map; /** TFR by table, for a table whose kept files a window opens (seal-core grant.rs `files`); absent before 22 Nov 2026. */ files: Map; } const utf8 = new TextEncoder(); // ── who may hold a window ──────────────────────────────────────────────── /** * Why this caller may not ask for a window, or null when it may. Every * assistant connection may ask, a lane's and the coordinator's included (plan * Q8 lifted, 15 Nov 2026): asking opens nothing, only the person's own device * allows. Kept as the one place a refusal would be said. */ export function windowRefusal(_caller: McpCaller): string | null { return null; } // ── the Worker secret ──────────────────────────────────────────────────── /** `WINDOW_KEY` as 32 bytes, or null when it is missing or not 32 bytes of base64url. */ export function windowKey(said: string | undefined): Uint8Array | null { if (!said) return null; try { const key = fromBase64Url(said); return key.length === 32 ? key : null; } catch { return null; } } async function gcmKey(key: Uint8Array, use: "encrypt" | "decrypt"): Promise { return crypto.subtle.importKey("raw", key, "AES-GCM", false, [use]); } /** `nonce12 || AES-256-GCM(key, bytes, aad)` as base64url. */ export async function sealSecret(key: Uint8Array, aad: string, bytes: Uint8Array): Promise { const nonce = crypto.getRandomValues(new Uint8Array(12)); const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: utf8.encode(aad) }, await gcmKey(key, "encrypt"), bytes)); const out = new Uint8Array(12 + body.length); out.set(nonce); out.set(body, 12); return toBase64Url(out); } /** What `sealSecret` kept, or null when it does not open under this key and aad. */ export async function openSecret(key: Uint8Array, aad: string, text: string): Promise { try { const blob = fromBase64Url(text); if (blob.length < 12 + 16) return null; return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: blob.slice(0, 12), additionalData: utf8.encode(aad) }, await gcmKey(key, "decrypt"), blob.slice(12))); } catch { return null; } } const requestAad = (requestId: string): string => `window-request-key|${requestId}`; const secretAad = (grantId: string): string => `window-secret|${grantId}`; // ── X25519 and the w1 wrap (cotton-core vault/wrap.rs) ─────────────────── /** A fresh X25519 pair: the private half's 32 bytes and the public half's. */ async function mintPair(): Promise<{ priv: Uint8Array; pub: Uint8Array }> { const pair = (await crypto.subtle.generateKey({ name: "X25519" }, true, ["deriveBits"])) as CryptoKeyPair; const pub = new Uint8Array((await crypto.subtle.exportKey("raw", pair.publicKey)) as ArrayBuffer); const jwk = (await crypto.subtle.exportKey("jwk", pair.privateKey)) as JsonWebKey; return { priv: fromBase64Url(jwk.d!), pub }; } async function privateKey(secret: Uint8Array): Promise { const pkcs8 = new Uint8Array(X25519_PKCS8.length + 32); pkcs8.set(X25519_PKCS8); pkcs8.set(secret, X25519_PKCS8.length); return crypto.subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]); } /** The w1 wrap's key: HKDF-SHA256(shared, salt = ephemeral_pub || recipient_pub, info "cotton-vault-wrap-v1"); null for an all-zero shared secret. */ async function wrapKey(shared: Uint8Array, ephemeralPub: Uint8Array, recipientPub: Uint8Array): Promise { if (shared.every((b) => b === 0)) return null; const salt = new Uint8Array(64); salt.set(ephemeralPub); salt.set(recipientPub, 32); const ikm = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]); const bits = new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: utf8.encode(WRAP_INFO) }, ikm, 256)); return crypto.subtle.importKey("raw", bits, "AES-GCM", false, ["decrypt", "encrypt"]); } /** Open a `w1:` wrap with the recipient's private half (`vault::wrap::unwrap`); null when it does not open. */ export async function unwrap(recipientSecret: Uint8Array, recipientPub: Uint8Array, wrapped: string): Promise { if (!wrapped.startsWith(WRAP_PREFIX)) return null; let body: Uint8Array; try { body = fromBase64Url(wrapped.slice(WRAP_PREFIX.length)); } catch { return null; } if (body.length < 32 + 12 + 16) return null; const ephemeralPub = body.slice(0, 32); try { const peer = await crypto.subtle.importKey("raw", ephemeralPub, { name: "X25519" }, false, []); const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: peer } as unknown as SubtleCryptoDeriveKeyAlgorithm, await privateKey(recipientSecret), 256)); const key = await wrapKey(shared, ephemeralPub, recipientPub); if (!key) return null; return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: body.slice(32, 44), additionalData: recipientPub }, key, body.slice(44))); } catch { return null; } } // ── the statement and the bundle (cotton-core seal/grant.rs) ───────────── /** A field of the statement: never empty, no separator (seal-core `plain_field`). */ function plainField(what: string, value: string): string { if (!value || /[\n|,]/.test(value)) refuse(400, "bad_args", `${what} ${JSON.stringify(value)} is empty or holds a separator`); return value; } /** Tables sorted and once each, at least one, each a plain field. */ export function sortedTables(tables: readonly string[]): string[] { const out = [...new Set(tables.map((t) => plainField("table", t)))].sort(); if (!out.length) refuse(400, "bad_args", "a grant names at least one table"); return out; } /** The bytes the person key signs (seal-core `unlock_statement`). */ export async function unlockStatement(databaseId: string, requestId: string, tokenId: string, tables: readonly string[], minutes: number, wrapped: string): Promise { return `${UNLOCK_CONTEXT}\n${plainField("database", databaseId)}\n${plainField("request", requestId)}\n${plainField("token", tokenId)}\n${sortedTables(tables).join(",")}\n${minutes}\n${await sha256Hex(wrapped)}`; } /** The bundle's JSON, read; null when it is not one (seal-core `parse_bundle`). */ export function parseBundle(text: string): Bundle | null { let value: unknown; try { value = JSON.parse(text); } catch { return null; } if (!value || typeof value !== "object" || Array.isArray(value)) return null; const v = value as Record; if (typeof v.request_id !== "string" || typeof v.token_id !== "string") return null; const key32 = (k: unknown): Uint8Array | null => { if (typeof k !== "string") return null; try { const b = fromBase64Url(k); return b.length === 32 ? b : null; } catch { return null; } }; const keys = new Map>(); if (!v.keys || typeof v.keys !== "object" || Array.isArray(v.keys)) return null; for (const [table, versions] of Object.entries(v.keys as Record)) { if (!versions || typeof versions !== "object" || Array.isArray(versions)) return null; const byV = new Map(); for (const [said, k] of Object.entries(versions as Record)) { const n = Number(said); const key = key32(k); if (!/^[1-9]\d{0,9}$/.test(said) || !key) return null; byV.set(n, key); } if (!byV.size) return null; keys.set(table, byV); } const blind = new Map(); if (!v.blind || typeof v.blind !== "object" || Array.isArray(v.blind)) return null; for (const [table, k] of Object.entries(v.blind as Record)) { const key = key32(k); if (!key) return null; blind.set(table, key); } const files = new Map(); if (v.files !== undefined) { if (!v.files || typeof v.files !== "object" || Array.isArray(v.files)) return null; for (const [table, k] of Object.entries(v.files as Record)) { const key = key32(k); if (!key || !keys.has(table)) return null; files.set(table, key); } } return { request_id: v.request_id, token_id: v.token_id, keys, blind, files }; } /** Open a grant's wrap with the request's private half and hold it to the request, token and tables it was signed for (seal-core `open_grant`). */ export async function openGrant(secret: Uint8Array, workerPub: Uint8Array, requestId: string, tokenId: string, tables: readonly string[], wrapped: string): Promise<{ bundle: Bundle; text: string } | null> { const plain = await unwrap(secret, workerPub, wrapped); if (!plain) return null; const text = new TextDecoder().decode(plain); const bundle = parseBundle(text); if (!bundle || bundle.request_id !== requestId || bundle.token_id !== tokenId) return null; const want = sortedTables(tables).join(","); if ([...bundle.keys.keys()].sort().join(",") !== want || [...bundle.blind.keys()].sort().join(",") !== want) return null; return { bundle, text }; } export async function verifySig(publicKey: string, sig: string, text: string): Promise { let pub: Uint8Array; let s: Uint8Array; try { pub = fromBase64Url(publicKey); s = fromBase64Url(sig); } catch { return false; } if (pub.length !== 32 || s.length !== 64) return false; try { const key = await crypto.subtle.importKey("raw", pub, { name: "Ed25519" }, false, ["verify"]); return await crypto.subtle.verify({ name: "Ed25519" }, key, s, utf8.encode(text)); } catch { return false; } } /** Does the person key `publicKey` sign this grant for this request (seal-core `verify_grant`)? The signer is its first 8 characters. */ export async function verifyGrant(publicKey: string, databaseId: string, requestId: string, tokenId: string, grant: { tables: readonly string[]; minutes: number; wrapped: string; signer: string; sig: string }): Promise { if (publicKey.slice(0, 8) !== grant.signer) return false; return verifySig(publicKey, grant.sig, await unlockStatement(databaseId, requestId, tokenId, grant.tables, grant.minutes, grant.wrapped)); } // ── the object's side ──────────────────────────────────────────────────── /** What the window code needs of its object. */ export interface WindowHost { sql: SqlStorage; store: Store; databaseId: string; /** `WINDOW_KEY`, or null when the Worker has none. */ key: Uint8Array | null; /** The person key's public half (base64url) under a fingerprint, or null. */ personKey(fingerprint: string): string | null; /** One write: a transaction and a fresh version. */ write(fn: (engine: Engine, version: number, outcome: Outcome) => T): T; } export interface PreparedAllow { request: StoredRow; grantId: string; tables: string[]; minutes: number; wrappedSha256: string; signer: string; sig: string; bundle: Bundle; blob: string; } function unavailable(): never { refuse(503, "window_unavailable", "this Worker holds no WINDOW_KEY: no window can be opened, and nothing is answered in the clear"); } const isoAfter = (ms: number): string => new Date(ms).toISOString(); function stringList(v: unknown, what: string): string[] { if (!Array.isArray(v) || v.some((t) => typeof t !== "string")) refuse(400, "bad_args", `${what} is a list of table ids`); return v as string[]; } /** A request's tables as held. */ function heldTables(row: StoredRow): string[] { return Array.isArray(row.data.tables) ? (row.data.tables as string[]) : []; } /** * The windows one object holds. The keys of an open window live here in * memory and, sealed under `WINDOW_KEY`, in `window_secret`; a new instance * (the object evicted) reads them back on its first call. */ export class Windows { private readonly held = new Map(); /** A connection's requests (one made before requests named their connection is its token's). */ private requestsOf(store: Store, connection: string): StoredRow[] { const byConnection = store.list(REQUEST_TABLE, { column: "connection_id", equals: connection }); const byToken = store.list(REQUEST_TABLE, { column: "token_id", equals: connection }).filter((r) => !r.data.connection_id); return [...byConnection, ...byToken]; } /** A waiting request of this connection, unexpired, or null. */ waiting(store: Store, connection: string, now: string): StoredRow | null { return this.requestsOf(store, connection).find((r) => r.data.state === "waiting" && String(r.data.expires_at) > now) ?? null; } /** This connection's latest declined request naming any of `tables`, while it has not passed its expires_at, or null. */ declined(store: Store, connection: string, tables: readonly string[], now: string): StoredRow | null { const hits = this.requestsOf(store, connection) .filter((r) => r.data.state === "declined" && String(r.data.expires_at) > now && tables.some((t) => heldTables(r).includes(t))) .sort((a, b) => String(b.data.requested_at).localeCompare(String(a.data.requested_at))); return hits[0] ?? null; } /** * Ask for a window (`request_unlock`, or a read reaching a sealed table): * while the owner's Not now on a request of this connection naming any * table asked stands (until that request's expires_at), that declined * request is answered and nothing is asked; a waiting request of this * connection for every table asked is answered again; otherwise a new one * is made, once the object has taken fewer than six this hour. `minutes` is * what the request suggests (one of DURATIONS); the person's pick wins. */ async request(host: WindowHost, caller: McpCaller, asked: { tables: string[]; reason: string; minutes: number }, nowMs: number): Promise { const refusal = windowRefusal(caller); if (refusal) refuse(403, "window_refused", refusal); const key = host.key ?? unavailable(); // A table no assistant is ever given (agent_statement CLOSED) is never on a card. const tables = sortedTables(asked.tables.filter((t) => !closed(t))); if (!tables.length) refuse(400, "bad_args", "name a sealed table to read"); const minutes = asked.minutes; if (!isDuration(minutes)) refuse(400, "bad_args", DURATION_SAID); const reason = asked.reason.trim().slice(0, REASON_LENGTH); const now = isoAfter(nowMs); const connection = connectionOf(host.store, caller.tokenId); const declined = this.declined(host.store, connection, tables, now); if (declined) return declined; const same = this.waiting(host.store, connection, now); if (same && tables.every((t) => heldTables(same).includes(t))) return same; const lastHour = [...host.store.scan(REQUEST_TABLE)].filter((r) => String(r.data.requested_at) > isoAfter(nowMs - 3_600_000)).length; if (lastHour >= REQUESTS_PER_HOUR) refuse(429, "too_many_requests", `this database took ${REQUESTS_PER_HOUR} unlock requests in the last hour: ask again later`); const pair = await mintPair(); const id = crypto.randomUUID(); const priv = await sealSecret(key, requestAad(id), pair.priv); pair.priv.fill(0); return host.write((engine, version, outcome) => { // A waiting request this token had for fewer tables is answered by the new one. if (same) this.settleRequest(host, engine, same, "expired", version, outcome); host.sql.exec("INSERT INTO window_request_key (request_id, priv) VALUES (?, ?)", id, priv); return engine.create( REQUEST_TABLE, { token_id: caller.tokenId, connection_id: connection, token_name: caller.name, client: caller.name || "an assistant", tables, reason, minutes, worker_pub: toBase64Url(pair.pub), requested_at: now, expires_at: isoAfter(nowMs + REQUEST_TTL_MS), state: "waiting", ...connectedAt(host.store, connection, caller.tokenId), ...askerOf(host.store, caller.tokenId) }, version, outcome, 0, { id }, ); }); } /** A request leaves waiting: its private half goes with it. */ private settleRequest(host: WindowHost, engine: Engine, row: StoredRow, state: "granted" | "declined" | "expired", version: number, outcome: Outcome): void { host.sql.exec("DELETE FROM window_request_key WHERE request_id = ?", row.id); if (row.data.state === "waiting") engine.update(row, { state }, version, outcome); } /** `unlock_allow`'s checks and its cryptography, before its transaction: the signature, the wrap, and the keys sealed for `window_secret`. */ async prepareAllow(host: WindowHost, args: Record, nowMs: number): Promise { const key = host.key ?? unavailable(); const requestId = typeof args.request_id === "string" && args.request_id ? args.request_id : refuse(400, "bad_args", "request_id is the unlock request's id"); const request = host.store.get(REQUEST_TABLE, requestId) ?? refuse(404, "no_such_request", `no unlock request ${requestId}`); if (request.data.state !== "waiting") refuse(409, "request_answered", `unlock request ${requestId} is ${String(request.data.state)} already`); if (String(request.data.expires_at) <= isoAfter(nowMs)) refuse(410, "request_expired", `unlock request ${requestId} expired at ${String(request.data.expires_at)}: the assistant asks again`); const tables = sortedTables(stringList(args.tables, "tables")); const stray = tables.find((t) => !heldTables(request).includes(t)); if (stray !== undefined) refuse(400, "bad_args", `the request did not ask for ${stray}`); // The person's pick wins over what the request suggested. const minutes = args.minutes; if (!isDuration(minutes)) refuse(400, "bad_args", DURATION_SAID); const { wrapped, signer, sig } = args; if (typeof wrapped !== "string" || !wrapped.startsWith(WRAP_PREFIX)) refuse(400, "bad_args", 'wrapped is the "w1:" wrap of the keys to the request\'s worker_pub'); if (typeof signer !== "string" || !signer) refuse(400, "bad_args", "signer is the person key's fingerprint"); if (typeof sig !== "string" || !sig) refuse(400, "bad_args", "sig is the Ed25519 signature, base64url"); const tokenId = String(request.data.token_id); const publicKey = host.personKey(signer) ?? refuse(409, "no_person_key", `this database holds no person key ${signer} to check the grant against`); if (!(await verifyGrant(publicKey, host.databaseId, requestId, tokenId, { tables, minutes, wrapped, signer, sig }))) refuse(403, "bad_signature", "the signature does not hold for this grant under the person key"); const held = host.sql.exec<{ priv: string }>("SELECT priv FROM window_request_key WHERE request_id = ?", requestId).toArray()[0]; if (!held) refuse(409, "request_spent", `unlock request ${requestId} holds no key any more: the assistant asks again`); const secret = (await openSecret(key, requestAad(requestId), held.priv)) ?? unavailable(); const opened = await openGrant(secret, fromBase64Url(String(request.data.worker_pub)), requestId, tokenId, tables, wrapped); secret.fill(0); if (!opened) refuse(400, "grant_does_not_open", "the wrap does not open to this request's keys for these tables"); const grantId = crypto.randomUUID(); const blob = await sealSecret(key, secretAad(grantId), utf8.encode(opened.text)); return { request, grantId, tables, minutes, wrappedSha256: await sha256Hex(wrapped), signer, sig, bundle: opened.bundle, blob }; } /** `unlock_allow` in its transaction: the private half deleted, the grant made, `ends_at` on the object's clock (or standing), the keys kept for the request's connection. */ applyAllow(host: WindowHost, engine: Engine, p: PreparedAllow, nowMs: number, version: number, outcome: Outcome): { grant: string; ends_at: string; standing: boolean } { const request = host.store.get(REQUEST_TABLE, p.request.id); if (!request || request.data.state !== "waiting") refuse(409, "request_answered", `unlock request ${p.request.id} was answered meanwhile`); const standing = p.minutes === STANDING; const endsAt = standing ? STANDING_ENDS : isoAfter(nowMs + p.minutes * 60_000); const tokenId = String(request.data.token_id); const connection = typeof request.data.connection_id === "string" && request.data.connection_id ? request.data.connection_id : connectionOf(host.store, tokenId); this.settleRequest(host, engine, request, "granted", version, outcome); outcome.made = engine.create( GRANT_TABLE, { request_id: request.id, token_id: tokenId, connection_id: connection, client: String(request.data.client ?? ""), standing, tables: p.tables, minutes: p.minutes, wrapped_sha256: p.wrappedSha256, signer: p.signer, sig: p.sig, granted_at: isoAfter(nowMs), ends_at: endsAt }, version, outcome, 0, { id: p.grantId }, ); host.sql.exec("INSERT INTO window_secret (grant_id, token_id, connection_id, tables, blob, ends_at) VALUES (?, ?, ?, ?, ?, ?)", p.grantId, tokenId, connection, JSON.stringify(p.tables), p.blob, endsAt); this.held.set(p.grantId, p.bundle); return { grant: p.grantId, ends_at: endsAt, standing }; } /** `unlock_decline { request_id }`: the owner said not now. */ decline(host: WindowHost, engine: Engine, args: Record, version: number, outcome: Outcome): void { const requestId = typeof args.request_id === "string" && args.request_id ? args.request_id : refuse(400, "bad_args", "request_id is the unlock request's id"); const request = host.store.get(REQUEST_TABLE, requestId) ?? refuse(404, "no_such_request", `no unlock request ${requestId}`); if (request.data.state !== "waiting") refuse(409, "request_answered", `unlock request ${requestId} is ${String(request.data.state)} already`); this.settleRequest(host, engine, request, "declined", version, outcome); } /** End one window: its kept keys deleted, from memory too, and the grant stamped. A window already ended is left as it is. */ end(host: WindowHost, engine: Engine, grantId: string, by: EndedBy, nowMs: number, version: number, outcome: Outcome): boolean { host.sql.exec("DELETE FROM window_secret WHERE grant_id = ?", grantId); this.held.delete(grantId); const grant = host.store.get(GRANT_TABLE, grantId); if (!grant || grant.data.ended_at) return false; // A window the timer ends ended at its own ends_at, whenever the clean-up came. const at = by === "timer" ? String(grant.data.ends_at) : isoAfter(Math.min(nowMs, Date.parse(String(grant.data.ends_at)) || nowMs)); engine.update(grant, { ended_at: at, ended_by: by }, version, outcome); return true; } /** `unlock_end { grant_id }`: the owner ends a window from the phone. */ endByPhone(host: WindowHost, engine: Engine, args: Record, nowMs: number, version: number, outcome: Outcome): void { const grantId = typeof args.grant_id === "string" && args.grant_id ? args.grant_id : refuse(400, "bad_args", "grant_id is the window's id"); if (!host.store.get(GRANT_TABLE, grantId)) refuse(404, "no_such_grant", `no window ${grantId}`); this.end(host, engine, grantId, "phone", nowMs, version, outcome); } /** Every window this connection holds ends (a revoked connection, or the assistant's own `end_unlock`); on a revoke its waiting request goes too. Answers how many ended. */ endForConnection(host: WindowHost, engine: Engine, connection: string, by: EndedBy, nowMs: number, version: number, outcome: Outcome): number { let ended = 0; const grants = [...host.store.list(GRANT_TABLE, { column: "connection_id", equals: connection }), ...host.store.list(GRANT_TABLE, { column: "token_id", equals: connection }).filter((g) => !g.data.connection_id)]; for (const g of grants) if (!g.data.ended_at && this.end(host, engine, g.id, by, nowMs, version, outcome)) ended++; for (const id of host.sql.exec<{ grant_id: string }>("SELECT grant_id FROM window_secret WHERE connection_id = ?", connection).toArray().map((r) => r.grant_id)) this.end(host, engine, id, by, nowMs, version, outcome); if (by === "token_revoked") for (const r of this.requestsOf(host.store, connection)) if (r.data.state === "waiting") this.settleRequest(host, engine, r, "expired", version, outcome); return ended; } /** The clean-up (the alarm, or a call that met it): windows past ends_at end, requests past expires_at expire. Never the guard. */ sweep(host: WindowHost, engine: Engine, nowMs: number, version: number, outcome: Outcome): void { const now = isoAfter(nowMs); for (const r of host.sql.exec<{ grant_id: string }>("SELECT grant_id FROM window_secret WHERE ends_at <= ?", now).toArray()) this.end(host, engine, r.grant_id, "timer", nowMs, version, outcome); for (const g of [...host.store.scan(GRANT_TABLE)]) if (!g.data.ended_at && String(g.data.ends_at) <= now) this.end(host, engine, g.id, "timer", nowMs, version, outcome); for (const r of [...host.store.scan(REQUEST_TABLE)]) if (r.data.state === "waiting" && String(r.data.expires_at) <= now) this.settleRequest(host, engine, r, "expired", version, outcome); // A key whose request is no longer waiting has no use: none is kept. for (const k of host.sql.exec<{ request_id: string }>("SELECT request_id FROM window_request_key").toArray()) { const r = host.store.get(REQUEST_TABLE, k.request_id); if (!r || r.data.state !== "waiting") host.sql.exec("DELETE FROM window_request_key WHERE request_id = ?", k.request_id); } } /** The next moment the clean-up has work: the soonest window end or request expiry, in ms, or null. */ nextDue(host: Pick): number | null { const ends = host.sql.exec<{ at: string | null }>("SELECT MIN(ends_at) AS at FROM window_secret WHERE ends_at < ?", STANDING_ENDS).one().at; const expiries = [...host.store.scan(REQUEST_TABLE)].filter((r) => r.data.state === "waiting").map((r) => Date.parse(String(r.data.expires_at))); const all = [...(ends ? [Date.parse(ends)] : []), ...expiries].filter((n) => !Number.isNaN(n)); return all.length ? Math.min(...all) : null; } /** * The guard and the keys: what this token's connection's open window holds * for `table`, or null. Checked on every call: `now < ends_at`, the grant * not ended, the token not revoked, `WINDOW_KEY` there and opening what it * kept. A window whose keys no longer open ends (key_lost); one past its end * is cleaned up. */ async keys(host: WindowHost, tokenId: string, table: string, nowMs: number): Promise { const now = isoAfter(nowMs); const token = host.store.get("mcp_token", tokenId); if (!token || token.data.revoked_at) return null; if (typeof token.data.expires_at === "string" && token.data.expires_at && token.data.expires_at <= now) return null; const connection = connectionOf(host.store, tokenId); const rows = host.sql.exec<{ grant_id: string; tables: string; blob: string; ends_at: string }>("SELECT grant_id, tables, blob, ends_at FROM window_secret WHERE connection_id = ? ORDER BY ends_at DESC", connection).toArray(); const lost: string[] = []; let overdue = false; let found: TableKeys | null = null; for (const r of rows) { if (r.ends_at <= now) { overdue = true; continue; } if (found || !(JSON.parse(r.tables) as string[]).includes(table)) continue; const grant = host.store.get(GRANT_TABLE, r.grant_id); if (!grant || grant.data.ended_at || String(grant.data.connection_id || grant.data.token_id) !== connection) continue; let bundle = this.held.get(r.grant_id) ?? null; if (!bundle) { const plain = host.key ? await openSecret(host.key, secretAad(r.grant_id), r.blob) : null; bundle = plain ? parseBundle(new TextDecoder().decode(plain)) : null; if (!bundle) { lost.push(r.grant_id); continue; } this.held.set(r.grant_id, bundle); } const tk = bundle.keys.get(table); const bk = bundle.blind.get(table); const files = bundle.files.get(table); if (tk && bk) found = { table, grant_id: r.grant_id, standing: r.ends_at === STANDING_ENDS, tk, bk, ...(files ? { files } : {}), ends_at: r.ends_at }; } if (lost.length || overdue) host.write((engine, version, outcome) => { for (const id of lost) this.end(host, engine, id, "key_lost", nowMs, version, outcome); if (overdue) this.sweep(host, engine, nowMs, version, outcome); }); return found; } /** The tables this token's connection's open windows hold and when each ends (no key is read). */ open(host: Pick, tokenId: string, nowMs: number): { tables: string[]; ends_at: string; standing: boolean }[] { return host.sql .exec<{ tables: string; ends_at: string }>("SELECT tables, ends_at FROM window_secret WHERE connection_id = ? AND ends_at > ? ORDER BY ends_at", connectionOf(host.store, tokenId), isoAfter(nowMs)) .toArray() .map((r) => ({ tables: JSON.parse(r.tables) as string[], ends_at: r.ends_at, standing: r.ends_at === STANDING_ENDS })); } /** What an assistant read or wrote in a window, written where the owner sees it (`assistant_read`): never a value, only who, which tables, the tool, how many rows, when. */ logRead(host: WindowHost, keys: readonly TableKeys[], tool: string, rows: number, nowMs: number, wrote = false): void { const byGrant = new Map>(); for (const k of keys) (byGrant.get(k.grant_id) ?? byGrant.set(k.grant_id, new Set()).get(k.grant_id)!).add(k.table); if (!byGrant.size) return; host.write((engine, version, outcome) => { for (const [grantId, tables] of byGrant) { const grant = host.store.get(GRANT_TABLE, grantId); engine.create(READ_TABLE, { grant_id: grantId, client: String(grant?.data.client || "an assistant"), tables: [...tables].sort(), tool, rows, wrote, read_at: isoAfter(nowMs) }, version, outcome); } }); } } /** When the asking connection was made, for the card ("Claude · connected 3 days ago"): its first token's making, else this token's. */ function connectedAt(store: Pick["store"], connection: string, tokenId: string): { connected_at?: string } { const made = store.get("mcp_token", connection)?.created_at ?? store.get("mcp_token", tokenId)?.created_at; return made ? { connected_at: made } : {}; }