294 lines · 17.0 KB · TypeScriptRaw
/** * A fake Google for the Calendar tests: the token, revoke and Calendar * endpoints answered by route, every call kept. The client, the codes and the * tokens are made up; no call leaves the test. * * FakeCalendar is a FAKE of Google Calendar's events API (v3), modelled on * Google's documented behaviour, not a recording of it: every change gives * the event a new etag (an attendee's answer too); a write with an If-Match * that is not the event's etag is answered 412; an insert takes the id it is * given (base32hex) and an id already used is answered 409; one occurrence of * a series is `<id>_<yyyymmddThhmmssZ>` (all-day `<id>_<yyyymmdd>`), and * patching or deleting it makes an exception with `recurringEventId` and * `originalStartTime`; `sendUpdates` is recorded on each write; guests carry * `responseStatus` ("needsAction" until they answer), kept by email across a * patch that lists them again; a deleted event is `cancelled`, answered by * events.get, and a later patch or delete of it is 410; a sync-token listing * reports cancelled events and occurrences; a dateTime without an offset is * read in its `timeZone` and answered with that zone's offset. */import { SELF } from "cloudflare:test";import { expect, vi } from "vitest";import { joinMoment } from "../src/mcp/tools/records/zone.ts";import { DATABASE_ID } from "./personal.ts";export interface Call { url: URL; method: string; authorization: string | null; form: Record<string, string>; headers: Headers; /** A JSON body, as sent. */ json: Record<string, unknown> | null;}export type Route = (call: Call) => Response | Promise<Response> | null;export const reply = (status: number, body: unknown): Response => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });/** Google, answering each call with the first route that answers it; a call no route answers fails the test. */export function google(...routes: Route[]): Call[] { const calls: Call[] = []; vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { const request = new Request(input as RequestInfo, init); const type = request.headers.get("content-type") ?? ""; const call: Call = { url: new URL(request.url), method: request.method, authorization: request.headers.get("authorization"), form: type.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries([...(await request.formData())].map(([k, v]) => [k, String(v)])) : {}, headers: request.headers, json: type.startsWith("application/json") ? ((await request.json()) as Record<string, unknown>) : null, }; calls.push(call); for (const route of routes) { const answer = await route(call); if (answer) return answer; } throw new Error(`Google was called where the test expects no call: ${call.method} ${call.url.toString()}`); }); return calls;}export const REFRESH = "1//test-refresh-token-abcd";export const ACCESS = "ya29.test-access-token";export const EMAIL = "owner@example.com";/** What Google grants when the person leaves both ticked: the address and the events of the calendars they own, read and written. */export const GRANTED = "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/calendar.events.owned";/** What Google granted from 22 to 24 Nov 2026, before the scope was narrowed: every calendar's events, read and written. */export const GRANTED_WIDE = "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/calendar.events";/** What Google granted before Days wrote: the address and the calendar's events, read only. */export const GRANTED_READONLY = "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/calendar.events.readonly";/** The token endpoint as for a grant made with `scope`: trading a code and refreshing. */export function tokensWith(scope: string): Route { return (call) => { if (call.url.href !== "https://oauth2.googleapis.com/token") return null; if (call.form.grant_type === "authorization_code") return reply(200, { access_token: ACCESS, refresh_token: REFRESH, expires_in: 3599, scope, token_type: "Bearer", id_token: idToken({ email: "Owner@Example.com", email_verified: true }) }); if (call.form.grant_type === "refresh_token") return reply(200, { access_token: ACCESS, expires_in: 3599, scope, token_type: "Bearer" }); return null; };}/** An ID token as Google's token endpoint answers it (header, claims, a signature nobody checks here). */export function idToken(claims: Record<string, unknown>): string { const part = (o: unknown) => btoa(JSON.stringify(o)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); return `${part({ alg: "RS256", typ: "JWT" })}.${part({ iss: "https://accounts.google.com", aud: "test-client.apps.googleusercontent.com", sub: "1234567890", ...claims })}.signature`;}/** The token endpoint trading a code, and refreshing, as Google does for a grant with the address and the calendar's events. */export const tokens: Route = (call) => { if (call.url.href !== "https://oauth2.googleapis.com/token") return null; if (call.form.grant_type === "authorization_code") return reply(200, { access_token: ACCESS, refresh_token: REFRESH, expires_in: 3599, scope: GRANTED, token_type: "Bearer", id_token: idToken({ email: "Owner@Example.com", email_verified: true }) }); if (call.form.grant_type === "refresh_token") return reply(200, { access_token: ACCESS, expires_in: 3599, scope: GRANTED, token_type: "Bearer" }); return null;};/** The primary calendar: its id is the account's address. */export const primary: Route = (call) => (call.url.pathname === "/calendar/v3/calendars/primary" ? reply(200, { id: "Owner@Example.com", summary: "Owner", timeZone: "Asia/Kolkata" }) : null);export const revoked: Route = (call) => (call.url.href === "https://oauth2.googleapis.com/revoke" ? new Response(null, { status: 200 }) : null);/** A callback page as the person's browser goes through it: a "Connect …?" page is tapped through (src/connect_confirm.ts). */export async function page(url: string): Promise<{ status: number; text: string }> { const res = await SELF.fetch(url, { redirect: "manual" }); const text = await res.text(); if (!text.includes('<form method="post"')) return { status: res.status, text }; const form = new URLSearchParams([...text.matchAll(/<input type="hidden" name="(\w+)" value="([^"]*)">/g)].map((m) => [m[1]!, m[2]!.replace(/&/g, "&")])); const tapped = await SELF.fetch(url.split("?")[0]!, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: form.toString() }); return { status: tapped.status, text: await tapped.text() };}/** Connect as the owner: the consent page's state, then Google's answer brought back through `/b/<slug>`. */export async function connectAccount(slug: string, owner: string): Promise<{ status: number; text: string; state: string }> { const res = await SELF.fetch(`https://example.test/b/${slug}/v1/google/connect`, { headers: { authorization: `Bearer ${owner}` } }); expect(res.status).toBe(200); const { state } = (await res.json()) as { state: string }; expect(state.startsWith(`${DATABASE_ID}.`)).toBe(true); return { ...(await page(`https://example.test/b/${slug}/v1/google/callback?code=test-code&state=${encodeURIComponent(state)}`)), state };}/** * Google's calendar as a little store: each change takes the next version; * a whole listing answers the live events as they stand, `pageSize` to a * page; a sync token `v<N>` answers every change after N, cancelled ones * too. The object's own alarm may ask at any moment: every answer is the * calendar as it stands, so an extra pass changes nothing. */type GEvent = Record<string, unknown>;type Guest = { email: string; displayName?: string; responseStatus: string; self?: boolean; organizer?: boolean };/** A dateTime as Google answers it: with an offset; one given without is read in its zone. */function withOffset(dateTime: string, zone: string | undefined): string { if (/(Z|[+-]\d{2}:\d{2})$/.test(dateTime)) return dateTime; const [day, clock] = dateTime.split("T") as [string, string]; const utc = Date.parse(joinMoment(day, clock.slice(0, 5), zone ?? "UTC")) + Number(clock.slice(6, 8) || 0) * 1000; const minutes = Math.round((Date.parse(`${dateTime}Z`) - utc) / 60_000); const sign = minutes < 0 ? "-" : "+"; const abs = Math.abs(minutes); return `${day}T${clock.slice(0, 8).padEnd(8, ":00")}${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`;}function moment(m: unknown): unknown { const x = m as { dateTime?: string; timeZone?: string } | undefined; return x?.dateTime ? { ...x, dateTime: withOffset(x.dateTime, x.timeZone) } : m;}/** One write as Google got it: what, to which id, and whether it mailed the guests. */export interface Written { method: string; id: string; sendUpdates: string | null; ifMatch: string | null; status: number;}export class FakeCalendar { version = 0; pageSize = 2; readonly events = new Map<string, { event: Record<string, unknown>; version: number }>(); /** Sync tokens Google has forgotten: answered 410. */ readonly gone = new Set<string>(); readonly asked: URL[] = []; /** Every write Google was asked, in order. */ readonly written: Written[] = []; /** The calendar's owner: the organizer of what Days inserts. */ owner = EMAIL; /** False: the grant cannot write (403 insufficientPermissions); "down": Google answers 503. */ writable: boolean | "down" = true; put(event: Record<string, unknown>): void { this.version += 1; // Every change is a new etag, whatever the event carried before (Google's own rule). this.events.set(String(event.id), { event: { status: "confirmed", ...event, etag: `"${this.version}"` }, version: this.version }); } cancel(id: string): void { const held = this.events.get(id); this.put({ ...(held?.event ?? { id }), id, status: "cancelled", etag: undefined }); } /** Gone with no trace, as an event deleted long ago is from a whole listing. */ purge(id: string): void { this.events.delete(id); } /** A guest answers the invitation in their own calendar: the event's etag changes. */ answer(id: string, email: string, responseStatus: "accepted" | "tentative" | "declined"): void { const held = this.events.get(id)!.event; const attendees = (held.attendees as Guest[]).map((g) => (g.email === email ? { ...g, responseStatus } : g)); this.next({ ...held, attendees }); } private next(event: GEvent): GEvent { this.version += 1; const etag = `"${this.version}-${Math.random().toString(36).slice(2, 8)}"`; const e: GEvent = { ...event, etag, updated: new Date().toISOString() }; this.events.set(String(e.id), { event: e, version: this.version }); return e; } private guests(given: unknown, before: Guest[] = []): Guest[] { return ((given as { email: string; displayName?: string }[]) ?? []).map((g) => { const was = before.find((b) => b.email.toLowerCase() === g.email.toLowerCase()); return { email: g.email, ...(g.displayName ? { displayName: g.displayName } : {}), responseStatus: was?.responseStatus ?? (g.email === this.owner ? "accepted" : "needsAction"), ...(g.email === this.owner ? { self: true, organizer: true } : {}) }; }); } /** An occurrence id's series and instant, for a series this calendar holds. */ private occurrence(id: string): { master: GEvent; original: { dateTime?: string; date?: string }; start: unknown; end: unknown } | null { const m = /^(.+)_(\d{8})(?:T(\d{2})(\d{2})(\d{2})Z)?$/.exec(id); const master = m ? this.events.get(m[1]!)?.event : undefined; if (!m || !master || !master.recurrence) return null; const day = `${m[2]!.slice(0, 4)}-${m[2]!.slice(4, 6)}-${m[2]!.slice(6, 8)}`; if (!m[3]) return { master, original: { date: day }, start: { date: day }, end: { date: day } }; const at = Date.parse(`${day}T${m[3]}:${m[4]}:${m[5]}Z`); const ms = master.start as { dateTime: string; timeZone?: string }; const length = Date.parse((master.end as { dateTime: string }).dateTime) - Date.parse(ms.dateTime); const iso = (t: number) => new Date(t).toISOString().replace(".000", ""); return { master, original: { dateTime: iso(at) }, start: { dateTime: iso(at), timeZone: ms.timeZone }, end: { dateTime: iso(at + length), timeZone: ms.timeZone } }; } /** events.insert, patch, delete and get, as Google answers them. */ readonly writes: Route = (call) => { const path = call.url.pathname; if (!path.startsWith("/calendar/v3/calendars/primary/events")) return null; const one = /^\/calendar\/v3\/calendars\/primary\/events\/(.+)$/.exec(path); if (!one && call.method === "GET") return null; const id = one ? decodeURIComponent(one[1]!) : String(call.json?.id ?? ""); const ifMatch = call.headers.get("if-match"); const note = (status: number, body: unknown): Response => { if (call.method !== "GET") this.written.push({ method: call.method, id, sendUpdates: call.url.searchParams.get("sendUpdates"), ifMatch, status }); return status === 204 ? new Response(null, { status }) : reply(status, body); }; const error = (status: number, reason: string, message: string) => note(status, { error: { code: status, message, errors: [{ domain: "global", reason, message }] } }); if (this.writable === "down") return error(503, "backendError", "Backend Error"); if (call.method !== "GET" && !this.writable) return error(403, "insufficientPermissions", "Request had insufficient authentication scopes."); const held = this.events.get(id)?.event; if (call.method === "GET") return held ? reply(200, held) : this.occurrence(id) ? reply(200, { ...this.occurrence(id)!.master, id, recurrence: undefined, recurringEventId: this.occurrence(id)!.master.id }) : error(404, "notFound", "Not Found"); if (call.method === "POST") { if (id && this.events.has(id)) return error(409, "duplicate", "The requested identifier already exists."); const made = id || `fk${this.version + 1}${Math.random().toString(32).slice(2, 10)}`; const body = call.json!; const e = this.next({ kind: "calendar#event", ...body, id: made, status: "confirmed", iCalUID: `${made}@google.com`, organizer: { email: this.owner, self: true }, creator: { email: this.owner, self: true }, start: moment(body.start), end: moment(body.end), ...(body.attendees ? { attendees: this.guests(body.attendees) } : {}) }); return note(200, e); } const occ = held ? null : this.occurrence(id); if (!held && !occ) return error(404, "notFound", "Not Found"); if (held?.status === "cancelled") return error(410, "deleted", "Resource has been deleted"); const base: GEvent = held ?? { ...occ!.master, id, recurrence: undefined, recurringEventId: occ!.master.id, originalStartTime: occ!.original, start: occ!.start, end: occ!.end }; const current = held?.etag ?? occ!.master.etag; if (ifMatch && ifMatch !== current) return error(412, "conditionNotMet", "Precondition Failed"); if (call.method === "DELETE") { this.next({ ...base, status: "cancelled" }); return note(204, null); } const body = call.json!; const e = this.next({ ...base, ...body, id, ...(body.start ? { start: moment(body.start) } : {}), ...(body.end ? { end: moment(body.end) } : {}), ...(body.attendees ? { attendees: this.guests(body.attendees, (base.attendees as Guest[]) ?? []) } : {}) }); return note(200, e); }; readonly route: Route = (call) => { if (call.method !== "GET") return this.writes(call); if (call.url.pathname !== "/calendar/v3/calendars/primary/events") return this.writes(call); this.asked.push(call.url); const p = call.url.searchParams; expect(p.get("singleEvents")).toBe("false"); let since: number; let offset = 0; let upto = this.version; const page = p.get("pageToken"); const sync = p.get("syncToken"); if (page) [since, offset, upto] = page.split(":").map(Number) as [number, number, number]; else if (sync) { if (this.gone.has(sync)) return reply(410, { error: { code: 410, message: "Sync token is no longer valid, a full sync is required." } }); since = Number(sync.slice(1)); } else { expect(p.get("timeMin")).toBeTruthy(); expect(p.get("timeMax")).toBeTruthy(); since = -1; } const all = [...this.events.values()] .filter((e) => e.version <= upto && (since < 0 ? e.event.status !== "cancelled" : e.version > since)) .sort((a, b) => a.version - b.version) .map((e) => e.event); const items = all.slice(offset, offset + this.pageSize); const more = offset + this.pageSize < all.length; return reply(200, { kind: "calendar#events", timeZone: "Asia/Kolkata", items, ...(more ? { nextPageToken: `${since}:${offset + this.pageSize}:${upto}` } : { nextSyncToken: `v${upto}` }) }); };}/** A calendar with nothing on it, for a test about the sign-in alone: the pull a connect wakes finds nothing. */export const quiet: Route = new FakeCalendar().route;