Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Control plane: FCM beside APNs for the phone push relay, collapse ids, platform column (#5981)
Milind Sonif413f5217e5c
diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.mdindex 3f87a77017..ce07103d8f 100644--- a/cloudflare/control-plane/README.md+++ b/cloudflare/control-plane/README.md@@ -190,42 +190,58 @@ unbounded scheduled invocation.### Phone push relay-Closed-app alerts for the iOS app (harness side: `server/phone-push.ts`,-wire contract version 1 in `shared/phone-push.ts`; app side:-`docs/ios-companion.md`). Apple accepts pushes for an App Store or-TestFlight build only when they are signed with the publishing team's key, and-a harness may run on a VPS or in a container. So the project's key lives here,-and a harness asks this Worker to push with the installation credential it-already holds. Account bearer tokens are refused. All three routes take-`application/json` and answer with the usual `{ "error": "<code>" }` shape.--- `register` `{ "v": 1, "token": "<lowercase hex>", "environment": "production" | "sandbox" }`- stores the APNs device token for this installation (idempotent; it updates- the environment). At most 50 tokens per installation (`409- push_device_limit`) and 120 registrations per hour. An environment- `APNS_ENVIRONMENTS` does not list is `400 push_environment_not_allowed`.-- `unregister` `{ "v": 1, "token": "…" }` deletes it. `204`.-- `send` `{ "v": 1, "token": "…", "pairing"?: "…", "notification": { "kind",- "title", "botId", "botName", "threadId", "roomId"?, "roomName"? } }` pushes- to a token **this** installation registered, else `404- push_device_unknown` (the harness then registers and retries once). The- schema is strict: `kind` is `[a-z-]`, ids are `[\w-]{1,120}`, `title` is one- line of at most 200 characters, names at most 80. Any other field (a- `body`, a message) is `400 invalid_request`, never silently dropped, so no- message text can reach Apple through this route. `202 { "sent": true }` on+Closed-app alerts for the phone app, on iPhone through APNs and on Android+through Firebase Cloud Messaging (HTTP v1). The design, the threat model and+the switch-on steps are in `docs/phone-push.md`; the harness side is+`server/phone-push.ts`, its wire types `packages/phone-protocol/src/phone-push.ts`.+Apple accepts pushes for an App Store or TestFlight build only when they are+signed with the publishing team's key, and Google only from a service account+of the Firebase project the Android build is registered in. So the project's+keys live here, and a harness asks this Worker to push with the installation+credential it already holds. Account bearer tokens are refused. All three+routes take `application/json` and answer with the usual `{ "error": "<code>" }`+shape.++- `register` `{ "v": 1, "platform"?: "apns", "token": "<lowercase hex>", "environment": "production" | "sandbox" }`+ or `{ "v": 1, "platform": "fcm", "token": "<FCM registration token>" }`+ stores the device token for this installation (idempotent; it updates the+ platform and environment). `platform` defaults to `apns`, so a harness that+ predates FCM keeps working. An FCM token has no environment (`production`+ is stored). At most 50 tokens per installation (`409 push_device_limit`)+ and 120 registrations per hour. An environment `APNS_ENVIRONMENTS` does not+ list is `400 push_environment_not_allowed`; a platform whose secrets are not+ set is `503 push_unavailable`.+- `unregister` `{ "v": 1, "platform"?: …, "token": "…" }` deletes it. `204`.+- `send` `{ "v": 1, "token": "…", "pairing"?: "…", "collapseId"?: "…",+ "notification": { "kind", "title", "botId", "botName", "threadId",+ "roomId"?, "roomName"? } }` pushes to a token **this** installation+ registered, else `404 push_device_unknown` (the harness then registers and+ retries once). The schema is strict: `kind` is `[a-z-]`, ids are+ `[\w-]{1,120}`, `title` is one line of at most 200 characters, names at most+ 80, `collapseId` is `[A-Za-z0-9._:-]{1,64}`. Any other field (a `body`, a+ message) is `400 invalid_request`, never silently dropped, so no message+ text can reach Apple or Google through this route. `202 { "sent": true }` onsuccess. Limits: 600 sends per installation and 60 per token per hour (`429rate_limited`, `Retry-After: 60`).-The APNs request is `POST https://api.push.apple.com/3/device/<token>` (or+`collapseId` is the identifier the phone gives the notification the live+stream would have posted (`openmaus.<threadId>.<seq>`), so a push and that+notification replace each other instead of showing twice. Without one, the+Worker uses the first 32 hex characters of SHA-256(`kind:threadId`).++**APNs.** `POST https://api.push.apple.com/3/device/<token>` (or`api.sandbox.push.apple.com` for a `sandbox` token) with `apns-push-type:alert`, `apns-priority: 10`, a 24-hour `apns-expiration`, `apns-topic` set to-the bundle id, and an `apns-collapse-id` derived from the kind and thread, so-a repeat replaces the older alert. The payload is-`{ "aps": { "alert": { "title" }, "sound": "default", "thread-id",+the bundle id, and `apns-collapse-id`. The payload is+`{ "aps": { "alert": { "title" }, "sound": "default", "thread-id", "category","interruption-level" }, "omb": { "v": 1, "kind", "botId", "botName",-"threadId", "roomId"?, "roomName"?, "pairing"? } }`; `interruption-level` is-`time-sensitive` for `approval`, `question`, `sign-in` and `mention`, else-`active`.+"threadId", "roomId"?, "roomName"?, "pairing"? }, "body": <the same as omb> }`.+`category` is the app's `OPENMAUS_APPROVAL`, `OPENMAUS_QUESTION` or+`OPENMAUS_UPDATE`, so the notification carries the app's buttons.+`interruption-level` is `time-sensitive` for `approval`, `question`,+`sign-in` and `mention`, else `active`. `body` repeats `omb` because the+phone's notification library hands the app only `body` as a remote+notification's data.The provider token is an ES256 JWT signed with WebCrypto (no dependency):`{ "alg": "ES256", "kid": APNS_KEY_ID }`, `{ "iss": APNS_TEAM_ID, "iat" }`.@@ -233,19 +249,34 @@ Its `iat` is the start of the current 50-minute window, so every isolatesigns for the same window and Apple's 20-to-60-minute refresh rule holdshowever many isolates send; each isolate caches its token for the window.-APNs answers are mapped for the harness: `410 Unregistered`,-`BadDeviceToken` and `DeviceTokenNotForTopic` delete the token for every-installation that registered it in the same APNs environment (for a `410`,-only registrations older than Apple's `timestamp`) and return `410-push_device_unregistered` (the harness drops it too); an expired or invalid provider token is re-signed and retried once,-then `503 push_unavailable`; APNs `429` is `429 rate_limited`; anything else-is `502 push_failed`. Failures log the request id, APNs status and reason-only, never the token or payload.--Without all of the settings below every push route answers `503-push_unavailable` and harnesses back off for an hour. Revoking an-installation deletes its tokens. D1 stores, per row, the installation id, the-token, its SHA-256, the environment and timestamps (`migrations/0008`).+**FCM.** An OAuth access token from `https://oauth2.googleapis.com/token`+(the JWT bearer grant: an RS256 assertion signed with the service account's+key, scope `firebase.messaging`; the file's own `token_uri` is ignored),+cached per isolate until five minutes before it expires. Then+`POST https://fcm.googleapis.com/v1/projects/<project_id>/messages:send` with+a data-only message the phone's notification library presents itself:+`{ "message": { "token", "data": { "title", "tag": <collapse id>,+"channelId", "categoryId", "threadIdentifier": <threadId>, "body": <omb as+JSON> }, "android": { "priority": "HIGH", "ttl": "86400s" } } }`. There is no+`message` key, so the notification shows its title and nothing else.+`channelId` is the app's `approval_question` for approvals, questions and+sign-ins, `routine_failed` for routines and `bot_messages` for the rest.++Provider answers are mapped for the harness. A dead token is deleted for+every installation that registered it and answers `410+push_device_unregistered` (the harness drops it too): APNs `410+Unregistered`, `BadDeviceToken` and `DeviceTokenNotForTopic` (in the same APNs+environment; for a `410`, only registrations older than Apple's `timestamp`),+FCM `UNREGISTERED`, `SENDER_ID_MISMATCH`, and an `INVALID_ARGUMENT` about the+registration token. An expired or refused provider or access token is renewed+and retried once, then `503 push_unavailable`; a `429` is `429 rate_limited`;+anything else is `502 push_failed`. Failures log the request id, the+platform, the provider's status and reason only, never the token or payload.++Without the secrets for a platform its routes answer `503 push_unavailable`+and harnesses back off for an hour. Revoking an installation deletes its+tokens. D1 stores, per row, the installation id, the token, its SHA-256, the+platform, the environment and timestamps (`migrations/0008`, `0017`).**Secrets the maintainer sets** (all with `wrangler secret put <NAME>--config wrangler.jsonc`; none belongs in `vars`, this file, or CI output):@@ -257,12 +288,14 @@ token, its SHA-256, the environment and timestamps (`migrations/0008`).| `APNS_PRIVATE_KEY` | The whole `.p8` file, PEM, e.g. `wrangler secret put APNS_PRIVATE_KEY < AuthKey_XXXXXXXXXX.p8`. Escaped `\n` newlines are accepted too. || `APNS_BUNDLE_ID` | The iOS app's bundle id, which is the APNs topic. || `APNS_ENVIRONMENTS` | Optional. `production` (default), `sandbox`, or `production,sandbox` to also accept development builds' tokens. |+| `FCM_SERVICE_ACCOUNT` | The whole service-account JSON file of the Firebase project (Project settings → Service accounts → Generate new private key), e.g. `wrangler secret put FCM_SERVICE_ACCOUNT < service-account.json`. Only `project_id`, `client_email` and `private_key` are read. |They are deliberately not in `secrets.required`: the Worker is complete-without them, with phone push off, until the Apple key exists. Apply `migrations/0008` before-deploying the Worker that uses it. For a local trial with `wrangler dev`,-`.dev.vars` is read only for declared names, so add these names to-`secrets.required` in a local, uncommitted copy of the config.+without them, with phone push off, until the keys exist. Apply+`migrations/0008` and `0017` before deploying the Worker that uses them. For+a local trial with `wrangler dev`, `.dev.vars` is read only for declared+names, so add these names to `secrets.required` in a local, uncommitted copy+of the config.### Tunnel capacity and idle reclaim@@ -854,9 +887,9 @@ Before a production deployment, an operator must:and added later (see **Several Cloudflare accounts**).7. Replace `ALLOWED_ORIGINS` with a comma-separated allow-list of exact HTTPSapplication origins. Wildcards are deliberately unsupported.-8. Optional, for closed-app phone alerts: apply `migrations/0008`, then set- the APNs secrets listed under **Phone push relay**. Without them the push- routes answer `503 push_unavailable` and nothing else changes.+8. Optional, for closed-app phone alerts: apply `migrations/0008` and `0017`, then set+ the APNs and FCM secrets listed under **Phone push relay**. Without them the+ push routes answer `503 push_unavailable` and nothing else changes.9. Deploy the Worker and verify that `GET <BETTER_AUTH_URL>/healthz` returns`"ok": true` and `"service": "openmausbot-control-plane"` over HTTPSbefore shipping the desktop build. Electron probes this endpoint anddiff --git a/cloudflare/control-plane/migrations/0017_push_platforms.sql b/cloudflare/control-plane/migrations/0017_push_platforms.sqlnew file mode 100644index 0000000000..5a925aa8a7--- /dev/null+++ b/cloudflare/control-plane/migrations/0017_push_platforms.sql@@ -0,0 +1,27 @@+-- FCM registration tokens beside APNs device tokens. An FCM token is longer+-- than the old CHECK allowed and is not hex, and SQLite cannot change a+-- CHECK in place, so the table is rebuilt with every row kept as 'apns'.+-- `environment` stays 'production' for an FCM token: FCM has one.+CREATE TABLE installation_push_devices_next (+ installation_id TEXT NOT NULL REFERENCES installations(id) ON DELETE CASCADE,+ token_hash TEXT NOT NULL CHECK (length(token_hash) = 64),+ platform TEXT NOT NULL DEFAULT 'apns' CHECK (platform IN ('apns', 'fcm')),+ token TEXT NOT NULL CHECK (length(token) BETWEEN 64 AND 4096),+ environment TEXT NOT NULL CHECK (environment IN ('production', 'sandbox')),+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ last_sent_at INTEGER,+ PRIMARY KEY (installation_id, token_hash)+);++INSERT INTO installation_push_devices_next+ (installation_id, token_hash, platform, token, environment, created_at, updated_at, last_sent_at)+SELECT installation_id, token_hash, 'apns', token, environment, created_at, updated_at, last_sent_at+ FROM installation_push_devices;++DROP TABLE installation_push_devices;++ALTER TABLE installation_push_devices_next RENAME TO installation_push_devices;++CREATE INDEX installation_push_devices_token_idx+ ON installation_push_devices(token_hash);diff --git a/cloudflare/control-plane/src/index.ts b/cloudflare/control-plane/src/index.tsindex 165293a743..dab87302f2 100644--- a/cloudflare/control-plane/src/index.ts+++ b/cloudflare/control-plane/src/index.ts@@ -72,7 +72,7 @@ async function route(config: ControlPlaneConfig,requestId: string,cloudflareFetch: CloudflareFetch,- apnsFetch: typeof fetch,+ pushFetch: typeof fetch,) {const url = new URL(request.url);if (request.method === "OPTIONS") return preflight(request, config);@@ -145,7 +145,7 @@ async function route(return unregisterPushDevice(request, env);}if (request.method === "POST" && url.pathname === "/v1/installations/self/push/send") {- return sendPush(request, env, apnsFetch, requestId);+ return sendPush(request, env, pushFetch, requestId);}const rotate = url.pathname.match(ROTATE_ROUTE);@@ -175,7 +175,7 @@ async function route(export function createWorker(cloudflareFetch: CloudflareFetch = fetch,- apnsFetch: typeof fetch = fetch,+ pushFetch: typeof fetch = fetch,) {return {async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {@@ -212,7 +212,7 @@ export function createWorker(}const boundedRequest = await withBoundedRequestBody(request);return secureResponse(- await route(boundedRequest, env, ctx, config, requestId, cloudflareFetch, apnsFetch),+ await route(boundedRequest, env, ctx, config, requestId, cloudflareFetch, pushFetch),request,config,requestId,diff --git a/cloudflare/control-plane/src/push-fcm.ts b/cloudflare/control-plane/src/push-fcm.tsnew file mode 100644index 0000000000..b4301adc54--- /dev/null+++ b/cloudflare/control-plane/src/push-fcm.ts@@ -0,0 +1,152 @@+// Firebase Cloud Messaging, HTTP v1: the Android half of the phone push relay.+import { sha256 } from "./installations";++export interface FcmConfig {+ projectId: string;+ clientEmail: string;+ /** The service account's RSA key as PEM (PKCS #8). */+ privateKey: string;+}++/** Fixed, never the `token_uri` from the service-account file, so a pasted file cannot point the Worker elsewhere. */+export const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";+export const FCM_HOST = "https://fcm.googleapis.com";+export const FCM_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";+/** Google issues an access token for an hour; it is renewed five minutes early. */+const ACCESS_TOKEN_MARGIN_MS = 5 * 60 * 1_000;+const ASSERTION_LIFETIME_SECONDS = 60 * 60;+const FCM_TIMEOUT_MS = 10_000;+export const FCM_TTL = "86400s";++const PROJECT_ID = /^[a-z][a-z0-9-]{4,61}[a-z0-9]$/;+const CLIENT_EMAIL = /^[A-Za-z0-9._%+-]{1,128}@[A-Za-z0-9.-]{1,128}\.iam\.gserviceaccount\.com$/;+const PEM = /^-----BEGIN PRIVATE KEY-----\n[\s\S]+\n-----END PRIVATE KEY-----$/;++/** `FCM_SERVICE_ACCOUNT`: the service-account JSON file Firebase gives, whole. */+export function readFcmConfig(env: Env): FcmConfig | null {+ const raw = (env as unknown as Partial<Record<string, unknown>>).FCM_SERVICE_ACCOUNT;+ if (typeof raw !== "string" || !raw.trim()) return null;+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return null;+ }+ if (!parsed || typeof parsed !== "object") return null;+ const file = parsed as Record<string, unknown>;+ const { project_id: projectId, client_email: clientEmail, private_key: rawKey } = file;+ if (typeof projectId !== "string" || !PROJECT_ID.test(projectId)) return null;+ if (typeof clientEmail !== "string" || !CLIENT_EMAIL.test(clientEmail)) return null;+ if (typeof rawKey !== "string") return null;+ const privateKey = rawKey.replace(/\\n/g, "\n").trim();+ if (!PEM.test(privateKey)) return null;+ return { projectId, clientEmail, privateKey };+}++function base64url(bytes: ArrayBuffer | Uint8Array): string {+ let binary = "";+ for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");+}++function pemBytes(pem: string): Uint8Array<ArrayBuffer> {+ const body = pem.replace(/-----(?:BEGIN|END) PRIVATE KEY-----/g, "").replace(/\s+/g, "");+ const binary = atob(body);+ const bytes = new Uint8Array(binary.length);+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);+ return bytes;+}++interface CachedAccess {+ fingerprint: string;+ expiresAt: number;+ token: string;+}+let cachedAccess: CachedAccess | null = null;++export function forgetFcmAccessToken(): void {+ cachedAccess = null;+}++/** RS256 per RFC 7518 §3.3, the OAuth 2.0 JWT bearer grant (RFC 7523) Google's service accounts use. */+export async function fcmAssertion(config: FcmConfig, now: number): Promise<string> {+ const key = await crypto.subtle.importKey("pkcs8", pemBytes(config.privateKey), { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"]);+ const encoder = new TextEncoder();+ const iat = Math.floor(now / 1_000);+ const header = base64url(encoder.encode(JSON.stringify({ alg: "RS256", typ: "JWT" })));+ const claims = base64url(encoder.encode(JSON.stringify({+ iss: config.clientEmail,+ scope: FCM_SCOPE,+ aud: GOOGLE_TOKEN_URL,+ iat,+ exp: iat + ASSERTION_LIFETIME_SECONDS,+ })));+ const signature = await crypto.subtle.sign({ name: "RSASSA-PKCS1-v1_5" }, key, encoder.encode(`${header}.${claims}`));+ return `${header}.${claims}.${base64url(signature)}`;+}++export type FcmAccess = { kind: "ok"; token: string } | { kind: "credentials" | "failed"; status: number; reason: string };++export async function fcmAccessToken(config: FcmConfig, pushFetch: typeof fetch, now: number): Promise<FcmAccess> {+ const fingerprint = `${config.projectId}:${config.clientEmail}:${await sha256(config.privateKey)}`;+ if (cachedAccess && cachedAccess.fingerprint === fingerprint && cachedAccess.expiresAt - ACCESS_TOKEN_MARGIN_MS > now) {+ return { kind: "ok", token: cachedAccess.token };+ }+ let assertion: string;+ try {+ assertion = await fcmAssertion(config, now);+ } catch {+ return { kind: "credentials", status: 0, reason: "invalid signing key" };+ }+ let response: Response;+ try {+ response = await pushFetch(GOOGLE_TOKEN_URL, {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion }).toString(),+ redirect: "manual",+ signal: AbortSignal.timeout(FCM_TIMEOUT_MS),+ });+ } catch {+ return { kind: "failed", status: 0, reason: "unreachable" };+ }+ const answer = await response.json<{ access_token?: unknown; expires_in?: unknown; error?: unknown }>().catch(() => null);+ if (response.status === 200 && typeof answer?.access_token === "string" && answer.access_token) {+ const lifetime = typeof answer.expires_in === "number" && Number.isFinite(answer.expires_in) ? answer.expires_in : 3_600;+ cachedAccess = { fingerprint, expiresAt: now + lifetime * 1_000, token: answer.access_token };+ return { kind: "ok", token: answer.access_token };+ }+ const reason = typeof answer?.error === "string" ? answer.error.slice(0, 64) : "";+ // invalid_grant / unauthorized_client: the key was revoked or the file is wrong.+ if (response.status === 400 || response.status === 401 || response.status === 403) return { kind: "credentials", status: response.status, reason };+ return { kind: "failed", status: response.status, reason };+}++export interface FcmError {+ status: number;+ errorCode: string;+ message: string;+}++export async function readFcmError(response: Response): Promise<FcmError> {+ const answer = await response.json<{ error?: { message?: unknown; status?: unknown; details?: unknown } }>().catch(() => null);+ const error = answer?.error;+ const details = Array.isArray(error?.details) ? error.details : [];+ const fcmDetail = details.find((detail): detail is { errorCode: string } =>+ Boolean(detail) && typeof detail === "object" && typeof (detail as { errorCode?: unknown }).errorCode === "string");+ const errorCode = fcmDetail?.errorCode ?? (typeof error?.status === "string" ? error.status : "");+ const message = typeof error?.message === "string" ? error.message : "";+ return { status: response.status, errorCode: errorCode.slice(0, 64), message: message.slice(0, 200) };+}++/** UNREGISTERED: the app was removed or the token expired. SENDER_ID_MISMATCH: a token of another Firebase project. */+export function fcmTokenIsDead(error: FcmError): boolean {+ if (error.errorCode === "UNREGISTERED" || error.errorCode === "SENDER_ID_MISMATCH") return true;+ return error.status === 400 && error.errorCode === "INVALID_ARGUMENT" && /registration token/i.test(error.message);+}++export function fcmSendUrl(config: FcmConfig): string {+ return `${FCM_HOST}/v1/projects/${config.projectId}/messages:send`;+}++export const FCM_TIMEOUT = FCM_TIMEOUT_MS;diff --git a/cloudflare/control-plane/src/push.ts b/cloudflare/control-plane/src/push.tsindex 94a19ec60c..fe94ce76a8 100644--- a/cloudflare/control-plane/src/push.ts+++ b/cloudflare/control-plane/src/push.ts@@ -1,8 +1,22 @@-// APNs accepts pushes for an App Store or TestFlight build only when signed with the publishing team's key.+// APNs accepts pushes for an App Store or TestFlight build only when signed with the publishing team's key; FCM only+// with a service account of the Firebase project the Android build was registered in.import { z } from "zod";import { errorResponse, HTTPError, json, readBoundedJSON } from "./http";import { requireInstallation, requireInstallationAndRead, sha256 } from "./installations";+import {+ FCM_TIMEOUT,+ FCM_TTL,+ fcmAccessToken,+ fcmSendUrl,+ fcmTokenIsDead,+ forgetFcmAccessToken,+ readFcmConfig,+ readFcmError,+ type FcmConfig,+} from "./push-fcm";++export type PushPlatform = "apns" | "fcm";export type ApnsEnvironment = "production" | "sandbox";@@ -34,10 +48,25 @@ const APNS_TIMEOUT_MS = 10_000;const KEY_OR_TEAM_ID = /^[A-Z0-9]{10}$/;const BUNDLE_ID = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;const TOKEN = /^[0-9a-f]{64,200}$/;+/** An FCM registration token: today `<instance id>:<token>`, about 160 characters; the format is Google's to change. */+const FCM_TOKEN = /^[A-Za-z0-9_:-]{64,4096}$/;+/** Either kind; the stored registration says which. */+const ANY_TOKEN = FCM_TOKEN;+/** APNs takes at most 64 bytes. The phone uses the same string as its own notification's identifier, so the push and+ * the notification the live stream would have posted replace each other instead of showing twice. */+const COLLAPSE_ID = /^[A-Za-z0-9._:-]{1,64}$/;const ID = /^[\w-]{1,120}$/;const KIND = /^[a-z][a-z-]{0,39}$/;const PAIRING = /^[A-Za-z0-9_-]{8,64}$/;const NEEDS_YOU = new Set(["approval", "question", "sign-in", "mention"]);+/** The phone app's notification categories (action buttons) and Android channels, by the ids the store apps created. */+const CATEGORY: Record<string, string> = { approval: "OPENMAUS_APPROVAL", question: "OPENMAUS_QUESTION" };+const CATEGORY_UPDATE = "OPENMAUS_UPDATE";+const CHANNEL_BLOCKING = "approval_question";+const CHANNEL_ROUTINES = "routine_failed";+const CHANNEL_MESSAGES = "bot_messages";+const BLOCKING_KINDS = new Set(["approval", "question", "sign-in"]);+const ROUTINE_KINDS = new Set(["routine-failed", "routine-deferred", "routine-blocked"]);function oneLine(max: number) {return z.string().min(1).max(max * 4).refine((value) => {@@ -46,19 +75,30 @@ function oneLine(max: number) {});}-const registerSchema = z.strictObject({- v: z.literal(1),- token: z.string().regex(TOKEN),- environment: z.enum(["production", "sandbox"]),-});+const registerSchema = z.union([+ z.strictObject({+ v: z.literal(1),+ platform: z.literal("apns").optional(),+ token: z.string().regex(TOKEN),+ environment: z.enum(["production", "sandbox"]),+ }),+ z.strictObject({+ v: z.literal(1),+ platform: z.literal("fcm"),+ token: z.string().regex(FCM_TOKEN),+ environment: z.literal("production").optional(),+ }),+]);const unregisterSchema = z.strictObject({v: z.literal(1),- token: z.string().regex(TOKEN),+ platform: z.enum(["apns", "fcm"]).optional(),+ token: z.string().regex(ANY_TOKEN),});const sendSchema = z.strictObject({v: z.literal(1),- token: z.string().regex(TOKEN),+ token: z.string().regex(ANY_TOKEN),pairing: z.string().regex(PAIRING).optional(),+ collapseId: z.string().regex(COLLAPSE_ID).optional(),notification: z.strictObject({kind: z.string().regex(KIND),title: oneLine(200),@@ -137,27 +177,79 @@ export async function apnsProviderToken(config: ApnsConfig, now = Date.now()): Preturn jwt;}+function ombPayload(request: PushSendRequest) {+ const notification = request.notification;+ return {+ v: 1,+ kind: notification.kind,+ botId: notification.botId,+ botName: notification.botName,+ threadId: notification.threadId,+ ...(notification.roomId && notification.roomName ? { roomId: notification.roomId, roomName: notification.roomName } : {}),+ ...(request.pairing ? { pairing: request.pairing } : {}),+ };+}++export function pushCategory(kind: string): string {+ return CATEGORY[kind] ?? CATEGORY_UPDATE;+}++export function pushChannel(kind: string): string {+ return BLOCKING_KINDS.has(kind) ? CHANNEL_BLOCKING : ROUTINE_KINDS.has(kind) ? CHANNEL_ROUTINES : CHANNEL_MESSAGES;+}++/** `body` repeats `omb` because expo-notifications (SDK 58) hands an app only a remote notification's `body` as its data. */export function apnsPayload(request: PushSendRequest) {const notification = request.notification;+ const omb = ombPayload(request);return {aps: {alert: { title: notification.title },sound: "default","thread-id": notification.threadId,+ category: pushCategory(notification.kind),"interruption-level": NEEDS_YOU.has(notification.kind) ? "time-sensitive" : "active",},- omb: {- v: 1,- kind: notification.kind,- botId: notification.botId,- botName: notification.botName,- threadId: notification.threadId,- ...(notification.roomId && notification.roomName ? { roomId: notification.roomId, roomName: notification.roomName } : {}),- ...(request.pairing ? { pairing: request.pairing } : {}),+ omb,+ body: omb,+ };+}++/** A data-only message in the shape expo-notifications (SDK 58) presents itself on Android: `title`, `tag` (the+ * notification's identifier), `channelId`, `categoryId`, `threadIdentifier` and `body` (the app's data, as JSON). No+ * `message`: the notification has no text beyond its title. */+export function fcmPayload(request: PushSendRequest, token: string, collapseId: string) {+ const notification = request.notification;+ return {+ message: {+ token,+ data: {+ title: notification.title,+ tag: collapseId,+ channelId: pushChannel(notification.kind),+ categoryId: pushCategory(notification.kind),+ threadIdentifier: notification.threadId,+ body: JSON.stringify(ombPayload(request)),+ },+ android: { priority: "HIGH", ttl: FCM_TTL },},};}+export async function pushCollapseId(request: PushSendRequest): Promise<string> {+ return request.collapseId ?? (await sha256(`${request.notification.kind}:${request.notification.threadId}`)).slice(0, 32);+}++interface PushConfig {+ apns: ApnsConfig | null;+ fcm: FcmConfig | null;+}++export function readPushConfig(env: Env): PushConfig | null {+ const config = { apns: readApnsConfig(env), fcm: readFcmConfig(env) };+ return config.apns || config.fcm ? config : null;+}+function unavailable(): never {throw new HTTPError(503, "push_unavailable");}@@ -190,25 +282,31 @@ function limitStatement(env: Env, installationId: string, action: string, limit:export async function registerPushDevice(request: Request, env: Env): Promise<Response> {const installation = await requireInstallation(request, env);- const config = readApnsConfig(env) ?? unavailable();+ const config = readPushConfig(env) ?? unavailable();const body = await parse(request, registerSchema);- if (!config.environments.has(body.environment)) throw new HTTPError(400, "push_environment_not_allowed");+ const platform: PushPlatform = body.platform ?? "apns";+ const environment: ApnsEnvironment = body.environment ?? "production";+ if (platform === "fcm" && !config.fcm) unavailable();+ if (platform === "apns") {+ const apns = config.apns ?? unavailable();+ if (!apns.environments.has(environment)) throw new HTTPError(400, "push_environment_not_allowed");+ }const now = Date.now();const [limited] = await env.DB.batch([limitStatement(env, installation.installation_id, "push_register", PUSH_REGISTER_LIMIT, now)]);if (limited?.meta.changes === 0) return rateLimited(60);const tokenHash = await sha256(body.token);const [updated, inserted] = await env.DB.batch([env.DB.prepare(- `UPDATE installation_push_devices SET environment = ?, updated_at = ?+ `UPDATE installation_push_devices SET platform = ?, environment = ?, updated_at = ?WHERE installation_id = ? AND token_hash = ?`,- ).bind(body.environment, now, installation.installation_id, tokenHash),+ ).bind(platform, environment, now, installation.installation_id, tokenHash),env.DB.prepare(`INSERT INTO installation_push_devices- (installation_id, token_hash, token, environment, created_at, updated_at)- SELECT ?, ?, ?, ?, ?, ?+ (installation_id, token_hash, platform, token, environment, created_at, updated_at)+ SELECT ?, ?, ?, ?, ?, ?, ?WHERE (SELECT COUNT(*) FROM installation_push_devices WHERE installation_id = ?) < ?ON CONFLICT(installation_id, token_hash) DO NOTHING`,- ).bind(installation.installation_id, tokenHash, body.token, body.environment, now, now, installation.installation_id, PUSH_DEVICE_LIMIT),+ ).bind(installation.installation_id, tokenHash, platform, body.token, environment, now, now, installation.installation_id, PUSH_DEVICE_LIMIT),]);if (updated?.meta.changes === 0 && inserted?.meta.changes === 0) throw new HTTPError(409, "push_device_limit");return json({ registered: true });@@ -225,13 +323,14 @@ export async function unregisterPushDevice(request: Request, env: Env): Promise<interface DeviceRow {token: string;+ platform: PushPlatform;environment: ApnsEnvironment;}export async function sendPush(request: Request,env: Env,- apnsFetch: typeof fetch,+ pushFetch: typeof fetch,requestId: string,): Promise<Response> {// Parse before authenticating so the device read rides in the authentication's own D1 batch.@@ -246,13 +345,15 @@ export async function sendPush(const tokenHash = body ? await sha256(body.token) : "";const { installation, row } = await requireInstallationAndRead<DeviceRow>(request, env, body? (installationId) => env.DB.prepare(- "SELECT token, environment FROM installation_push_devices WHERE installation_id = ? AND token_hash = ?",+ "SELECT token, platform, environment FROM installation_push_devices WHERE installation_id = ? AND token_hash = ?",).bind(installationId, tokenHash): null);- const config = readApnsConfig(env) ?? unavailable();+ const config = readPushConfig(env) ?? unavailable();if (parseError || !body) throw parseError ?? new HTTPError(400, "invalid_request");// Only a token this installation registered, so a relay credential cannot be pointed at somebody else's phone.if (!row || row.token !== body.token) return errorResponse(404, "push_device_unknown");+ const apns = row.platform === "apns" ? config.apns : null;+ const fcm = row.platform === "fcm" ? config.fcm : null;const now = Date.now();// Read both windows before taking from either, so a send refused by one limit does not spend the other.@@ -269,7 +370,10 @@ export async function sendPush(const taken = await env.DB.batch(limits.map(({ action, limit }) => limitStatement(env, installation.installation_id, action, limit, now)));if (taken.some((result) => result.meta.changes === 0)) return rateLimited(60);- const outcome = await deliver(config, row.environment, body, apnsFetch, now);+ let outcome: Delivery;+ if (apns) outcome = await deliverApns(apns, row.environment, body, pushFetch, now);+ else if (fcm) outcome = await deliverFcm(fcm, body, pushFetch, now);+ else return errorResponse(503, "push_unavailable");if (outcome.kind === "sent") {await env.DB.prepare("UPDATE installation_push_devices SET last_sent_at = ? WHERE installation_id = ? AND token_hash = ?").bind(now, installation.installation_id, tokenHash)@@ -277,13 +381,16 @@ export async function sendPush(return json({ sent: true }, 202);}if (outcome.kind === "dead") {- // APNs judges a token per environment and topic; a 410's timestamp spares registrations made after it.- await env.DB.prepare("DELETE FROM installation_push_devices WHERE token_hash = ? AND environment = ? AND updated_at <= ?")- .bind(tokenHash, row.environment, Math.min(outcome.invalidSince ?? now, now))- .run();+ // APNs judges a token per environment and topic; a 410's timestamp spares registrations made after it. FCM judges+ // a token for its one project.+ await (row.platform === "fcm"+ ? env.DB.prepare("DELETE FROM installation_push_devices WHERE token_hash = ? AND platform = 'fcm'").bind(tokenHash)+ : env.DB.prepare("DELETE FROM installation_push_devices WHERE token_hash = ? AND platform = 'apns' AND environment = ? AND updated_at <= ?")+ .bind(tokenHash, row.environment, Math.min(outcome.invalidSince ?? now, now))+ ).run();return errorResponse(410, "push_device_unregistered");}- console.error(JSON.stringify({ message: "apns push failed", requestId, status: outcome.status, reason: outcome.reason }));+ console.error(JSON.stringify({ message: `${row.platform} push failed`, requestId, status: outcome.status, reason: outcome.reason }));if (outcome.kind === "throttled") return rateLimited(60);if (outcome.kind === "credentials") return errorResponse(503, "push_unavailable");return errorResponse(502, "push_failed");@@ -297,7 +404,7 @@ type Delivery =const DEAD_TOKEN_REASONS = new Set(["BadDeviceToken", "DeviceTokenNotForTopic", "Unregistered"]);const PROVIDER_TOKEN_REASONS = new Set(["ExpiredProviderToken", "InvalidProviderToken", "MissingProviderToken"]);-async function deliver(+async function deliverApns(config: ApnsConfig,environment: ApnsEnvironment,request: PushSendRequest,@@ -305,8 +412,7 @@ async function deliver(now: number,): Promise<Delivery> {const payload = JSON.stringify(apnsPayload(request));- // Repeats for one kind in one conversation replace each other on the lock screen.- const collapseId = (await sha256(`${request.notification.kind}:${request.notification.threadId}`)).slice(0, 32);+ const collapseId = await pushCollapseId(request);for (let attempt = 0; attempt < 2; attempt += 1) {let providerToken: string;try {@@ -352,3 +458,34 @@ async function deliver(}return { kind: "credentials", status: 403, reason: "provider token refused twice" };}++async function deliverFcm(config: FcmConfig, request: PushSendRequest, pushFetch: typeof fetch, now: number): Promise<Delivery> {+ const payload = JSON.stringify(fcmPayload(request, request.token, await pushCollapseId(request)));+ for (let attempt = 0; attempt < 2; attempt += 1) {+ const access = await fcmAccessToken(config, pushFetch, now);+ if (access.kind !== "ok") return access;+ let response: Response;+ try {+ response = await pushFetch(fcmSendUrl(config), {+ method: "POST",+ headers: { authorization: `Bearer ${access.token}`, "content-type": "application/json" },+ body: payload,+ redirect: "manual",+ signal: AbortSignal.timeout(FCM_TIMEOUT),+ });+ } catch {+ return { kind: "failed", status: 0, reason: "unreachable" };+ }+ if (response.status === 200) return { kind: "sent" };+ const error = await readFcmError(response);+ if (fcmTokenIsDead(error)) return { kind: "dead" };+ if (response.status === 401 && attempt === 0) {+ forgetFcmAccessToken();+ continue;+ }+ if (response.status === 401 || response.status === 403) return { kind: "credentials", status: response.status, reason: error.errorCode };+ if (response.status === 429) return { kind: "throttled", status: 429, reason: error.errorCode };+ return { kind: "failed", status: response.status, reason: error.errorCode };+ }+ return { kind: "credentials", status: 401, reason: "access token refused twice" };+}diff --git a/cloudflare/control-plane/test/migrations.test.ts b/cloudflare/control-plane/test/migrations.test.tsindex 7e90cdf81e..20f2fc3b13 100644--- a/cloudflare/control-plane/test/migrations.test.ts+++ b/cloudflare/control-plane/test/migrations.test.ts@@ -45,3 +45,39 @@ describe("migration 0013", () => {expect(await schemaNames(env.DB, "highlevel%")).toEqual([]);});});++describe("migration 0017", () => {+ it("rebuilds the push table for FCM tokens and keeps every APNs registration as one", async () => {+ const db = env.PUSH_MIGRATION_DB;+ const rebuild = migrationIndex("0017_");+ expect(rebuild).toBeGreaterThan(migrationIndex("0016_"));+ await applyD1Migrations(db, env.TEST_MIGRATIONS.slice(0, rebuild));+ await db.batch([+ db.prepare(`INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES ('user_1', 'Owner', '[email protected]', 1, 1, 1)`),+ db.prepare("INSERT INTO installations (id, owner_user_id, client_instance_id, display_name, platform, created_at, updated_at) VALUES ('inst_1', 'user_1', 'client_1', 'Mac', 'darwin', 1, 1)"),+ db.prepare(+ `INSERT INTO installation_push_devices (installation_id, token_hash, token, environment, created_at, updated_at, last_sent_at)+ VALUES ('inst_1', ?, ?, 'sandbox', 10, 20, 30)`,+ ).bind("c".repeat(64), "ab".repeat(32)),+ ]);++ await applyD1Migrations(db, env.TEST_MIGRATIONS);++ expect(await db.prepare("SELECT * FROM installation_push_devices").all()).toMatchObject({+ results: [{ installation_id: "inst_1", token_hash: "c".repeat(64), platform: "apns", token: "ab".repeat(32), environment: "sandbox", created_at: 10, updated_at: 20, last_sent_at: 30 }],+ });+ expect(await schemaNames(db, "installation_push_devices%")).toEqual([+ { type: "index", name: "installation_push_devices_token_idx" },+ { type: "table", name: "installation_push_devices" },+ ]);+ const long = `fcm:${"x".repeat(300)}`;+ await db.prepare(+ `INSERT INTO installation_push_devices (installation_id, token_hash, platform, token, environment, created_at, updated_at)+ VALUES ('inst_1', ?, 'fcm', ?, 'production', 1, 1)`,+ ).bind("d".repeat(64), long).run();+ await expect(db.prepare(+ `INSERT INTO installation_push_devices (installation_id, token_hash, platform, token, environment, created_at, updated_at)+ VALUES ('inst_1', ?, 'webpush', ?, 'production', 1, 1)`,+ ).bind("e".repeat(64), long).run()).rejects.toThrow();+ });+});diff --git a/cloudflare/control-plane/test/push-fcm.test.ts b/cloudflare/control-plane/test/push-fcm.test.tsnew file mode 100644index 0000000000..f1861178ea--- /dev/null+++ b/cloudflare/control-plane/test/push-fcm.test.ts@@ -0,0 +1,339 @@+import { env } from "cloudflare:workers";+import { createExecutionContext, waitOnExecutionContext } from "cloudflare:test";+import { beforeEach, describe, expect, it } from "vitest";++import { createAuth } from "../src/auth";+import { readConfig } from "../src/config";+import { createWorker } from "../src/index";+import { FCM_SCOPE, GOOGLE_TOKEN_URL, forgetFcmAccessToken, readFcmConfig } from "../src/push-fcm";++const BASE_URL = "https://auth.openmausbot.test";+const FCM_TOKEN = `cXyZ_1234567890-abc:APA91b${"F".repeat(140)}`;+const OTHER_FCM_TOKEN = `dQwE_0987654321-xyz:APA91b${"G".repeat(140)}`;+const APNS_TOKEN = "a1".repeat(32);+const PROJECT = "mausbot-test-1";++type TestWorker = ReturnType<typeof createWorker>;++interface Call {+ url: string;+ headers: Record<string, string>;+ text: string;+}++interface Answer {+ status: number;+ body?: unknown;+}++/** One fake for Google's token endpoint, FCM and APNs, each with its own queue of answers (200 when it runs out). */+function fakeProviders(answers: { oauth?: Answer[]; fcm?: Answer[]; apns?: Answer[] } = {}) {+ const calls: Call[] = [];+ const queues = { oauth: [...(answers.oauth ?? [])], fcm: [...(answers.fcm ?? [])], apns: [...(answers.apns ?? [])] };+ const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const request = new Request(input, init);+ const headers: Record<string, string> = {};+ request.headers.forEach((value, name) => {+ headers[name] = value;+ });+ calls.push({ url: request.url, headers, text: new TextDecoder().decode(await request.arrayBuffer()) });+ const host = new URL(request.url).host;+ const queue = host === "oauth2.googleapis.com" ? queues.oauth : host === "fcm.googleapis.com" ? queues.fcm : queues.apns;+ const fallback: Answer = host === "oauth2.googleapis.com"+ ? { status: 200, body: { access_token: `ya29.test-${calls.length}`, expires_in: 3599, token_type: "Bearer" } }+ : host === "fcm.googleapis.com" ? { status: 200, body: { name: `projects/${PROJECT}/messages/1` } } : { status: 200 };+ const answer = queue.shift() ?? fallback;+ return new Response(answer.body === undefined ? null : JSON.stringify(answer.body), { status: answer.status });+ }) as typeof fetch;+ const of = (host: string) => calls.filter((call) => new URL(call.url).host === host);+ return { calls, fetch: fetchImpl, oauth: () => of("oauth2.googleapis.com"), fcm: () => of("fcm.googleapis.com"), apns: () => of("api.push.apple.com").concat(of("api.sandbox.push.apple.com")) };+}++function pem(bytes: ArrayBuffer): string {+ let binary = "";+ for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);+ return `-----BEGIN PRIVATE KEY-----\n${btoa(binary).match(/.{1,64}/g)!.join("\n")}\n-----END PRIVATE KEY-----`;+}++async function serviceAccount() {+ const pair = await crypto.subtle.generateKey(+ { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },+ true,+ ["sign", "verify"],+ ) as CryptoKeyPair;+ const privateKey = pem(await crypto.subtle.exportKey("pkcs8", pair.privateKey) as ArrayBuffer);+ const file = {+ type: "service_account",+ project_id: PROJECT,+ private_key_id: "0123456789abcdef",+ private_key: privateKey,+ client_email: `firebase-adminsdk-test@${PROJECT}.iam.gserviceaccount.com`,+ token_uri: "https://attacker.example/token",+ };+ return { publicKey: pair.publicKey, json: JSON.stringify(file), file };+}++async function apnsKeyPem() {+ const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]) as CryptoKeyPair;+ return pem(await crypto.subtle.exportKey("pkcs8", pair.privateKey) as ArrayBuffer);+}++function testEnv(extra: Record<string, string>): Env {+ return { ...env, ...extra } as unknown as Env;+}++async function call(worker: TestWorker, environment: Env, path: string, options: { body?: unknown; token?: string } = {}) {+ const headers = new Headers();+ if (options.token) headers.set("authorization", `Bearer ${options.token}`);+ if (options.body !== undefined) headers.set("content-type", "application/json");+ const request = new Request(`${BASE_URL}${path}`, {+ method: "POST",+ headers,+ body: options.body === undefined ? undefined : JSON.stringify(options.body),+ });+ const ctx = createExecutionContext();+ const response = await worker.fetch(request, environment, ctx);+ await waitOnExecutionContext(ctx);+ return response;+}++async function installation(worker: TestWorker, environment: Env, email: string) {+ const ctx = createExecutionContext();+ const auth = createAuth(env, ctx, readConfig(env), crypto.randomUUID());+ const otp = await auth.api.createVerificationOTP({ body: { email, type: "sign-in" } });+ await waitOnExecutionContext(ctx);+ const signedIn = await call(worker, environment, "/api/auth/sign-in/email-otp", { body: { email, name: "Push owner", otp } });+ expect(signedIn.status).toBe(200);+ const created = await call(worker, environment, "/v1/installations", {+ token: signedIn.headers.get("set-auth-token")!,+ body: { clientInstanceId: crypto.randomUUID(), name: "Test computer", platform: "linux" },+ });+ expect(created.status).toBe(201);+ const body = await created.json<{ credential: string; installation: { id: string } }>();+ return { credential: body.credential, id: body.installation.id };+}++const notification = { kind: "approval", title: "Scout needs approval", botId: "bot_1", botName: "Scout", threadId: "th_1" };++const registerFcm = (worker: TestWorker, environment: Env, credential: string, token = FCM_TOKEN) =>+ call(worker, environment, "/v1/installations/self/push/register", { token: credential, body: { v: 1, platform: "fcm", token } });+const send = (worker: TestWorker, environment: Env, credential: string, body: Record<string, unknown> = {}) =>+ call(worker, environment, "/v1/installations/self/push/send", {+ token: credential,+ body: { v: 1, token: FCM_TOKEN, pairing: "pair-tag-1", collapseId: "openmaus.th_1.42", notification, ...body },+ });++const decode = (part: string) => JSON.parse(atob(part.replaceAll("-", "+").replaceAll("_", "/")));++describe("phone push relay, FCM", () => {+ beforeEach(() => forgetFcmAccessToken());++ it("is unavailable for FCM until the service account is set, whatever APNs has", async () => {+ const providers = fakeProviders();+ const worker = createWorker(fetch, providers.fetch);+ const apnsOnly = testEnv({+ APNS_KEY_ID: "KEY1234567",+ APNS_TEAM_ID: "TEAM123456",+ APNS_BUNDLE_ID: "com.example.mausbot",+ APNS_PRIVATE_KEY: await apnsKeyPem(),+ });+ const { credential } = await installation(worker, apnsOnly, "[email protected]");+ const refused = await registerFcm(worker, apnsOnly, credential);+ expect(refused.status).toBe(503);+ expect(await refused.json()).toEqual({ error: "push_unavailable" });+ const apns = await call(worker, apnsOnly, "/v1/installations/self/push/register", { token: credential, body: { v: 1, token: APNS_TOKEN, environment: "production" } });+ expect(apns.status).toBe(200);+ expect(providers.calls).toEqual([]);+ });++ it("signs an RS256 assertion for Google and sends a data-only message with no message text", async () => {+ const account = await serviceAccount();+ const environment = testEnv({ FCM_SERVICE_ACCOUNT: account.json });+ const providers = fakeProviders();+ const worker = createWorker(fetch, providers.fetch);+ const { credential } = await installation(worker, environment, "[email protected]");+ expect((await registerFcm(worker, environment, credential)).status).toBe(200);+ const sent = await send(worker, environment, credential, { notification: { ...notification, roomId: "grp_1", roomName: "Launch" } });+ expect(sent.status).toBe(202);+ expect(await sent.json()).toEqual({ sent: true });++ const [oauth] = providers.oauth();+ expect(oauth!.url).toBe(GOOGLE_TOKEN_URL);+ const form = new URLSearchParams(oauth!.text);+ expect(form.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:jwt-bearer");+ const [header, claims, signature] = form.get("assertion")!.split(".");+ expect(decode(header!)).toEqual({ alg: "RS256", typ: "JWT" });+ expect(decode(claims!)).toMatchObject({ iss: account.file.client_email, scope: FCM_SCOPE, aud: GOOGLE_TOKEN_URL });+ expect(decode(claims!).exp - decode(claims!).iat).toBe(3600);+ const raw = Uint8Array.from(atob(signature!.replaceAll("-", "+").replaceAll("_", "/")), (char) => char.charCodeAt(0));+ expect(await crypto.subtle.verify({ name: "RSASSA-PKCS1-v1_5" }, account.publicKey, raw, new TextEncoder().encode(`${header}.${claims}`))).toBe(true);++ const [message] = providers.fcm();+ expect(message!.url).toBe(`https://fcm.googleapis.com/v1/projects/${PROJECT}/messages:send`);+ expect(message!.headers.authorization).toBe("Bearer ya29.test-1");+ expect(JSON.parse(message!.text)).toEqual({+ message: {+ token: FCM_TOKEN,+ data: {+ title: "Scout needs approval",+ tag: "openmaus.th_1.42",+ channelId: "approval_question",+ categoryId: "OPENMAUS_APPROVAL",+ threadIdentifier: "th_1",+ body: JSON.stringify({ v: 1, kind: "approval", botId: "bot_1", botName: "Scout", threadId: "th_1", roomId: "grp_1", roomName: "Launch", pairing: "pair-tag-1" }),+ },+ android: { priority: "HIGH", ttl: "86400s" },+ },+ });+ // the token_uri in the pasted file is never used+ expect(providers.calls.some((one) => one.url.includes("attacker"))).toBe(false);+ });++ it("reuses Google's access token until it nears expiry, and maps a finished turn to the messages channel", async () => {+ const account = await serviceAccount();+ const environment = testEnv({ FCM_SERVICE_ACCOUNT: account.json });+ const providers = fakeProviders();+ const worker = createWorker(fetch, providers.fetch);+ const { credential } = await installation(worker, environment, "[email protected]");+ await registerFcm(worker, environment, credential);+ expect((await send(worker, environment, credential)).status).toBe(202);+ expect((await send(worker, environment, credential, { collapseId: undefined, notification: { ...notification, kind: "done", title: "Scout finished" } })).status).toBe(202);+ expect(providers.oauth()).toHaveLength(1);+ const second = JSON.parse(providers.fcm()[1]!.text) as { message: { data: Record<string, string> } };+ expect(second.message.data).toMatchObject({ channelId: "bot_messages", categoryId: "OPENMAUS_UPDATE" });+ expect(second.message.data.tag).toMatch(/^[0-9a-f]{32}$/);+ });++ it("drops a token FCM calls unregistered or foreign, for every installation", async () => {+ const account = await serviceAccount();+ const environment = testEnv({ FCM_SERVICE_ACCOUNT: account.json });+ const providers = fakeProviders({+ fcm: [+ { status: 404, body: { error: { code: 404, status: "NOT_FOUND", message: "Requested entity was not found.", details: [{ "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError", errorCode: "UNREGISTERED" }] } } },+ { status: 403, body: { error: { code: 403, status: "PERMISSION_DENIED", message: "SenderId mismatch", details: [{ "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError", errorCode: "SENDER_ID_MISMATCH" }] } } },+ ],+ });+ const worker = createWorker(fetch, providers.fetch);+ const first = await installation(worker, environment, "[email protected]");+ const second = await installation(worker, environment, "[email protected]");+ await registerFcm(worker, environment, first.credential);+ await registerFcm(worker, environment, second.credential);+ const dead = await send(worker, environment, first.credential);+ expect(dead.status).toBe(410);+ expect(await dead.json()).toEqual({ error: "push_device_unregistered" });+ expect((await send(worker, environment, second.credential)).status).toBe(404);++ await registerFcm(worker, environment, first.credential, OTHER_FCM_TOKEN);+ expect((await send(worker, environment, first.credential, { token: OTHER_FCM_TOKEN })).status).toBe(410);+ const rows = await env.DB.prepare("SELECT COUNT(*) AS n FROM installation_push_devices").first<{ n: number }>();+ expect(rows?.n).toBe(0);+ });++ it("keeps a token when FCM refuses the message itself, and tells throttling and outages apart", async () => {+ const account = await serviceAccount();+ const environment = testEnv({ FCM_SERVICE_ACCOUNT: account.json });+ const providers = fakeProviders({+ fcm: [+ { status: 400, body: { error: { code: 400, status: "INVALID_ARGUMENT", message: "Invalid value at 'message.data'", details: [{ errorCode: "INVALID_ARGUMENT" }] } } },+ { status: 429, body: { error: { code: 429, status: "RESOURCE_EXHAUSTED", message: "quota", details: [{ errorCode: "QUOTA_EXCEEDED" }] } } },+ { status: 503, body: { error: { code: 503, status: "UNAVAILABLE", message: "try later" } } },+ ],+ });+ const worker = createWorker(fetch, providers.fetch);+ const { credential } = await installation(worker, environment, "[email protected]");+ await registerFcm(worker, environment, credential);+ expect((await send(worker, environment, credential)).status).toBe(502);+ const throttled = await send(worker, environment, credential);+ expect(throttled.status).toBe(429);+ expect(throttled.headers.get("retry-after")).toBe("60");+ expect((await send(worker, environment, credential)).status).toBe(502);+ const rows = await env.DB.prepare("SELECT platform, environment FROM installation_push_devices").all<{ platform: string; environment: string }>();+ expect(rows.results).toEqual([{ platform: "fcm", environment: "production" }]);+ });++ it("renews the access token once when FCM refuses it, then reports the relay unavailable", async () => {+ const account = await serviceAccount();+ const environment = testEnv({ FCM_SERVICE_ACCOUNT: account.json });+ const unauthenticated = { status: 401, body: { error: { code: 401, status: "UNAUTHENTICATED", message: "Request had invalid authentication credentials." } } };+ const providers = fakeProviders({ fcm: [unauthenticated, { status: 200, body: {} }, unauthenticated, unauthenticated] });+ const worker = createWorker(fetch, providers.fetch);+ const { credential } = await installation(worker, environment, "[email protected]");+ await registerFcm(worker, environment, credential);+ expect((await send(worker, environment, credential)).status).toBe(202);+ expect(providers.oauth()).toHaveLength(2);+ const refused = await send(worker, environment, credential);+ expect(refused.status).toBe(503);+ expect(await refused.json()).toEqual({ error: "push_unavailable" });++ const badGrant = fakeProviders({ oauth: [{ status: 400, body: { error: "invalid_grant" } }] });+ forgetFcmAccessToken();+ const response = await send(createWorker(fetch, badGrant.fetch), environment, credential);+ expect(response.status).toBe(503);+ expect(badGrant.fcm()).toEqual([]);+ });++ it("checks platform, token, environment and collapse id strictly", async () => {+ const account = await serviceAccount();+ const environment = testEnv({ FCM_SERVICE_ACCOUNT: account.json });+ const providers = fakeProviders();+ const worker = createWorker(fetch, providers.fetch);+ const { credential } = await installation(worker, environment, "[email protected]");+ const register = (body: Record<string, unknown>) => call(worker, environment, "/v1/installations/self/push/register", { token: credential, body: { v: 1, ...body } });+ for (const body of [+ { platform: "fcm", token: FCM_TOKEN, environment: "sandbox" },+ { platform: "fcm", token: "short:token" },+ { platform: "fcm", token: `${FCM_TOKEN} ` },+ { platform: "apns", token: FCM_TOKEN, environment: "production" },+ { platform: "webpush", token: FCM_TOKEN },+ { token: FCM_TOKEN, environment: "production" },+ ]) {+ expect((await register(body)).status, JSON.stringify(body)).toBe(400);+ }+ expect((await register({ platform: "fcm", token: FCM_TOKEN, environment: "production" })).status).toBe(200);+ for (const collapseId of ["x".repeat(65), "has space", "slash/inside", ""]) {+ expect((await send(worker, environment, credential, { collapseId })).status, collapseId).toBe(400);+ }+ expect((await send(worker, environment, credential, { notification: { ...notification, body: "the reply text" } })).status).toBe(400);+ expect(providers.fcm()).toEqual([]);+ const removed = await call(worker, environment, "/v1/installations/self/push/unregister", { token: credential, body: { v: 1, platform: "fcm", token: FCM_TOKEN } });+ expect(removed.status).toBe(204);+ expect((await send(worker, environment, credential)).status).toBe(404);+ });++ it("sends an APNs push with the harness's collapse id when it gives one", async () => {+ const environment = testEnv({+ APNS_KEY_ID: "KEY1234567",+ APNS_TEAM_ID: "TEAM123456",+ APNS_BUNDLE_ID: "com.example.mausbot",+ APNS_PRIVATE_KEY: await apnsKeyPem(),+ });+ const providers = fakeProviders();+ const worker = createWorker(fetch, providers.fetch);+ const { credential } = await installation(worker, environment, "[email protected]");+ await call(worker, environment, "/v1/installations/self/push/register", { token: credential, body: { v: 1, platform: "apns", token: APNS_TOKEN, environment: "production" } });+ expect((await send(worker, environment, credential, { token: APNS_TOKEN, notification: { ...notification, kind: "sign-in", title: "Scout needs you to sign in to a website" } })).status).toBe(202);+ const [apns] = providers.apns();+ expect(apns!.headers["apns-collapse-id"]).toBe("openmaus.th_1.42");+ expect(JSON.parse(apns!.text).aps).toMatchObject({ category: "OPENMAUS_UPDATE", "interruption-level": "time-sensitive" });+ const row = await env.DB.prepare("SELECT platform FROM installation_push_devices").first<{ platform: string }>();+ expect(row?.platform).toBe("apns");+ });++ it("reads the service-account file whole, and nothing malformed", async () => {+ const account = await serviceAccount();+ expect(readFcmConfig(testEnv({ FCM_SERVICE_ACCOUNT: account.json }))).toMatchObject({ projectId: PROJECT, clientEmail: account.file.client_email });+ const escaped = JSON.stringify({ ...account.file, private_key: account.file.private_key.replaceAll("\n", "\\n") });+ expect(readFcmConfig(testEnv({ FCM_SERVICE_ACCOUNT: escaped }))).not.toBeNull();+ for (const broken of [+ "not json",+ JSON.stringify({ ...account.file, project_id: "Bad Project" }),+ JSON.stringify({ ...account.file, client_email: "[email protected]" }),+ JSON.stringify({ ...account.file, private_key: "not a key" }),+ JSON.stringify([account.file]),+ "",+ ]) {+ expect(readFcmConfig(testEnv({ FCM_SERVICE_ACCOUNT: broken })), broken.slice(0, 30)).toBeNull();+ }+ expect(readFcmConfig(env)).toBeNull();+ });+});diff --git a/cloudflare/control-plane/test/push.test.ts b/cloudflare/control-plane/test/push.test.tsindex 925fb7e793..485f809de9 100644--- a/cloudflare/control-plane/test/push.test.ts+++ b/cloudflare/control-plane/test/push.test.ts@@ -181,9 +181,11 @@ describe("phone push relay", () => {alert: { title: "Scout in Launch needs approval" },sound: "default","thread-id": "th_1",+ category: "OPENMAUS_APPROVAL","interruption-level": "time-sensitive",},omb: { v: 1, kind: "approval", botId: "bot_1", botName: "Scout", threadId: "th_1", roomId: "grp_1", roomName: "Launch", pairing: "pair-tag-1" },+ body: { v: 1, kind: "approval", botId: "bot_1", botName: "Scout", threadId: "th_1", roomId: "grp_1", roomName: "Launch", pairing: "pair-tag-1" },});const jwt = sent!.headers.authorization!.replace(/^bearer /, "");diff --git a/cloudflare/control-plane/test/setup.ts b/cloudflare/control-plane/test/setup.tsindex 8be521fc85..cbccd86616 100644--- a/cloudflare/control-plane/test/setup.ts+++ b/cloudflare/control-plane/test/setup.ts@@ -10,6 +10,7 @@ declare global {namespace Cloudflare {interface Env {MIGRATION_DB: D1Database;+ PUSH_MIGRATION_DB: D1Database;TEST_MIGRATIONS: D1Migration[];/** wrangler.jsonc's CLOUDFLARE_ENDPOINT_ACCOUNTS, as JSON. */TEST_PRODUCTION_ENDPOINT_ACCOUNTS: string;diff --git a/cloudflare/control-plane/vitest.config.ts b/cloudflare/control-plane/vitest.config.tsindex 6e2723a285..551b6a39d0 100644--- a/cloudflare/control-plane/vitest.config.ts+++ b/cloudflare/control-plane/vitest.config.ts@@ -38,7 +38,7 @@ export default defineConfig({},// An empty database for migration tests that need data written by an// older schema before the next migration runs.- d1Databases: ["MIGRATION_DB"],+ d1Databases: ["MIGRATION_DB", "PUSH_MIGRATION_DB"],},})),],