Cotton code
306 lines · 25.0 KB · TypeScriptRaw
/** * GCAL READY (coordinator, 24 Nov 2026): Days and Google Calendar end to end against the fake Google * (src/fake_google), as a phone does it, so the day the real OAuth client exists the only change is its two secrets * and this proof run once against the real Google by hand (assets/design/days/GCAL-GO-LIVE.md). An invented +1555 * account and an invented Google account: *   1. connect: the consent page is the fake's (GOOGLE_BASE), asking `openid email calendar.events.owned`; unticking *      the calendar, Cancel, and a spent state each leave nothing connected (and the half grant revoked at Google); *   2. import: the events Google holds come into Days, the 90 days back and the whole future, a series as one row; *   3. changes in Google: moved, deleted, added, read by the sync token; the token expired (410) and the whole window *      read again; a rate limit said, kept trying, and cleared; an access token expired and refreshed; *   4. edit to Google: a Days change patched with its etag, sendUpdates none; a stale etag answered with Google's *      event; a Days event inserted under its own id and deleted; *   5. revoked at Google (the person in their Google account): the pull says connect again; *   6. disconnect: revoked at Google, forgotten, its events out of Days, Google's own events untouched. * *   pnpm -s exec tsx scripts/gcal-proof.ts --google <fake base> --fake-admin-file <path> [--base <url>] [--code-file <path>] * * Refuses any server but the dev Worker or a local wrangler dev. Nothing secret is printed. */import { generateKeyPairSync, randomBytes, randomUUID } from "node:crypto";import { readFileSync } from "node:fs";import { homedir } from "node:os";import { devBase } from "./dev-server";const arg = (name: string, fallback?: string) => {  const i = process.argv.indexOf(`--${name}`);  return i > 0 ? process.argv[i + 1]! : fallback;};const DEV = arg("base", devBase())!;if (DEV !== devBase() && !/^http:\/\/127\.0\.0\.1:\d+$/.test(DEV)) throw new Error("--base is the dev Worker or a local wrangler dev");const GOOGLE = (arg("google") ?? "").replace(/\/+$/, "");if (!GOOGLE || /googleapis\.com|google\.com/.test(GOOGLE)) throw new Error("--google is the fake Google's base, never Google's");const CODE = readFileSync(arg("code-file", `${homedir()}/.cotton-credentials/cotton/dev-otp`)!, "utf8").replace(/\D/g, "");const FAKE_ADMIN = readFileSync(arg("fake-admin-file")!, "utf8").trim();const say = (line: string) => console.log(`[gcal-proof] ${new Date().toISOString().slice(11, 19)} ${line}`);let passed = 0;const failed: string[] = [];const check = (what: string, ok: boolean, detail = "") => {  if (ok) passed++;  else failed.push(`${what}${detail ? `: ${detail}` : ""}`);  say(`${ok ? "ok  " : "FAIL"} ${what}${!ok && detail ? ` (${detail})` : ""}`);};const wait = (ms: number) => new Promise((done) => setTimeout(done, ms));type Answer = { status: number; body: Record<string, unknown>; text: string; location: string | null };async function http(url: string, init: RequestInit = {}): Promise<Answer> {  for (let attempt = 0; ; attempt++) {    try {      const res = await fetch(url, { redirect: "manual", ...init });      const text = await res.text();      if (res.status >= 500 && res.status !== 502 && res.status !== 503 && attempt < 3) throw new Error(`${res.status} ${text.slice(0, 160)}`);      let body: Record<string, unknown> = {};      try {        body = text ? JSON.parse(text) : {};      } catch {        body = {};      }      return { status: res.status, body, text, location: res.headers.get("location") };    } catch (error) {      if (attempt >= 3) throw error;      await wait(2_000 * (attempt + 1));    }  }}const short = (a: Answer) => `${a.status} ${a.text.slice(0, 200)}`;const call = (method: string, path: string, body: unknown, bearer: string) =>  http(`${DEV}${path}`, { method, headers: { "content-type": "application/json", authorization: `Bearer ${bearer}` }, body: body === undefined ? undefined : JSON.stringify(body) });const fake = (path: string, body?: unknown) =>  http(`${GOOGLE}${path}`, { method: body === undefined ? "GET" : "POST", headers: { "content-type": "application/json", authorization: `Bearer ${FAKE_ADMIN}` }, body: body === undefined ? undefined : JSON.stringify(body) });async function signIn(number: string): Promise<string> {  const device = randomBytes(32).toString("base64url");  const asked = await http(`${DEV}/v1/code`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ phone: number, device_id: device }) });  if (asked.status !== 200) throw new Error(`code: ${short(asked)}`);  const signed = await http(`${DEV}/v1/sign-in`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ database_id: asked.body.database_id, challenge_id: asked.body.challenge_id, code: CODE, device_id: device }) });  if (signed.status !== 200) throw new Error(`sign-in: ${short(signed)}`);  return String(signed.body.credential);}/** The consent page, answered as a person does: the account named, the scopes ticked, Continue or Cancel. */async function consent(authorizeUrl: string, email: string, tick: (scope: string) => boolean, answer: "allow" | "cancel"): Promise<Answer> {  const shown = await http(authorizeUrl);  if (shown.status !== 200) throw new Error(`consent page: ${short(shown)}`);  const hidden = Object.fromEntries([...shown.text.matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)">/g)].map((m) => [m[1]!, m[2]!.replace(/&#(\d+);/g, (_x, c: string) => String.fromCharCode(Number(c)))]));  const form = new URLSearchParams(hidden);  form.set("email", email);  form.set("answer", answer);  for (const m of shown.text.matchAll(/name="grant" value="([^"]+)"/g)) if (tick(m[1]!.replace(/&#(\d+);/g, (_x, c: string) => String.fromCharCode(Number(c))))) form.append("grant", m[1]!.replace(/&#(\d+);/g, (_x, c: string) => String.fromCharCode(Number(c))));  const back = await http(`${GOOGLE}/o/oauth2/v2/auth/consent`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: form.toString() });  if (back.status !== 302 || !back.location) throw new Error(`consent: ${short(back)}`);  // Google sends the browser to the callback on the open host; a local wrangler dev is that host on its own port.  const to = new URL(back.location);  const local = (u: URL) => (DEV.startsWith("http://127.0.0.1") ? `${DEV}${u.pathname}${u.search}` : u.toString());  const arrived = await http(local(to));  // The code is traded only on the person's Connect tap (src/connect_confirm.ts): the page names the Cotton account first.  const tap = /<form method="post" action="([^"]*)">(.*?)<\/form>/s.exec(arrived.text);  if (!tap) return arrived;  confirmPages.push(arrived.text);  const fields = new URLSearchParams([...tap[2]!.matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)">/g)].map((m): [string, string] => [m[1]!, m[2]!.replace(/&#(\d+);/g, (_x, c: string) => String.fromCharCode(Number(c))).replace(/&amp;/g, "&")]));  const action = new URL(tap[1]!.replace(/&amp;/g, "&"), to);  return http(local(action), { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: fields.toString() });}/** Every Connect page shown: each must name the account by its number's last four. */const confirmPages: string[] = [];type Row = { table: string; id: string; data: Record<string, unknown>; deleted?: boolean };async function events(credential: string): Promise<Row[]> {  const page = await call("GET", "/v1/sync?since=0&limit=2000", undefined, credential);  if (page.status !== 200) throw new Error(`sync: ${short(page)}`);  return ((page.body.rows ?? []) as Row[]).filter((r) => r.table === "event");}const live = (rows: Row[], account: string) => rows.filter((r) => !r.deleted && r.data?.account === account && r.data?.gcal_id && !r.data?.trashed_at);type Calendar = { phase: string; syncing: boolean; syncedAt: string | null; lastPassAt: string | null; lastError: string | null; eventCount: number };async function calendar(credential: string): Promise<{ available: boolean; accounts: { googleEmail: string; canWrite: boolean; calendar: Calendar }[] }> {  const s = await call("GET", "/v1/google/status", undefined, credential);  if (s.status !== 200) throw new Error(`status: ${short(s)}`);  return s.body as never;}/** Wakes the pull (dev only) and waits for a pass that ends after now; the pass's calendar state. */async function pulled(credential: string, until: (c: Calendar) => boolean = (c) => c.phase === "synced" && !c.syncing): Promise<Calendar> {  const since = new Date().toISOString();  const woke = await call("POST", "/v1/google/pull", {}, credential);  if (woke.status !== 200) throw new Error(`pull: ${short(woke)}`);  for (let i = 0; i < 60; i++) {    await wait(1_000);    const c = (await calendar(credential)).accounts[0]?.calendar;    if (c && c.lastPassAt && c.lastPassAt >= since && until(c)) return c;  }  const c = (await calendar(credential)).accounts[0]?.calendar;  throw new Error(`no pass ended as wanted in 60 s: ${JSON.stringify(c)}`);}const day = (offset: number, hour = 9) => {  const d = new Date(Date.now() + offset * 86_400_000);  d.setUTCHours(hour, 0, 0, 0);  return d.toISOString().replace(/\.\d{3}Z$/, "Z");};const later = (iso: string, minutes: number) => new Date(Date.parse(iso) + minutes * 60_000).toISOString().replace(/\.\d{3}Z$/, "Z");const gid = (n: number) => `proof${String(n).padStart(5, "0")}`;async function main(): Promise<void> {  const number = `+1555${String(Math.floor(1_000_000 + Math.random() * 8_999_999))}`;  const email = `days.proof.${randomBytes(4).toString("hex")}@example.test`;  const credential = await signIn(number);  say(`signed in an invented number; the invented Google account is ${email}`);  // What a Days phone does once signed in: hands the object its arrival key, so what Google brings is sealed at arrival.  const pub = String(generateKeyPairSync("x25519").publicKey.export({ format: "jwk" }).x);  const handed = await call("POST", "/v1/act", { act: "create", args: { table: "seal_key", id: "arrival", data: { pub } } }, credential);  if (handed.status !== 200) throw new Error(`arrival key: ${short(handed)}`);  const first = await calendar(credential);  check("Google is available on this Worker (its client id and secret are set)", first.available === true, JSON.stringify(first));  // ── 1. connect, and the ways it is not ──  const asked = await call("GET", "/v1/google/connect", undefined, credential);  const authorize = new URL(String(asked.body.authorizeUrl));  check("the consent page is the fake Google's (GOOGLE_BASE honoured on this Worker)", `${authorize.origin}${authorize.pathname}` === `${GOOGLE}/o/oauth2/v2/auth`, authorize.origin);  check("it asks openid, email and calendar.events.owned, offline, with consent", authorize.searchParams.get("scope") === "openid email https://www.googleapis.com/auth/calendar.events.owned" && authorize.searchParams.get("access_type") === "offline" && authorize.searchParams.get("prompt") === "consent");  const unticked = await consent(authorize.toString(), email, (s) => !s.includes("calendar"), "allow");  check("calendar unticked: not connected, the page says to leave it ticked", unticked.status === 400 && unticked.text.includes("Calendar access was not ticked"), short(unticked));  const grantsAfter = (await fake(`/fake/admin/grants?email=${encodeURIComponent(email)}`)).body;  check("…and the half grant was revoked at Google", grantsAfter.live === 0 && grantsAfter.revoked === 1, JSON.stringify(grantsAfter));  const spent = await consent(authorize.toString(), email, () => true, "allow");  check("the same state again: expired or already used", spent.status === 400 && spent.text.includes("expired or was already used"), short(spent));  const cancelled = await consent(String((await call("GET", "/v1/google/connect", undefined, credential)).body.authorizeUrl), email, () => true, "cancel");  check("Cancel on Google's page: not connected", cancelled.status === 200 && cancelled.text.includes("did not give Days access"), short(cancelled));  check("nothing is connected after those three", (await calendar(credential)).accounts.length === 0);  // What the invented Google Calendar holds before Days connects: 30 events over 60 days back to 90 ahead, two all-day, a weekly series, one from 200 days ago.  for (let n = 0; n < 30; n++) {    const start = day(-60 + n * 5, 8 + (n % 8));    await fake("/fake/admin/events", { email, event: { id: gid(n), summary: `Invented meeting ${n}`, start: { dateTime: start }, end: { dateTime: later(start, 45) } } });  }  await fake("/fake/admin/events", { email, event: { id: gid(100), summary: "Invented holiday", start: { date: day(10).slice(0, 10) }, end: { date: day(12).slice(0, 10) } } });  await fake("/fake/admin/events", { email, event: { id: gid(101), summary: "Invented birthday", start: { date: day(20).slice(0, 10) }, end: { date: day(21).slice(0, 10) } } });  await fake("/fake/admin/events", { email, event: { id: gid(102), summary: "Invented weekly", start: { dateTime: day(-14, 4) }, end: { dateTime: later(day(-14, 4), 60) }, recurrence: ["RRULE:FREQ=WEEKLY;COUNT=20"] } });  await fake("/fake/admin/events", { email, event: { id: gid(103), summary: "Invented, long ago", start: { dateTime: day(-200) }, end: { dateTime: later(day(-200), 30) } } });  const expected = new Set([...Array.from({ length: 30 }, (_x, n) => gid(n)), gid(100), gid(101), gid(102)]);  const connected = await consent(String((await call("GET", "/v1/google/connect", undefined, credential)).body.authorizeUrl), email, () => true, "allow");  check("allowed: connected, and the page says changes go back", connected.status === 200 && connected.text.includes(`events of ${email}`) && connected.text.includes("saves the changes"), short(connected));  check("each Connect page names this Cotton account by its number's last four, before anything is traded", confirmPages.length >= 2 && confirmPages.every((p) => p.includes(number.slice(-4))), `${confirmPages.length} pages`);  const status = await calendar(credential);  check("status: one account, the invented address, can write", status.accounts.length === 1 && status.accounts[0]!.googleEmail === email && status.accounts[0]!.canWrite === true, JSON.stringify(status.accounts));  // ── 2. import ──  const c1 = await pulled(credential);  let rows = live(await events(credential), email);  const ids = new Set(rows.map((r) => String(r.data.gcal_id)));  check(`import: the ${expected.size} events in the window came in, the one 200 days ago did not`, ids.size === expected.size && [...expected].every((id) => ids.has(id)) && !ids.has(gid(103)), `${ids.size} rows: ${[...ids].filter((i) => !expected.has(i)).join(",")}`);  check("status counts them", c1.eventCount === expected.size, String(c1.eventCount));  const r5 = rows.find((r) => r.data.gcal_id === gid(5))!;  check("a timed event keeps Google's start and etag in the clear columns", r5 && Date.parse(String(r5.data.starts_at)) === Date.parse(day(-60 + 25, 8 + 5)) && typeof r5.data.gcal_etag === "string", JSON.stringify(r5?.data).slice(0, 200));  const allDay = rows.find((r) => r.data.gcal_id === gid(100));  check("an all-day event is all day", allDay?.data.all_day === true || allDay?.data.all_day === 1, JSON.stringify(allDay?.data).slice(0, 200));  const series = rows.find((r) => r.data.gcal_id === gid(102));  check("the series is one row carrying its rule", !!series && String(series.data.rrule ?? "").includes("FREQ=WEEKLY"), JSON.stringify(series?.data).slice(0, 200));  const lists1 = (await fake(`/fake/admin/events?email=${encodeURIComponent(email)}`)).body.lists as { kind: string; status: number }[];  check("the first pass read the whole window", lists1.some((l) => l.kind === "window" && l.status === 200));  // ── 3. changes in Google ──  const moved = day(30, 15);  await fake("/fake/admin/events", { email, event: { id: gid(3), start: { dateTime: moved }, end: { dateTime: later(moved, 30) } } });  await fake("/fake/admin/events/delete", { email, id: gid(4) });  const added = day(40, 10);  await fake("/fake/admin/events", { email, event: { id: gid(200), summary: "Invented, made in Google", start: { dateTime: added }, end: { dateTime: later(added, 60) } } });  await pulled(credential);  rows = live(await events(credential), email);  const lists2 = (await fake(`/fake/admin/events?email=${encodeURIComponent(email)}`)).body.lists as { kind: string; status: number }[];  check("the next pass read by the sync token", lists2.length > lists1.length && lists2.slice(lists1.length).every((l) => l.kind === "sync" && l.status === 200), JSON.stringify(lists2.slice(lists1.length)));  check("moved in Google: moved in Days", Date.parse(String(rows.find((r) => r.data.gcal_id === gid(3))?.data.starts_at)) === Date.parse(moved));  check("deleted in Google: out of Days", !rows.some((r) => r.data.gcal_id === gid(4)));  check("made in Google: in Days", rows.some((r) => r.data.gcal_id === gid(200)));  await fake("/fake/admin/expire-sync", { email });  await fake("/fake/admin/events", { email, event: { id: gid(6), summary: "Invented, renamed after the token expired" } });  const c410 = await pulled(credential);  const lists3 = ((await fake(`/fake/admin/events?email=${encodeURIComponent(email)}`)).body.lists as { kind: string; status: number }[]).slice(lists2.length);  check("sync token expired: Google said 410 and the whole window was read again", lists3[0]?.kind === "sync" && lists3[0]?.status === 410 && lists3.some((l) => l.kind === "window" && l.status === 200), JSON.stringify(lists3));  rows = live(await events(credential), email);  check("…and Days holds the same events, none doubled", c410.phase === "synced" && rows.length === expected.size && new Set(rows.map((r) => r.data.gcal_id)).size === rows.length, `${rows.length} rows, phase ${c410.phase}`);  // Google's per-user limit: every Calendar call refused, as Google says it (403 rateLimitExceeded).  await fake("/fake/admin/rate", { email, per_minute: 0, status: 403 });  await fake("/fake/admin/events", { email, event: { id: gid(7), summary: "Invented, renamed while limited" } });  const cLimited = await pulled(credential, (c) => !c.syncing && !!c.lastError);  check("rate limited (403 rateLimitExceeded): said as rate_limited, still connected", cLimited.lastError === "rate_limited" && cLimited.phase !== "reconnect", JSON.stringify(cLimited));  await fake("/fake/admin/rate", { email, per_minute: null });  const cCleared = await pulled(credential);  check("limit lifted: the next pass lands, the change made meanwhile with it", cCleared.phase === "synced" && !cCleared.lastError, JSON.stringify(cCleared));  await fake("/fake/admin/expire-access", { email });  await fake("/fake/admin/events", { email, event: { id: gid(8), summary: "Invented, after the access token expired" } });  const cRefresh = await pulled(credential);  check("access token expired: refreshed, the pass lands", cRefresh.phase === "synced" && !cRefresh.lastError, JSON.stringify(cRefresh));  // ── 4. edit to Google ──  rows = live(await events(credential), email);  const target = rows.find((r) => r.data.gcal_id === gid(10))!;  const newStart = day(50, 11);  const patched = await call("POST", "/v1/google/events", { op: "patch", gcalId: gid(10), etag: target.data.gcal_etag, event: { summary: "Changed in Days", start: { dateTime: newStart }, end: { dateTime: later(newStart, 30) } } }, credential);  let held = (await fake(`/fake/admin/events?email=${encodeURIComponent(email)}`)).body;  const g10 = (held.events as Record<string, unknown>[]).find((e) => e.id === gid(10))!;  check("a Days change patched to Google with its etag", patched.status === 200 && patched.body.gcalId === gid(10) && g10.summary === "Changed in Days" && Date.parse(String((g10.start as { dateTime?: string } | undefined)?.dateTime)) === Date.parse(newStart) && patched.body.etag === g10.etag, short(patched));  const lastWrite = (held.writes as { method: string; id: string; sendUpdates: string | null }[]).at(-1);  check("…sending no mail to guests (sendUpdates none)", lastWrite?.method === "patch" && lastWrite.sendUpdates === "none", JSON.stringify(lastWrite));  const stale = await call("POST", "/v1/google/events", { op: "patch", gcalId: gid(10), etag: target.data.gcal_etag, event: { summary: "Stale" } }, credential);  check("a stale etag: Google's 412 answered with Google's event, nothing overwritten", stale.status === 200 && stale.body.changed === true && (stale.body.event as { summary?: string } | undefined)?.summary === "Changed in Days", short(stale));  const own = randomUUID();  const start = day(60, 9);  const inserted = await call("POST", "/v1/google/events", { op: "insert", id: own, event: { summary: "Made in Days", start: { dateTime: start }, end: { dateTime: later(start, 30) } } }, credential);  held = (await fake(`/fake/admin/events?email=${encodeURIComponent(email)}`)).body;  const made = (held.events as Record<string, unknown>[]).find((e) => e.id === inserted.body.gcalId);  check("a Days event inserted in Google under an id from its own", inserted.status === 200 && /^[a-v0-9]{5,}$/.test(String(inserted.body.gcalId)) && made?.summary === "Made in Days", short(inserted));  const again = await call("POST", "/v1/google/events", { op: "insert", id: own, event: { summary: "Made in Days", start: { dateTime: start }, end: { dateTime: later(start, 30) } } }, credential);  check("the same insert again (a retry) does not make a second", again.status === 200 && (((await fake(`/fake/admin/events?email=${encodeURIComponent(email)}`)).body.events as Record<string, unknown>[]).filter((e) => e.summary === "Made in Days").length === 1), short(again));  const removed = await call("POST", "/v1/google/events", { op: "delete", gcalId: inserted.body.gcalId }, credential);  held = (await fake(`/fake/admin/events?email=${encodeURIComponent(email)}`)).body;  check("deleted from Days: cancelled in Google", removed.status === 200 && removed.body.deleted === true && (held.events as Record<string, unknown>[]).find((e) => e.id === inserted.body.gcalId)?.status === "cancelled", short(removed));  const twice = await call("POST", "/v1/google/events", { op: "delete", gcalId: inserted.body.gcalId }, credential);  check("deleted again: said gone, not an error", twice.status < 500, short(twice));  // ── 6. disconnect ──  const grant = await fake(`/fake/admin/grants?email=${encodeURIComponent(email)}`);  const all = await fake(`/fake/admin/events?email=${encodeURIComponent(email)}`);  const googleCount = (all.body.events as Record<string, unknown>[]).filter((e) => e.status !== "cancelled").length;  const before = live(await events(credential), email).length;  const off = await call("POST", "/v1/google/disconnect", {}, credential);  const grantsOff = (await fake(`/fake/admin/grants?email=${encodeURIComponent(email)}`)).body;  check("disconnect: answered with the events taken out", off.status === 200 && off.body.ok === true && off.body.removed === before, `${short(off)} vs ${before}`);  check("…the grant revoked at Google", grantsOff.live === 0 && grantsOff.revoked === Number(grant.body.revoked) + Number(grant.body.live), JSON.stringify(grantsOff));  check("…nothing connected, no Google event left in Days", (await calendar(credential)).accounts.length === 0 && live(await events(credential), email).length === 0);  const after = ((await fake(`/fake/admin/events?email=${encodeURIComponent(email)}`)).body.events as Record<string, unknown>[]).filter((e) => e.status !== "cancelled").length;  check("…and Google's own events untouched", after === googleCount, `${after} vs ${googleCount}`);  // ── 5. revoked at Google rather than from Days: connect again, then the person removes Days at Google ──  const back = await consent(String((await call("GET", "/v1/google/connect", undefined, credential)).body.authorizeUrl), email, () => true, "allow");  check("connected again", back.status === 200, short(back));  await pulled(credential);  await fake("/fake/admin/expire-access", { email });  // The person removes Days at myaccount.google.com: every grant of this account revoked.  const revokedAll = await revokeAtGoogle(email);  const cGone = await pulled(credential, (c) => c.phase === "reconnect");  check("revoked at Google: Days says connect again", cGone.phase === "reconnect" && cGone.lastError === "reconnect_required" && revokedAll > 0, JSON.stringify(cGone));  const cleaned = await call("POST", "/v1/google/disconnect", {}, credential);  check("…and disconnecting then still clears it", cleaned.status === 200 && (await calendar(credential)).accounts.length === 0, short(cleaned));  say(`${passed} of ${passed + failed.length} checks passed`);  if (failed.length) {    for (const f of failed) say(`FAILED: ${f}`);    process.exit(1);  }}/** What myaccount.google.com's "Remove access" does: the fake's admin route for it. */async function revokeAtGoogle(email: string): Promise<number> {  const r = await fake("/fake/admin/revoke-all", { email });  return Number(r.body.revoked ?? 0);}main().catch((error) => {  say(`STOPPED: ${error instanceof Error ? error.message : String(error)}`);  process.exit(1);});