Cotton code
177 lines · 8.7 KB · TypeScriptRaw
/** * INVITATIONS BETWEEN PEOPLE ON COTTON (Days, CONTRACT §17, 22 Nov 2026): * an event's invitation, its calling off and the guest's answer, carried * object to object between two people who accepted each other on Cotton. * * SEALED ALL THE WAY. The inviter's phone seals each message to the guest's * sharing key (cotton-core `seal::share`, a `p1:` box bound to * `invite:<invite id>:<kind>`); the objects route the box and never open it. * What an object keeps is the box's outside: who it is from, its kind, the * invitation's id and when it came. * * WHO. Only one of this person's people: a number its owner accepted (chat's * `chat_peer`, src/chat/chat.ts) and has not blocked (Calling's * `call_block`). The sender's object sends only to such a number; the * receiver's holds only from one. A number that is not one, a stranger, a * blocked number, a number not on Cotton and one over the limits are all * answered `{ ok: true }` the same: a sender never learns which. * *   POST /v1/invite/send  (owner) { to, kind, id, box } → { ok: true } always *   GET  /v1/invite/inbox (owner) → { held: [{ seq, from, kind, id, box, at }] }, oldest first *   POST /v1/invite/taken (owner) { seqs } → { ok: true }: the phone landed them * * THE TABLE is the Worker's own, never a kit's: `invite_held`, one row a * waiting box, dropped once taken or after HOLD_DAYS (on every read and * every arrival). The limits count in `invite_hit`. Both are made with the * object's other tables (src/business.ts constructor). */import * as handover from "./handover.ts";import { blocked, keyOf, numberOf } from "./calling/calls.ts";import { directory } from "./directory.ts";import * as gate from "./chat/gate.ts";import type { Env } from "./env.ts";import { json, readJson, refuse } from "./http.ts";export const SCHEMA = `CREATE TABLE IF NOT EXISTS invite_held (seq INTEGER PRIMARY KEY AUTOINCREMENT, from_number TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, box TEXT NOT NULL, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS invite_hit (who TEXT NOT NULL, at INTEGER NOT NULL);`;/** A box waits this long for the phone, then goes. */export const HOLD_DAYS = 30;export const HOLD_MS = HOLD_DAYS * 24 * 3_600_000;/** A box's length at most: an invitation's words, its repeat and its note fit many times over. */export const BOX_MAX = 64 * 1024;/** Messages one object sends in an hour, and takes from one person in a day; the rest are dropped unsaid. */export const SENDS_PER_HOUR = 120;export const FROM_PEER_DAY = 300;/** Boxes taken in one `taken`, at most. */const TAKEN_MAX = 500;export const KINDS = ["invite", "cancel", "answer"] as const;export type Kind = (typeof KINDS)[number];const ID = /^[A-Za-z0-9_-]{8,64}$/;const BOX = /^p1:[A-Za-z0-9_-]+$/;const HOUR = 3_600_000;const DAY = 24 * HOUR;/** What one object hands another. */export interface InviteDelivery {  from: string;  kind: Kind;  id: string;  box: string;}export interface InviteHost {  sql: SqlStorage;  env: Env;  slug: string;  ownerPhone: string | null;  waitUntil(work: Promise<unknown>): void;}/** The routes under /v1/invite, for the owner's signed-in phone; null for any other path. */export async function route(host: InviteHost, caller: { deviceId: string | null; owner: boolean }, request: Request, url: URL): Promise<Response | null> {  const path = url.pathname;  if (!path.startsWith("/v1/invite/")) return null;  if (!caller.deviceId) refuse(401, "sign_in", "invitations are sent and taken from a signed-in phone");  if (!caller.owner) refuse(403, "owner_only", "only the owner's phone sends and takes invitations");  sweep(host.sql);  const method = request.method;  if (method === "POST" && path === "/v1/invite/send") {    await send(host, await readJson(request));    return json({ ok: true });  }  if (method === "GET" && path === "/v1/invite/inbox") return json({ held: inbox(host.sql) });  if (method === "POST" && path === "/v1/invite/taken") {    taken(host.sql, (await readJson(request)).seqs);    return json({ ok: true });  }  refuse(404, "not_found", `nothing answers ${method} ${path}`);}/** What the box's outside must be; a malformed one is the phone's error, said by name. */function deliveryOf(body: Record<string, unknown>): Omit<InviteDelivery, "from"> & { to: string } {  const to = numberOf(body.to);  const kind = KINDS.includes(body.kind as Kind) ? (body.kind as Kind) : refuse(400, "bad_kind", "kind: invite, cancel or answer");  const id = typeof body.id === "string" && ID.test(body.id) ? body.id : refuse(400, "bad_id", "id: the invitation's id, 8 to 64 letters, digits, - or _");  const box = typeof body.box === "string" && BOX.test(body.box) ? body.box : refuse(400, "bad_box", "box: the message sealed to the guest's sharing key (p1:)");  if (box.length > BOX_MAX) refuse(413, "box_too_big", `box: at most ${BOX_MAX} characters`);  return { to, kind, id, box };}/** `POST /v1/invite/send`: handed to the number's object when it is one of this person's people; else nothing, said the same. */async function send(host: InviteHost, body: Record<string, unknown>): Promise<void> {  const { to, kind, id, box } = deliveryOf(body);  if (!host.ownerPhone || to === host.ownerPhone) return;  if (!(await isPeer(host.sql, to)) || (await blocked(host.sql, to))) return;  if (hits(host.sql, "out", HOUR) >= SENDS_PER_HOUR) return;  hit(host.sql, "out");  const delivery: InviteDelivery = { from: host.ownerPhone, kind, id, box };  host.waitUntil(handOver(host, to, delivery));}async function handOver(host: InviteHost, to: string, delivery: InviteDelivery): Promise<void> {  try {    const slug = await directory(host.env).lookup(to);    if (!slug || slug === host.slug) return;    const peer = host.env.BUSINESS.get(host.env.BUSINESS.idFromName(slug), { locationHint: "apac" }) as unknown as { inviteDeliver(d: InviteDelivery): Promise<void> };    await peer.inviteDeliver(delivery);  } catch (error) {    // Refused as "try again" (a frozen account): kept and tried again on this object's alarm (src/handover.ts).    if (handover.retryable(error)) handover.keep(host.sql, "invite", to, delivery);    // Else: not handed over reads as never answered: the inviter's phone sees no answer.  }}/** Another object's message arriving: held only from one of this person's people, under the limits; else dropped unsaid. */export async function deliverIn(host: InviteHost, delivery: InviteDelivery): Promise<void> {  sweep(host.sql);  let from: string;  try {    from = numberOf(delivery?.from);  } catch {    return;  }  if (from === host.ownerPhone || !KINDS.includes(delivery.kind) || typeof delivery.id !== "string" || !ID.test(delivery.id)) return;  if (typeof delivery.box !== "string" || !BOX.test(delivery.box) || delivery.box.length > BOX_MAX) return;  if ((await blocked(host.sql, from)) || !(await isPeer(host.sql, from))) return;  const who = `in:${await keyOf(host.sql, from)}`;  if (hits(host.sql, who, DAY) >= FROM_PEER_DAY) return;  hit(host.sql, who);  host.sql.exec("INSERT INTO invite_held (from_number, kind, id, box, at) VALUES (?, ?, ?, ?, ?)", from, delivery.kind, delivery.id, delivery.box, Date.now());}/** `GET /v1/invite/inbox`: every box waiting, oldest first. */function inbox(sql: SqlStorage): { seq: number; from: string; kind: string; id: string; box: string; at: string }[] {  return sql    .exec<{ seq: number; from_number: string; kind: string; id: string; box: string; at: number }>("SELECT seq, from_number, kind, id, box, at FROM invite_held ORDER BY seq")    .toArray()    .map((r) => ({ seq: Number(r.seq), from: r.from_number, kind: r.kind, id: r.id, box: r.box, at: new Date(Number(r.at)).toISOString() }));}/** `POST /v1/invite/taken { seqs }`: the boxes the phone landed, gone. */function taken(sql: SqlStorage, raw: unknown): void {  if (!Array.isArray(raw) || raw.length > TAKEN_MAX || !raw.every((n) => Number.isInteger(n) && n > 0)) refuse(400, "bad_seqs", `seqs: the inbox's seq numbers, at most ${TAKEN_MAX}`);  for (const seq of raw as number[]) sql.exec("DELETE FROM invite_held WHERE seq = ?", seq);}function sweep(sql: SqlStorage): void {  sql.exec("DELETE FROM invite_held WHERE at < ?", Date.now() - HOLD_MS);  sql.exec("DELETE FROM invite_hit WHERE at < ?", Date.now() - DAY);}/** Accepted by this owner, blocked or not: the gate's rule (src/chat/gate.ts). */async function isPeer(sql: SqlStorage, number: string): Promise<boolean> {  return gate.accepted(sql, number);}function hits(sql: SqlStorage, who: string, within: number): number {  return sql.exec<{ n: number }>("SELECT count(*) AS n FROM invite_hit WHERE who = ? AND at >= ?", who, Date.now() - within).one().n;}function hit(sql: SqlStorage, who: string): void {  sql.exec("INSERT INTO invite_hit (who, at) VALUES (?, ?)", who, Date.now());}