Cotton code
145 lines · 8.5 KB · TypeScriptRaw
/** * THE CIRCLE'S INVITATION LINK (PEOPLE-DESIGN c "Invite", 28 Nov 2026): someone not on Cotton yet is * invited by a link he sends himself, from his own messages, through the system share sheet. Cotton sends nothing. * *   cottondb.com/c/<code>#<secret> * * - His phone makes the secret and keeps it in the link's fragment, which never reaches a server. The object keeps only *   the code, the secret's SHA-256 and the times; the directory keeps the code and which object made it, so the person *   who opens it later can be routed to it. * - When they have signed up and their app opens the link, their object hands the code and the secret to his object *   (`circleRedeem`). His object accepts them because he invited them: the code is live, the secret matches, and the *   link is unused. Each side then holds the other as one of its people (chat_peer), so both are in the Circle. * - The link ends after 30 days, at his Stop, or once used. A wrong secret, an ended code and a made-up one all *   answer the same. */import { refuse } from "../http.ts";import { directory } from "../directory.ts";import type { ChatHost } from "./chat.ts";export const SCHEMA = `CREATE TABLE IF NOT EXISTS circle_invite (id TEXT PRIMARY KEY, code TEXT NOT NULL UNIQUE, secret_hash TEXT NOT NULL, made_at TEXT NOT NULL, ends_at TEXT NOT NULL, stopped_at TEXT, used_at TEXT, used_by TEXT);`;/** How long a link stands. */export const INVITE_DAYS = 30;/** Links a person makes in an hour. */export const INVITES_PER_HOUR = 20;/** Redeems a person's object tries in an hour (a guessing guard on top of the secret). */export const REDEEMS_PER_HOUR = 20;const HASH = /^[A-Za-z0-9_-]{43}$/;const CODE = /^[a-z0-9]{12}$/;const SECRET = /^[A-Za-z0-9_-]{22,64}$/;const NOT_ONE = "This invitation has ended, or it isn't one. Ask them to send you a new link.";export interface InviteHost extends Pick<ChatHost, "sql" | "env" | "slug" | "ownerPhone"> {  ownerName?(): string | null;}function ensure(sql: SqlStorage): void {  sql.exec(SCHEMA);  sql.exec("CREATE TABLE IF NOT EXISTS circle_invite_hit (what TEXT NOT NULL, at INTEGER NOT NULL)");}function limited(sql: SqlStorage, what: string, most: number): void {  const hour = Date.now() - 3_600_000;  sql.exec("DELETE FROM circle_invite_hit WHERE at < ?", hour);  const n = sql.exec<{ n: number }>("SELECT count(*) AS n FROM circle_invite_hit WHERE what = ?", what).one().n;  if (n >= most) refuse(429, "too_many_invites", "Too many tries in the last hour; try again later.");  sql.exec("INSERT INTO circle_invite_hit (what, at) VALUES (?, ?)", what, Date.now());}/** Lower-case letters and digits, `n` of them, from the system's randomness. */function code(n = 12): string {  const alphabet = "abcdefghijkmnpqrstuvwxyz23456789";  const bytes = crypto.getRandomValues(new Uint8Array(n));  return [...bytes].map((b) => alphabet[b % alphabet.length]).join("").padEnd(n, "a");}export async function sha256Text(text: string): Promise<string> {  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));  return btoa(String.fromCharCode(...digest)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}/** `POST /v1/circle/invite { secret_hash }`: a new link's code, kept with the directory for 30 days. */export async function make(host: InviteHost, body: Record<string, unknown>): Promise<{ id: string; code: string; ends_at: string }> {  ensure(host.sql);  const hash = body.secret_hash;  if (typeof hash !== "string" || !HASH.test(hash)) refuse(400, "bad_request", "secret_hash: the link secret's SHA-256, base64url");  limited(host.sql, "make", INVITES_PER_HOUR);  const id = crypto.randomUUID();  const made = new Date();  const ends = new Date(made.getTime() + INVITE_DAYS * 86_400_000);  const c = code();  await directory(host.env).circleInviteKeep(c, host.slug, ends.getTime());  host.sql.exec("INSERT INTO circle_invite (id, code, secret_hash, made_at, ends_at) VALUES (?, ?, ?, ?, ?)", id, c, hash, made.toISOString(), ends.toISOString());  return { id, code: c, ends_at: ends.toISOString() };}/** `POST /v1/circle/invite/stop { id }`: the link ends now. */export async function stop(host: InviteHost, body: Record<string, unknown>): Promise<{ ok: true }> {  ensure(host.sql);  const row = host.sql.exec<{ code: string }>("SELECT code FROM circle_invite WHERE id = ?", String(body.id ?? "")).toArray()[0];  if (!row) refuse(404, "no_such_invite", "No such invitation.");  host.sql.exec("UPDATE circle_invite SET stopped_at = COALESCE(stopped_at, ?) WHERE id = ?", new Date().toISOString(), String(body.id));  await directory(host.env).circleInviteDrop(row.code);  return { ok: true };}/** `GET /v1/circle/invites`: his links still standing. */export function standing(host: InviteHost): { invites: { id: string; code: string; made_at: string; ends_at: string }[] } {  ensure(host.sql);  const now = new Date().toISOString();  return { invites: host.sql.exec<{ id: string; code: string; made_at: string; ends_at: string }>("SELECT id, code, made_at, ends_at FROM circle_invite WHERE stopped_at IS NULL AND used_at IS NULL AND ends_at > ? ORDER BY made_at DESC", now).toArray() };}/** What the inviter's object answers a redeem that holds: its owner's number and the name they give. */export interface Redeemed {  number: string;  name: string | null;}/** * `POST /v1/circle/redeem { code, secret }` on the invited person's own object: found through the directory, handed to * the inviter's object, and on a match the inviter is one of this person's people. `accept` is the object's own add * (chat.ts `decide` accept and its ask over), which makes both sides connected. */export async function redeem(host: InviteHost, body: Record<string, unknown>, accept: (number: string) => Promise<void>, peerOf: (slug: string) => { circleRedeem(r: { code: string; secret: string; from: string; name: string | null }): Promise<Redeemed | null> }): Promise<Redeemed> {  ensure(host.sql);  const c = typeof body.code === "string" ? body.code.trim().toLowerCase() : "";  const secret = typeof body.secret === "string" ? body.secret.trim() : "";  if (!host.ownerPhone) refuse(409, "no_owner", "This account has no number to be invited with.");  limited(host.sql, "redeem", REDEEMS_PER_HOUR);  if (!CODE.test(c) || !SECRET.test(secret)) refuse(404, "invite_ended", NOT_ONE);  const slug = await directory(host.env).circleInviteFind(c);  if (!slug || slug === host.slug) refuse(404, "invite_ended", NOT_ONE);  const answer = await peerOf(slug).circleRedeem({ code: c, secret, from: host.ownerPhone, name: host.ownerName?.() ?? null });  if (!answer) refuse(404, "invite_ended", NOT_ONE);  await accept(answer.number);  return answer;}/** * The inviter's object, asked by the invited person's object: a live, unused code whose secret matches is used now, * and `from` becomes one of this owner's people (`accept`, chat.ts `decide` accept). Anything else answers null, the * same for every reason. */export async function redeemed(host: InviteHost, r: { code: string; secret: string; from: string; name: string | null }, accept: (number: string, name: string | null) => Promise<boolean>): Promise<Redeemed | null> {  ensure(host.sql);  if (!host.ownerPhone || r.from === host.ownerPhone) return null;  const row = host.sql.exec<{ id: string; secret_hash: string; ends_at: string; stopped_at: string | null; used_at: string | null }>("SELECT id, secret_hash, ends_at, stopped_at, used_at FROM circle_invite WHERE code = ?", r.code).toArray()[0];  if (!row || row.stopped_at || row.used_at || row.ends_at <= new Date().toISOString()) return null;  if ((await sha256Text(r.secret)) !== row.secret_hash) return null;  // AUDIT D: claimed in one statement before anything else is awaited. The hash and the add await, and an object takes  // other calls meanwhile: two redeems of one forwarded link both passed the check above and both got in. Only the one  // whose claim lands goes on; a refused add gives the link back.  const claimed = host.sql.exec("UPDATE circle_invite SET used_at = ?, used_by = 'redeemed' WHERE id = ? AND used_at IS NULL AND stopped_at IS NULL AND ends_at > ?", new Date().toISOString(), row.id, new Date().toISOString()).rowsWritten;  if (claimed !== 1) return null;  if (!(await accept(r.from, r.name))) {    host.sql.exec("UPDATE circle_invite SET used_at = NULL, used_by = NULL WHERE id = ?", row.id);    return null;  }  await directory(host.env).circleInviteDrop(r.code);  return { number: host.ownerPhone, name: host.ownerName?.() ?? null };}