Cotton code
533 lines · 32.5 KB · TypeScriptRaw
/** * THE FAKE GOOGLE (coordinator, 24 Nov 2026: "a dev-only fake Google that behaves as Google does for * calendar.events.owned"). Google's OAuth 2.0 for a web client and the Calendar API v3's primary calendar, as Google * documents them, so the Worker's Google code (src/google.ts, google_calendar.ts, google_write.ts) runs end to end on * dev before the real OAuth client exists. The Worker reaches it through GOOGLE_BASE, honoured on the dev and test * Workers alone (src/google.ts `googleUrls`); the paths are Google's own, under that base: * *   GET  /o/oauth2/v2/auth             the consent page: an unknown client or a redirect not registered is Google's *                                      error page (no redirect); each scope can be unticked (granular consent); *                                      Cancel brings back `error=access_denied` *   POST /token                        authorization_code (one use, ten minutes, the same redirect, the client's *                                      secret; a refresh token only with access_type=offline and prompt=consent or a *                                      first grant; an ID token for openid) and refresh_token (invalid_grant once *                                      revoked) *   POST /revoke                       a refresh token, or an access token and with it its refresh token *   GET  /calendar/v3/calendars/primary/events      pages (maxResults, pageToken), a window (timeMin, timeMax), a *                                      sync token (changes since, cancelled ones included; with any restriction 400; *                                      once expired 410 fullSyncRequired), nextSyncToken on the last page *   POST|GET|PATCH|DELETE …/events[/id] insert (the id given, base32hex, 409 if used), get (a deleted one answers *                                      cancelled), patch (If-Match, else 412; a deleted one 410), delete (204, then *                                      410); an occurrence `<id>_<yyyymmddThhmmssZ>` becomes an exception *   every Calendar call: 401 for an unknown, expired or revoked access token; 403 insufficientPermissions for a *                                      grant without the scope (a read-only grant cannot write); the account's rate *                                      limit when one is set (403 or 429 rateLimitExceeded) * * And, for a proof, what a person does in Google Calendar itself, outside Google's API (`/fake/admin/*`, with the * fake's admin token): make, change and delete events, read every event and write, expire the sync tokens or the * access tokens, set a rate limit, reset. Every account, event and token here is invented. */export const CALENDAR_SCOPES = {  owned: "https://www.googleapis.com/auth/calendar.events.owned",  events: "https://www.googleapis.com/auth/calendar.events",  readonly: "https://www.googleapis.com/auth/calendar.events.readonly",} as const;const EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";const WRITES = new Set<string>([CALENDAR_SCOPES.owned, CALENDAR_SCOPES.events]);const READS = new Set<string>([...WRITES, CALENDAR_SCOPES.readonly]);const KNOWN = new Set<string>(["openid", "email", EMAIL_SCOPE, ...READS]);const CODE_MS = 10 * 60_000;const ACCESS_MS = 3_600_000;const ID_FORM = /^[a-v0-9]{5,1024}$/;export interface Client {  secret: string;  redirects: string[];}interface Code {  client: string;  redirect: string;  email: string;  scopes: string[];  offline: boolean;  exp: number;  used: boolean;}interface Grant {  client: string;  email: string;  scopes: string[];  revoked: boolean;}interface Access {  refresh: string | null;  client: string;  email: string;  scopes: string[];  exp: number;  revoked: boolean;}export type Event = Record<string, unknown> & { id: string; status: string; etag: string; updated: string; _seq: number };interface User {  tz: string;  seq: number;  events: Record<string, Event>;  /** Sync tokens made before this seq are expired (410). */  syncFloor: number;  /** Calendar requests allowed a minute (0: every one refused), and how the limit is said; no limit when negative. */  rate: { perMinute: number; status: 403 | 429; window: number; count: number };  writes: { at: string; method: string; id: string; sendUpdates: string | null }[];  /** Each listing asked, by kind: what a proof reads to see a sync token used, a 410 met and a whole window read again. */  lists: { at: string; kind: "window" | "sync" | "page"; status: number }[];}export interface State {  codes: Record<string, Code>;  grants: Record<string, Grant>;  access: Record<string, Access>;  users: Record<string, User>;  consented: string[];}export const empty = (): State => ({ codes: {}, grants: {}, access: {}, users: {}, consented: [] });const json = (status: number, body: unknown, headers: Record<string, string> = {}) => new Response(status === 204 ? null : JSON.stringify(body), { status, headers: status === 204 ? headers : { "content-type": "application/json; charset=UTF-8", ...headers } });/** Google's error body for the Calendar API. */const apiError = (code: number, reason: string, message: string, status: string) => json(code, { error: { code, message, errors: [{ domain: code === 403 && reason.startsWith("rate") ? "usageLimits" : "global", reason, message }], status } });const oauthError = (status: number, error: string, description: string) => json(status, { error, error_description: description });const page = (title: string, body: string, status = 200) =>  new Response(`<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font-family:sans-serif;max-width:32em;margin:2em auto">${body}</body>`, { status, headers: { "content-type": "text/html; charset=utf-8" } });const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);const b64url = (s: string) => btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");const fromB64url = (s: string) => atob(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (s.length % 4)) % 4));export class FakeGoogle {  readonly state: State;  private readonly clients: Record<string, Client>;  private readonly now: () => number;  private readonly token: () => string;  private readonly adminToken: string | null;  constructor(state: State, clients: Record<string, Client>, now: () => number, token: () => string, adminToken: string | null) {    this.state = state;    this.clients = clients;    this.now = now;    this.token = token;    this.adminToken = adminToken;  }  private iso(at = this.now()): string {    return new Date(at).toISOString().replace(/\.\d{3}Z$/, ".000Z");  }  private user(email: string): User {    const key = email.toLowerCase();    return (this.state.users[key] ??= { tz: "Asia/Kolkata", seq: 0, events: {}, syncFloor: 0, rate: { perMinute: -1, status: 403, window: 0, count: 0 }, writes: [], lists: [] });  }  async handle(request: Request): Promise<Response> {    const url = new URL(request.url);    const p = url.pathname;    if (p === "/o/oauth2/v2/auth" && request.method === "GET") return this.consentPage(url);    if (p === "/o/oauth2/v2/auth/consent" && request.method === "POST") return this.consented(await request.formData());    if (p === "/token" && request.method === "POST") return this.tokenEndpoint(await request.formData());    if (p === "/revoke" && request.method === "POST") return this.revoke(url, request);    if (p.startsWith("/calendar/v3/")) return this.calendar(request, url);    if (p.startsWith("/fake/admin/")) return this.admin(request, url);    return apiError(404, "notFound", "Not Found", "NOT_FOUND");  }  // ── OAuth ──────────────────────────────────────────────────────────  private consentPage(url: URL): Response {    const q = url.searchParams;    const clientId = q.get("client_id") ?? "";    const client = this.clients[clientId];    // Google shows its own error page and never redirects to a redirect it cannot trust.    if (!client) return page("Error 401: invalid_client", `<h1>Access blocked: authorization error</h1><p>The OAuth client was not found.</p><p>Error 401: invalid_client</p>`, 401);    const redirect = q.get("redirect_uri") ?? "";    if (!client.redirects.includes(redirect)) return page("Error 400: redirect_uri_mismatch", `<h1>Access blocked: this app's request is invalid</h1><p>Error 400: redirect_uri_mismatch</p>`, 400);    const state = q.get("state") ?? "";    const back = (params: Record<string, string>) => {      const to = new URL(redirect);      for (const [k, v] of Object.entries(params)) to.searchParams.set(k, v);      if (state) to.searchParams.set("state", state);      return new Response(null, { status: 302, headers: { location: to.toString() } });    };    if (q.get("response_type") !== "code") return back({ error: "unsupported_response_type" });    const scopes = (q.get("scope") ?? "").split(" ").filter(Boolean);    if (!scopes.length || scopes.some((s) => !KNOWN.has(s))) return back({ error: "invalid_scope" });    const hidden = (name: string, value: string) => `<input type="hidden" name="${name}" value="${esc(value)}">`;    const choices = scopes      .filter((s) => s !== "openid")      .map((s) => `<p><label><input type="checkbox" name="grant" value="${esc(s)}" checked> ${esc(s === "email" || s === EMAIL_SCOPE ? "See your primary Google Account email address" : s === CALENDAR_SCOPES.owned ? "See, create, change, and delete events on Google calendars you own" : s === CALENDAR_SCOPES.events ? "View and edit events on all your calendars" : "View events on all your calendars")}</label></p>`)      .join("");    return page(      "Sign in - Google Accounts",      `<h1>Choose what Cotton (fake Google) can access</h1><form method="post" action="/o/oauth2/v2/auth/consent">${hidden("client_id", clientId)}${hidden("redirect_uri", redirect)}${hidden("state", state)}${hidden("scope", scopes.join(" "))}${hidden("access_type", q.get("access_type") ?? "online")}${hidden("prompt", q.get("prompt") ?? "")}<p><label>Account <input name="email" value="invented.person@example.test"></label></p>${choices}<button name="answer" value="allow">Continue</button> <button name="answer" value="cancel">Cancel</button></form>`,    );  }  private consented(form: FormData): Response {    const clientId = String(form.get("client_id") ?? "");    const client = this.clients[clientId];    const redirect = String(form.get("redirect_uri") ?? "");    if (!client || !client.redirects.includes(redirect)) return page("Error 400: invalid_request", "<p>Error 400: invalid_request</p>", 400);    const to = new URL(redirect);    const state = String(form.get("state") ?? "");    if (state) to.searchParams.set("state", state);    if (form.get("answer") !== "allow") {      to.searchParams.set("error", "access_denied");      return new Response(null, { status: 302, headers: { location: to.toString() } });    }    const asked = String(form.get("scope") ?? "").split(" ").filter(Boolean);    const ticked = new Set(form.getAll("grant").map(String));    // What Google answers is the scopes' full names: `email` comes back as userinfo.email.    const granted = [...new Set(asked.filter((s) => s === "openid" || ticked.has(s)).map((s) => (s === "email" ? EMAIL_SCOPE : s)))];    const email = String(form.get("email") ?? "").trim().toLowerCase() || "invented.person@example.test";    const first = !this.state.consented.includes(`${clientId} ${email}`);    if (first) this.state.consented.push(`${clientId} ${email}`);    const code = `4/0A${this.token()}`;    this.state.codes[code] = { client: clientId, redirect, email, scopes: granted, offline: form.get("access_type") === "offline" && (first || form.get("prompt") === "consent"), exp: this.now() + CODE_MS, used: false };    to.searchParams.set("code", code);    to.searchParams.set("scope", granted.join(" "));    return new Response(null, { status: 302, headers: { location: to.toString() } });  }  private idToken(client: string, email: string): string {    const iat = Math.floor(this.now() / 1000);    return `${b64url(JSON.stringify({ alg: "RS256", kid: "fake", typ: "JWT" }))}.${b64url(JSON.stringify({ iss: "https://accounts.google.com", azp: client, aud: client, sub: String(Math.abs([...email].reduce((a, c) => (a * 31 + c.charCodeAt(0)) | 0, 7))), email, email_verified: true, iat, exp: iat + 3600 }))}.fake-signature`;  }  private mintAccess(refresh: string | null, g: { client: string; email: string; scopes: string[] }): string {    const token = `ya29.${this.token()}`;    this.state.access[token] = { refresh, client: g.client, email: g.email, scopes: g.scopes, exp: this.now() + ACCESS_MS, revoked: false };    return token;  }  private tokenEndpoint(form: FormData): Response {    const clientId = String(form.get("client_id") ?? "");    const client = this.clients[clientId];    if (!client || client.secret !== String(form.get("client_secret") ?? "")) return oauthError(401, "invalid_client", "Unauthorized");    const grantType = String(form.get("grant_type") ?? "");    if (grantType === "authorization_code") {      const code = this.state.codes[String(form.get("code") ?? "")];      if (!code || code.client !== clientId || code.used || code.exp < this.now()) return oauthError(400, "invalid_grant", "Bad Request");      if (String(form.get("redirect_uri") ?? "") !== code.redirect) return oauthError(400, "redirect_uri_mismatch", "Bad Request");      code.used = true;      let refresh: string | null = null;      if (code.offline) {        refresh = `1//0g${this.token()}`;        this.state.grants[refresh] = { client: clientId, email: code.email, scopes: code.scopes, revoked: false };      }      const access = this.mintAccess(refresh, code);      return json(200, { access_token: access, expires_in: 3599, ...(refresh ? { refresh_token: refresh } : {}), scope: code.scopes.join(" "), token_type: "Bearer", ...(code.scopes.includes("openid") ? { id_token: this.idToken(clientId, code.email) } : {}) });    }    if (grantType === "refresh_token") {      const refresh = String(form.get("refresh_token") ?? "");      const grant = this.state.grants[refresh];      if (!grant || grant.revoked || grant.client !== clientId) return oauthError(400, "invalid_grant", "Token has been expired or revoked.");      const access = this.mintAccess(refresh, grant);      return json(200, { access_token: access, expires_in: 3599, scope: grant.scopes.join(" "), token_type: "Bearer", ...(grant.scopes.includes("openid") ? { id_token: this.idToken(clientId, grant.email) } : {}) });    }    return oauthError(400, "unsupported_grant_type", "Invalid grant_type: " + grantType);  }  private async revoke(url: URL, request: Request): Promise<Response> {    const body = request.headers.get("content-type")?.includes("application/x-www-form-urlencoded") ? new URLSearchParams(await request.text()) : new URLSearchParams();    const token = body.get("token") ?? url.searchParams.get("token") ?? "";    const grant = this.state.grants[token];    const access = this.state.access[token];    if ((!grant || grant.revoked) && (!access || access.revoked)) return oauthError(400, "invalid_token", "Token expired or revoked");    // Revoking an access token revokes the grant it came from too, as Google does.    const refresh = grant ? token : access?.refresh ?? null;    if (refresh && this.state.grants[refresh]) this.state.grants[refresh]!.revoked = true;    for (const a of Object.values(this.state.access)) if (a === access || (refresh && a.refresh === refresh)) a.revoked = true;    return json(200, {});  }  // ── Calendar ───────────────────────────────────────────────────────  private authorize(request: Request, write: boolean): { email: string } | Response {    const bearer = /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ?? "";    const a = this.state.access[bearer];    if (!a || a.revoked || a.exp < this.now()) return apiError(401, "authError", "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential.", "UNAUTHENTICATED");    if (!a.scopes.some((s) => (write ? WRITES : READS).has(s))) return apiError(403, "insufficientPermissions", "Request had insufficient authentication scopes.", "PERMISSION_DENIED");    const u = this.user(a.email);    if (u.rate.perMinute >= 0) {      const minute = Math.floor(this.now() / 60_000);      if (u.rate.window !== minute) u.rate = { ...u.rate, window: minute, count: 0 };      u.rate.count++;      if (u.rate.count > u.rate.perMinute) return u.rate.status === 429 ? apiError(429, "rateLimitExceeded", "Rate Limit Exceeded", "RESOURCE_EXHAUSTED") : apiError(403, "rateLimitExceeded", "Rate Limit Exceeded", "PERMISSION_DENIED");    }    return { email: a.email };  }  private async calendar(request: Request, url: URL): Promise<Response> {    const m = /^\/calendar\/v3\/calendars\/([^/]+)(?:\/events(?:\/([^/]+))?)?$/.exec(url.pathname);    if (!m) return apiError(404, "notFound", "Not Found", "NOT_FOUND");    const write = !["GET", "HEAD"].includes(request.method);    const who = this.authorize(request, write);    if (who instanceof Response) return who;    // Only the calendars the person owns: their primary, by its name or their address.    const calendar = decodeURIComponent(m[1]!);    if (calendar !== "primary" && calendar.toLowerCase() !== who.email) return apiError(404, "notFound", "Not Found", "NOT_FOUND");    const u = this.user(who.email);    if (url.pathname.endsWith(`/calendars/${m[1]}`) && request.method === "GET") return json(200, { kind: "calendar#calendar", id: who.email, summary: who.email, timeZone: u.tz });    const id = m[2] ? decodeURIComponent(m[2]) : null;    const sendUpdates = url.searchParams.get("sendUpdates");    if (sendUpdates !== null && !["all", "externalOnly", "none"].includes(sendUpdates)) return apiError(400, "invalid", "Invalid sendUpdates value.", "INVALID_ARGUMENT");    if (!id && request.method === "GET") {      const answer = this.list(u, url);      (u.lists ??= []).push({ at: this.iso(), kind: url.searchParams.has("pageToken") ? "page" : url.searchParams.has("syncToken") ? "sync" : "window", status: answer.status });      return answer;    }    if (!id && request.method === "POST") return this.insert(u, who.email, (await request.json().catch(() => null)) as Record<string, unknown> | null, sendUpdates);    if (id && request.method === "GET") return this.get(u, id);    if (id && (request.method === "PATCH" || request.method === "PUT")) return this.patch(u, id, request.headers.get("if-match"), (await request.json().catch(() => null)) as Record<string, unknown> | null, sendUpdates, request.method === "PUT");    if (id && request.method === "DELETE") return this.remove(u, id, request.headers.get("if-match"), sendUpdates);    return apiError(405, "methodNotAllowed", "Method Not Allowed", "METHOD_NOT_ALLOWED");  }  private visible(e: Event): Record<string, unknown> {    return Object.fromEntries(Object.entries(e).filter(([k]) => !k.startsWith("_")));  }  private stamp(u: User, e: Event): Event {    u.seq++;    e._seq = u.seq;    e.etag = `"${3_400_000_000_000_000 + u.seq}"`;    e.updated = this.iso();    return e;  }  private list(u: User, url: URL): Response {    const q = url.searchParams;    const max = Math.min(Math.max(Number(q.get("maxResults") ?? 250) || 250, 1), 2500);    let cursor: { o: number; s: number | null; from: string | null; to: string | null; at: number; deleted: boolean };    const pageToken = q.get("pageToken");    if (pageToken) {      try {        cursor = JSON.parse(fromB64url(pageToken)) as typeof cursor;      } catch {        return apiError(400, "invalid", "Invalid page token value.", "INVALID_ARGUMENT");      }    } else {      const sync = q.get("syncToken");      if (sync !== null) {        if (["timeMin", "timeMax", "updatedMin", "orderBy", "q", "iCalUID", "privateExtendedProperty", "sharedExtendedProperty"].some((k) => q.has(k))) return apiError(400, "invalid", "Sync token cannot be used with other request restrictions.", "INVALID_ARGUMENT");        let seq: number;        try {          seq = (JSON.parse(fromB64url(sync)) as { s: number }).s;        } catch {          return apiError(400, "invalid", "Invalid sync token value.", "INVALID_ARGUMENT");        }        if (seq < u.syncFloor) return apiError(410, "fullSyncRequired", "Sync token is no longer valid, a full sync is required.", "GONE");        cursor = { o: 0, s: seq, from: null, to: null, at: u.seq, deleted: true };      } else {        cursor = { o: 0, s: null, from: q.get("timeMin"), to: q.get("timeMax"), at: u.seq, deleted: q.get("showDeleted") === "true" };      }    }    const at = (v: unknown): number => {      const t = v as { dateTime?: string; date?: string } | undefined;      return t?.dateTime ? Date.parse(t.dateTime) : t?.date ? Date.parse(`${t.date}T00:00:00Z`) : NaN;    };    const all = Object.values(u.events)      .filter((e) => e._seq <= cursor.at)      .filter((e) => (cursor.s !== null ? e._seq > cursor.s : cursor.deleted || e.status !== "cancelled"))      .filter((e) => {        if (cursor.s !== null) return true;        // A window holds what overlaps it; a series is held if it began before the window ends.        const start = at(e.start);        const end = e.recurrence ? Infinity : at(e.end);        return (!cursor.to || start < Date.parse(cursor.to)) && (!cursor.from || end > Date.parse(cursor.from));      })      .sort((a, b) => a._seq - b._seq);    const items = all.slice(cursor.o, cursor.o + max).map((e) => this.visible(e));    const more = cursor.o + max < all.length;    return json(200, {      kind: "calendar#events",      etag: `"p${u.seq}"`,      summary: "primary",      updated: this.iso(),      timeZone: u.tz,      accessRole: "owner",      defaultReminders: [{ method: "popup", minutes: 30 }],      items,      ...(more ? { nextPageToken: b64url(JSON.stringify({ ...cursor, o: cursor.o + max })) } : { nextSyncToken: b64url(JSON.stringify({ s: cursor.at, n: this.token().slice(0, 6) })) }),    });  }  private checkTimes(body: Record<string, unknown>): Response | null {    const t = (v: unknown) => v as { dateTime?: string; date?: string } | undefined;    const start = t(body.start);    const end = t(body.end);    if (!start || (!start.dateTime && !start.date)) return apiError(400, "required", "Missing start time.", "INVALID_ARGUMENT");    if (!end || (!end.dateTime && !end.date)) return apiError(400, "required", "Missing end time.", "INVALID_ARGUMENT");    const s = start.dateTime ? Date.parse(start.dateTime) : Date.parse(`${start.date}T00:00:00Z`);    const e = end.dateTime ? Date.parse(end.dateTime) : Date.parse(`${end.date}T00:00:00Z`);    if (Number.isNaN(s) || Number.isNaN(e)) return apiError(400, "invalid", "Invalid start or end time.", "INVALID_ARGUMENT");    if (e < s || (start.date && e === s)) return apiError(400, "timeRangeEmpty", "The specified time range is empty.", "INVALID_ARGUMENT");    return null;  }  private insert(u: User, email: string, body: Record<string, unknown> | null, sendUpdates: string | null): Response {    if (!body) return apiError(400, "parseError", "Parse Error", "INVALID_ARGUMENT");    const bad = this.checkTimes(body);    if (bad) return bad;    let id = typeof body.id === "string" ? body.id : null;    if (id !== null && !ID_FORM.test(id)) return apiError(400, "invalid", "Invalid resource id value.", "INVALID_ARGUMENT");    // An id once used stays used, a deleted event's too.    if (id !== null && u.events[id]) return apiError(409, "duplicate", "The requested identifier already exists.", "ALREADY_EXISTS");    id ??= [...this.token().toLowerCase().replace(/[^a-v0-9]/g, "")].slice(0, 26).join("").padEnd(26, "0");    const event = this.stamp(u, {      ...body,      kind: "calendar#event",      id,      status: "confirmed",      htmlLink: `https://www.google.com/calendar/event?eid=${b64url(`${id} ${email}`)}`,      created: this.iso(),      iCalUID: `${id}@google.com`,      sequence: 0,      creator: { email, self: true },      organizer: { email, self: true },      reminders: body.reminders ?? { useDefault: true },      eventType: "default",      etag: "",      updated: "",      _seq: 0,    } as Event);    if (Array.isArray(event.attendees)) event.attendees = (event.attendees as Record<string, unknown>[]).map((a) => ({ responseStatus: "needsAction", ...a }));    u.events[id] = event;    u.writes.push({ at: this.iso(), method: "insert", id, sendUpdates });    return json(200, this.visible(event));  }  /** An occurrence of a series (`<id>_<yyyymmddThhmmssZ>`, or `_<yyyymmdd>` all day) not yet an exception: made one. */  private occurrence(u: User, id: string): Event | null {    const m = /^([a-v0-9]{5,1024})_(\d{8})(?:T(\d{6})Z)?$/.exec(id);    const series = m ? u.events[m[1]!] : undefined;    if (!m || !series || !series.recurrence || series.status === "cancelled") return null;    const day = `${m[2]!.slice(0, 4)}-${m[2]!.slice(4, 6)}-${m[2]!.slice(6, 8)}`;    const original = m[3] ? { dateTime: `${day}T${m[3].slice(0, 2)}:${m[3].slice(2, 4)}:${m[3].slice(4, 6)}Z` } : { date: day };    const length = Date.parse(String((series.end as { dateTime?: string }).dateTime ?? `${(series.end as { date: string }).date}T00:00:00Z`)) - Date.parse(String((series.start as { dateTime?: string }).dateTime ?? `${(series.start as { date: string }).date}T00:00:00Z`));    const start = original.dateTime ? { dateTime: original.dateTime } : { date: day };    const end = original.dateTime ? { dateTime: new Date(Date.parse(original.dateTime) + length).toISOString().replace(/\.\d{3}Z$/, "Z") } : { date: new Date(Date.parse(`${day}T00:00:00Z`) + Math.max(length, 86_400_000)).toISOString().slice(0, 10) };    const { recurrence: _r, ...rest } = series;    return { ...rest, id, recurringEventId: series.id, originalStartTime: original, start, end, iCalUID: series.iCalUID, etag: "", updated: "", _seq: 0, status: "confirmed" } as Event;  }  private get(u: User, id: string): Response {    const e = u.events[id] ?? this.occurrence(u, id);    if (!e) return apiError(404, "notFound", "Not Found", "NOT_FOUND");    return json(200, this.visible(e._seq ? e : this.stamp(u, e)));  }  private patch(u: User, id: string, ifMatch: string | null, body: Record<string, unknown> | null, sendUpdates: string | null, replace: boolean): Response {    if (!body) return apiError(400, "parseError", "Parse Error", "INVALID_ARGUMENT");    let e = u.events[id];    if (!e) {      const made = this.occurrence(u, id);      if (!made) return apiError(404, "notFound", "Not Found", "NOT_FOUND");      e = u.events[id] = this.stamp(u, made);    }    if (e.status === "cancelled") return apiError(410, "deleted", "Resource has been deleted", "GONE");    if (ifMatch && ifMatch !== e.etag) return apiError(412, "conditionNotMet", "Precondition Failed", "FAILED_PRECONDITION");    const merged: Record<string, unknown> = replace ? { ...Object.fromEntries(Object.entries(e).filter(([k]) => ["kind", "id", "status", "htmlLink", "created", "iCalUID", "sequence", "creator", "organizer", "recurringEventId", "originalStartTime", "_seq", "etag", "updated"].includes(k))) } : { ...e };    for (const [k, v] of Object.entries(body)) {      if (["id", "etag", "kind", "created", "updated", "creator", "organizer", "iCalUID", "htmlLink"].includes(k)) continue;      if (v === null) delete merged[k];      else merged[k] = v;    }    const bad = this.checkTimes(merged);    if (bad) return bad;    // A guest's answer is kept by their address across a patch that lists them again.    if (Array.isArray(body.attendees)) {      const before = new Map(((e.attendees as Record<string, unknown>[] | undefined) ?? []).map((a) => [String(a.email).toLowerCase(), a.responseStatus]));      merged.attendees = (body.attendees as Record<string, unknown>[]).map((a) => ({ ...a, responseStatus: a.responseStatus ?? before.get(String(a.email).toLowerCase()) ?? "needsAction" }));    }    if (JSON.stringify(merged.start) !== JSON.stringify(e.start) || JSON.stringify(merged.end) !== JSON.stringify(e.end)) merged.sequence = Number(e.sequence ?? 0) + 1;    u.events[id] = this.stamp(u, merged as Event);    u.writes.push({ at: this.iso(), method: replace ? "update" : "patch", id, sendUpdates });    return json(200, this.visible(u.events[id]!));  }  private remove(u: User, id: string, ifMatch: string | null, sendUpdates: string | null): Response {    let e = u.events[id];    if (!e) {      const made = this.occurrence(u, id);      if (!made) return apiError(404, "notFound", "Not Found", "NOT_FOUND");      e = u.events[id] = made;    }    if (e.status === "cancelled") return apiError(410, "deleted", "Resource has been deleted", "GONE");    if (ifMatch && e._seq && ifMatch !== e.etag) return apiError(412, "conditionNotMet", "Precondition Failed", "FAILED_PRECONDITION");    e.status = "cancelled";    this.stamp(u, e);    // A cancelled series takes its exceptions with it.    if (e.recurrence) for (const x of Object.values(u.events)) if (x.recurringEventId === id && x.status !== "cancelled") this.stamp(u, Object.assign(x, { status: "cancelled" }));    u.writes.push({ at: this.iso(), method: "delete", id, sendUpdates });    return json(204, null);  }  // ── what a person does in Google Calendar itself, and the proof's knobs ──  private async admin(request: Request, url: URL): Promise<Response> {    if (!this.adminToken || request.headers.get("authorization") !== `Bearer ${this.adminToken}`) return json(403, { error: "the fake's admin token only" });    const body = request.method === "POST" ? ((await request.json().catch(() => ({}))) as Record<string, unknown>) : {};    const email = String(body.email ?? url.searchParams.get("email") ?? "").toLowerCase();    const u = email ? this.user(email) : null;    switch (url.pathname) {      case "/fake/admin/reset":        Object.assign(this.state, empty());        return json(200, { reset: true });      case "/fake/admin/events":        if (request.method === "GET") return json(200, { events: Object.values(u!.events).map((e) => this.visible(e)), writes: u!.writes, lists: u!.lists ?? [], seq: u!.seq });        {          // An event made or changed in Google Calendar on the web: inserted, or merged into the one it names.          const event = (body.event ?? {}) as Record<string, unknown>;          const id = typeof event.id === "string" ? event.id : null;          const held = id ? u!.events[id] : undefined;          if (held) {            u!.events[id!] = this.stamp(u!, { ...held, ...event, status: String(event.status ?? held.status) } as Event);            return json(200, this.visible(u!.events[id!]!));          }          const made = await this.insert(u!, email, event, null).json();          u!.writes.pop();          return json(200, made);        }      case "/fake/admin/events/delete": {        const e = u!.events[String(body.id ?? "")];        if (!e) return json(404, { error: "no such event" });        e.status = "cancelled";        this.stamp(u!, e);        return json(200, { deleted: e.id });      }      case "/fake/admin/expire-sync":        u!.syncFloor = u!.seq + 1;        return json(200, { expired: true });      case "/fake/admin/expire-access":        for (const a of Object.values(this.state.access)) if (a.email === email) a.exp = 0;        return json(200, { expired: true });      case "/fake/admin/rate":        u!.rate = { perMinute: body.per_minute === null || body.per_minute === undefined ? -1 : Number(body.per_minute), status: body.status === 429 ? 429 : 403, window: 0, count: 0 };        return json(200, { rate: u!.rate });      case "/fake/admin/revoke-all": {        // What "Remove access" at myaccount.google.com does: every grant of this account to every client, and their access tokens.        let revoked = 0;        for (const g of Object.values(this.state.grants)) {          if (g.email !== email || g.revoked) continue;          g.revoked = true;          revoked++;        }        for (const a of Object.values(this.state.access)) if (a.email === email) a.revoked = true;        return json(200, { revoked });      }      case "/fake/admin/grants":        return json(200, { live: Object.values(this.state.grants).filter((g) => g.email === email && !g.revoked).length, revoked: Object.values(this.state.grants).filter((g) => g.email === email && g.revoked).length });      case "/fake/admin/timezone":        u!.tz = String(body.tz ?? u!.tz);        return json(200, { tz: u!.tz });    }    return json(404, { error: "no such admin route" });  }}