Cotton code
473 lines · 24.9 KB · TypeScriptRaw
/** * Google Calendar on the person's own object (owner, 27 Oct 2026): one Google * sign-in from the phone, the grant kept sealed by the object, the calendar * pulled on the object's own alarm (src/google_calendar.ts), and written * from the phone through the object (src/google_write.ts). Calendar only: * mail comes in through the Mac's importer. The scopes asked (22 Nov 2026, * assets/design/days/GOOGLE.md §1, reversed the same day once Days writes) * are `calendar.events.owned` (24 Nov 2026, narrowed from `calendar.events`, * whose grants keep working), the primary calendar's events read and written, and * `openid email` for the account's address; a grant missing either is given * back. A grant made before with `calendar.events.readonly` keeps reading: * its account says `can_write: false` until the person connects again. * *   GET  /v1/google/connect     (owner) { authorizeUrl, state }: Google's *        consent page for a WEB client whose one redirect is the callback *        on the open host; the phone opens it in the system browser *   GET  /v1/google/callback    Google sends the browser back here with *        `code` and `state`; the open host finds the object by the *        state's database id (src/open.ts), the object trades the code *        against the redirect the state was given with, seals the *        refresh token into a `secret` row and answers a plain page *   GET  /v1/google/status      (owner) { available, keep, accounts: [{ googleEmail, *        connectedAt, canWrite, calendar: { phase, syncing, syncedAt, lastPassAt, *        lastError, lastErrorMessage, eventCount, pulled } }] } *   POST /v1/google/events      (owner) one write to Google (src/google_write.ts) *   POST /v1/google/settings    (owner) { keep }: "Also keep my Days events in *        Google Calendar", kept in the meta for the phone's core to read back *   POST /v1/google/pull        (owner, dev and test Workers only) the pull now, for a proof against the fake Google *   POST /v1/google/disconnect  (owner) { account? }: revokes the grant at *        Google, forgets it, and bins every event pulled from it (a *        disconnected calendar's events leave Days: they would never change *        again and could not be changed); answers { ok, account, removed } * * STATE is one-shot, bound to the object (`<database id>.<random>`, its hash * kept in this object's meta alone) and lives ten minutes. * * THE GRANT is a `secret` row of kind api_key, service `google`, named * `google.<email>` (the old server's own name for it): its `sealed` column is * the refresh token sealed under SERVICE_TOKEN_KEY (t1, src/vault.ts) with the row's id bound in, its * `hint` the last four characters. No answer, page or log line carries it. * * Which Google account a grant is: the address in the ID token Google answers * the code with (`openid email`), straight from Google's token endpoint over * TLS, so its signature need not be checked. The calendar's time zone comes * with its first listing (src/google_calendar.ts). */import type { Engine, Outcome } from "./engine.ts";import { devWorker, type Env } from "./env.ts";import { esc, page } from "./oauth.ts";import { randomToken, readJson, refuse, sha256Hex } from "./http.ts";import { equalSql } from "./mcp/tools/records/where.ts";import type { Store } from "./store.ts";import * as vault from "./vault.ts";/** * The calendar scope asked: events on the calendars the person owns, read and written (Days writes the person's * changes back). Every call is on `calendars/primary`, which the person owns, so this is the narrowest scope that * writes (coordinator, 24 Nov 2026, NARROW; assets/design/days/GOOGLE-VERIFICATION.md §1). Google shows it as "See, * create, change, and delete events on Google calendars you own". */export const SCOPE = "https://www.googleapis.com/auth/calendar.events.owned";/** * The wider scope asked from 22 to 24 Nov 2026 ("View and edit events on all your calendars"). A grant already * holding it keeps reading and writing as before: nobody has to connect again. A new connect asks [SCOPE]. */export const WIDE_SCOPE = "https://www.googleapis.com/auth/calendar.events";/** The scope asked before Days wrote (until 22 Nov 2026): a grant carrying it alone keeps reading, and cannot write. */export const READ_SCOPE = "https://www.googleapis.com/auth/calendar.events.readonly";/** The address scope Google grants for `email`. */export const EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";/** What the consent page asks: the account's address and the events of the calendars the person owns, read and written. */export const SCOPES = `openid email ${SCOPE}`;export const AUTHORIZE_URL = "https://accounts.google.com/o/oauth2/v2/auth";export const TOKEN_URL = "https://oauth2.googleapis.com/token";export const REVOKE_URL = "https://oauth2.googleapis.com/revoke";export const CALENDAR_API = "https://www.googleapis.com/calendar/v3";export const CALLBACK_PATH = "/v1/google/callback";/** * Where each call goes: Google's own hosts, or on the dev and test Workers alone the fake Google named by * GOOGLE_BASE (apps/fake-google: its paths are Google's). Anywhere else GOOGLE_BASE is ignored, so a live Worker * can never be pointed away from Google by a var. */export function googleUrls(env: Env): { authorize: string; token: string; revoke: string; calendar: string } {  const base = env.GOOGLE_BASE && devWorker(env) ? env.GOOGLE_BASE.replace(/\/+$/, "") : null;  if (!base) return { authorize: AUTHORIZE_URL, token: TOKEN_URL, revoke: REVOKE_URL, calendar: CALENDAR_API };  return { authorize: `${base}/o/oauth2/v2/auth`, token: `${base}/token`, revoke: `${base}/revoke`, calendar: `${base}/calendar/v3` };}/** The routes this module answers on a personal object. */export const GOOGLE_PATH = /^\/v1\/google\/(connect|callback|status|disconnect|events|settings|pull)$/;/** How long a consent page's state is honoured. */export const STATE_TTL_MS = 10 * 60 * 1000;/** The meta keys: the accounts' state, the states waiting for their callback. */const ACCOUNTS = "google_accounts";const PENDING = "google_pending";/** "1" while the person keeps their own Days events in Google Calendar too (CONTRACT §16 `keep`). */const KEEP = "google_keep";const SECRET = "secret";const SERVICE = "google";/** Where an account's calendar pull stands. */export type Phase = "waiting" | "syncing" | "synced" | "reconnect";export interface PassError {  code: string;  message: string;  at: string;}/** One connected Google account, as this object keeps it in its meta (never synced). */export interface Account {  email: string;  /** The `secret` row the refresh token is sealed in. */  secret: string;  connected_at: string;  /** Whether Google granted `calendar.events` (writing); absent on an account connected before Days wrote: read-only. */  can_write?: boolean;  /** The scopes Google said it granted at the last connect, as it said them. */  scopes?: string[];  /** The primary calendar's own zone: an all-day event's day is read in it. */  timezone: string | null;  phase: Phase;  /** Google's cursor after the last whole pass; null until the first lands, and after a 410. */  sync_token: string | null;  /** The next page of a pass that stopped at its bound; it carries on at the next alarm. */  page_token: string | null;  /** A whole listing's window (no sync token), kept across its pages: what the reconcile at its end judges by. */  window: { from: string; to: string } | null;  synced_at: string | null;  last_pass_at: string | null;  last_error: PassError | null;  /** What the last pass did. */  pulled: { created: number; updated: number; binned: number };}/** What the object lends this module: its store, its writer and its alarm. */export interface GoogleHost {  env: Env;  store: Store;  /** The object's own SQLite: the pull's private note of what a whole listing carried. */  sql: SqlStorage;  databaseId: string;  /** The database's own zone: an account whose calendar names none reads its days here. */  zone: string;  /** Writes in one transaction and one version, logged as Google's. */  write<T>(fn: (engine: Engine, version: number, outcome: Outcome) => T): T;  /** The same, with what it makes or changes in a sealed table sealed at arrival (src/arrival_seam.ts): `fn` runs twice, so it changes nothing outside the store but its answer. */  writeSealed<T>(fn: (engine: Engine, version: number, outcome: Outcome) => T): Promise<T>;  /** Sets the object's alarm for now: a new grant is pulled at once. */  wake(): Promise<void>;}// ── the accounts in the meta ─────────────────────────────────────────────export function readAccounts(store: Store): Account[] {  const raw = store.meta(ACCOUNTS);  if (!raw) return [];  try {    const parsed = JSON.parse(raw) as unknown;    return Array.isArray(parsed) ? (parsed as Account[]) : [];  } catch {    return [];  }}export function writeAccounts(store: Store, accounts: Account[]): void {  store.setMeta(ACCOUNTS, accounts.length ? JSON.stringify(accounts) : null);}/** What a pass says when an account's grant does not open (src/google_calendar.ts): the one stop a rekey undoes. */export const GRANT_UNOPENED = "the grant is not in the vault any more";/** * The accounts a pass stopped for want of an unopened grant, whose grant the * SERVICE_TOKEN_KEY rekey has just moved (`secrets`), pull again: a pass * that ran between the deploy and the rekey must not leave an account asking * to connect again. Answers how many. */export function reviveRekeyed(store: Store, secrets: Set<string>): number {  let revived = 0;  const accounts = readAccounts(store).map((a) => {    if (a.phase !== "reconnect" || !secrets.has(a.secret) || !a.last_error?.message.startsWith(GRANT_UNOPENED)) return a;    revived++;    return { ...a, phase: a.sync_token ? ("synced" as const) : ("waiting" as const), last_error: null };  });  if (revived) writeAccounts(store, accounts);  return revived;}/** One account's state replaced in place, read fresh: a pass never writes over a disconnect that landed meanwhile. */export function saveAccount(store: Store, account: Account): void {  const all = readAccounts(store);  const at = all.findIndex((a) => a.email === account.email);  if (at < 0) return;  all[at] = account;  writeAccounts(store, all);}// ── routes ───────────────────────────────────────────────────────────────/** The client this Worker is, or a refusal naming the secret it lacks. */export function client(env: Env): { id: string; secret: string } {  if (!env.GOOGLE_CLIENT_ID || !env.GOOGLE_CLIENT_SECRET) refuse(503, "google_unavailable", "this Worker has no Google client yet (GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)");  return { id: env.GOOGLE_CLIENT_ID, secret: env.GOOGLE_CLIENT_SECRET };}/** * Where Google brings the browser back: the callback on the open host, the * Web client's one registered redirect. The object is found by the state, * never by the host. */export function redirectUri(env: Env): string {  if (!env.OPEN_HOST) refuse(503, "google_unavailable", "this Worker has no open host to bring Google's answer back to (OPEN_HOST)");  return `https://${env.OPEN_HOST}${CALLBACK_PATH}`;}/** `GET /v1/google/connect`: Google's consent page for this object, and its one-shot state. */export async function connect(host: GoogleHost): Promise<{ authorizeUrl: string; state: string }> {  const { id } = client(host.env);  const state = `${host.databaseId}.${randomToken(24)}`;  const now = Date.now();  const redirect = redirectUri(host.env);  const pending = readPending(host.store).filter((p) => p.expires > now);  // The redirect goes with the state: Google's code is traded only against the redirect it was given for.  pending.push({ hash: await sha256Hex(state), expires: now + STATE_TTL_MS, redirect });  host.store.setMeta(PENDING, JSON.stringify(pending));  const url = new URL(googleUrls(host.env).authorize);  url.search = new URLSearchParams({    client_id: id,    redirect_uri: redirect,    response_type: "code",    scope: SCOPES,    access_type: "offline",    prompt: "consent",    include_granted_scopes: "false",    state,  }).toString();  return { authorizeUrl: url.toString(), state };}interface Pending {  hash: string;  expires: number;  redirect: string;}function readPending(store: Store): Pending[] {  try {    const parsed = JSON.parse(store.meta(PENDING) ?? "[]") as unknown;    return Array.isArray(parsed) ? (parsed as Pending[]) : [];  } catch {    return [];  }}/** Whether `state` is one this object gave, unspent and in time: looked at, not spent (the confirming page). */export async function awaiting(store: Store, state: string): Promise<boolean> {  const hash = await sha256Hex(state);  return readPending(store).some((p) => p.hash === hash && p.expires > Date.now());}/** A state this object gave and has not spent: its redirect once, and never again (null). */async function spend(store: Store, state: string): Promise<string | null> {  const hash = await sha256Hex(state);  const now = Date.now();  const pending = readPending(store);  const held = pending.find((p) => p.hash === hash && p.expires > now);  const left = pending.filter((p) => p.hash !== hash && p.expires > now);  store.setMeta(PENDING, left.length ? JSON.stringify(left) : null);  return held?.redirect ?? null;}/** The words the callback page says, plainly: the browser is all the person sees. */function said(title: string, line: string, status = 200): Response {  return page(title, `<p>${esc(line)}</p>`, status);}/** * `GET /v1/google/callback?code&state` (or `?error&state` when the person * declined): the state is spent first, whatever follows, then the code is * traded, the account named, the grant sealed and the pull woken. */export async function callback(host: GoogleHost, url: URL): Promise<Response> {  const state = url.searchParams.get("state") ?? "";  const redirect = state.startsWith(`${host.databaseId}.`) ? await spend(host.store, state) : null;  if (!redirect) {    return said("Google Calendar was not connected", "This link has expired or was already used. Start again from Days.", 400);  }  if (url.searchParams.get("error")) return said("Google Calendar was not connected", "Google did not give Days access. You can close this page.", 200);  const code = url.searchParams.get("code");  if (!code) return said("Google Calendar was not connected", "Google sent no code back. Start again from Days.", 400);  const c = client(host.env);  const traded = await fetch(googleUrls(host.env).token, {    method: "POST",    headers: { "content-type": "application/x-www-form-urlencoded" },    body: new URLSearchParams({ grant_type: "authorization_code", code, client_id: c.id, client_secret: c.secret, redirect_uri: redirect }).toString(),  });  const grant = (await traded.json().catch(() => ({}))) as { access_token?: string; refresh_token?: string; scope?: string; id_token?: string };  if (!traded.ok || !grant.access_token) return said("Google Calendar was not connected", "Google refused the sign-in. Start again from Days.", 502);  // Google's consent lets a person untick each scope; a grant without the calendar reads nothing, one without the address names no account.  const granted = (grant.scope ?? "").split(" ").filter(Boolean);  const canWrite = granted.includes(SCOPE) || granted.includes(WIDE_SCOPE);  if (!canWrite && !granted.includes(READ_SCOPE)) {    await revoke(host.env, grant.refresh_token ?? grant.access_token);    return said("Google Calendar was not connected", "Calendar access was not ticked on Google's page. Start again from Days and leave it ticked.", 400);  }  const email = granted.includes(EMAIL_SCOPE) || granted.includes("email") ? addressOf(grant.id_token) : null;  if (!email) {    await revoke(host.env, grant.refresh_token ?? grant.access_token);    return said("Google Calendar was not connected", "Google did not share which account this is. Start again from Days and leave your email address ticked.", 400);  }  if (!grant.refresh_token) return said("Google Calendar was not connected", "Google gave no lasting access. Start again from Days.", 502);  await keepGrant(host, email, grant.refresh_token, null, canWrite, granted);  await host.wake();  return said(    "Google Calendar is connected",    canWrite      ? `Days now brings in the events of ${email}, and saves the changes you make in Days back to it. You can close this page and go back to Days.`      : `Days now brings in the events of ${email}. You can close this page and go back to Days.`,  );}/** The verified address an ID token names, lower-cased; null when it names none. */export function addressOf(idToken: string | undefined): string | null {  const payload = idToken?.split(".")[1];  if (!payload) return null;  try {    const claims = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(payload.length / 4) * 4, "="))) as { email?: unknown; email_verified?: unknown };    if (typeof claims.email !== "string" || !claims.email.includes("@") || claims.email_verified === false) return null;    return claims.email.trim().toLowerCase();  } catch {    return null;  }}/** The refresh token sealed into its secret row, and the account entered (or brought back) in the meta: a new grant replaces the old one whole, what it may do too. */async function keepGrant(host: GoogleHost, email: string, refreshToken: string, timezone: string | null, canWrite: boolean, scopes: string[]): Promise<void> {  const name = `google.${email}`;  // Its row is the one the account names (a sealed name is never read here, OPEN-TABLES.md §3), or the one by that name.  const pointed = readAccounts(host.store).find((a) => a.email === email)?.secret;  const held = (pointed ? host.store.get(SECRET, pointed) : null) ?? host.store.select(SECRET, [equalSql("service", SERVICE), equalSql("name", name)], "created_at, id", 1)[0] ?? null;  const id = held?.id ?? crypto.randomUUID();  const sealed = await vault.sealServiceToken(host.env, id, JSON.stringify({ kind: "api_key", key: refreshToken }));  const patch = { sealed, hint: [...refreshToken].slice(-4).join(""), kind: "api_key", site: "calendar.google.com", trashed_at: null };  // Sealed at arrival when the passwords are sealed: the token column stays the object's own, the site and hint sealed.  await host.writeSealed((engine, version, outcome) => {    const row = held ? host.store.get(SECRET, held.id) : null;    if (row) engine.update(row, patch, version, outcome);    else engine.create(SECRET, { ...patch, name, service: SERVICE }, version, outcome, 0, { id });    const accounts = readAccounts(host.store);    const was = accounts.find((a) => a.email === email);    const account: Account = was      ? { ...was, secret: id, timezone, can_write: canWrite, scopes, phase: was.sync_token ? "synced" : "waiting", last_error: null }      : { email, secret: id, connected_at: new Date().toISOString(), can_write: canWrite, scopes, timezone, phase: "waiting", sync_token: null, page_token: null, window: null, synced_at: null, last_pass_at: null, last_error: null, pulled: { created: 0, updated: 0, binned: 0 } };    writeAccounts(host.store, [...accounts.filter((a) => a.email !== email), account]);  });}/** The refresh token an account's secret row seals, or null when it does not open (gone, or another key). */export async function refreshTokenOf(host: GoogleHost, account: Account): Promise<string | null> {  const row = host.store.get(SECRET, account.secret);  const sealed = typeof row?.data.sealed === "string" ? row.data.sealed : null;  if (!sealed) return null;  const opened = await vault.openServiceToken(host.env, account.secret, sealed);  if (!opened) return null;  try {    const payload = JSON.parse(opened) as { key?: unknown };    return typeof payload.key === "string" ? payload.key : null;  } catch {    return null;  }}/** Revokes a token at Google; true when Google no longer honours it (revoked now, or already). */async function revoke(env: Env, token: string): Promise<boolean> {  const res = await fetch(googleUrls(env).revoke, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ token }).toString() });  // 400 is Google's word for a token it does not know: already revoked or run out.  return res.ok || res.status === 400;}/** * `GET /v1/google/status`: whether this Worker can connect at all, and each * account's calendar block in the shape the phone's Connected line reads * (`GoogleStatusLines.swift`): `lastError` the code alone (its words beside it * in `lastErrorMessage`), `syncing` while a pass has pages left. */export function status(host: GoogleHost): Record<string, unknown> {  return {    available: Boolean(host.env.GOOGLE_CLIENT_ID && host.env.GOOGLE_CLIENT_SECRET && host.env.OPEN_HOST),    keep: readKeep(host.store),    accounts: readAccounts(host.store).map((a) => ({      googleEmail: a.email,      connectedAt: a.connected_at,      canWrite: a.can_write === true,      calendar: {        phase: a.phase,        syncing: a.phase === "syncing",        syncedAt: a.synced_at,        lastPassAt: a.last_pass_at,        lastError: a.last_error?.code ?? null,        lastErrorMessage: a.last_error?.message ?? null,        eventCount: host.store.count("event", [equalSql("account", a.email), { sql: "json_extract(data, '$.gcal_id') IS NOT NULL", args: [] }]),        pulled: a.pulled,      },    })),  };}/** Whether the person keeps their own Days events in Google Calendar too; off until they turn it on. */export function readKeep(store: Store): boolean {  return store.meta(KEEP) === "1";}/** `POST /v1/google/settings { keep }`: the switch kept in the meta, answered back. */export async function settings(host: GoogleHost, request: Request): Promise<{ keep: boolean }> {  const body = await readJson(request);  if (typeof body.keep !== "boolean") refuse(400, "bad_request", "keep: true or false");  host.store.setMeta(KEEP, body.keep ? "1" : null);  return { keep: body.keep };}/** `POST /v1/google/disconnect { account? }`: the grant revoked at Google, its secret binned, the account forgotten, its events binned. */export async function disconnect(host: GoogleHost, request: Request): Promise<Record<string, unknown>> {  const body = await readJson(request);  const accounts = readAccounts(host.store);  const asked = typeof body.account === "string" ? body.account.trim().toLowerCase() : null;  if (!asked && accounts.length > 1) refuse(400, "bad_request", "name the account to disconnect: more than one is connected");  const account = asked ? accounts.find((a) => a.email === asked) : accounts[0];  if (!account) refuse(404, "not_connected", asked ? `${asked} is not connected` : "no Google account is connected");  const token = await refreshTokenOf(host, account);  if (token && !(await revoke(host.env, token))) refuse(502, "google_unreachable", "Google did not take the revocation; nothing was forgotten. Try again.");  const removed = host.write((engine, version, outcome) => {    const row = host.store.get(SECRET, account.secret);    if (row) engine.delete(row, version, outcome);    writeAccounts(host.store, readAccounts(host.store).filter((a) => a.email !== account.email));    // Every event pulled from it leaves: a series with its occurrences, each counted once.    const pulled = engine.store.select("event", [equalSql("account", account.email), { sql: "json_extract(data, '$.gcal_id') IS NOT NULL", args: [] }], "created_at, id", 1_000_000);    const gone = new Set<string>();    for (const held of pulled) {      if (gone.has(held.id)) continue;      for (const occurrence of engine.store.select("event", [equalSql("series_id", held.id)], "created_at, id", 10_000)) {        if (!gone.has(occurrence.id)) engine.delete(occurrence, version, outcome);        gone.add(occurrence.id);      }      engine.delete(held, version, outcome);      gone.add(held.id);    }    return pulled.length;  });  host.sql.exec("CREATE TABLE IF NOT EXISTS google_seen (account TEXT NOT NULL, gcal_id TEXT NOT NULL, PRIMARY KEY (account, gcal_id))");  host.sql.exec("DELETE FROM google_seen WHERE account = ?", account.email);  return { ok: true, account: account.email, removed };}/** * Every grant this object holds revoked at Google, for an account being * deleted (src/account_delete.ts): how many were held and how many Google no * longer honours. Nothing is forgotten here: the deletion takes the whole * storage afterwards. */export async function revokeAll(host: GoogleHost): Promise<{ held: number; revoked: number }> {  const accounts = readAccounts(host.store);  let revoked = 0;  for (const account of accounts) {    const token = await refreshTokenOf(host, account);    if (!token || (await revoke(host.env, token))) revoked += 1;  }  return { held: accounts.length, revoked };}