Cotton code
446 lines · 25.8 KB · TypeScriptRaw
/** * SECRETS BETWEEN PEOPLE (assets/design/keys/CONTRACT.md, "The Worker", rows 14 and 15; DECISIONS.md S1 to S5). * * A share is two `p1:` boxes sealed by the giver's phone to the holder's sharing key: the card (name, kind, site), * bound to `secret-card:<share>`, and the value, bound to `secret-value:<share>:<version>`. An ask is one box, bound * to `secret-ask:<ask>`. The objects route the boxes object to object and never open one. What the server learns is * who shares with whom, when, and how many times a share was opened (S2). * * WHO. As Send and the invitations (src/invite.ts): only one of this person's people, accepted both ways and not * blocked. A share or an ask to anyone else, a number not on Cotton, a blocked number or one over the limits is * answered `{ ok: true }` the same, and the giver's own list shows it as given: the giver never learns which. * *   GET  /v1/secret/note                → { notes: [{ key, box }] }            the giver's own record, sealed to *   PUT  /v1/secret/note { key, box }   → { ok: true }                         their own sharing key *   POST /v1/secret/share { to, share, card, value, version, until, may_copy } → { ok: true } *   POST /v1/secret/share/update { share, value, version }                    → { ok: true } *   POST /v1/secret/share/take { share }                                      → { ok: true }  gone on both objects *   GET  /v1/secret/share/out           → { shares: [{ share, to, delivered_at, opens, last_open, until, state }] } *   GET  /v1/secret/share/in            → { shares: [{ share, from, card, until, may_copy }] } *   POST /v1/secret/share/value { share } → { value, version }: one open, counted and told to the giver's object; *                                          404 share_gone past `until`, after a take back or a drop *   POST /v1/secret/share/drop { share }  → { ok: true } *   POST /v1/secret/ask { to, ask, box }  → { ok: true } *   GET  /v1/secret/ask/in              → { asks: [{ ask, from, box, state, at }] } *   POST /v1/secret/ask/answer { ask, state: "shared" | "no" } → { ok: true }  told to the asker's object *   POST /v1/secret/ask/withdraw { ask } → { ok: true }  the asker takes a waiting ask back, on both objects *   GET  /v1/secret/ask/out             → { asks: [{ ask, to, state, at }] }   the asks this person sent * * Times are milliseconds since 1970 (the phone's `from_ms`); `until` null is "until taken back". The owner's own * signed-in phones alone call these. Past `until` every object's sweep (each call and the alarm) deletes the boxes * it holds: the holder's object its card and value, the giver's its share's outside turns `expired`. * * THE TABLES are the Worker's own, never a kit's, made with the object's other tables (src/business.ts). */import * as handover from "../handover.ts";import { blocked, keyOf, numberOf } from "../calling/calls.ts";import { directory } from "../directory.ts";import type { Env } from "../env.ts";import { json, readJson, refuse } from "../http.ts";import { isPersonOf } from "./send.ts";export const SCHEMA = `CREATE TABLE IF NOT EXISTS secret_note (key TEXT PRIMARY KEY, box TEXT NOT NULL, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS secret_out (share TEXT PRIMARY KEY, to_number TEXT NOT NULL, delivered_at INTEGER NOT NULL, opens INTEGER NOT NULL DEFAULT 0, last_open INTEGER, until INTEGER, state TEXT NOT NULL);CREATE TABLE IF NOT EXISTS secret_held (share TEXT PRIMARY KEY, from_number TEXT NOT NULL, card TEXT NOT NULL, value TEXT NOT NULL, version INTEGER NOT NULL, until INTEGER, may_copy INTEGER NOT NULL, opens INTEGER NOT NULL DEFAULT 0, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS secret_ask_in (ask TEXT PRIMARY KEY, from_number TEXT NOT NULL, box TEXT NOT NULL, state TEXT NOT NULL, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS secret_ask_out (ask TEXT PRIMARY KEY, to_number TEXT NOT NULL, state TEXT NOT NULL, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS secret_hit (who TEXT NOT NULL, at INTEGER NOT NULL);`;/** The giver's own record: a key at most this long (`share:<id>`, `pin:<print>`), a box at most this, this many notes. */export const NOTE_KEY_MAX = 80;export const NOTE_BOX_MAX = 16 * 1024;export const NOTES_MAX = 5000;/** A card and an ask fit a name, a site and a few words many times over; a value fits a long note or a key file. */export const CARD_MAX = 16 * 1024;export const VALUE_MAX = 64 * 1024;export const ASK_MAX = 16 * 1024;/** As Send's: what one object gives or asks in an hour, and takes from one person in a day; the rest dropped unsaid. */export const SENDS_PER_HOUR = 120;export const FROM_PEER_DAY = 300;/** An ask waits this long for an answer, then goes. */export const ASK_HOLD_MS = 30 * 24 * 3_600_000;const ID = /^[A-Za-z0-9_-]{8,64}$/;const BOX = /^p1:[A-Za-z0-9_-]+$/;const NOTE_KEY = /^[\x21-\x7e]{1,80}$/;const HOUR = 3_600_000;const DAY = 24 * HOUR;export type ShareState = "live" | "taken" | "expired";export interface SecretHost {  sql: SqlStorage;  env: Env;  slug: string;  ownerPhone: string | null;  now(): number;  waitUntil(work: Promise<unknown>): void;}/** One share as the giver's object hands it to the holder's. */export interface SecretDelivery {  from: string;  share: string;  card: string;  value: string;  version: number;  until: number | null;  may_copy: boolean;}/** What one object asks of another, by RPC (src/business.ts). */export interface SecretPeer {  secretDeliver(d: SecretDelivery): Promise<void>;  secretUpdated(from: string, share: string, value: string, version: number): Promise<void>;  secretTaken(from: string, share: string): Promise<void>;  secretOpened(from: string, share: string, opens: number, at: number): Promise<void>;  secretAsked(from: string, ask: string, box: string): Promise<void>;  secretAskWithdrawn(from: string, ask: string): Promise<void>;  secretAskAnswered(from: string, ask: string, state: "shared" | "no"): Promise<void>;}/** The routes under /v1/secret/ (but the rewrap, src/business.ts), for the owner's signed-in phone; null for any other path. */export async function route(host: SecretHost, caller: { deviceId: string | null; owner: boolean }, request: Request, url: URL): Promise<Response | null> {  const path = url.pathname;  if (!path.startsWith("/v1/secret/") || path === "/v1/secret/rewrap") return null;  if (!caller.deviceId) refuse(401, "sign_in", "secrets are shared from a signed-in phone");  if (!caller.owner) refuse(403, "owner_only", "only the owner's own phones share and hold secrets");  sweep(host);  const method = request.method;  if (path === "/v1/secret/note") {    if (method === "GET") return json({ notes: host.sql.exec<{ key: string; box: string }>("SELECT key, box FROM secret_note ORDER BY key").toArray().map((r) => ({ key: r.key, box: r.box })) });    if (method === "PUT") {      putNote(host, await readJson(request));      return json({ ok: true });    }  }  if (method === "POST" && path === "/v1/secret/share") return json(await give(host, await readJson(request)));  if (method === "POST" && path === "/v1/secret/share/update") return json(await update(host, await readJson(request)));  if (method === "POST" && path === "/v1/secret/share/take") return json(await take(host, await readJson(request)));  if (method === "GET" && path === "/v1/secret/share/out") return json({ shares: out(host.sql) });  if (method === "GET" && path === "/v1/secret/share/in") return json({ shares: held(host.sql) });  if (method === "POST" && path === "/v1/secret/share/value") return json(await value(host, await readJson(request)));  if (method === "POST" && path === "/v1/secret/share/drop") {    host.sql.exec("DELETE FROM secret_held WHERE share = ?", idOf((await readJson(request)).share, "share"));    return json({ ok: true });  }  if (method === "POST" && path === "/v1/secret/ask") return json(await ask(host, await readJson(request)));  if (method === "GET" && path === "/v1/secret/ask/in") return json({ asks: asksIn(host.sql) });  if (method === "POST" && path === "/v1/secret/ask/answer") return json(answer(host, await readJson(request)));  if (method === "POST" && path === "/v1/secret/ask/withdraw") return json(withdraw(host, await readJson(request)));  if (method === "GET" && path === "/v1/secret/ask/out") return json({ asks: asksOut(host.sql) });  refuse(404, "not_found", `nothing answers ${method} ${path}`);}function idOf(raw: unknown, what: string): string {  return typeof raw === "string" && ID.test(raw) ? raw : refuse(400, `bad_${what}`, `${what}: an id of 8 to 64 letters, digits, - or _`);}function boxOf(raw: unknown, what: string, max: number): string {  const box = typeof raw === "string" && BOX.test(raw) ? raw : refuse(400, `bad_${what}`, `${what}: a box sealed to the person's sharing key (p1:)`);  if (box.length > max) refuse(413, `${what}_too_big`, `${what}: at most ${max} characters`);  return box;}function versionOf(raw: unknown): number {  return Number.isInteger(raw) && (raw as number) >= 1 ? (raw as number) : refuse(400, "bad_version", "version: the value's version, from 1");}function untilOf(raw: unknown, now: number): number | null {  if (raw === null || raw === undefined) return null;  if (!Number.isInteger(raw) || (raw as number) <= now) refuse(400, "bad_until", "until: a time to come, in milliseconds, or null until taken back");  return raw as number;}function putNote(host: SecretHost, body: Record<string, unknown>): void {  const key = typeof body.key === "string" && NOTE_KEY.test(body.key) ? body.key : refuse(400, "bad_key", `key: at most ${NOTE_KEY_MAX} printable characters (share:<id>, pin:<print>)`);  const box = boxOf(body.box, "box", NOTE_BOX_MAX);  const had = host.sql.exec("SELECT 1 FROM secret_note WHERE key = ?", key).toArray().length > 0;  if (!had && host.sql.exec<{ n: number }>("SELECT count(*) AS n FROM secret_note").one().n >= NOTES_MAX) refuse(413, "too_many_notes", `at most ${NOTES_MAX} notes`);  host.sql.exec("INSERT INTO secret_note (key, box, at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET box = excluded.box, at = excluded.at", key, box, host.now());}/** `POST /v1/secret/share`: kept as given, and handed to the number's object when it is one of this person's people. */async function give(host: SecretHost, body: Record<string, unknown>): Promise<{ ok: true }> {  const now = host.now();  const to = numberOf(body.to);  const share = idOf(body.share, "share");  const card = boxOf(body.card, "card", CARD_MAX);  const val = boxOf(body.value, "value", VALUE_MAX);  const version = versionOf(body.version);  const until = untilOf(body.until, now);  const mayCopy = body.may_copy === true;  if (!host.ownerPhone || to === host.ownerPhone) refuse(400, "bad_to", "to: one of your people, not yourself");  if (host.sql.exec("SELECT 1 FROM secret_out WHERE share = ?", share).toArray().length) refuse(409, "share_exists", "a share with this id was given already");  // Given, as far as the giver's list says, whoever the number is: unknown, blocked and over the limits read the same.  host.sql.exec("INSERT INTO secret_out (share, to_number, delivered_at, opens, last_open, until, state) VALUES (?, ?, ?, 0, NULL, ?, 'live')", share, to, now, until);  if (!(await mayReach(host, to))) return { ok: true };  const delivery: SecretDelivery = { from: host.ownerPhone, share, card, value: val, version, until, may_copy: mayCopy };  host.waitUntil(toPeer(host, to, (peer) => peer.secretDeliver(delivery), () => handover.keep(host.sql, "secret", to, delivery)));  return { ok: true };}/** One of this person's people, under the hour's limit: the hit is counted here. */async function mayReach(host: SecretHost, to: string): Promise<boolean> {  if (!(await isPersonOf(host.sql, to))) return false;  if (hits(host.sql, "out", HOUR) >= SENDS_PER_HOUR) return false;  hit(host.sql, "out", host.now());  return true;}function liveOut(host: SecretHost, share: string): { to_number: string } {  const row = host.sql.exec<{ to_number: string; state: string }>("SELECT to_number, state FROM secret_out WHERE share = ?", share).toArray()[0];  if (!row || row.state !== "live") refuse(404, "share_gone", "this share was taken back or has ended");  return row;}/** `POST /v1/secret/share/update`: the value box replaced on the holder's object (a newer version only). */async function update(host: SecretHost, body: Record<string, unknown>): Promise<{ ok: true }> {  const share = idOf(body.share, "share");  const val = boxOf(body.value, "value", VALUE_MAX);  const version = versionOf(body.version);  const { to_number: to } = liveOut(host, share);  const from = host.ownerPhone!;  if (await isPersonOf(host.sql, to)) host.waitUntil(toPeer(host, to, (peer) => peer.secretUpdated(from, share, val, version)));  return { ok: true };}/** `POST /v1/secret/share/take`: gone from the holder's object now, and taken on the giver's list. *//** * AUDIT D: whether a share is still given (not taken back), so a delivery that waited in the retry queue (the holder's * account was frozen) is never handed over after the giver took it back or removed them. */export function stillGiven(sql: SqlStorage, share: string): boolean {  return sql.exec<{ state: string }>("SELECT state FROM secret_out WHERE share = ?", share).toArray()[0]?.state === "live";}async function take(host: SecretHost, body: Record<string, unknown>): Promise<{ ok: true }> {  const share = idOf(body.share, "share");  const row = host.sql.exec<{ to_number: string; state: string }>("SELECT to_number, state FROM secret_out WHERE share = ?", share).toArray()[0];  if (!row) refuse(404, "share_gone", "no share with this id was given");  host.sql.exec("UPDATE secret_out SET state = 'taken' WHERE share = ?", share);  // At once: the holder's object deletes its boxes before this call is answered (a take back is never "later").  // AUDIT D: a holder's object that can't take it now (a frozen account) is told again on the alarm until it does; a  // take-back that failed there used to be dropped while the giver was told it was done.  await toPeer(host, row.to_number, (peer) => peer.secretTaken(host.ownerPhone!, share), () => handover.keep(host.sql, "secret_take", row.to_number, { from: host.ownerPhone, share }));  return { ok: true };}/** `POST /v1/secret/share/value`: the value box, one open counted here and told to the giver's object. */async function value(host: SecretHost, body: Record<string, unknown>): Promise<{ value: string; version: number }> {  const share = idOf(body.share, "share");  const now = host.now();  const row = host.sql.exec<{ from_number: string; value: string; version: number; until: number | null; opens: number }>("SELECT from_number, value, version, until, opens FROM secret_held WHERE share = ?", share).toArray()[0];  if (!row || (row.until !== null && Number(row.until) <= now)) {    if (row) host.sql.exec("DELETE FROM secret_held WHERE share = ?", share);    refuse(404, "share_gone", "this share was taken back or has ended");  }  const opens = Number(row.opens) + 1;  host.sql.exec("UPDATE secret_held SET opens = ? WHERE share = ?", opens, share);  const from = row.from_number;  host.waitUntil(toPeer(host, from, (peer) => peer.secretOpened(host.ownerPhone!, share, opens, now)));  return { value: row.value, version: Number(row.version) };}/** `POST /v1/secret/ask`: handed to the number's object when it is one of this person's people; else nothing, said the same. */async function ask(host: SecretHost, body: Record<string, unknown>): Promise<{ ok: true }> {  const to = numberOf(body.to);  const id = idOf(body.ask, "ask");  const box = boxOf(body.box, "box", ASK_MAX);  if (!host.ownerPhone || to === host.ownerPhone) refuse(400, "bad_to", "to: one of your people, not yourself");  // The asker's own list holds it as asked whether or not it reached anyone: the asker never learns which.  host.sql.exec("INSERT INTO secret_ask_out (ask, to_number, state, at) VALUES (?, ?, 'waiting', ?) ON CONFLICT (ask) DO NOTHING", id, to, host.now());  if (!(await mayReach(host, to))) return { ok: true };  const from = host.ownerPhone;  host.waitUntil(toPeer(host, to, (peer) => peer.secretAsked(from, id, box)));  return { ok: true };}function answer(host: SecretHost, body: Record<string, unknown>): { ok: true } {  const id = idOf(body.ask, "ask");  const state = body.state === "shared" || body.state === "no" ? body.state : refuse(400, "bad_state", 'state: "shared" or "no"');  const [row] = host.sql.exec<{ from_number: string; state: string }>("SELECT from_number, state FROM secret_ask_in WHERE ask = ?", id).toArray();  if (!row || row.state === "withdrawn") refuse(404, "ask_gone", "no such ask is waiting");  host.sql.exec("UPDATE secret_ask_in SET state = ? WHERE ask = ?", state, id);  if (host.ownerPhone) {    const me = host.ownerPhone;    host.waitUntil(toPeer(host, row.from_number, (peer) => peer.secretAskAnswered(me, id, state)));  }  return { ok: true };}/** `POST /v1/secret/ask/withdraw`: a waiting ask this person sent goes, here and on the holder's object; an answered one stays answered. */function withdraw(host: SecretHost, body: Record<string, unknown>): { ok: true } {  const id = idOf(body.ask, "ask");  const [row] = host.sql.exec<{ to_number: string; state: string }>("SELECT to_number, state FROM secret_ask_out WHERE ask = ?", id).toArray();  if (!row) refuse(404, "ask_gone", "no such ask was sent");  if (row.state !== "waiting") return { ok: true };  host.sql.exec("UPDATE secret_ask_out SET state = 'withdrawn' WHERE ask = ?", id);  if (host.ownerPhone) {    const me = host.ownerPhone;    host.waitUntil(toPeer(host, row.to_number, (peer) => peer.secretAskWithdrawn(me, id)));  }  return { ok: true };}function asksOut(sql: SqlStorage): { ask: string; to: string; state: string; at: number }[] {  return sql    .exec<{ ask: string; to_number: string; state: string; at: number }>("SELECT ask, to_number, state, at FROM secret_ask_out ORDER BY at, ask")    .toArray()    .map((r) => ({ ask: r.ask, to: r.to_number, state: r.state, at: Number(r.at) }));}function out(sql: SqlStorage): { share: string; to: string; delivered_at: number; opens: number; last_open: number | null; until: number | null; state: string }[] {  return sql    .exec<{ share: string; to_number: string; delivered_at: number; opens: number; last_open: number | null; until: number | null; state: string }>("SELECT * FROM secret_out ORDER BY delivered_at, share")    .toArray()    .map((r) => ({ share: r.share, to: r.to_number, delivered_at: Number(r.delivered_at), opens: Number(r.opens), last_open: r.last_open === null ? null : Number(r.last_open), until: r.until === null ? null : Number(r.until), state: r.state }));}function held(sql: SqlStorage): { share: string; from: string; card: string; until: number | null; may_copy: boolean }[] {  return sql    .exec<{ share: string; from_number: string; card: string; until: number | null; may_copy: number }>("SELECT share, from_number, card, until, may_copy FROM secret_held ORDER BY at, share")    .toArray()    .map((r) => ({ share: r.share, from: r.from_number, card: r.card, until: r.until === null ? null : Number(r.until), may_copy: Number(r.may_copy) === 1 }));}function asksIn(sql: SqlStorage): { ask: string; from: string; box: string; state: string; at: number }[] {  return sql    .exec<{ ask: string; from_number: string; box: string; state: string; at: number }>("SELECT ask, from_number, box, state, at FROM secret_ask_in ORDER BY at, ask")    .toArray()    .map((r) => ({ ask: r.ask, from: r.from_number, box: r.box, state: r.state, at: Number(r.at) }));}// ── What another object asks of this one (by RPC, src/business.ts): each only from one of this person's people ──async function fromPeer(host: SecretHost, raw: unknown): Promise<string | null> {  let from: string;  try {    from = numberOf(raw);  } catch {    return null;  }  if (from === host.ownerPhone || (await blocked(host.sql, from)) || !(await isPersonOf(host.sql, from))) return null;  return from;}async function underPeerLimit(host: SecretHost, from: string): Promise<boolean> {  const who = `in:${await keyOf(host.sql, from)}`;  if (hits(host.sql, who, DAY) >= FROM_PEER_DAY) return false;  hit(host.sql, who, host.now());  return true;}/** A share arriving: held only from one of this person's people, under the limits, well formed; else dropped unsaid. */export async function deliverIn(host: SecretHost, d: SecretDelivery): Promise<void> {  sweep(host);  const from = await fromPeer(host, d?.from);  if (!from) return;  const now = host.now();  const ok =    typeof d.share === "string" && ID.test(d.share) &&    typeof d.card === "string" && BOX.test(d.card) && d.card.length <= CARD_MAX &&    typeof d.value === "string" && BOX.test(d.value) && d.value.length <= VALUE_MAX &&    Number.isInteger(d.version) && d.version >= 1 &&    (d.until === null || (Number.isInteger(d.until) && d.until > now));  if (!ok || !(await underPeerLimit(host, from))) return;  // A share id another person's share holds already is left as it is: one person cannot overwrite another's.  host.sql.exec(    "INSERT INTO secret_held (share, from_number, card, value, version, until, may_copy, opens, at) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?) ON CONFLICT (share) DO NOTHING",    d.share, from, d.card, d.value, d.version, d.until, d.may_copy === true ? 1 : 0, now,  );}/** The giver's object replaced a share's value: taken only from that giver, and only a newer version. */export async function updatedIn(host: SecretHost, rawFrom: string, share: string, val: string, version: number): Promise<void> {  const from = await fromPeer(host, rawFrom);  if (!from || typeof val !== "string" || !BOX.test(val) || val.length > VALUE_MAX || !Number.isInteger(version)) return;  host.sql.exec("UPDATE secret_held SET value = ?, version = ? WHERE share = ? AND from_number = ? AND version < ?", val, version, share, from, version);}/** The giver's object took a share back: its boxes go here, whoever the giver is to this person now. */export function takenIn(host: SecretHost, rawFrom: string, share: string): void {  let from: string;  try {    from = numberOf(rawFrom);  } catch {    return;  }  host.sql.exec("DELETE FROM secret_held WHERE share = ? AND from_number = ?", share, from);}/** The holder's object counted an open of a share this person gave it. */export function openedIn(host: SecretHost, rawFrom: string, share: string, opens: number, at: number): void {  let from: string;  try {    from = numberOf(rawFrom);  } catch {    return;  }  if (!Number.isInteger(opens) || opens < 1 || !Number.isInteger(at)) return;  host.sql.exec("UPDATE secret_out SET opens = max(opens, ?), last_open = max(coalesce(last_open, 0), ?) WHERE share = ? AND to_number = ?", opens, at, share, from);}/** An ask arriving: held only from one of this person's people, under the limits; else dropped unsaid. */export async function askedIn(host: SecretHost, rawFrom: string, id: string, box: string): Promise<void> {  sweep(host);  const from = await fromPeer(host, rawFrom);  if (!from || typeof id !== "string" || !ID.test(id) || typeof box !== "string" || !BOX.test(box) || box.length > ASK_MAX) return;  if (!(await underPeerLimit(host, from))) return;  host.sql.exec("INSERT INTO secret_ask_in (ask, from_number, box, state, at) VALUES (?, ?, ?, 'waiting', ?) ON CONFLICT (ask) DO NOTHING", id, from, box, host.now());}/** The asker's object took its ask back: it reads withdrawn here, only from that asker and only while it waited. */export function askWithdrawnIn(host: SecretHost, rawFrom: string, id: string): void {  let from: string;  try {    from = numberOf(rawFrom);  } catch {    return;  }  host.sql.exec("UPDATE secret_ask_in SET state = 'withdrawn' WHERE ask = ? AND from_number = ? AND state = 'waiting'", id, from);}/** The holder's object answered an ask this person sent: only from the one it was sent to, and only while it waited. */export function askAnsweredIn(host: SecretHost, rawFrom: string, id: string, state: string): void {  let from: string;  try {    from = numberOf(rawFrom);  } catch {    return;  }  if (state !== "shared" && state !== "no") return;  host.sql.exec("UPDATE secret_ask_out SET state = ? WHERE ask = ? AND to_number = ? AND state = 'waiting'", state, id, from);}/** Past `until`: the holder's boxes go, the giver's share reads expired; old asks and limit counts go. Each call and the alarm. */export function sweep(host: Pick<SecretHost, "sql" | "now">): void {  const now = host.now();  host.sql.exec("DELETE FROM secret_held WHERE until IS NOT NULL AND until <= ?", now);  host.sql.exec("UPDATE secret_out SET state = 'expired' WHERE state = 'live' AND until IS NOT NULL AND until <= ?", now);  host.sql.exec("DELETE FROM secret_ask_in WHERE at < ?", now - ASK_HOLD_MS);  host.sql.exec("DELETE FROM secret_ask_out WHERE at < ?", now - ASK_HOLD_MS);  host.sql.exec("DELETE FROM secret_hit WHERE at < ?", now - DAY);}async function toPeer(host: SecretHost, number: string, call: (peer: SecretPeer) => Promise<void>, onRetry?: () => void): Promise<void> {  try {    const slug = await directory(host.env).lookup(number);    if (!slug || slug === host.slug) return;    await call(host.env.BUSINESS.get(host.env.BUSINESS.idFromName(slug), { locationHint: "apac" }) as unknown as SecretPeer);  } catch (error) {    // A share refused as "try again" (a frozen account) is kept and tried again on the alarm (src/handover.ts).    if (onRetry && handover.retryable(error)) onRetry();    // Else: not reached reads as never opened: the giver's list says delivered with no open, and nothing more.  }}function hits(sql: SqlStorage, who: string, within: number): number {  return sql.exec<{ n: number }>("SELECT count(*) AS n FROM secret_hit WHERE who = ? AND at >= ?", who, Date.now() - within).one().n;}function hit(sql: SqlStorage, who: string, at: number): void {  sql.exec("INSERT INTO secret_hit (who, at) VALUES (?, ?)", who, at);}