diff --git a/emulators/manifest.json b/emulators/manifest.json index 2c36142357..677e16bed0 100644 --- a/emulators/manifest.json +++ b/emulators/manifest.json @@ -88,8 +88,8 @@ "packages/eliza-harness/src/providers/google-gmail.ts" ], "status": "unverified", - "contractHash": "c1c4a60423aca8493082aaeae2c1fe37e184814085c6ae161430246f89352fdf", - "notes": "Stateful OAuth2 PKCE + Gmail REST API emulator. Unverified against live Gmail API because no live user OAuth refresh token with gmail.readonly scope is provisioned locally." + "contractHash": "eebd9ee47ff96103cd9798e890261df962624ef1bcc478649cde6dd39944747a", + "notes": "Stateful multi-account Google OAuth2 PKCE, Gmail (read, drafts, send), Calendar v3 (calendarList, events CRUD, freeBusy), and FaultArmory emulator. Unverified against live Google APIs because no live user OAuth refresh token is provisioned locally." }, { "service": "google-maps", @@ -174,8 +174,8 @@ "packages/eliza-harness/src/providers/shared.ts" ], "status": "unverified", - "contractHash": "d4c8af5b255213407ca61a1421abe03d7af0bfd80fc6cc2cc1edd910695bf1ae", - "notes": "Stateful Slack user-account HTTP+SSE emulator built on vibestack/emulate. Unverified against live Slack API because no live xoxp- user token is provisioned locally." + "contractHash": "65442a24681962bc402cf36e192eecff5b6f0c8c469c55ee0b00c20f7b125a64", + "notes": "Stateful Slack user-account HTTP+SSE emulator with V2 external file uploads built on vibestack/emulate. Unverified against live Slack API because no live xoxp- user token is provisioned locally." }, { "service": "stripe", diff --git a/packages/eliza-harness/src/index.ts b/packages/eliza-harness/src/index.ts index 926891dba3..d398e3aa7d 100644 --- a/packages/eliza-harness/src/index.ts +++ b/packages/eliza-harness/src/index.ts @@ -17,8 +17,24 @@ export { type RecordedRequest, type RunningProvider, } from "./providers/shared.ts"; +export { + type GmailAnswer, + type GmailSeed, + type GoogleAccountSeed, + type GoogleProviderOptions, + type SeededCalendar, + type SeededCalendarAttendee, + type SeededCalendarEvent, + type SeededCalendarEventTime, + type SeededDraft, + type SeededMail, + googleGmailFake, + qaGmail, + startGoogleProvider, +} from "./providers/google-gmail.ts"; export { type SlackChannel, + type SlackFile, type SlackMessage, type SlackReaction, type SlackUser, diff --git a/packages/eliza-harness/src/providers/google-gmail.ts b/packages/eliza-harness/src/providers/google-gmail.ts index d7bb5a3ef0..0acd68ea06 100644 --- a/packages/eliza-harness/src/providers/google-gmail.ts +++ b/packages/eliza-harness/src/providers/google-gmail.ts @@ -1,6 +1,22 @@ import { createHash } from "node:crypto"; -import type { IncomingHttpHeaders } from "node:http"; -import { randomToken, verifyPkceS256 } from "vibestack/emulate"; +import type { IncomingHttpHeaders, ServerResponse } from "node:http"; +import { + FaultArmory, + type FaultRule, + type ParsedRequest, + type ProviderOptions, + type RunningProvider, + asBoolean, + asNumber, + asRecord, + asString, + createProviderServer, + randomToken, + sendBytes, + sendJson, + sendRedirect, + verifyPkceS256, +} from "./shared.ts"; /** One seeded Gmail message the fake returns over Google's Gmail REST API. */ export interface SeededMail { @@ -15,13 +31,78 @@ export interface SeededMail { readonly bodyHtml?: string; readonly labels: readonly string[]; readonly receivedAt: number; + readonly raw?: string; + readonly rfc822MessageId?: string; } -/** What the fake Google OAuth + Gmail provider holds for one local QA cloud run. */ -export interface GmailSeed { +/** One seeded Gmail draft belonging to an account mailbox. */ +export interface SeededDraft { + readonly id: string; + readonly message: SeededMail; +} + +/** One seeded Google Calendar list entry. */ +export interface SeededCalendar { + readonly id: string; + readonly summary: string; + readonly description?: string; + readonly timeZone?: string; + readonly primary?: boolean; + readonly accessRole?: "owner" | "writer" | "reader" | "freeBusyReader"; + readonly selected?: boolean; + readonly hidden?: boolean; +} + +/** Start or end boundary for a Google Calendar v3 event. */ +export interface SeededCalendarEventTime { + readonly date?: string; + readonly dateTime?: string; + readonly timeZone?: string; +} + +/** Attendee record on a Google Calendar v3 event. */ +export interface SeededCalendarAttendee { + readonly email: string; + readonly displayName?: string; + readonly responseStatus?: "needsAction" | "declined" | "tentative" | "accepted"; + readonly self?: boolean; + readonly organizer?: boolean; + readonly optional?: boolean; +} + +/** One seeded Google Calendar v3 event. */ +export interface SeededCalendarEvent { + readonly id: string; + readonly calendarId?: string; + readonly summary: string; + readonly description?: string; + readonly location?: string; + readonly status?: "confirmed" | "tentative" | "cancelled"; + readonly start: SeededCalendarEventTime; + readonly end: SeededCalendarEventTime; + readonly attendees?: readonly SeededCalendarAttendee[]; + readonly recurrence?: readonly string[]; + readonly visibility?: string; + readonly reminders?: { readonly useDefault: boolean }; + readonly etag?: string; + readonly created?: string; + readonly updated?: string; +} + +/** Per-account mailbox, drafts, calendars, and events for multi-account Google emulation. */ +export interface GoogleAccountSeed { readonly email: string; readonly subject: string; + readonly name?: string; readonly messages: readonly SeededMail[]; + readonly drafts?: readonly SeededDraft[]; + readonly calendars?: readonly SeededCalendar[]; + readonly events?: readonly SeededCalendarEvent[]; +} + +/** What the fake Google OAuth + Gmail + Calendar provider holds for one local QA cloud run. */ +export interface GmailSeed extends GoogleAccountSeed { + readonly accounts?: Readonly>; } /** One answer of the fake, as the cloud's Google provider reads it off the wire. */ @@ -30,6 +111,13 @@ export interface GmailAnswer { readonly type: string; readonly body: Uint8Array; readonly location?: string; + readonly headers?: Readonly>; +} + +/** Startup configuration for the standalone loopback Google OAuth + Gmail + Calendar v3 provider. */ +export interface GoogleProviderOptions extends ProviderOptions { + readonly seed?: GmailSeed; + readonly clientSecret?: string; } const minuteMs = 60_000; @@ -37,15 +125,19 @@ const hourMs = 3_600_000; const dayMs = 86_400_000; /** - * The seeded mailbox a QA run's connected Gmail account holds: today's mail from Lena Ruiz (one unread important - * contract message and one plain-text Friday tacos message) and Acme Billing (one formatted HTML December invoice), - * plus older read mail from Sam Lee and a newsletter. + * The seeded mailbox and primary calendar a QA run's connected Google account holds: today's mail from Lena Ruiz + * (one unread important contract message and one plain-text Friday tacos message) and Acme Billing (one formatted + * HTML December invoice), older read mail from Sam Lee and a newsletter, plus default primary calendar events. */ export function qaGmail(now = Date.now(), email = "gmail@alpha.test"): GmailSeed { const startOfDay = new Date(now); startOfDay.setHours(0, 0, 0, 0); const floor = startOfDay.getTime() + minuteMs; const today = (minutesAgo: number) => Math.max(floor, now - minutesAgo * minuteMs); + const standupStart = new Date(now + 2 * hourMs).toISOString(); + const standupEnd = new Date(now + 2 * hourMs + 30 * minuteMs).toISOString(); + const reviewStart = new Date(now + dayMs).toISOString(); + const reviewEnd = new Date(now + dayMs + hourMs).toISOString(); return { email, subject: "qa-google-owner", @@ -106,6 +198,40 @@ export function qaGmail(now = Date.now(), email = "gmail@alpha.test"): GmailSeed receivedAt: now - 3 * dayMs - hourMs, }, ], + calendars: [ + { + id: email, + summary: email, + timeZone: "UTC", + primary: true, + accessRole: "owner", + selected: true, + hidden: false, + }, + ], + events: [ + { + id: "qa-evt-standup", + calendarId: email, + summary: "Morning Standup", + description: "Daily engineering sync", + location: "Room 2A", + status: "confirmed", + start: { dateTime: standupStart, timeZone: "UTC" }, + end: { dateTime: standupEnd, timeZone: "UTC" }, + }, + { + id: "qa-evt-review", + calendarId: email, + summary: "Contract Review with Lena", + description: "Walk through updated contract clauses", + location: "Video call", + status: "confirmed", + start: { dateTime: reviewStart, timeZone: "UTC" }, + end: { dateTime: reviewEnd, timeZone: "UTC" }, + attendees: [{ email: "lena@ruiz.example", displayName: "Lena Ruiz", responseStatus: "accepted" }], + }, + ], }; } @@ -125,24 +251,320 @@ interface Grant { readonly clientId: string; } +interface StoredMail { + id: string; + threadId: string; + from: string; + to: string[]; + cc?: string[]; + subject: string; + snippet?: string; + bodyText?: string; + bodyHtml?: string; + labels: string[]; + receivedAt: number; + raw?: string; + rfc822MessageId?: string; +} + +interface StoredDraft { + readonly id: string; + message: StoredMail; +} + +interface StoredCalendar { + readonly id: string; + readonly summary: string; + readonly description?: string; + readonly timeZone: string; + readonly primary: boolean; + readonly accessRole: "owner" | "writer" | "reader" | "freeBusyReader"; + readonly selected: boolean; + readonly hidden: boolean; +} + +interface StoredEvent { + readonly id: string; + readonly calendarId: string; + summary: string; + description?: string; + location?: string; + status: "confirmed" | "tentative" | "cancelled"; + start: SeededCalendarEventTime; + end: SeededCalendarEventTime; + attendees?: SeededCalendarAttendee[]; + recurrence?: string[]; + visibility?: string; + reminders?: { readonly useDefault: boolean }; + etagVersion: number; + etag: string; + readonly created: string; + updated: string; +} + +interface AccountState { + readonly email: string; + readonly subject: string; + readonly name: string; + historyId: number; + msgSeq: number; + draftSeq: number; + eventSeq: number; + readonly primaryCalendarId: string; + readonly messages: Map; + readonly drafts: Map; + readonly calendars: Map; + readonly events: Map>; + readonly deletedEvents: Map>; +} + +interface FakeRuntime { + readonly consents: Map; + readonly accessTokens: Map; + readonly refreshTokens: Map; + readonly accounts: Map; + readonly faults: FaultArmory; +} + +const ACCESS_ROLE_RANK: Readonly> = { + freeBusyReader: 1, + reader: 2, + writer: 3, + owner: 4, +}; + const encodePart = (text: string) => Buffer.from(text, "utf8").toString("base64url"); -function json(status: number, body: unknown): GmailAnswer { - return { status, type: "application/json", body: Buffer.from(JSON.stringify(body)) }; +function json(status: number, body: unknown, headers?: Readonly>): GmailAnswer { + return { + status, + type: "application/json", + body: Buffer.from(JSON.stringify(body)), + ...(headers !== undefined ? { headers } : {}), + }; +} + +function googleError(status: number, statusText: string, message: string, headers?: Readonly>): GmailAnswer { + return json(status, { error: { code: status, message, status: statusText } }, headers); +} + +function parseJsonBody(body: string): Record | undefined { + if (body.trim() === "") return undefined; + try { + return asRecord(JSON.parse(body) as unknown); + } catch { + return undefined; + } +} + +function defaultGoogleFaultBody(pathname: string, fault: FaultRule): unknown { + const status = fault.status ?? 503; + if (pathname === "/token" && (status === 400 || status === 401)) { + return { error: "invalid_grant", error_description: "Token has been expired or revoked." }; + } + if (status === 401) { + return { error: { code: 401, message: "Request had invalid authentication credentials.", status: "UNAUTHENTICATED" } }; + } + if (status === 429) { + return { + error: { + code: 429, + message: "Rate Limit Exceeded", + status: "RESOURCE_EXHAUSTED", + errors: [{ domain: "usageLimits", reason: "rateLimitExceeded", message: "Rate Limit Exceeded" }], + }, + }; + } + return { error: { code: status, message: `Injected HTTP ${status} fault`, status: "UNAVAILABLE" } }; +} + +function buildFaultAnswer(pathname: string, fault: FaultRule): GmailAnswer { + const status = fault.status ?? 503; + const headers: Record = { ...(fault.headers ?? {}) }; + if (fault.retryAfter !== undefined) { + headers["retry-after"] = String(Math.max(0, Math.ceil(fault.retryAfter))); + } + const payload = fault.body !== undefined ? fault.body : defaultGoogleFaultBody(pathname, fault); + return json(status, payload, Object.keys(headers).length > 0 ? headers : undefined); +} + +function cloneMail(message: SeededMail): StoredMail { + return { + id: message.id, + threadId: message.threadId, + from: message.from, + to: [...message.to], + ...(message.cc !== undefined ? { cc: [...message.cc] } : {}), + subject: message.subject, + ...(message.snippet !== undefined ? { snippet: message.snippet } : {}), + ...(message.bodyText !== undefined ? { bodyText: message.bodyText } : {}), + ...(message.bodyHtml !== undefined ? { bodyHtml: message.bodyHtml } : {}), + labels: [...message.labels], + receivedAt: message.receivedAt, + ...(message.raw !== undefined ? { raw: message.raw } : {}), + ...(message.rfc822MessageId !== undefined ? { rfc822MessageId: message.rfc822MessageId } : {}), + }; +} + +function createStoredEvent(calendarId: string, event: SeededCalendarEvent, fallbackIso: string): StoredEvent { + const etag = event.etag ?? '"1"'; + return { + id: event.id, + calendarId, + summary: event.summary, + ...(event.description !== undefined ? { description: event.description } : {}), + ...(event.location !== undefined ? { location: event.location } : {}), + status: event.status ?? "confirmed", + start: { ...event.start }, + end: { ...event.end }, + ...(event.attendees !== undefined ? { attendees: event.attendees.map((item) => ({ ...item })) } : {}), + ...(event.recurrence !== undefined ? { recurrence: [...event.recurrence] } : {}), + ...(event.visibility !== undefined ? { visibility: event.visibility } : {}), + ...(event.reminders !== undefined ? { reminders: { ...event.reminders } } : {}), + etagVersion: 1, + etag, + created: event.created ?? fallbackIso, + updated: event.updated ?? fallbackIso, + }; } -function headersOf(message: SeededMail): readonly { readonly name: string; readonly value: string }[] { +function buildAccountState(accountSeed: GoogleAccountSeed): AccountState { + const messages = new Map(); + for (const message of accountSeed.messages) { + messages.set(message.id, cloneMail(message)); + } + const drafts = new Map(); + for (const draft of accountSeed.drafts ?? []) { + drafts.set(draft.id, { id: draft.id, message: cloneMail(draft.message) }); + } + const calendars = new Map(); + let primaryCalendarId: string | undefined; + for (const cal of accountSeed.calendars ?? []) { + const isPrimary = cal.primary === true || cal.id === "primary" || cal.id.toLowerCase() === accountSeed.email.toLowerCase(); + const resolvedId = cal.id === "primary" ? accountSeed.email : cal.id; + const stored: StoredCalendar = { + id: resolvedId, + summary: cal.summary, + ...(cal.description !== undefined ? { description: cal.description } : {}), + timeZone: cal.timeZone ?? "UTC", + primary: isPrimary, + accessRole: cal.accessRole ?? "owner", + selected: cal.selected ?? true, + hidden: cal.hidden ?? false, + }; + calendars.set(resolvedId, stored); + if (isPrimary && primaryCalendarId === undefined) primaryCalendarId = resolvedId; + } + if (primaryCalendarId === undefined) { + primaryCalendarId = accountSeed.email; + calendars.set(primaryCalendarId, { + id: primaryCalendarId, + summary: accountSeed.email, + timeZone: "UTC", + primary: true, + accessRole: "owner", + selected: true, + hidden: false, + }); + } + const events = new Map>(); + const deletedEvents = new Map>(); + for (const calId of calendars.keys()) { + events.set(calId, new Map()); + deletedEvents.set(calId, new Map()); + } + const fallbackIso = new Date().toISOString(); + for (const event of accountSeed.events ?? []) { + const rawCalId = event.calendarId ?? primaryCalendarId; + const resolvedCalId = rawCalId === "primary" ? primaryCalendarId : rawCalId; + if (!events.has(resolvedCalId)) { + events.set(resolvedCalId, new Map()); + deletedEvents.set(resolvedCalId, new Map()); + } + const stored = createStoredEvent(resolvedCalId, event, fallbackIso); + if (stored.status === "cancelled") { + deletedEvents.get(resolvedCalId)?.set(stored.id, stored); + } else { + events.get(resolvedCalId)?.set(stored.id, stored); + } + } + return { + email: accountSeed.email, + subject: accountSeed.subject, + name: accountSeed.name ?? "Alpha Owner", + historyId: 1001, + msgSeq: 0, + draftSeq: 0, + eventSeq: 0, + primaryCalendarId, + messages, + drafts, + calendars, + events, + deletedEvents, + }; +} + +function createRuntime(seed: GmailSeed): FakeRuntime { + const accounts = new Map(); + const primary = buildAccountState({ + email: seed.email, + subject: seed.subject, + name: seed.name, + messages: seed.messages, + drafts: seed.drafts, + calendars: seed.calendars, + events: seed.events, + }); + accounts.set(primary.email.toLowerCase(), primary); + if (seed.accounts !== undefined) { + for (const extra of Object.values(seed.accounts)) { + accounts.set(extra.email.toLowerCase(), buildAccountState(extra)); + } + } + return { + consents: new Map(), + accessTokens: new Map(), + refreshTokens: new Map(), + accounts, + faults: new FaultArmory(), + }; +} + +function getOrCreateAccount(runtime: FakeRuntime, email: string): AccountState { + const key = email.toLowerCase(); + const existing = runtime.accounts.get(key); + if (existing !== undefined) return existing; + const subject = `qa-google-${createHash("sha256").update(email).digest("hex").slice(0, 12)}`; + const created = buildAccountState({ email, subject, messages: [] }); + runtime.accounts.set(key, created); + return created; +} + +function headersOf(message: StoredMail): readonly { readonly name: string; readonly value: string }[] { + const messageId = message.rfc822MessageId ?? `<${message.id}@qa.alpha.test>`; return [ { name: "From", value: message.from }, { name: "To", value: message.to.join(", ") }, ...(message.cc !== undefined && message.cc.length > 0 ? [{ name: "Cc", value: message.cc.join(", ") }] : []), { name: "Subject", value: message.subject }, { name: "Date", value: new Date(message.receivedAt).toUTCString() }, - { name: "Message-ID", value: `<${message.id}@qa.alpha.test>` }, + { name: "Message-ID", value: messageId }, + ]; +} + +function synthesizeRawMime(message: StoredMail): string { + if (message.raw !== undefined) return message.raw; + const lines = [ + ...headersOf(message).map((entry) => `${entry.name}: ${entry.value}`), + `Content-Type: ${message.bodyHtml !== undefined && message.bodyText === undefined ? "text/html" : "text/plain"}; charset=utf-8`, + "", + message.bodyText ?? message.bodyHtml ?? message.snippet ?? "", ]; + return encodePart(lines.join("\r\n")); } -function payloadOf(message: SeededMail, format: string, metadataHeaders: readonly string[]) { +function payloadOf(message: StoredMail, format: string, metadataHeaders: readonly string[]) { const allHeaders = headersOf(message); if (format === "metadata") { const headers = metadataHeaders.length === 0 @@ -174,8 +596,19 @@ function payloadOf(message: SeededMail, format: string, metadataHeaders: readonl }; } -function shown(message: SeededMail, historyId: string, format: string, metadataHeaders: readonly string[]) { +function shown(message: StoredMail, historyId: string, format: string, metadataHeaders: readonly string[]) { const snippet = message.snippet ?? message.bodyText ?? ""; + if (format === "raw") { + return { + id: message.id, + threadId: message.threadId, + labelIds: [...message.labels], + historyId, + snippet, + internalDate: String(message.receivedAt), + raw: synthesizeRawMime(message), + }; + } return { id: message.id, threadId: message.threadId, @@ -187,6 +620,85 @@ function shown(message: SeededMail, historyId: string, format: string, metadataH }; } +function parseAddressList(raw: unknown): string[] { + if (typeof raw === "string") { + return raw.split(",").map((item) => item.trim()).filter(Boolean); + } + if (Array.isArray(raw)) { + return raw.filter((item): item is string => typeof item === "string" && item.trim() !== "").map((item) => item.trim()); + } + return []; +} + +function decodeMimeToMail( + payload: Record, + senderEmail: string, + id: string, + fallbackThreadId: string, + labels: readonly string[], + now: number, +): StoredMail | undefined { + const rawField = asString(payload.raw); + const threadId = asString(payload.threadId) ?? fallbackThreadId; + if (rawField !== undefined && rawField.trim() !== "") { + const decoded = Buffer.from(rawField, "base64url").toString("utf8"); + const splitCrlf = decoded.indexOf("\r\n\r\n"); + const splitLf = decoded.indexOf("\n\n"); + const splitIndex = splitCrlf >= 0 ? splitCrlf : splitLf; + const sepLen = splitCrlf >= 0 ? 4 : 2; + const headerBlock = splitIndex >= 0 ? decoded.slice(0, splitIndex) : decoded; + const bodyContent = splitIndex >= 0 ? decoded.slice(splitIndex + sepLen) : ""; + const parsedHeaders = new Map(); + for (const line of headerBlock.split(/\r?\n/)) { + const colon = line.indexOf(":"); + if (colon <= 0) continue; + parsedHeaders.set(line.slice(0, colon).trim().toLowerCase(), line.slice(colon + 1).trim()); + } + const contentType = (parsedHeaders.get("content-type") ?? "").toLowerCase(); + const isHtml = contentType.includes("text/html"); + const to = parseAddressList(parsedHeaders.get("to") ?? payload.to); + const cc = parseAddressList(parsedHeaders.get("cc") ?? payload.cc); + const subject = parsedHeaders.get("subject") ?? asString(payload.subject) ?? "(no subject)"; + const from = parsedHeaders.get("from") ?? senderEmail; + const rfc822MessageId = parsedHeaders.get("message-id"); + return { + id, + threadId, + from, + to, + ...(cc.length > 0 ? { cc } : {}), + subject, + snippet: bodyContent.trim().slice(0, 140), + ...(isHtml ? { bodyHtml: bodyContent } : { bodyText: bodyContent }), + labels: [...labels], + receivedAt: now, + raw: rawField, + ...(rfc822MessageId !== undefined ? { rfc822MessageId } : {}), + }; + } + const to = parseAddressList(payload.to); + const cc = parseAddressList(payload.cc); + const subject = asString(payload.subject); + const bodyText = asString(payload.bodyText) ?? asString(payload.body); + const bodyHtml = asString(payload.bodyHtml); + if (to.length === 0 && subject === undefined && bodyText === undefined && bodyHtml === undefined) { + return undefined; + } + return { + id, + threadId, + from: asString(payload.from) ?? senderEmail, + to, + ...(cc.length > 0 ? { cc } : {}), + subject: subject ?? "(no subject)", + snippet: (bodyText ?? bodyHtml ?? "").trim().slice(0, 140), + ...(bodyText !== undefined ? { bodyText } : {}), + ...(bodyHtml !== undefined ? { bodyHtml } : {}), + labels: [...labels], + receivedAt: now, + }; +} + function parseDurationMs(raw: string): number | undefined { const matched = /^(\d+)([hdmy])$/i.exec(raw); if (matched === null) return undefined; @@ -211,7 +723,7 @@ function parseDateMs(raw: string): number | undefined { function tokenizeQuery(query: string): string[] { const tokens: string[] = []; - const pattern = /-?[a-z_]+:"[^"]*"|"[^"]*"|\S+/gi; + const pattern = /-?[a-z0-9_]+:"[^"]*"|"[^"]*"|\S+/gi; for (const match of query.matchAll(pattern)) { const token = match[0].replace(/^[({]+|[)}]+$/g, ""); if (token !== "") tokens.push(token); @@ -219,7 +731,7 @@ function tokenizeQuery(query: string): string[] { return tokens; } -function matchesTerm(message: SeededMail, rawTerm: string, now: number): boolean { +function matchesTerm(message: StoredMail, rawTerm: string, now: number): boolean { const negated = rawTerm.startsWith("-"); const term = negated ? rawTerm.slice(1) : rawTerm; const labels = new Set(message.labels.map((label) => label.toUpperCase())); @@ -251,6 +763,9 @@ function matchesTerm(message: SeededMail, rawTerm: string, now: number): boolean matched = message.to.some((recipient) => recipient.toLowerCase().includes(value)); } else if (key === "subject") { matched = message.subject.toLowerCase().includes(value); + } else if (key === "rfc822msgid") { + const normalized = (message.rfc822MessageId ?? `<${message.id}@qa.alpha.test>`).replace(/^<|>$/g, "").toLowerCase(); + matched = normalized === value.replace(/^<|>$/g, ""); } else if (key === "newer_than") { const span = parseDurationMs(value); matched = span === undefined ? true : now - message.receivedAt <= span; @@ -276,7 +791,7 @@ function matchesTerm(message: SeededMail, rawTerm: string, now: number): boolean return negated ? !matched : matched; } -function matchesQuery(message: SeededMail, query: URLSearchParams, now: number): boolean { +function matchesQuery(message: StoredMail, query: URLSearchParams, now: number): boolean { const requiredLabels = query.getAll("labelIds"); if (!requiredLabels.every((label) => message.labels.includes(label))) return false; const includeSpamTrash = query.get("includeSpamTrash") === "true"; @@ -295,35 +810,704 @@ function matchesQuery(message: SeededMail, query: URLSearchParams, now: number): return groups.some((group) => group.length > 0 && group.every((term) => matchesTerm(message, term, now))); } +function resolveCalendar(account: AccountState, rawCalendarId: string): StoredCalendar | undefined { + const decoded = decodeURIComponent(rawCalendarId); + if (decoded === "primary") return account.calendars.get(account.primaryCalendarId); + const exact = account.calendars.get(decoded); + if (exact !== undefined) return exact; + if (decoded.toLowerCase() === account.email.toLowerCase()) { + return account.calendars.get(account.primaryCalendarId); + } + return undefined; +} + +function calendarEntryResponse(calendar: StoredCalendar) { + return { + kind: "calendar#calendarListEntry", + etag: `"cal-${calendar.id}"`, + id: calendar.id, + summary: calendar.summary, + ...(calendar.description !== undefined ? { description: calendar.description } : {}), + timeZone: calendar.timeZone, + ...(calendar.primary ? { primary: true } : {}), + accessRole: calendar.accessRole, + selected: calendar.selected, + hidden: calendar.hidden, + }; +} + +function eventStartMs(event: StoredEvent): number { + const raw = event.start.dateTime ?? event.start.date; + return raw !== undefined ? Date.parse(raw) : Number.NaN; +} + +function eventEndMs(event: StoredEvent): number { + const raw = event.end.dateTime ?? event.end.date; + if (raw === undefined) return Number.NaN; + return event.end.date !== undefined ? Date.parse(`${raw}T23:59:59.999Z`) : Date.parse(raw); +} + +function eventIsoBounds(event: StoredEvent): { readonly start: string; readonly end: string } | undefined { + const startRaw = event.start.dateTime ?? (event.start.date !== undefined ? `${event.start.date}T00:00:00.000Z` : undefined); + const endRaw = event.end.dateTime ?? (event.end.date !== undefined ? `${event.end.date}T00:00:00.000Z` : undefined); + if (startRaw === undefined || endRaw === undefined) return undefined; + const startMs = Date.parse(startRaw); + const endMs = Date.parse(endRaw); + if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return undefined; + return { start: new Date(startMs).toISOString(), end: new Date(endMs).toISOString() }; +} + +function eventResponse(account: AccountState, event: StoredEvent) { + return { + kind: "calendar#event", + etag: event.etag, + id: event.id, + status: event.status, + htmlLink: `https://calendar.google.com/calendar/event?eid=${encodePart(`${event.calendarId}:${event.id}`)}`, + created: event.created, + updated: event.updated, + summary: event.summary, + ...(event.description !== undefined ? { description: event.description } : {}), + ...(event.location !== undefined ? { location: event.location } : {}), + organizer: { email: account.email, displayName: account.name, self: true }, + start: event.start, + end: event.end, + ...(event.attendees !== undefined ? { attendees: event.attendees } : {}), + ...(event.recurrence !== undefined ? { recurrence: event.recurrence } : {}), + ...(event.visibility !== undefined ? { visibility: event.visibility } : {}), + ...(event.reminders !== undefined ? { reminders: event.reminders } : {}), + iCalUID: `${event.id}@qa.alpha.test`, + }; +} + +function parseEventTime(raw: unknown): SeededCalendarEventTime | undefined { + const rec = asRecord(raw); + if (rec === undefined) return undefined; + const date = asString(rec.date); + const dateTime = asString(rec.dateTime); + const timeZone = asString(rec.timeZone); + if (date === undefined && dateTime === undefined) return undefined; + return { + ...(date !== undefined ? { date } : {}), + ...(dateTime !== undefined ? { dateTime } : {}), + ...(timeZone !== undefined ? { timeZone } : {}), + }; +} + +function validEventBounds(start: SeededCalendarEventTime, end: SeededCalendarEventTime): boolean { + const allDay = start.date !== undefined || end.date !== undefined; + const startRaw = allDay ? start.date : start.dateTime; + const endRaw = allDay ? end.date : end.dateTime; + if (startRaw === undefined || endRaw === undefined) return false; + const s = Date.parse(startRaw); + const e = Date.parse(endRaw); + return Number.isFinite(s) && Number.isFinite(e) && s <= e; +} + +function parseAttendees(raw: unknown): SeededCalendarAttendee[] | undefined { + if (!Array.isArray(raw)) return undefined; + const items: SeededCalendarAttendee[] = []; + for (const entry of raw) { + const rec = asRecord(entry); + const email = asString(rec?.email); + if (rec === undefined || email === undefined) continue; + const responseStatus = asString(rec.responseStatus); + items.push({ + email, + ...(asString(rec.displayName) !== undefined ? { displayName: asString(rec.displayName) } : {}), + ...(responseStatus === "needsAction" || responseStatus === "declined" || responseStatus === "tentative" || responseStatus === "accepted" + ? { responseStatus } + : {}), + ...(asBoolean(rec.self) !== undefined ? { self: asBoolean(rec.self) } : {}), + ...(asBoolean(rec.organizer) !== undefined ? { organizer: asBoolean(rec.organizer) } : {}), + ...(asBoolean(rec.optional) !== undefined ? { optional: asBoolean(rec.optional) } : {}), + }); + } + return items; +} + +function parseRecurrence(raw: unknown): string[] | undefined { + if (!Array.isArray(raw)) return undefined; + return raw.filter((line): line is string => typeof line === "string"); +} + +function checkIfMatch(headers: IncomingHttpHeaders, currentEtag: string): GmailAnswer | undefined { + const raw = typeof headers["if-match"] === "string" ? headers["if-match"].trim() : undefined; + if (raw === undefined || raw === "" || raw === "*") return undefined; + if (raw !== currentEtag) { + return googleError(412, "FAILED_PRECONDITION", "Precondition Failed"); + } + return undefined; +} + +function sliceOffsetPage( + rows: readonly T[], + query: URLSearchParams, + defaultLimit: number, +): { readonly page: readonly T[]; readonly nextPageToken?: string } { + const maxResults = Math.max(1, Math.min(defaultLimit, Number(query.get("maxResults") ?? String(defaultLimit)) || defaultLimit)); + const offset = Math.max(0, Number(query.get("pageToken") ?? "0") || 0); + const page = rows.slice(offset, offset + maxResults); + const nextPageToken = offset + maxResults < rows.length ? String(offset + maxResults) : undefined; + return { page, ...(nextPageToken === undefined ? {} : { nextPageToken }) }; +} + +function handleGmailRoutes( + account: AccountState, + method: string, + rest: string, + url: URL, + body: string, +): GmailAnswer | undefined { + const historyId = String(account.historyId); + if (method === "GET" && rest === "/profile") { + const threadIds = new Set([...account.messages.values()].map((msg) => msg.threadId)); + return json(200, { + emailAddress: account.email, + messagesTotal: account.messages.size, + threadsTotal: threadIds.size, + historyId, + }); + } + if (method === "GET" && rest === "/history") { + return json(200, { historyId }); + } + if (method === "GET" && rest === "/messages") { + const now = Date.now(); + const rows = [...account.messages.values()] + .filter((message) => !message.labels.includes("DRAFT") && matchesQuery(message, url.searchParams, now)) + .toSorted((left, right) => right.receivedAt - left.receivedAt); + const { page, nextPageToken } = sliceOffsetPage(rows, url.searchParams, 100); + return json(200, { + messages: page.map((message) => ({ id: message.id, threadId: message.threadId })), + resultSizeEstimate: rows.length, + ...(nextPageToken === undefined ? {} : { nextPageToken }), + }); + } + if (method === "POST" && rest === "/messages/send") { + const parsed = parseJsonBody(body); + if (parsed === undefined) return googleError(400, "INVALID_ARGUMENT", "Invalid JSON message payload"); + account.msgSeq += 1; + const id = `qa-sent-${account.msgSeq}`; + const built = decodeMimeToMail(parsed, account.email, id, `qa-thread-sent-${account.msgSeq}`, ["SENT"], Date.now()); + if (built === undefined) return googleError(400, "INVALID_ARGUMENT", "Missing message content"); + account.messages.set(built.id, built); + account.historyId += 1; + return json(200, { id: built.id, threadId: built.threadId, labelIds: [...built.labels] }); + } + const messageMatch = /^\/messages\/([A-Za-z0-9_-]+)$/.exec(rest); + if (method === "GET" && messageMatch !== null) { + const message = account.messages.get(messageMatch[1] ?? ""); + if (message === undefined) return googleError(404, "NOT_FOUND", "Message not found"); + const format = url.searchParams.get("format") ?? "full"; + return json(200, shown(message, historyId, format, url.searchParams.getAll("metadataHeaders"))); + } + const threadMatch = /^\/threads\/([A-Za-z0-9_-]+)$/.exec(rest); + if (method === "GET" && threadMatch !== null) { + const threadMessages = [...account.messages.values()] + .filter((message) => message.threadId === threadMatch[1]) + .toSorted((left, right) => left.receivedAt - right.receivedAt); + if (threadMessages.length === 0) return googleError(404, "NOT_FOUND", "Thread not found"); + const format = url.searchParams.get("format") ?? "full"; + return json(200, { + id: threadMatch[1], + historyId, + messages: threadMessages.map((message) => shown(message, historyId, format, url.searchParams.getAll("metadataHeaders"))), + }); + } + if (method === "GET" && rest === "/drafts") { + const now = Date.now(); + const rows = [...account.drafts.values()] + .filter((draft) => matchesQuery(draft.message, url.searchParams, now)) + .toSorted((left, right) => right.message.receivedAt - left.message.receivedAt); + const { page, nextPageToken } = sliceOffsetPage(rows, url.searchParams, 100); + return json(200, { + drafts: page.map((draft) => ({ id: draft.id, message: { id: draft.message.id, threadId: draft.message.threadId } })), + resultSizeEstimate: rows.length, + ...(nextPageToken === undefined ? {} : { nextPageToken }), + }); + } + if (method === "POST" && rest === "/drafts") { + const parsed = parseJsonBody(body); + const messagePayload = asRecord(parsed?.message) ?? parsed; + if (messagePayload === undefined) return googleError(400, "INVALID_ARGUMENT", "Invalid draft payload"); + account.draftSeq += 1; + account.msgSeq += 1; + const draftId = `qa-draft-${account.draftSeq}`; + const msgId = `qa-draft-msg-${account.msgSeq}`; + const built = decodeMimeToMail(messagePayload, account.email, msgId, `qa-thread-draft-${account.draftSeq}`, ["DRAFT"], Date.now()); + if (built === undefined) return googleError(400, "INVALID_ARGUMENT", "Missing draft message content"); + const draft: StoredDraft = { id: draftId, message: built }; + account.drafts.set(draft.id, draft); + account.historyId += 1; + return json(200, { id: draft.id, message: shown(draft.message, String(account.historyId), "full", []) }); + } + if (method === "POST" && rest === "/drafts/send") { + const parsed = parseJsonBody(body); + const draftId = asString(parsed?.id); + if (draftId === undefined) return googleError(400, "INVALID_ARGUMENT", "Draft id is required"); + const existing = account.drafts.get(draftId); + if (existing === undefined) return googleError(404, "NOT_FOUND", "Draft not found"); + const updatedPayload = asRecord(parsed?.message); + const now = Date.now(); + const sentBase = updatedPayload !== undefined + ? decodeMimeToMail(updatedPayload, account.email, existing.message.id, existing.message.threadId, ["SENT"], now) ?? existing.message + : existing.message; + const sent: StoredMail = { ...sentBase, labels: ["SENT"], receivedAt: now }; + account.drafts.delete(draftId); + account.messages.set(sent.id, sent); + account.historyId += 1; + return json(200, { id: sent.id, threadId: sent.threadId, labelIds: [...sent.labels] }); + } + const draftMatch = /^\/drafts\/([A-Za-z0-9_-]+)$/.exec(rest); + if (draftMatch !== null) { + const draftId = draftMatch[1] ?? ""; + const existing = account.drafts.get(draftId); + if (existing === undefined) return googleError(404, "NOT_FOUND", "Draft not found"); + if (method === "GET") { + const format = url.searchParams.get("format") ?? "full"; + return json(200, { + id: existing.id, + message: shown(existing.message, historyId, format, url.searchParams.getAll("metadataHeaders")), + }); + } + if (method === "PUT") { + const parsed = parseJsonBody(body); + const messagePayload = asRecord(parsed?.message) ?? parsed; + if (messagePayload === undefined) return googleError(400, "INVALID_ARGUMENT", "Invalid draft payload"); + const built = decodeMimeToMail(messagePayload, account.email, existing.message.id, existing.message.threadId, ["DRAFT"], Date.now()); + if (built === undefined) return googleError(400, "INVALID_ARGUMENT", "Missing draft message content"); + existing.message = built; + account.historyId += 1; + return json(200, { id: existing.id, message: shown(existing.message, String(account.historyId), "full", []) }); + } + if (method === "DELETE") { + account.drafts.delete(draftId); + account.historyId += 1; + return { status: 204, type: "text/plain", body: Buffer.from("") }; + } + } + return undefined; +} + +function calendarEventMaps(account: AccountState, calendarId: string) { + return { + activeMap: account.events.get(calendarId) ?? new Map(), + deletedMap: account.deletedEvents.get(calendarId) ?? new Map(), + }; +} + +function handleCalendarListRoutes( + account: AccountState, + method: string, + rest: string, + url: URL, +): GmailAnswer | undefined { + if (method === "GET" && rest === "/users/me/calendarList") { + const minRoleRaw = url.searchParams.get("minAccessRole"); + const minRank = minRoleRaw !== null && minRoleRaw in ACCESS_ROLE_RANK + ? ACCESS_ROLE_RANK[minRoleRaw as StoredCalendar["accessRole"]] + : 0; + const showHidden = url.searchParams.get("showHidden") === "true"; + const items = [...account.calendars.values()] + .filter((cal) => (showHidden || !cal.hidden) && ACCESS_ROLE_RANK[cal.accessRole] >= minRank) + .map(calendarEntryResponse); + const { page, nextPageToken } = sliceOffsetPage(items, url.searchParams, 250); + return json(200, { + kind: "calendar#calendarList", + etag: `"list-${account.historyId}"`, + items: page, + ...(nextPageToken === undefined ? {} : { nextPageToken }), + }); + } + const singleCalMatch = /^\/users\/me\/calendarList\/([^/]+)$/.exec(rest); + if (method === "GET" && singleCalMatch !== null) { + const calendar = resolveCalendar(account, singleCalMatch[1] ?? ""); + if (calendar === undefined) return googleError(404, "NOT_FOUND", "Calendar not found"); + return json(200, calendarEntryResponse(calendar)); + } + return undefined; +} + +function handleCalendarFreeBusy(account: AccountState, body: string): GmailAnswer { + const parsed = parseJsonBody(body); + const timeMin = asString(parsed?.timeMin); + const timeMax = asString(parsed?.timeMax); + const items = Array.isArray(parsed?.items) ? parsed.items : undefined; + const minMs = timeMin !== undefined ? Date.parse(timeMin) : Number.NaN; + const maxMs = timeMax !== undefined ? Date.parse(timeMax) : Number.NaN; + if (!Number.isFinite(minMs) || !Number.isFinite(maxMs) || minMs > maxMs || items === undefined) { + return googleError(400, "INVALID_ARGUMENT", "timeMin, timeMax, and items are required"); + } + const calendars: Record = {}; + for (const item of items) { + const id = asString(asRecord(item)?.id); + if (id === undefined) continue; + const resolved = resolveCalendar(account, id); + if (resolved === undefined) { + calendars[id] = { errors: [{ domain: "global", reason: "notFound" }], busy: [] }; + continue; + } + const calEvents = account.events.get(resolved.id); + const busy = [...(calEvents?.values() ?? [])] + .filter((event) => event.status !== "cancelled") + .map((event) => eventIsoBounds(event)) + .filter((bounds): bounds is { readonly start: string; readonly end: string } => { + if (bounds === undefined) return false; + const startMs = Date.parse(bounds.start); + const endMs = Date.parse(bounds.end); + return endMs > minMs && startMs < maxMs; + }) + .toSorted((left, right) => Date.parse(left.start) - Date.parse(right.start)); + calendars[id] = { busy }; + } + return json(200, { kind: "calendar#freeBusy", timeMin, timeMax, calendars }); +} + +function handleCalendarEventsCollection( + account: AccountState, + calendar: StoredCalendar, + method: string, + url: URL, + body: string, +): GmailAnswer | undefined { + const { activeMap, deletedMap } = calendarEventMaps(account, calendar.id); + if (method === "GET") { + const showDeleted = url.searchParams.get("showDeleted") === "true"; + const timeMinRaw = url.searchParams.get("timeMin"); + const timeMaxRaw = url.searchParams.get("timeMax"); + const updatedMinRaw = url.searchParams.get("updatedMin"); + const q = (url.searchParams.get("q") ?? "").trim().toLowerCase(); + const minMs = timeMinRaw !== null ? Date.parse(timeMinRaw) : undefined; + const maxMs = timeMaxRaw !== null ? Date.parse(timeMaxRaw) : undefined; + const updatedMinMs = updatedMinRaw !== null ? Date.parse(updatedMinRaw) : undefined; + const pool = showDeleted ? [...activeMap.values(), ...deletedMap.values()] : [...activeMap.values()]; + const filtered = pool + .filter((event) => { + if (minMs !== undefined && Number.isFinite(minMs) && eventEndMs(event) <= minMs) return false; + if (maxMs !== undefined && Number.isFinite(maxMs) && eventStartMs(event) >= maxMs) return false; + if (updatedMinMs !== undefined && Number.isFinite(updatedMinMs) && Date.parse(event.updated) < updatedMinMs) return false; + if (q !== "") { + const hay = `${event.summary} ${event.description ?? ""} ${event.location ?? ""} ${(event.attendees ?? []).map((a) => a.email).join(" ")}`.toLowerCase(); + if (!hay.includes(q)) return false; + } + return true; + }) + .toSorted((left, right) => { + if (url.searchParams.get("orderBy") === "updated") { + return Date.parse(left.updated) - Date.parse(right.updated); + } + return eventStartMs(left) - eventStartMs(right); + }); + const { page, nextPageToken } = sliceOffsetPage(filtered, url.searchParams, 250); + return json(200, { + kind: "calendar#events", + etag: `"events-${calendar.id}-${account.historyId}"`, + summary: calendar.summary, + timeZone: calendar.timeZone, + items: page.map((event) => eventResponse(account, event)), + ...(nextPageToken === undefined ? {} : { nextPageToken }), + }); + } + if (method === "POST") { + const parsed = parseJsonBody(body); + const start = parseEventTime(parsed?.start); + const end = parseEventTime(parsed?.end); + if (parsed === undefined || start === undefined || end === undefined || !validEventBounds(start, end)) { + return googleError(400, "INVALID_ARGUMENT", "Valid start and end times are required"); + } + const requestedId = asString(parsed.id); + if (requestedId !== undefined && (activeMap.has(requestedId) || deletedMap.has(requestedId))) { + return googleError(409, "ALREADY_EXISTS", "The requested identifier already exists."); + } + account.eventSeq += 1; + const id = requestedId ?? `qa_evt_${account.eventSeq}`; + const nowIso = new Date().toISOString(); + const attendees = parseAttendees(parsed.attendees); + const recurrence = parseRecurrence(parsed.recurrence); + const remindersRec = asRecord(parsed.reminders); + const created: StoredEvent = { + id, + calendarId: calendar.id, + summary: asString(parsed.summary) ?? "", + ...(asString(parsed.description) !== undefined ? { description: asString(parsed.description) } : {}), + ...(asString(parsed.location) !== undefined ? { location: asString(parsed.location) } : {}), + status: "confirmed", + start, + end, + ...(attendees !== undefined ? { attendees } : {}), + ...(recurrence !== undefined ? { recurrence } : {}), + ...(asString(parsed.visibility) !== undefined ? { visibility: asString(parsed.visibility) } : {}), + ...(remindersRec !== undefined ? { reminders: { useDefault: asBoolean(remindersRec.useDefault) ?? true } } : {}), + etagVersion: 1, + etag: '"1"', + created: nowIso, + updated: nowIso, + }; + activeMap.set(created.id, created); + account.events.set(calendar.id, activeMap); + account.historyId += 1; + return json(200, eventResponse(account, created)); + } + return undefined; +} + +function handleCalendarEventItem( + account: AccountState, + calendar: StoredCalendar, + eventId: string, + method: string, + headers: IncomingHttpHeaders, + body: string, +): GmailAnswer | undefined { + const { activeMap, deletedMap } = calendarEventMaps(account, calendar.id); + const existing = activeMap.get(eventId); + if (existing === undefined) return googleError(404, "NOT_FOUND", "Event not found"); + if (method === "GET") { + return json(200, eventResponse(account, existing)); + } + const mismatch = checkIfMatch(headers, existing.etag); + if (mismatch !== undefined) return mismatch; + if (method === "DELETE") { + activeMap.delete(eventId); + existing.status = "cancelled"; + existing.etagVersion += 1; + existing.etag = `"${existing.etagVersion}"`; + existing.updated = new Date().toISOString(); + deletedMap.set(eventId, existing); + account.deletedEvents.set(calendar.id, deletedMap); + account.historyId += 1; + return { status: 204, type: "text/plain", body: Buffer.from("") }; + } + if (method === "PATCH" || method === "PUT") { + const parsed = parseJsonBody(body); + if (parsed === undefined) return googleError(400, "INVALID_ARGUMENT", "Invalid event JSON body"); + const nextStart = parsed.start !== undefined ? parseEventTime(parsed.start) : existing.start; + const nextEnd = parsed.end !== undefined ? parseEventTime(parsed.end) : existing.end; + if (nextStart === undefined || nextEnd === undefined || !validEventBounds(nextStart, nextEnd)) { + return googleError(400, "INVALID_ARGUMENT", "Invalid event start/end time"); + } + const replace = method === "PUT"; + existing.summary = asString(parsed.summary) ?? (replace ? "" : existing.summary); + if (parsed.description !== undefined) existing.description = asString(parsed.description); + else if (replace) delete existing.description; + if (parsed.location !== undefined) existing.location = asString(parsed.location); + else if (replace) delete existing.location; + existing.start = nextStart; + existing.end = nextEnd; + if (parsed.attendees !== undefined) existing.attendees = parseAttendees(parsed.attendees); + else if (replace) delete existing.attendees; + if (parsed.recurrence !== undefined) existing.recurrence = parseRecurrence(parsed.recurrence); + else if (replace) delete existing.recurrence; + if (parsed.visibility !== undefined) existing.visibility = asString(parsed.visibility); + else if (replace) delete existing.visibility; + if (parsed.reminders !== undefined) { + const rem = asRecord(parsed.reminders); + existing.reminders = { useDefault: asBoolean(rem?.useDefault) ?? true }; + } else if (replace) { + delete existing.reminders; + } + const statusRaw = asString(parsed.status); + if (statusRaw === "confirmed" || statusRaw === "tentative" || statusRaw === "cancelled") { + existing.status = statusRaw; + } + existing.etagVersion += 1; + existing.etag = `"${existing.etagVersion}"`; + existing.updated = new Date().toISOString(); + account.historyId += 1; + return json(200, eventResponse(account, existing)); + } + return undefined; +} + +function handleCalendarRoutes( + account: AccountState, + method: string, + rest: string, + url: URL, + headers: IncomingHttpHeaders, + body: string, +): GmailAnswer | undefined { + const listAnswer = handleCalendarListRoutes(account, method, rest, url); + if (listAnswer !== undefined) return listAnswer; + if (method === "POST" && rest === "/freeBusy") { + return handleCalendarFreeBusy(account, body); + } + const eventsCollectionMatch = /^\/calendars\/([^/]+)\/events$/.exec(rest); + if (eventsCollectionMatch !== null) { + const calendar = resolveCalendar(account, eventsCollectionMatch[1] ?? ""); + if (calendar === undefined) return googleError(404, "NOT_FOUND", "Calendar not found"); + return handleCalendarEventsCollection(account, calendar, method, url, body); + } + const eventItemMatch = /^\/calendars\/([^/]+)\/events\/([^/]+)$/.exec(rest); + if (eventItemMatch !== null) { + const calendar = resolveCalendar(account, eventItemMatch[1] ?? ""); + if (calendar === undefined) return googleError(404, "NOT_FOUND", "Calendar not found"); + const eventId = decodeURIComponent(eventItemMatch[2] ?? ""); + return handleCalendarEventItem(account, calendar, eventId, method, headers, body); + } + return undefined; +} + +function armFaultsInto(armory: FaultArmory, payload: Record): void { + if (asBoolean(payload.clear) === true) { + armory.clear(); + return; + } + const rawRules = Array.isArray(payload.rules) ? payload.rules : [payload]; + for (const rawRule of rawRules) { + const rec = asRecord(rawRule); + if (rec === undefined) continue; + armory.arm({ + method: asString(rec.method), + path: asString(rec.path) ?? "*", + status: asNumber(rec.status) ?? 503, + retryAfter: asNumber(rec.retryAfter ?? rec.retry_after), + body: rec.body, + remaining: asNumber(rec.remaining ?? rec.count) ?? 1, + }); + } +} + +function snapshotAccounts(runtime: FakeRuntime) { + return [...runtime.accounts.values()].map((account) => ({ + email: account.email, + subject: account.subject, + messageCount: account.messages.size, + draftCount: account.drafts.size, + calendarCount: account.calendars.size, + eventCount: [...account.events.values()].reduce((sum, map) => sum + map.size, 0), + })); +} + +function handleControlRoutes( + runtime: FakeRuntime, + resetRuntime: () => FakeRuntime, + method: string, + pathname: string, + body: string, +): GmailAnswer | undefined { + if (pathname === "/__control/fault" && method === "POST") { + const parsed = parseJsonBody(body) ?? {}; + armFaultsInto(runtime.faults, parsed); + return json(200, { ok: true, armed: runtime.faults.list() }); + } + if (pathname === "/__control/fault" && method === "GET") { + return json(200, { ok: true, armed: runtime.faults.list() }); + } + if (pathname === "/__control/reset" && method === "POST") { + const next = resetRuntime(); + return json(200, { ok: true, reset: true, accounts: snapshotAccounts(next) }); + } + if (pathname === "/__control/state" && method === "GET") { + return json(200, { ok: true, accounts: snapshotAccounts(runtime) }); + } + if (pathname === "/__control/revoke" && method === "POST") { + const parsed = parseJsonBody(body) ?? {}; + const email = asString(parsed.email)?.toLowerCase(); + const token = asString(parsed.token); + let revoked = 0; + for (const [key, grant] of [...runtime.accessTokens.entries()]) { + if (token !== undefined && key !== token) continue; + if (email !== undefined && grant.email.toLowerCase() !== email) continue; + runtime.accessTokens.delete(key); + revoked += 1; + } + for (const [key, grant] of [...runtime.refreshTokens.entries()]) { + if (token !== undefined && key !== token) continue; + if (email !== undefined && grant.email.toLowerCase() !== email) continue; + runtime.refreshTokens.delete(key); + revoked += 1; + } + return json(200, { ok: true, revoked }); + } + return undefined; +} + +function handleTokenEndpoint(runtime: FakeRuntime, clientSecret: string, body: string): GmailAnswer { + const form = new URLSearchParams(body); + if (form.get("client_secret") !== clientSecret) return json(401, { error: "invalid_client" }); + const grantType = form.get("grant_type"); + if (grantType === "authorization_code") { + const code = form.get("code") ?? ""; + const consent = runtime.consents.get(code); + if (consent === undefined) return json(400, { error: "invalid_grant" }); + runtime.consents.delete(code); + if (form.get("client_id") !== consent.clientId) return json(401, { error: "invalid_client" }); + if (form.get("redirect_uri") !== consent.redirectUri || !verifyPkceS256(form.get("code_verifier") ?? "", consent.challenge)) { + return json(400, { error: "invalid_grant" }); + } + const grant: Grant = { email: consent.email, subject: consent.subject, scopes: consent.scopes, clientId: consent.clientId }; + const accessToken = randomToken("qa_goog_at_", 18); + const refreshToken = randomToken("qa_goog_rt_", 18); + runtime.accessTokens.set(accessToken, grant); + runtime.refreshTokens.set(refreshToken, grant); + return json(200, { + access_token: accessToken, + token_type: "Bearer", + expires_in: 3600, + scope: consent.scopes.join(" "), + refresh_token: refreshToken, + }); + } + if (grantType === "refresh_token") { + const refreshToken = form.get("refresh_token") ?? ""; + const grant = runtime.refreshTokens.get(refreshToken); + if (grant === undefined || form.get("client_id") !== grant.clientId) { + return json(400, { error: "invalid_grant", error_description: "Token has been expired or revoked." }); + } + const accessToken = randomToken("qa_goog_at_", 18); + runtime.accessTokens.set(accessToken, grant); + return json(200, { + access_token: accessToken, + token_type: "Bearer", + expires_in: 3600, + scope: grant.scopes.join(" "), + }); + } + return json(400, { error: "unsupported_grant_type" }); +} + /** - * Google OAuth2 + Gmail API as the local cloud's `managedGoogle` provider calls it, faked once at that network - * boundary: `/accounts`, `/token`, `/revoke`, `/oauth2/v2/userinfo`, and `/gmail/v1/users/me/*`, answering from `seed`. + * Multi-account Google OAuth2 + Gmail + Calendar v3 API emulator at the HTTP wire boundary: + * `/accounts`, `/token`, `/revoke`, `/jwks`, `/oauth2/v2/userinfo`, `/gmail/v1/users/me/*`, + * `/calendar/v3/*`, and `/__control/{fault,reset,state,revoke}`. */ export function googleGmailFake(seed: GmailSeed, clientSecret: string) { - const consents = new Map(); - const accessTokens = new Map(); - const refreshTokens = new Map(); - const historyId = "1001"; - const byId = new Map(seed.messages.map((message) => [message.id, message])); + let runtime = createRuntime(seed); + const resetRuntime = (): FakeRuntime => { + runtime = createRuntime(seed); + return runtime; + }; const bearerGrant = (headers: IncomingHttpHeaders): Grant | undefined => { const auth = typeof headers.authorization === "string" ? headers.authorization : ""; const matched = /^Bearer (\S+)$/.exec(auth); - return matched === null ? undefined : accessTokens.get(matched[1] ?? ""); + return matched === null ? undefined : runtime.accessTokens.get(matched[1] ?? ""); }; return (method: string, url: URL, headers: IncomingHttpHeaders, body: string): GmailAnswer | undefined => { + if (url.pathname.startsWith("/__control/")) { + return handleControlRoutes(runtime, resetRuntime, method, url.pathname, body); + } + + const injected = runtime.faults.consume(method, url.pathname); + if (injected !== undefined) { + return buildFaultAnswer(url.pathname, injected); + } + if (method === "GET" && url.pathname === "/accounts" && url.searchParams.get("access_type") === "offline") { const redirectUri = url.searchParams.get("redirect_uri") ?? ""; const state = url.searchParams.get("state") ?? ""; const code = randomToken("", 16); const scopes = (url.searchParams.get("scope") ?? "").split(/\s+/).filter(Boolean); const emailHeader = typeof headers["x-qa-google-email"] === "string" ? headers["x-qa-google-email"].trim() : ""; - const email = emailHeader === "" ? seed.email : emailHeader; - const subject = email === seed.email ? seed.subject : `qa-google-${createHash("sha256").update(email).digest("hex").slice(0, 12)}`; - consents.set(code, { - email, - subject, + const loginHint = (url.searchParams.get("login_hint") ?? "").trim(); + const email = emailHeader !== "" ? emailHeader : loginHint !== "" ? loginHint : seed.email; + const account = getOrCreateAccount(runtime, email); + runtime.consents.set(code, { + email: account.email, + subject: account.subject, scopes, clientId: url.searchParams.get("client_id") ?? "", redirectUri, @@ -334,52 +1518,14 @@ export function googleGmailFake(seed: GmailSeed, clientSecret: string) { } if (method === "POST" && url.pathname === "/token") { - const form = new URLSearchParams(body); - if (form.get("client_secret") !== clientSecret) return json(401, { error: "invalid_client" }); - const grantType = form.get("grant_type"); - if (grantType === "authorization_code") { - const code = form.get("code") ?? ""; - const consent = consents.get(code); - if (consent === undefined) return json(400, { error: "invalid_grant" }); - consents.delete(code); - if (form.get("client_id") !== consent.clientId) return json(401, { error: "invalid_client" }); - if (form.get("redirect_uri") !== consent.redirectUri || !verifyPkceS256(form.get("code_verifier") ?? "", consent.challenge)) { - return json(400, { error: "invalid_grant" }); - } - const grant: Grant = { email: consent.email, subject: consent.subject, scopes: consent.scopes, clientId: consent.clientId }; - const accessToken = randomToken("qa_goog_at_", 18); - const refreshToken = randomToken("qa_goog_rt_", 18); - accessTokens.set(accessToken, grant); - refreshTokens.set(refreshToken, grant); - return json(200, { - access_token: accessToken, - token_type: "Bearer", - expires_in: 3600, - scope: consent.scopes.join(" "), - refresh_token: refreshToken, - }); - } - if (grantType === "refresh_token") { - const refreshToken = form.get("refresh_token") ?? ""; - const grant = refreshTokens.get(refreshToken); - if (grant === undefined || form.get("client_id") !== grant.clientId) return json(400, { error: "invalid_grant" }); - const accessToken = randomToken("qa_goog_at_", 18); - accessTokens.set(accessToken, grant); - return json(200, { - access_token: accessToken, - token_type: "Bearer", - expires_in: 3600, - scope: grant.scopes.join(" "), - }); - } - return json(400, { error: "unsupported_grant_type" }); + return handleTokenEndpoint(runtime, clientSecret, body); } if (method === "POST" && url.pathname === "/revoke") { const form = new URLSearchParams(body); const token = form.get("token") ?? ""; - accessTokens.delete(token); - refreshTokens.delete(token); + runtime.accessTokens.delete(token); + runtime.refreshTokens.delete(token); return json(200, {}); } @@ -389,68 +1535,70 @@ export function googleGmailFake(seed: GmailSeed, clientSecret: string) { if (method === "GET" && url.pathname === "/oauth2/v2/userinfo") { const grant = bearerGrant(headers); - if (grant === undefined) return json(401, { error: { code: 401, status: "UNAUTHENTICATED" } }); - return json(200, { id: grant.subject, email: grant.email, verified_email: true, name: "Alpha Owner" }); - } - - const prefix = "/gmail/v1/users/me"; - if (!url.pathname.startsWith(`${prefix}/`)) return undefined; - const grant = bearerGrant(headers); - if (grant === undefined) return json(401, { error: { code: 401, status: "UNAUTHENTICATED" } }); - const rest = url.pathname.slice(prefix.length); - - if (method === "GET" && rest === "/profile") { - return json(200, { emailAddress: grant.email, historyId }); - } - - if (method === "GET" && rest === "/history") { - return json(200, { historyId }); + if (grant === undefined) return googleError(401, "UNAUTHENTICATED", "Request had invalid authentication credentials."); + const account = getOrCreateAccount(runtime, grant.email); + return json(200, { id: account.subject, email: account.email, verified_email: true, name: account.name }); } - if (method === "GET" && rest === "/messages") { - const now = Date.now(); - const rows = seed.messages - .filter((message) => !message.labels.includes("DRAFT") && matchesQuery(message, url.searchParams, now)) - .toSorted((left, right) => right.receivedAt - left.receivedAt); - const maxResults = Math.max(1, Math.min(100, Number(url.searchParams.get("maxResults") ?? "100") || 100)); - const offset = Math.max(0, Number(url.searchParams.get("pageToken") ?? "0") || 0); - const page = rows.slice(offset, offset + maxResults); - const next = offset + maxResults < rows.length ? String(offset + maxResults) : undefined; - return json(200, { - messages: page.map((message) => ({ id: message.id, threadId: message.threadId })), - resultSizeEstimate: rows.length, - ...(next === undefined ? {} : { nextPageToken: next }), - }); + const gmailPrefix = "/gmail/v1/users/me"; + if (url.pathname.startsWith(`${gmailPrefix}/`)) { + const grant = bearerGrant(headers); + if (grant === undefined) return googleError(401, "UNAUTHENTICATED", "Request had invalid authentication credentials."); + const account = getOrCreateAccount(runtime, grant.email); + return handleGmailRoutes(account, method, url.pathname.slice(gmailPrefix.length), url, body); } - const messageMatch = /^\/messages\/([A-Za-z0-9_-]+)$/.exec(rest); - if (method === "GET" && messageMatch !== null) { - const message = byId.get(messageMatch[1] ?? ""); - if (message === undefined) return json(404, { error: { code: 404, status: "NOT_FOUND" } }); - const format = url.searchParams.get("format") ?? "full"; - return json(200, shown(message, historyId, format, url.searchParams.getAll("metadataHeaders"))); + const calendarPrefix = "/calendar/v3"; + if (url.pathname.startsWith(`${calendarPrefix}/`)) { + const grant = bearerGrant(headers); + if (grant === undefined) return googleError(401, "UNAUTHENTICATED", "Request had invalid authentication credentials."); + const account = getOrCreateAccount(runtime, grant.email); + return handleCalendarRoutes(account, method, url.pathname.slice(calendarPrefix.length), url, headers, body); } - const threadMatch = /^\/threads\/([A-Za-z0-9_-]+)$/.exec(rest); - if (method === "GET" && threadMatch !== null) { - const messages = seed.messages.filter((message) => message.threadId === threadMatch[1]); - if (messages.length === 0) return json(404, { error: { code: 404, status: "NOT_FOUND" } }); - const format = url.searchParams.get("format") ?? "full"; - return json(200, { - id: threadMatch[1], - historyId, - messages: messages.map((message) => shown(message, historyId, format, url.searchParams.getAll("metadataHeaders"))), - }); - } + return undefined; + }; +} - if (method === "GET" && rest === "/drafts") { - return json(200, { drafts: [] }); - } +function writeAnswer(res: ServerResponse, answer: GmailAnswer | undefined): void { + if (answer === undefined) { + sendJson(res, 404, { error: { code: 404, message: "Not Found", status: "NOT_FOUND" } }); + return; + } + if (answer.location !== undefined) { + sendRedirect(res, answer.location, answer.headers, answer.status); + return; + } + sendBytes(res, answer.status, answer.body, answer.type, answer.headers); +} - if (method === "GET" && /^\/drafts\/([A-Za-z0-9_-]+)$/.test(rest)) { - return json(404, { error: { code: 404, status: "NOT_FOUND" } }); - } +interface GoogleServerState { + handler: ReturnType; +} - return undefined; - }; +/** Start a standalone loopback HTTP server for multi-account Google OAuth2 + Gmail + Calendar v3 with fault injection. */ +export async function startGoogleProvider(options?: GoogleProviderOptions): Promise { + const seed = options?.seed ?? qaGmail(); + const clientSecret = options?.clientSecret ?? "qa-google-secret"; + return createProviderServer({ + options, + createInitial: () => ({ handler: googleGmailFake(seed, clientSecret) }), + serializeState: (state) => { + const answer = state.handler("GET", new URL("http://127.0.0.1/__control/state"), {}, ""); + return answer === undefined ? {} : (JSON.parse(Buffer.from(answer.body).toString("utf8")) as unknown); + }, + defaultFaultBody: (fault) => defaultGoogleFaultBody(fault.path, fault), + onControl: (req: ParsedRequest, res: ServerResponse, ctx) => { + if (req.pathname === "/__control/revoke" && req.method === "POST") { + const answer = ctx.getState().handler(req.method, req.url, req.headers, req.rawBody); + writeAnswer(res, answer); + return true; + } + return false; + }, + onRequest: (req: ParsedRequest, res: ServerResponse, ctx) => { + const answer = ctx.getState().handler(req.method, req.url, req.headers, req.rawBody); + writeAnswer(res, answer); + }, + }); } diff --git a/packages/eliza-harness/src/providers/shared.ts b/packages/eliza-harness/src/providers/shared.ts index 4bc35f07b1..0cdfc5bc79 100644 --- a/packages/eliza-harness/src/providers/shared.ts +++ b/packages/eliza-harness/src/providers/shared.ts @@ -1,7 +1,7 @@ import type { ServerResponse } from "node:http"; import { type EmulatorOptions, - type FaultArmory, + FaultArmory, type FaultRule, type ParsedRequest, type RecordedRequest, @@ -9,6 +9,7 @@ import { type SseHub, asBoolean, asNumber, + asRecord, asString, asStringArray, bearerToken, @@ -18,6 +19,7 @@ import { paginateSlice, pruneRecordCap, randomToken, + sendBytes, sendHtml, sendJson, sendRedirect, @@ -25,11 +27,13 @@ import { } from "vibestack/emulate"; export { + FaultArmory, type FaultRule, type ParsedRequest, type RecordedRequest, asBoolean, asNumber, + asRecord, asString, asStringArray, bearerToken, @@ -38,6 +42,7 @@ export { paginateSlice, pruneRecordCap, randomToken, + sendBytes, sendHtml, sendJson, sendRedirect, @@ -45,7 +50,7 @@ export { }; /** Startup configuration shared by standalone HTTP provider servers. */ -export type ProviderOptions = Pick; +export type ProviderOptions = Pick; /** Running loopback HTTP+SSE provider server handle. */ export interface RunningProvider { diff --git a/packages/eliza-harness/src/providers/slack-provider.ts b/packages/eliza-harness/src/providers/slack-provider.ts index d2a4d8989a..bed6ea89db 100644 --- a/packages/eliza-harness/src/providers/slack-provider.ts +++ b/packages/eliza-harness/src/providers/slack-provider.ts @@ -7,6 +7,7 @@ import { type RunningProvider, asBoolean, asNumber, + asRecord, asString, asStringArray, bearerToken, @@ -16,6 +17,7 @@ import { paginateSlice, pruneRecordCap, randomToken, + sendBytes, sendHtml, sendJson, sendRedirect, @@ -42,6 +44,24 @@ export interface SlackReaction { count: number; } +/** Uploaded file attachment record attached to a Slack message. */ +export interface SlackFile { + readonly id: string; + readonly created: number; + readonly timestamp: number; + readonly name: string; + readonly title: string; + readonly mimetype: string; + readonly filetype: string; + readonly size: number; + readonly user: string; + readonly url_private: string; + readonly url_private_download: string; + readonly permalink: string; + readonly channels: readonly string[]; + readonly alt_txt?: string; +} + /** Slack stored message record. */ export interface SlackMessage { readonly type: "message"; @@ -57,6 +77,7 @@ export interface SlackMessage { reactions: SlackReaction[]; edited?: { readonly user: string; readonly ts: string }; readonly subtype?: string; + readonly files?: readonly SlackFile[]; } /** Slack conversation (public/private channel, DM, or MPIM). */ @@ -110,13 +131,37 @@ interface SlackUserToken { revoked: boolean; } +interface SlackPendingUpload { + readonly id: string; + readonly team_id: string; + readonly user_id: string; + readonly filename: string; + readonly declaredLength: number; + readonly alt_txt?: string; + readonly snippet_type?: string; + uploaded: boolean; + completed: boolean; + actualLength: number; + mimetype: string; + contentBase64?: string; +} + +interface SlackStoredFile { + readonly team_id: string; + readonly file: SlackFile; + readonly contentBase64: string; +} + interface SlackState { eventSeq: number; tsCounter: number; + fileSeq: number; readonly workspaces: Record; readonly authCodes: Record; readonly tokens: Record; readonly idempotency: Record; + readonly uploads: Record; + readonly files: Record; } interface ResolvedAuth { @@ -137,6 +182,8 @@ const DEFAULT_USER_SCOPES = [ "mpim:history", "mpim:write", "chat:write", + "files:read", + "files:write", "reactions:read", "reactions:write", "search:read", @@ -147,12 +194,14 @@ const DEFAULT_USER_SCOPES = [ const APP_ID = "A01ALPHA"; const MAX_IDEMPOTENCY = 500; const MAX_AUTH_CODES = 500; +const MAX_UPLOADS = 500; +const MAX_SLACK_UPLOAD_BYTES = 8 * 1024 * 1024; function makeMessage( ts: string, user: string, text: string, - extra?: Partial>, + extra?: Partial>, ): SlackMessage { return { type: "message", @@ -164,6 +213,7 @@ function makeMessage( ...(extra?.reply_broadcast !== undefined ? { reply_broadcast: extra.reply_broadcast } : {}), ...(extra?.edited !== undefined ? { edited: extra.edited } : {}), ...(extra?.subtype !== undefined ? { subtype: extra.subtype } : {}), + ...(extra?.files !== undefined && extra.files.length > 0 ? { files: extra.files } : {}), }; } @@ -405,6 +455,7 @@ function createInitialSlackState(): SlackState { return { eventSeq: 0, tsCounter: 1000, + fileSeq: 0, workspaces: { [alpha.id]: alpha, [design.id]: design, @@ -429,6 +480,8 @@ function createInitialSlackState(): SlackState { }, }, idempotency: {}, + uploads: {}, + files: {}, }; } @@ -788,12 +841,14 @@ function appendSlackMessage( threadTs: string | undefined, replyBroadcast: boolean | undefined, advanceRead: boolean, + files?: readonly SlackFile[], ): SlackMessage { const state = ctx.getState(); const ts = nextSlackTs(state); const message = makeMessage(ts, userId, text, { ...(threadTs ? { thread_ts: threadTs } : {}), ...(threadTs && replyBroadcast ? { reply_broadcast: true } : {}), + ...(files !== undefined && files.length > 0 ? { files } : {}), }); channel.messages.push(message); if (threadTs) { @@ -810,6 +865,7 @@ function appendSlackMessage( ts, ...(threadTs ? { thread_ts: threadTs } : {}), ...(threadTs && replyBroadcast ? { reply_broadcast: true } : {}), + ...(files !== undefined && files.length > 0 ? { files } : {}), }); return message; } @@ -1179,7 +1235,8 @@ function handleSearchMessages(req: ParsedRequest, res: ServerResponse, auth: Res ) { continue; } - const lower = msg.text.toLowerCase(); + const fileText = (msg.files ?? []).map((item) => `${item.name} ${item.title}`).join(" "); + const lower = `${msg.text} ${fileText}`.toLowerCase(); if (!textTerms.every((term) => lower.includes(term))) continue; matches.push({ type: "message", @@ -1190,6 +1247,7 @@ function handleSearchMessages(req: ParsedRequest, res: ServerResponse, auth: Res channel: { id: channel.id, name: channel.name }, permalink: `${auth.workspace.url}archives/${channel.id}/p${msg.ts.replace(".", "")}`, ...(msg.thread_ts ? { thread_ts: msg.thread_ts } : {}), + ...(msg.files !== undefined && msg.files.length > 0 ? { files: msg.files } : {}), }); } } @@ -1327,7 +1385,277 @@ function handleSlackControl( return false; } +const MIME_BY_EXTENSION: Readonly> = { + png: "image/png", + jpg: "image/jpeg", + jpeg: "image/jpeg", + gif: "image/gif", + webp: "image/webp", + svg: "image/svg+xml", + pdf: "application/pdf", + txt: "text/plain", + md: "text/markdown", + json: "application/json", + csv: "text/csv", + wav: "audio/wav", + mp3: "audio/mpeg", + mp4: "video/mp4", +}; + +function inferFileMetadata(filename: string, headerType: string | undefined): { readonly filetype: string; readonly mimetype: string } { + const dot = filename.lastIndexOf("."); + const ext = dot >= 0 && dot < filename.length - 1 ? filename.slice(dot + 1).toLowerCase() : ""; + const filetype = ext !== "" ? ext : "bin"; + const cleanedHeader = headerType?.split(";")[0]?.trim().toLowerCase(); + if ( + cleanedHeader !== undefined && + cleanedHeader !== "" && + cleanedHeader !== "application/octet-stream" && + !cleanedHeader.startsWith("multipart/") + ) { + return { filetype, mimetype: cleanedHeader }; + } + const fromExt = ownGet(MIME_BY_EXTENSION, ext); + return { filetype, mimetype: fromExt ?? "application/octet-stream" }; +} + +function extractUploadBytes(req: ParsedRequest): { readonly bytes: Buffer; readonly partContentType?: string } { + const contentType = req.headers["content-type"] ?? ""; + const boundaryMatch = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType); + if (!contentType.toLowerCase().includes("multipart/form-data") || boundaryMatch === null) { + return { bytes: req.rawBytes, partContentType: contentType || undefined }; + } + const boundary = boundaryMatch[1] ?? boundaryMatch[2] ?? ""; + if (boundary === "") return { bytes: req.rawBytes }; + const delimiter = Buffer.from(`--${boundary}`); + const headerSep = Buffer.from("\r\n\r\n"); + let offset = req.rawBytes.indexOf(delimiter); + while (offset >= 0) { + const partStart = offset + delimiter.byteLength; + if (req.rawBytes.subarray(partStart, partStart + 2).toString("ascii") === "--") break; + const nextDelimiter = req.rawBytes.indexOf(delimiter, partStart); + if (nextDelimiter < 0) break; + const part = req.rawBytes.subarray(partStart, nextDelimiter); + const sepIndex = part.indexOf(headerSep); + if (sepIndex >= 0) { + const headersText = part.subarray(0, sepIndex).toString("utf8"); + if (/filename=/i.test(headersText) || /name="file"/i.test(headersText)) { + let payload = part.subarray(sepIndex + headerSep.byteLength); + if (payload.byteLength >= 2 && payload[payload.byteLength - 2] === 13 && payload[payload.byteLength - 1] === 10) { + payload = payload.subarray(0, payload.byteLength - 2); + } + const ctMatch = /content-type:\s*([^\r\n]+)/i.exec(headersText); + return { bytes: Buffer.from(payload), partContentType: ctMatch?.[1]?.trim() }; + } + } + offset = nextDelimiter; + } + return { bytes: req.rawBytes }; +} + +function requestOrigin(req: ParsedRequest): string { + const host = req.headers.host; + if (host !== undefined && host.trim() !== "") return `http://${host.trim()}`; + return req.url.origin; +} + +function handleGetUploadUrlExternal( + req: ParsedRequest, + res: ServerResponse, + auth: ResolvedAuth, + ctx: ProviderContext, +): void { + const filename = asString(req.params.filename)?.trim(); + const length = asNumber(req.params.length); + if (!filename) { + sendJson(res, 200, { ok: false, error: "invalid_arguments" }); + return; + } + if (length === undefined || !Number.isFinite(length) || length <= 0) { + sendJson(res, 200, { ok: false, error: "invalid_arguments" }); + return; + } + const state = ctx.getState(); + state.fileSeq += 1; + const fileId = `F01${String(state.fileSeq).padStart(7, "0")}`; + const { mimetype } = inferFileMetadata(filename, undefined); + state.uploads[fileId] = { + id: fileId, + team_id: auth.workspace.id, + user_id: auth.userId, + filename, + declaredLength: Math.floor(length), + ...(asString(req.params.alt_txt) !== undefined ? { alt_txt: asString(req.params.alt_txt) } : {}), + ...(asString(req.params.snippet_type) !== undefined ? { snippet_type: asString(req.params.snippet_type) } : {}), + uploaded: false, + completed: false, + actualLength: 0, + mimetype, + }; + pruneRecordCap(state.uploads, MAX_UPLOADS); + ctx.save(); + sendJson(res, 200, { + ok: true, + upload_url: `${requestOrigin(req)}/__upload/${fileId}`, + file_id: fileId, + }); +} + +function handleExternalUploadSink( + req: ParsedRequest, + res: ServerResponse, + ctx: ProviderContext, + fileId: string, +): void { + const state = ctx.getState(); + const pending = ownGet(state.uploads, fileId); + if (!pending) { + sendJson(res, 404, { ok: false, error: "file_not_found" }); + return; + } + if (pending.completed) { + sendJson(res, 409, { ok: false, error: "file_already_completed" }); + return; + } + const { bytes, partContentType } = extractUploadBytes(req); + if (bytes.byteLength === 0) { + sendJson(res, 400, { ok: false, error: "empty_upload" }); + return; + } + const { mimetype } = inferFileMetadata(pending.filename, partContentType); + pending.uploaded = true; + pending.actualLength = bytes.byteLength; + pending.mimetype = mimetype; + pending.contentBase64 = bytes.toString("base64"); + ctx.save(); + sendBytes(res, 200, Buffer.from(`OK - ${bytes.byteLength}`, "utf8"), "text/plain; charset=utf-8"); +} + +function parseCompletionFiles(raw: unknown): readonly { readonly id: string; readonly title?: string }[] | undefined { + let decoded: unknown = raw; + if (typeof raw === "string") { + try { + decoded = JSON.parse(raw) as unknown; + } catch { + return undefined; + } + } + if (!Array.isArray(decoded) || decoded.length === 0) return undefined; + const items: { readonly id: string; readonly title?: string }[] = []; + for (const entry of decoded) { + const rec = asRecord(entry); + const id = asString(rec?.id)?.trim(); + if (!id) return undefined; + const title = asString(rec?.title); + items.push({ id, ...(title !== undefined ? { title } : {}) }); + } + return items; +} + +function handleCompleteUploadExternal( + req: ParsedRequest, + res: ServerResponse, + auth: ResolvedAuth, + ctx: ProviderContext, +): void { + const requested = parseCompletionFiles(req.params.files); + if (requested === undefined) { + sendJson(res, 200, { ok: false, error: "invalid_arguments" }); + return; + } + const channelParam = asString(req.params.channel_id) ?? asString(req.params.channels)?.split(",")[0]?.trim(); + let channel: SlackChannel | undefined; + if (channelParam !== undefined && channelParam !== "") { + channel = ownGet(auth.workspace.channels, channelParam); + if (!channel || !canAccessChannel(channel, auth.userId)) { + sendJson(res, 200, { ok: false, error: "channel_not_found" }); + return; + } + } + const threadTs = asString(req.params.thread_ts); + if (threadTs !== undefined && channel !== undefined && !channel.messages.some((item) => item.ts === threadTs)) { + sendJson(res, 200, { ok: false, error: "thread_not_found" }); + return; + } + const state = ctx.getState(); + const pendingList: { readonly pending: SlackPendingUpload; readonly title?: string }[] = []; + for (const spec of requested) { + const pending = ownGet(state.uploads, spec.id); + if (!pending || pending.team_id !== auth.workspace.id) { + sendJson(res, 200, { ok: false, error: "file_not_found" }); + return; + } + if (!pending.uploaded || pending.contentBase64 === undefined) { + sendJson(res, 200, { ok: false, error: "file_not_uploaded" }); + return; + } + if (pending.completed) { + sendJson(res, 200, { ok: false, error: "file_already_completed" }); + return; + } + pendingList.push({ pending, title: spec.title }); + } + + const origin = requestOrigin(req); + const nowSec = Math.floor(Date.now() / 1000); + const completedFiles: SlackFile[] = []; + for (const { pending, title } of pendingList) { + const { filetype } = inferFileMetadata(pending.filename, pending.mimetype); + const file: SlackFile = { + id: pending.id, + created: nowSec, + timestamp: nowSec, + name: pending.filename, + title: title ?? pending.filename, + mimetype: pending.mimetype, + filetype, + size: pending.actualLength, + user: auth.userId, + url_private: `${origin}/__files/${pending.id}`, + url_private_download: `${origin}/__files/${pending.id}?download=1`, + permalink: `${auth.workspace.url}files/${auth.userId}/${pending.id}/${encodeURIComponent(pending.filename)}`, + channels: channel ? [channel.id] : [], + ...(pending.alt_txt !== undefined ? { alt_txt: pending.alt_txt } : {}), + }; + pending.completed = true; + state.files[pending.id] = { + team_id: auth.workspace.id, + file, + contentBase64: pending.contentBase64 ?? "", + }; + completedFiles.push(file); + } + pruneRecordCap(state.files, MAX_UPLOADS); + if (channel) { + const initialComment = asString(req.params.initial_comment) ?? ""; + appendSlackMessage(ctx, auth.workspace, channel, auth.userId, initialComment, threadTs, undefined, true, completedFiles); + } else { + ctx.save(); + } + sendJson(res, 200, { ok: true, files: completedFiles }); +} + +function handleFileDownload( + res: ServerResponse, + auth: ResolvedAuth, + state: SlackState, + fileId: string, +): void { + const stored = ownGet(state.files, fileId); + if (!stored || stored.team_id !== auth.workspace.id) { + sendJson(res, 404, { ok: false, error: "file_not_found" }); + return; + } + const bytes = Buffer.from(stored.contentBase64, "base64"); + sendBytes(res, 200, bytes, stored.file.mimetype); +} + function handleSlackApi(req: ParsedRequest, res: ServerResponse, ctx: ProviderContext): void { + const uploadMatch = /^\/__upload\/([A-Za-z0-9_-]+)$/.exec(req.pathname); + if (uploadMatch !== null && (req.method === "POST" || req.method === "PUT")) { + handleExternalUploadSink(req, res, ctx, uploadMatch[1] ?? ""); + return; + } if (req.pathname === "/.well-known/alpha-slack" && req.method === "GET") { sendJson(res, 200, { clientId: "123.456", notifications: true }); return; @@ -1356,6 +1684,12 @@ function handleSlackApi(req: ParsedRequest, res: ServerResponse, ctx: ProviderCo const auth = resolveSlackAuth(req, res, state); if (!auth) return; + const downloadMatch = /^\/__files\/([A-Za-z0-9_-]+)$/.exec(req.pathname); + if (downloadMatch !== null && req.method === "GET") { + handleFileDownload(res, auth, state, downloadMatch[1] ?? ""); + return; + } + switch (req.pathname) { case "/api/slack/events/read": { const cursor = asNumber(req.params.cursor) ?? state.eventSeq; @@ -1443,6 +1777,12 @@ function handleSlackApi(req: ParsedRequest, res: ServerResponse, ctx: ProviderCo case "/api/reactions.remove": handleReaction(req, res, auth, ctx, "remove"); return; + case "/api/files.getUploadURLExternal": + handleGetUploadUrlExternal(req, res, auth, ctx); + return; + case "/api/files.completeUploadExternal": + handleCompleteUploadExternal(req, res, auth, ctx); + return; case "/api/search.messages": handleSearchMessages(req, res, auth); return; @@ -1482,7 +1822,7 @@ function defaultSlackFaultBody(fault: FaultRule): unknown { /** Start a stateful, wire-faithful Slack OAuth2 v2 User Token (`xoxp-`) + Web API + SSE provider server. */ export async function startSlackProvider(options?: ProviderOptions): Promise { return createProviderServer({ - options, + options: { maxBodyBytes: MAX_SLACK_UPLOAD_BYTES, ...options }, createInitial: createInitialSlackState, preflightHeaders: (path) => /^\/api\/[a-zA-Z]+\.[a-zA-Z.]+$/.test(path) ? "x-slack-version-ts" : undefined, defaultFaultBody: defaultSlackFaultBody, diff --git a/packages/eliza-harness/test/providers.test.ts b/packages/eliza-harness/test/providers.test.ts index 95a35a6d06..15855507c2 100644 --- a/packages/eliza-harness/test/providers.test.ts +++ b/packages/eliza-harness/test/providers.test.ts @@ -10,10 +10,14 @@ import { } from "vibestack/emulate"; import { DEFAULT_CARTESIA_VOICE_ID, + type GmailSeed, type RunningCartesiaVoiceProvider, type RunningProvider, + type SlackFile, + type SlackMessage, scratch, startCartesiaVoiceProvider, + startGoogleProvider, startSlackProvider, } from "../src/index.ts"; import { googleGmailFake, qaGmail } from "../src/providers/google-gmail.ts"; @@ -492,6 +496,162 @@ describe("Slack user-account HTTP+SSE provider", () => { ); expect(yesterdaySearch.json.messages.matches.map((item) => item.text)).not.toContain("Today direct ping from Maya"); }); + + it("supports Stage 2 V2 external file uploads into channels, threads, history, SSE, and binary downloads", async () => { + const alphaAuth = { authorization: "Bearer xoxp-alpha-team-owner-initial" }; + const designAuth = { authorization: "Bearer xoxp-design-guild-owner-initial" }; + const sse = await openSse(`${slack.origin}/alpha/slack/events`, alphaAuth); + + try { + const badArgs = await postJson<{ ok: boolean; error?: string }>( + `${slack.origin}/api/files.getUploadURLExternal`, + { filename: "", length: 0 }, + alphaAuth, + ); + expect(badArgs.json).toEqual({ ok: false, error: "invalid_arguments" }); + + const noteBytes = Buffer.from("quarterly launch report bytes"); + const getUrlRes = await fetch(`${slack.origin}/api/files.getUploadURLExternal`, { + method: "POST", + headers: { ...alphaAuth, "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ filename: "launch-report.txt", length: String(noteBytes.byteLength) }).toString(), + }); + const uploadMeta = (await getUrlRes.json()) as { ok: boolean; upload_url: string; file_id: string }; + expect(uploadMeta.ok).toBe(true); + expect(uploadMeta.file_id).toMatch(/^F01/); + expect(uploadMeta.upload_url).toBe(`${slack.origin}/__upload/${uploadMeta.file_id}`); + + const premature = await postJson<{ ok: boolean; error?: string }>( + `${slack.origin}/api/files.completeUploadExternal`, + { files: [{ id: uploadMeta.file_id }], channel_id: "C01GENERAL" }, + alphaAuth, + ); + expect(premature.json).toEqual({ ok: false, error: "file_not_uploaded" }); + + const emptyUpload = await fetch(uploadMeta.upload_url, { + method: "POST", + headers: { "content-type": "application/octet-stream" }, + body: Buffer.alloc(0), + }); + expect(emptyUpload.status).toBe(400); + + const uploadRes = await fetch(uploadMeta.upload_url, { + method: "POST", + headers: { "content-type": "text/plain" }, + body: noteBytes, + }); + expect(uploadRes.status).toBe(200); + expect(await uploadRes.text()).toBe(`OK - ${noteBytes.byteLength}`); + + const crossWorkspaceComplete = await postJson<{ ok: boolean; error?: string }>( + `${slack.origin}/api/files.completeUploadExternal`, + { files: [{ id: uploadMeta.file_id }], channel_id: "C11CRITIQUE" }, + designAuth, + ); + expect(crossWorkspaceComplete.json).toEqual({ ok: false, error: "file_not_found" }); + + const completeFormRes = await fetch(`${slack.origin}/api/files.completeUploadExternal`, { + method: "POST", + headers: { ...alphaAuth, "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + files: JSON.stringify([{ id: uploadMeta.file_id, title: "Launch Report" }]), + channel_id: "C01GENERAL", + initial_comment: "Attached the report.", + }).toString(), + }); + const completed = (await completeFormRes.json()) as { ok: boolean; files: SlackFile[] }; + expect(completed.ok).toBe(true); + expect(completed.files).toHaveLength(1); + expect(completed.files[0]).toMatchObject({ + id: uploadMeta.file_id, + name: "launch-report.txt", + title: "Launch Report", + mimetype: "text/plain", + filetype: "txt", + size: noteBytes.byteLength, + channels: ["C01GENERAL"], + }); + + const dupComplete = await postJson<{ ok: boolean; error?: string }>( + `${slack.origin}/api/files.completeUploadExternal`, + { files: [{ id: uploadMeta.file_id }], channel_id: "C01GENERAL" }, + alphaAuth, + ); + expect(dupComplete.json).toEqual({ ok: false, error: "file_already_completed" }); + + const event = await sse.nextEvent(); + const envelope = event.data as { event: { type: string; text: string; files?: SlackFile[] } }; + expect(envelope.event.type).toBe("message"); + expect(envelope.event.text).toBe("Attached the report."); + expect(envelope.event.files?.[0]?.id).toBe(uploadMeta.file_id); + + const history = await postJson<{ ok: boolean; messages: SlackMessage[] }>( + `${slack.origin}/api/conversations.history`, + { channel: "C01GENERAL", limit: 5 }, + alphaAuth, + ); + expect(history.json.ok).toBe(true); + expect(history.json.messages[0]?.files?.[0]?.id).toBe(uploadMeta.file_id); + + const downloadOk = await fetch(completed.files[0].url_private, { headers: alphaAuth }); + expect(downloadOk.status).toBe(200); + expect(downloadOk.headers.get("content-type")).toBe("text/plain"); + expect(Buffer.from(await downloadOk.arrayBuffer()).equals(noteBytes)).toBe(true); + + const downloadDenied = await fetch(completed.files[0].url_private, { headers: designAuth }); + expect(downloadDenied.status).toBe(404); + + const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x01]); + const threadMeta = await postJson<{ ok: boolean; upload_url: string; file_id: string }>( + `${slack.origin}/api/files.getUploadURLExternal`, + { filename: "diagram.png", length: pngBytes.byteLength }, + alphaAuth, + ); + expect(threadMeta.json.ok).toBe(true); + + const boundary = "alphaBoundary42"; + const multipartBody = Buffer.concat([ + Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="diagram.png"\r\nContent-Type: image/png\r\n\r\n`, "utf8"), + pngBytes, + Buffer.from(`\r\n--${boundary}--\r\n`, "utf8"), + ]); + const threadUpload = await fetch(threadMeta.json.upload_url, { + method: "POST", + headers: { "content-type": `multipart/form-data; boundary=${boundary}` }, + body: multipartBody, + }); + expect(threadUpload.status).toBe(200); + + const threadComplete = await postJson<{ ok: boolean; files: SlackFile[] }>( + `${slack.origin}/api/files.completeUploadExternal`, + { + files: [{ id: threadMeta.json.file_id, title: "Latency Diagram" }], + channel_id: "C01GENERAL", + thread_ts: "1730000100.000100", + initial_comment: "Added diagram in thread.", + }, + alphaAuth, + ); + expect(threadComplete.json.ok).toBe(true); + expect(threadComplete.json.files[0]).toMatchObject({ mimetype: "image/png", filetype: "png", size: pngBytes.byteLength }); + + const replies = await postJson<{ ok: boolean; messages: SlackMessage[] }>( + `${slack.origin}/api/conversations.replies`, + { channel: "C01GENERAL", ts: "1730000100.000100" }, + alphaAuth, + ); + expect(replies.json.ok).toBe(true); + const lastReply = replies.json.messages[replies.json.messages.length - 1]; + expect(lastReply?.text).toBe("Added diagram in thread."); + expect(lastReply?.files?.[0]?.id).toBe(threadMeta.json.file_id); + + const pngDownload = await fetch(threadComplete.json.files[0].url_private, { headers: alphaAuth }); + expect(pngDownload.status).toBe(200); + expect(Buffer.from(await pngDownload.arrayBuffer()).equals(pngBytes)).toBe(true); + } finally { + sse.close(); + } + }); }); describe("Provider persistence", () => { @@ -623,8 +783,306 @@ describe("Google OAuth + Gmail QA fake", () => { }).toString()); expect(refreshedRes?.status).toBe(200); }); + + it("isolates multi-account Gmail mailboxes, drafts, and sends over HTTP", async () => { + await withMultiGoogle(async ({ origin, personalAuth, workAuth }) => { + const personalInfo = (await (await fetch(`${origin}/oauth2/v2/userinfo`, { headers: personalAuth })).json()) as { id: string; email: string }; + const workInfo = (await (await fetch(`${origin}/oauth2/v2/userinfo`, { headers: workAuth })).json()) as { id: string; email: string }; + expect(personalInfo).toMatchObject({ id: "sub-personal", email: "personal@alpha.test" }); + expect(workInfo).toMatchObject({ id: "sub-work", email: "work@alpha.test" }); + + const workMsgs = (await (await fetch(`${origin}/gmail/v1/users/me/messages`, { headers: workAuth })).json()) as { messages: { id: string }[] }; + expect(workMsgs.messages.map((m) => m.id)).toEqual(["work-msg-1"]); + expect((await fetch(`${origin}/gmail/v1/users/me/messages/qa-msg-contract`, { headers: workAuth })).status).toBe(404); + expect((await fetch(`${origin}/gmail/v1/users/me/messages/work-msg-1`, { headers: personalAuth })).status).toBe(404); + + const rawDraft = Buffer.from( + "To: lena@ruiz.example\r\nSubject: Signed contract\r\nMessage-ID: \r\n\r\nAttached is the signed PDF.", + "utf8", + ).toString("base64url"); + const createdDraft = await postJson<{ id: string; message: { id: string } }>( + `${origin}/gmail/v1/users/me/drafts`, + { message: { raw: rawDraft } }, + personalAuth, + ); + expect(createdDraft.status).toBe(200); + + const personalDrafts = (await (await fetch(`${origin}/gmail/v1/users/me/drafts`, { headers: personalAuth })).json()) as { drafts: { id: string }[] }; + const workDrafts = (await (await fetch(`${origin}/gmail/v1/users/me/drafts`, { headers: workAuth })).json()) as { drafts: { id: string }[] }; + expect(personalDrafts.drafts.map((d) => d.id)).toEqual([createdDraft.json.id]); + expect(workDrafts.drafts).toEqual([]); + + const rawDraftRead = (await (await fetch(`${origin}/gmail/v1/users/me/drafts/${createdDraft.json.id}?format=raw`, { headers: personalAuth })).json()) as { + id: string; + message: { raw: string }; + }; + expect(rawDraftRead.message.raw).toBe(rawDraft); + + const sentDraft = await postJson<{ id: string; labelIds: string[] }>( + `${origin}/gmail/v1/users/me/drafts/send`, + { id: createdDraft.json.id }, + personalAuth, + ); + expect(sentDraft.status).toBe(200); + expect(sentDraft.json.labelIds).toEqual(["SENT"]); + expect((await fetch(`${origin}/gmail/v1/users/me/drafts/${createdDraft.json.id}`, { headers: personalAuth })).status).toBe(404); + + const directMime = Buffer.from("To: team@work.example\r\nSubject: Ship note\r\n\r\nRelease is live.", "utf8").toString("base64url"); + const directSent = await postJson<{ id: string; labelIds: string[] }>( + `${origin}/gmail/v1/users/me/messages/send`, + { raw: directMime }, + workAuth, + ); + expect(directSent.status).toBe(200); + const workSentList = (await (await fetch(`${origin}/gmail/v1/users/me/messages?q=in:sent`, { headers: workAuth })).json()) as { messages: { id: string }[] }; + expect(workSentList.messages.map((m) => m.id)).toEqual([directSent.json.id]); + const personalSentList = (await (await fetch(`${origin}/gmail/v1/users/me/messages?q=in:sent`, { headers: personalAuth })).json()) as { messages: { id: string }[] }; + expect(personalSentList.messages.map((m) => m.id)).toEqual([sentDraft.json.id]); + }); + }); + + it("supports stateful Google Calendar v3 CRUD, freeBusy, ETag checks, and FaultArmory 401/429 injection", async () => { + await withMultiGoogle(async ({ origin, secret, workTokens, personalAuth, workAuth }) => { + const workCalList = (await (await fetch(`${origin}/calendar/v3/users/me/calendarList`, { headers: workAuth })).json()) as { items: { id: string }[] }; + expect(workCalList.items.map((c) => c.id)).toEqual(["work@alpha.test", "team-oncall@work.example"]); + + const insertedEvent = await postJson<{ id: string; etag: string; summary: string }>( + `${origin}/calendar/v3/calendars/primary/events`, + { + id: "work-evt-deploy", + summary: "Deploy Window", + location: "War Room", + start: { dateTime: "2026-12-04T20:00:00.000Z" }, + end: { dateTime: "2026-12-04T21:00:00.000Z" }, + }, + workAuth, + ); + expect(insertedEvent.status).toBe(200); + expect(insertedEvent.json.id).toBe("work-evt-deploy"); + expect(insertedEvent.json.etag).toBe('"1"'); + + const dupEvent = await postJson( + `${origin}/calendar/v3/calendars/primary/events`, + { + id: "work-evt-deploy", + summary: "Duplicate", + start: { dateTime: "2026-12-04T20:00:00.000Z" }, + end: { dateTime: "2026-12-04T21:00:00.000Z" }, + }, + workAuth, + ); + expect(dupEvent.status).toBe(409); + + const personalEvents = (await (await fetch(`${origin}/calendar/v3/calendars/primary/events`, { headers: personalAuth })).json()) as { items: { id: string }[] }; + expect(personalEvents.items.some((ev) => ev.id === "work-evt-deploy")).toBe(false); + + const stalePatch = await fetch(`${origin}/calendar/v3/calendars/primary/events/work-evt-deploy`, { + method: "PATCH", + headers: { ...workAuth, "content-type": "application/json", "if-match": '"999"' }, + body: JSON.stringify({ summary: "Stale Update" }), + }); + expect(stalePatch.status).toBe(412); + + const patchedRes = await fetch(`${origin}/calendar/v3/calendars/primary/events/work-evt-deploy`, { + method: "PATCH", + headers: { ...workAuth, "content-type": "application/json", "if-match": insertedEvent.json.etag }, + body: JSON.stringify({ summary: "Deploy Window Updated" }), + }); + expect(patchedRes.status).toBe(200); + const patched = (await patchedRes.json()) as { summary: string; etag: string }; + expect(patched.summary).toBe("Deploy Window Updated"); + expect(patched.etag).toBe('"2"'); + + const freeBusy = await postJson<{ + calendars: Record; + }>( + `${origin}/calendar/v3/freeBusy`, + { + timeMin: "2026-12-04T17:00:00.000Z", + timeMax: "2026-12-04T22:00:00.000Z", + items: [{ id: "primary" }, { id: "missing@work.example" }], + }, + workAuth, + ); + expect(freeBusy.status).toBe(200); + expect(freeBusy.json.calendars["primary"]?.busy).toEqual([ + { start: "2026-12-04T18:00:00.000Z", end: "2026-12-04T19:00:00.000Z" }, + { start: "2026-12-04T20:00:00.000Z", end: "2026-12-04T21:00:00.000Z" }, + ]); + expect(freeBusy.json.calendars["missing@work.example"]?.errors?.[0]?.reason).toBe("notFound"); + + const deleted = await fetch(`${origin}/calendar/v3/calendars/primary/events/work-evt-deploy`, { + method: "DELETE", + headers: { ...workAuth, "if-match": patched.etag }, + }); + expect(deleted.status).toBe(204); + expect((await fetch(`${origin}/calendar/v3/calendars/primary/events/work-evt-deploy`, { headers: workAuth })).status).toBe(404); + const withDeleted = (await (await fetch(`${origin}/calendar/v3/calendars/primary/events?showDeleted=true`, { headers: workAuth })).json()) as { + items: { id: string; status: string }[]; + }; + expect(withDeleted.items.find((ev) => ev.id === "work-evt-deploy")?.status).toBe("cancelled"); + + await postJson(`${origin}/__control/fault`, { + method: "GET", + path: "/calendar/v3/calendars/primary/events", + status: 429, + retryAfter: 3, + remaining: 1, + }); + const rateLimited = await fetch(`${origin}/calendar/v3/calendars/primary/events`, { headers: workAuth }); + expect(rateLimited.status).toBe(429); + expect(rateLimited.headers.get("retry-after")).toBe("3"); + const recovered = await fetch(`${origin}/calendar/v3/calendars/primary/events`, { headers: workAuth }); + expect(recovered.status).toBe(200); + + await postJson(`${origin}/__control/fault`, { + method: "POST", + path: "/token", + status: 401, + remaining: 1, + }); + const expiredRefresh = await fetch(`${origin}/token`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "refresh_token", + refresh_token: workTokens.refresh_token, + client_id: "qa-google-client", + client_secret: secret, + }).toString(), + }); + expect(expiredRefresh.status).toBe(401); + expect((await expiredRefresh.json()) as { error: string }).toMatchObject({ error: "invalid_grant" }); + + const revoked = await postJson<{ ok: boolean; revoked: number }>( + `${origin}/__control/revoke`, + { email: "work@alpha.test" }, + ); + expect(revoked.json.ok).toBe(true); + expect(revoked.json.revoked).toBeGreaterThanOrEqual(2); + expect((await fetch(`${origin}/gmail/v1/users/me/profile`, { headers: workAuth })).status).toBe(401); + expect((await fetch(`${origin}/gmail/v1/users/me/profile`, { headers: personalAuth })).status).toBe(200); + }); + }); }); +interface MultiGoogleFixture { + readonly origin: string; + readonly secret: string; + readonly personalTokens: { readonly access_token: string; readonly refresh_token: string }; + readonly workTokens: { readonly access_token: string; readonly refresh_token: string }; + readonly personalAuth: Readonly>; + readonly workAuth: Readonly>; +} + +async function withMultiGoogle(run: (fixture: MultiGoogleFixture) => Promise): Promise { + const now = Date.parse("2026-12-04T15:00:00.000Z"); + const secret = "qa-multi-google-secret"; + const google = await startGoogleProvider({ seed: buildMultiGoogleSeed(now), clientSecret: secret }); + try { + const personalTokens = await completeGoogleOAuth(google.origin, secret, "personal@alpha.test", false); + const workTokens = await completeGoogleOAuth(google.origin, secret, "work@alpha.test", true); + await run({ + origin: google.origin, + secret, + personalTokens, + workTokens, + personalAuth: { authorization: `Bearer ${personalTokens.access_token}` }, + workAuth: { authorization: `Bearer ${workTokens.access_token}` }, + }); + } finally { + await google.stop(); + } +} + +function buildMultiGoogleSeed(now: number): GmailSeed { + return { + ...qaGmail(now, "personal@alpha.test"), + subject: "sub-personal", + name: "Personal Owner", + accounts: { + "work@alpha.test": { + email: "work@alpha.test", + subject: "sub-work", + name: "Work Owner", + messages: [ + { + id: "work-msg-1", + threadId: "work-thread-1", + from: "VP Eng ", + to: ["work@alpha.test"], + subject: "Q4 Architecture Review", + snippet: "Please review the Q4 roadmap before Thursday.", + bodyText: "Please review the Q4 roadmap before Thursday.", + labels: ["INBOX", "UNREAD"], + receivedAt: now - 60_000, + }, + ], + calendars: [ + { + id: "work@alpha.test", + summary: "Work Primary", + timeZone: "America/Los_Angeles", + primary: true, + accessRole: "owner", + }, + { + id: "team-oncall@work.example", + summary: "Team Oncall", + timeZone: "UTC", + accessRole: "reader", + }, + ], + events: [ + { + id: "work-evt-1", + calendarId: "work@alpha.test", + summary: "Q4 Planning", + start: { dateTime: "2026-12-04T18:00:00.000Z" }, + end: { dateTime: "2026-12-04T19:00:00.000Z" }, + }, + ], + }, + }, + }; +} + +async function completeGoogleOAuth(origin: string, secret: string, email: string, viaLoginHint: boolean) { + const verifier = `pkce-verifier-${email.replace(/[^a-z0-9]/gi, "")}-0123456789`; + const challenge = createHash("sha256").update(verifier, "ascii").digest("base64url"); + const params = new URLSearchParams({ + client_id: "qa-google-client", + redirect_uri: "http://127.0.0.1/oauth/google/callback", + response_type: "code", + state: `st-${email}`, + code_challenge: challenge, + code_challenge_method: "S256", + scope: "https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/calendar", + access_type: "offline", + ...(viaLoginHint ? { login_hint: email } : {}), + }); + const authz = await fetch(`${origin}/accounts?${params}`, { + redirect: "manual", + headers: viaLoginHint ? {} : { "x-qa-google-email": email }, + }); + expect(authz.status).toBe(302); + const code = new URL(authz.headers.get("location")!).searchParams.get("code")!; + const tokenRes = await fetch(`${origin}/token`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code, + client_id: "qa-google-client", + client_secret: secret, + redirect_uri: "http://127.0.0.1/oauth/google/callback", + code_verifier: verifier, + }).toString(), + }); + expect(tokenRes.status).toBe(200); + return (await tokenRes.json()) as { access_token: string; refresh_token: string }; +} + describe("Cartesia stateful HTTP+WebSocket voice emulator", () => { let cartesia: RunningCartesiaVoiceProvider;