Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Control plane: Live Activities and Android ongoing notifications by push (#5988)
Milind Sonib7c3c67cc7e1
diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.mdindex ce07103d8f..5e20c96517 100644--- a/cloudflare/control-plane/README.md+++ b/cloudflare/control-plane/README.md@@ -224,6 +224,22 @@ shape.success. Limits: 600 sends per installation and 60 per token per hour (`429rate_limited`, `Retry-After: 60`).+- `register` also takes `"purpose": "activity"` (one Live Activity's update+ token) or `"activity-start"` (the app's Live Activity push-to-start token) for+ an APNs token; the default is `alert`. A send is refused (`404+ push_device_unknown`) for a token registered for another purpose: alerts go+ to `alert` tokens, a start to the `activity-start` token, an update or end to+ that activity's own token.+- `activity` `{ "v": 1, "token", "event": "start" | "update" | "end", "alert"?,+ "activity": { "botId", "botName", "kind": "needsYou" | "working", "headline",+ "since", "link", "color", "gradient", "body" } }` starts, updates or ends a+ bot's Live Activity on iPhone, or sends an FCM token the data message the+ Android app turns into its ongoing "working" notification. The schema is as+ strict as `send`'s: `headline` is one line of at most 120 characters (the+ phone's own words, "Scout needs you", with the name filled in), `link` must+ be the app's chat link, colours are `#rrggbb`, and there is no field for a+ line of text or an answer. Same limits and answers as `send`.+`collapseId` is the identifier the phone gives the notification the livestream would have posted (`openmaus.<threadId>.<seq>`), so a push and thatnotification replace each other instead of showing twice. Without one, the@@ -249,6 +265,19 @@ 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.+**Live Activities.** `POST https://api.push.apple.com/3/device/<token>`+with `apns-push-type: liveactivity`, `apns-topic: <bundle id>.push-type.liveactivity`,+priority 10 for a start or a ringing update and 5 otherwise, a 15-minute+expiration, and `{ "aps": { "timestamp", "event", "content-state": { "name":+"BotActivity", "props": <the app's BotActivityProps as JSON, with an empty line+and no answers> }, "stale-date" (now + 15 min) | "dismissal-date" (an end),+"attributes-type": "LiveActivityAttributes" and "attributes": { "url" } (a+start), "alert"? } }`. `BotActivity` and `LiveActivityAttributes` are the+names the phone app's Live Activity is registered under (expo-widgets). For an+FCM token: a data-only message `{ "omb_kind": "activity", "event", "bot_id",+"bot_name", "kind", "headline", "since", "link", "alert", "sent_at" }`, priority+`HIGH` when the bot needs the person or the activity ends, else `NORMAL`.+**FCM.** An OAuth access token from `https://oauth2.googleapis.com/token`(the JWT bearer grant: an RS256 assertion signed with the service account'skey, scope `firebase.messaging`; the file's own `token_uri` is ignored),@@ -276,7 +305,8 @@ 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 itstokens. D1 stores, per row, the installation id, the token, its SHA-256, the-platform, the environment and timestamps (`migrations/0008`, `0017`).+platform, the purpose, the environment and timestamps (`migrations/0008`, `0017`,+`0018`).**Secrets the maintainer sets** (all with `wrangler secret put <NAME>--config wrangler.jsonc`; none belongs in `vars`, this file, or CI output):@@ -292,7 +322,7 @@ platform, the environment and timestamps (`migrations/0008`, `0017`).They are deliberately not in `secrets.required`: the Worker is completewithout them, with phone push off, until the keys exist. Apply-`migrations/0008` and `0017` before deploying the Worker that uses them. For+`migrations/0008`, `0017` and `0018` before deploying the Worker that uses them. Fora local trial with `wrangler dev`, `.dev.vars` is read only for declarednames, so add these names to `secrets.required` in a local, uncommitted copyof the config.@@ -887,7 +917,7 @@ 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` and `0017`, then set+8. Optional, for closed-app phone alerts: apply `migrations/0008`, `0017` and `0018`, then setthe APNs and FCM secrets listed under **Phone push relay**. Without them thepush routes answer `503 push_unavailable` and nothing else changes.9. Deploy the Worker and verify that `GET <BETTER_AUTH_URL>/healthz` returnsdiff --git a/cloudflare/control-plane/migrations/0018_push_purpose.sql b/cloudflare/control-plane/migrations/0018_push_purpose.sqlnew file mode 100644index 0000000000..39f8f2b451--- /dev/null+++ b/cloudflare/control-plane/migrations/0018_push_purpose.sql@@ -0,0 +1,5 @@+-- What an APNs token is for: alerts (every row so far), one Live Activity's+-- update token, or the app's Live Activity push-to-start token. A send is+-- refused for a token registered for another purpose.+ALTER TABLE installation_push_devices+ ADD COLUMN purpose TEXT NOT NULL DEFAULT 'alert' CHECK (purpose IN ('alert', 'activity', 'activity-start'));diff --git a/cloudflare/control-plane/src/index.ts b/cloudflare/control-plane/src/index.tsindex dab87302f2..bf7d3c4a5f 100644--- a/cloudflare/control-plane/src/index.ts+++ b/cloudflare/control-plane/src/index.ts@@ -13,6 +13,7 @@ import {sweepManagedEndpointCleanup,} from "./endpoints";import { registerPushDevice, sendPush, unregisterPushDevice } from "./push";+import { sendActivityPush } from "./push-activity";import { issueRelayToken, relayAdoption } from "./relay";import { releaseTunnels, tunnelReleaseHealth } from "./tunnel-release";import { capacityHealth, reportEndpointAccountProblems, scanTunnelCapacity } from "./tunnel-capacity";@@ -147,6 +148,9 @@ async function route(if (request.method === "POST" && url.pathname === "/v1/installations/self/push/send") {return sendPush(request, env, pushFetch, requestId);}+ if (request.method === "POST" && url.pathname === "/v1/installations/self/push/activity") {+ return sendActivityPush(request, env, pushFetch, requestId);+ }const rotate = url.pathname.match(ROTATE_ROUTE);if (request.method === "POST" && rotate) {diff --git a/cloudflare/control-plane/src/push-activity.ts b/cloudflare/control-plane/src/push-activity.tsnew file mode 100644index 0000000000..36dfbb5566--- /dev/null+++ b/cloudflare/control-plane/src/push-activity.ts@@ -0,0 +1,122 @@+// A bot's Live Activity on iPhone (APNs `liveactivity`) and its ongoing "working" notification on Android (an FCM data+// message), started, updated and ended by push while the phone app is closed. Names, kind and a headline only: never+// message text, never an answer link.+import { z } from "zod";++import { errorResponse } from "./http";+import { FCM_TTL } from "./push-fcm";+import { sendToRegistered, type PlannedDelivery } from "./push";++/** The phone app's Live Activity, as expo-widgets (SDK 58) registers it: its name, and its ActivityAttributes type. */+export const LIVE_ACTIVITY_NAME = "BotActivity";+export const LIVE_ACTIVITY_ATTRIBUTES = "LiveActivityAttributes";+/** How long an activity is shown as current without news; the phone app's own freshness window. */+export const ACTIVITY_STALE_SECONDS = 15 * 60;+const ACTIVITY_EXPIRATION_SECONDS = 15 * 60;++const TOKEN = /^[A-Za-z0-9_:-]{64,4096}$/;+const ID = /^[\w-]{1,120}$/;+const HEX = /^#[0-9A-Fa-f]{6}$/;+const BODY = /^[a-z][a-z0-9-]{0,39}$/;+/** A chat link in any of the app's schemes. */+const LINK = /^openmausbot(?:-dev|-next)?:\/\/chat\/[A-Za-z0-9%_.-]{1,360}$/;++function oneLine(max: number) {+ return z.string().min(1).max(max * 4).refine((value) => {+ if (value.trim() !== value || [...value].length > max) return false;+ return !/[\p{Cc}\u2028\u2029]/u.test(value);+ });+}++const activitySchema = z.strictObject({+ v: z.literal(1),+ token: z.string().regex(TOKEN),+ event: z.enum(["start", "update", "end"]),+ /** Ring with the headline: a bot started needing the person. */+ alert: z.boolean().optional(),+ activity: z.strictObject({+ botId: z.string().regex(ID),+ botName: oneLine(80),+ kind: z.enum(["needsYou", "working"]),+ /** "Scout needs you", in the phone's language: the phone registered the words, the server filled the name. */+ headline: oneLine(120),+ /** When the current kind began (epoch ms). */+ since: z.number().int().nonnegative().max(8.64e15),+ link: z.string().regex(LINK),+ color: z.string().regex(HEX),+ gradient: z.array(z.string().regex(HEX)).min(1).max(4),+ body: z.string().regex(BODY),+ }),+});+export type ActivitySendRequest = z.infer<typeof activitySchema>;++/** The phone app's `BotActivityProps` for a pushed state: no line of text, no answers. */+export function activityProps(activity: ActivitySendRequest["activity"]) {+ return {+ botId: activity.botId,+ name: activity.botName,+ color: activity.color,+ gradient: activity.gradient,+ body: activity.body,+ mood: activity.kind,+ kind: activity.kind,+ headline: activity.headline,+ line: "",+ since: activity.since,+ link: activity.link,+ answers: [],+ };+}++export function liveActivityPayload(request: ActivitySendRequest, now: number) {+ const seconds = Math.floor(now / 1_000);+ const contentState = { name: LIVE_ACTIVITY_NAME, props: JSON.stringify(activityProps(request.activity)) };+ return {+ aps: {+ timestamp: seconds,+ event: request.event,+ "content-state": contentState,+ ...(request.event === "end" ? { "dismissal-date": seconds } : { "stale-date": seconds + ACTIVITY_STALE_SECONDS }),+ ...(request.event === "start" ? { "attributes-type": LIVE_ACTIVITY_ATTRIBUTES, attributes: { url: request.activity.link } } : {}),+ ...(request.alert && request.event !== "end" ? { alert: { title: request.activity.headline, body: request.activity.botName, sound: "default" } } : {}),+ },+ };+}++/** A data message the phone's own messaging service turns into its ongoing notification (`omb_kind: activity`). */+export function activityFcmPayload(request: ActivitySendRequest, now: number) {+ const { activity } = request;+ return {+ message: {+ token: request.token,+ data: {+ omb_kind: "activity",+ event: request.event,+ bot_id: activity.botId,+ bot_name: activity.botName,+ kind: activity.kind,+ headline: activity.headline,+ since: String(activity.since),+ link: activity.link,+ alert: request.alert ? "1" : "0",+ sent_at: String(now),+ },+ android: { priority: activity.kind === "needsYou" || request.event === "end" ? "HIGH" : "NORMAL", ttl: FCM_TTL },+ },+ };+}++export async function sendActivityPush(request: Request, env: Env, pushFetch: typeof fetch, requestId: string): Promise<Response> {+ return sendToRegistered(request, env, pushFetch, requestId, activitySchema, async (body, row, config, now): Promise<PlannedDelivery | Response> => {+ if (row.platform === "fcm") {+ if (!config.fcm) return errorResponse(503, "push_unavailable");+ return { kind: "fcm", config: config.fcm, payload: activityFcmPayload(body, now) };+ }+ // A start goes to the push-to-start token only, an update or an end to that activity's own token only.+ const wanted = body.event === "start" ? "activity-start" : "activity";+ if (row.purpose !== wanted) return errorResponse(404, "push_device_unknown");+ if (!config.apns) return errorResponse(503, "push_unavailable");+ const priority = body.alert || body.event === "start" ? 10 : 5;+ return { kind: "apns", config: config.apns, pushType: "liveactivity", priority, expiresInSeconds: ACTIVITY_EXPIRATION_SECONDS, payload: liveActivityPayload(body, now) };+ });+}diff --git a/cloudflare/control-plane/src/push.ts b/cloudflare/control-plane/src/push.tsindex fe94ce76a8..97ac1720e0 100644--- a/cloudflare/control-plane/src/push.ts+++ b/cloudflare/control-plane/src/push.ts@@ -17,6 +17,8 @@ import {} from "./push-fcm";export type PushPlatform = "apns" | "fcm";+/** What an APNs token is for: alerts, one Live Activity's updates, or starting a Live Activity (push-to-start). */+export type PushPurpose = "alert" | "activity" | "activity-start";export type ApnsEnvironment = "production" | "sandbox";@@ -79,6 +81,7 @@ const registerSchema = z.union([z.strictObject({v: z.literal(1),platform: z.literal("apns").optional(),+ purpose: z.enum(["alert", "activity", "activity-start"]).optional(),token: z.string().regex(TOKEN),environment: z.enum(["production", "sandbox"]),}),@@ -240,7 +243,7 @@ export async function pushCollapseId(request: PushSendRequest): Promise<string>return request.collapseId ?? (await sha256(`${request.notification.kind}:${request.notification.threadId}`)).slice(0, 32);}-interface PushConfig {+export interface PushConfig {apns: ApnsConfig | null;fcm: FcmConfig | null;}@@ -250,11 +253,11 @@ export function readPushConfig(env: Env): PushConfig | null {return config.apns || config.fcm ? config : null;}-function unavailable(): never {+export function unavailable(): never {throw new HTTPError(503, "push_unavailable");}-async function parse<T>(request: Request, schema: z.ZodType<T>): Promise<T> {+export async function parse<T>(request: Request, schema: z.ZodType<T>): Promise<T> {const parsed = schema.safeParse(await readBoundedJSON(request));if (!parsed.success) throw new HTTPError(400, "invalid_request");return parsed.data;@@ -286,6 +289,7 @@ export async function registerPushDevice(request: Request, env: Env): Promise<Reconst body = await parse(request, registerSchema);const platform: PushPlatform = body.platform ?? "apns";const environment: ApnsEnvironment = body.environment ?? "production";+ const purpose: PushPurpose = body.platform === "fcm" ? "alert" : body.purpose ?? "alert";if (platform === "fcm" && !config.fcm) unavailable();if (platform === "apns") {const apns = config.apns ?? unavailable();@@ -297,16 +301,16 @@ export async function registerPushDevice(request: Request, env: Env): Promise<Reconst tokenHash = await sha256(body.token);const [updated, inserted] = await env.DB.batch([env.DB.prepare(- `UPDATE installation_push_devices SET platform = ?, environment = ?, updated_at = ?+ `UPDATE installation_push_devices SET platform = ?, environment = ?, purpose = ?, updated_at = ?WHERE installation_id = ? AND token_hash = ?`,- ).bind(platform, environment, now, installation.installation_id, tokenHash),+ ).bind(platform, environment, purpose, now, installation.installation_id, tokenHash),env.DB.prepare(`INSERT INTO installation_push_devices- (installation_id, token_hash, platform, token, environment, created_at, updated_at)- SELECT ?, ?, ?, ?, ?, ?, ?+ (installation_id, token_hash, platform, token, environment, purpose, 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, platform, body.token, environment, now, now, installation.installation_id, PUSH_DEVICE_LIMIT),+ ).bind(installation.installation_id, tokenHash, platform, body.token, environment, purpose, 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 });@@ -321,23 +325,46 @@ export async function unregisterPushDevice(request: Request, env: Env): Promise<return new Response(null, { status: 204, headers: { "cache-control": "no-store" } });}-interface DeviceRow {+export interface DeviceRow {token: string;platform: PushPlatform;environment: ApnsEnvironment;+ purpose: PushPurpose;}-export async function sendPush(+/** What one provider request is: APNs headers and body for a token, or an FCM message. */+export type PlannedDelivery =+ | { kind: "apns"; config: ApnsConfig; pushType: "alert" | "liveactivity"; priority: 5 | 10; expiresInSeconds: number; collapseId?: string; payload: unknown }+ | { kind: "fcm"; config: FcmConfig; payload: unknown };++export async function sendPush(request: Request, env: Env, pushFetch: typeof fetch, requestId: string): Promise<Response> {+ return sendToRegistered(request, env, pushFetch, requestId, sendSchema, async (body, row, config) => {+ if (row.purpose !== "alert") return errorResponse(404, "push_device_unknown");+ const collapseId = await pushCollapseId(body);+ if (row.platform === "apns" && config.apns) {+ return { kind: "apns", config: config.apns, pushType: "alert", priority: 10, expiresInSeconds: APNS_EXPIRATION_SECONDS, collapseId, payload: apnsPayload(body) };+ }+ if (row.platform === "fcm" && config.fcm) return { kind: "fcm", config: config.fcm, payload: fcmPayload(body, body.token, collapseId) };+ return errorResponse(503, "push_unavailable");+ });+}++/**+ * The shared half of every send: parse, authenticate (the device read rides in the authentication's own D1 batch),+ * check the token is this installation's, take from both rate windows, ask the provider, and map its answer.+ */+export async function sendToRegistered<T extends { token: string }>(request: Request,env: Env,pushFetch: typeof fetch,requestId: string,+ schema: z.ZodType<T>,+ plan: (body: T, row: DeviceRow, config: PushConfig, now: number) => Promise<PlannedDelivery | Response>,): Promise<Response> {- // Parse before authenticating so the device read rides in the authentication's own D1 batch.- let body: PushSendRequest | null = null;+ let body: T | null = null;let parseError: HTTPError | null = null;try {- body = await parse(request, sendSchema);+ body = await parse(request, schema);} catch (error) {if (!(error instanceof HTTPError)) throw error;parseError = error;@@ -345,17 +372,17 @@ 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, platform, environment FROM installation_push_devices WHERE installation_id = ? AND token_hash = ?",+ "SELECT token, platform, environment, purpose FROM installation_push_devices WHERE installation_id = ? AND token_hash = ?",).bind(installationId, tokenHash): null);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();+ const planned = await plan(body, row, config, now);+ if (planned instanceof Response) return planned;// Read both windows before taking from either, so a send refused by one limit does not spend the other.const limits = [{ action: "push_send", limit: PUSH_SEND_LIMIT },@@ -370,10 +397,9 @@ 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);- 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");+ const outcome = planned.kind === "apns"+ ? await deliverApns(planned, row.environment, body.token, pushFetch, now)+ : await deliverFcm(planned.config, JSON.stringify(planned.payload), pushFetch, now);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)@@ -405,14 +431,14 @@ const DEAD_TOKEN_REASONS = new Set(["BadDeviceToken", "DeviceTokenNotForTopic",const PROVIDER_TOKEN_REASONS = new Set(["ExpiredProviderToken", "InvalidProviderToken", "MissingProviderToken"]);async function deliverApns(- config: ApnsConfig,+ planned: Extract<PlannedDelivery, { kind: "apns" }>,environment: ApnsEnvironment,- request: PushSendRequest,+ token: string,apnsFetch: typeof fetch,now: number,): Promise<Delivery> {- const payload = JSON.stringify(apnsPayload(request));- const collapseId = await pushCollapseId(request);+ const { config } = planned;+ const payload = JSON.stringify(planned.payload);for (let attempt = 0; attempt < 2; attempt += 1) {let providerToken: string;try {@@ -422,15 +448,16 @@ async function deliverApns(}let response: Response;try {- response = await apnsFetch(`${APNS_HOSTS[environment]}/3/device/${request.token}`, {+ response = await apnsFetch(`${APNS_HOSTS[environment]}/3/device/${token}`, {method: "POST",headers: {authorization: `bearer ${providerToken}`,- "apns-topic": config.bundleId,- "apns-push-type": "alert",- "apns-priority": "10",- "apns-expiration": String(Math.floor(now / 1_000) + APNS_EXPIRATION_SECONDS),- "apns-collapse-id": collapseId,+ // A Live Activity push goes to the app's topic with Apple's fixed suffix.+ "apns-topic": planned.pushType === "liveactivity" ? `${config.bundleId}.push-type.liveactivity` : config.bundleId,+ "apns-push-type": planned.pushType,+ "apns-priority": String(planned.priority),+ "apns-expiration": String(Math.floor(now / 1_000) + planned.expiresInSeconds),+ ...(planned.collapseId ? { "apns-collapse-id": planned.collapseId } : {}),"content-type": "application/json",},body: payload,@@ -459,8 +486,7 @@ async function deliverApns(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)));+async function deliverFcm(config: FcmConfig, payload: string, pushFetch: typeof fetch, now: number): Promise<Delivery> {for (let attempt = 0; attempt < 2; attempt += 1) {const access = await fcmAccessToken(config, pushFetch, now);if (access.kind !== "ok") return access;diff --git a/cloudflare/control-plane/test/migrations.test.ts b/cloudflare/control-plane/test/migrations.test.tsindex 20f2fc3b13..5094e59909 100644--- a/cloudflare/control-plane/test/migrations.test.ts+++ b/cloudflare/control-plane/test/migrations.test.ts@@ -81,3 +81,18 @@ describe("migration 0017", () => {).bind("e".repeat(64), long).run()).rejects.toThrow();});});++describe("migration 0018", () => {+ it("gives every existing push token the alert purpose and refuses an unknown one", async () => {+ const rows = await env.DB.prepare("SELECT purpose FROM installation_push_devices LIMIT 1").all();+ expect(rows.success).toBe(true);+ const db = env.PUSH_MIGRATION_DB;+ // 0017's test left one apns row in this database, written before 0018 existed.+ const kept = await db.prepare("SELECT purpose FROM installation_push_devices WHERE token_hash = ?").bind("c".repeat(64)).first<{ purpose: string }>();+ expect(kept?.purpose).toBe("alert");+ await expect(db.prepare(+ `INSERT INTO installation_push_devices (installation_id, token_hash, platform, token, environment, purpose, created_at, updated_at)+ VALUES ('inst_1', ?, 'apns', ?, 'production', 'banner', 1, 1)`,+ ).bind("f".repeat(64), "ab".repeat(32)).run()).rejects.toThrow();+ });+});diff --git a/cloudflare/control-plane/test/push-activity.test.ts b/cloudflare/control-plane/test/push-activity.test.tsnew file mode 100644index 0000000000..453233e1d6--- /dev/null+++ b/cloudflare/control-plane/test/push-activity.test.ts@@ -0,0 +1,196 @@+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 { forgetFcmAccessToken } from "../src/push-fcm";++const BASE_URL = "https://auth.openmausbot.test";+const ACTIVITY_TOKEN = "ac".repeat(40);+const START_TOKEN = "5a".repeat(40);+const ALERT_TOKEN = "a1".repeat(32);+const FCM_TOKEN = `cXyZ_1234567890-abc:APA91b${"F".repeat(140)}`;++type TestWorker = ReturnType<typeof createWorker>;+interface Call { url: string; headers: Record<string, string>; text: string }++function fakeProviders() {+ const calls: Call[] = [];+ 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;+ if (host === "oauth2.googleapis.com") return Response.json({ access_token: "ya29.test", expires_in: 3599 });+ return new Response(host === "fcm.googleapis.com" ? "{}" : null, { status: 200 });+ }) as typeof fetch;+ const apns = () => calls.filter((call) => call.url.includes("push.apple.com"));+ const fcm = () => calls.filter((call) => call.url.includes("fcm.googleapis.com"));+ return { calls, fetch: fetchImpl, apns, fcm };+}++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 pushEnv(): Promise<Env> {+ const ec = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]) as CryptoKeyPair;+ const rsa = 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;+ return {+ ...env,+ APNS_KEY_ID: "KEY1234567",+ APNS_TEAM_ID: "TEAM123456",+ APNS_BUNDLE_ID: "com.example.mausbot",+ APNS_PRIVATE_KEY: pem(await crypto.subtle.exportKey("pkcs8", ec.privateKey) as ArrayBuffer),+ FCM_SERVICE_ACCOUNT: JSON.stringify({ project_id: "mausbot-test-1", client_email: "[email protected]", private_key: pem(await crypto.subtle.exportKey("pkcs8", rsa.privateKey) as ArrayBuffer) }),+ } 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 ctx = createExecutionContext();+ const response = await worker.fetch(new Request(`${BASE_URL}${path}`, { method: "POST", headers, body: options.body === undefined ? undefined : JSON.stringify(options.body) }), 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 } });+ const created = await call(worker, environment, "/v1/installations", {+ token: signedIn.headers.get("set-auth-token")!,+ body: { clientInstanceId: crypto.randomUUID(), name: "Test computer", platform: "linux" },+ });+ return (await created.json<{ credential: string }>()).credential;+}++const activity = {+ botId: "bot_1",+ botName: "Scout",+ kind: "needsYou",+ headline: "Scout needs you",+ since: 1_794_700_000_000,+ link: "openmausbot://chat/th_1",+ color: "#7C5CFF",+ gradient: ["#7C5CFF", "#4A2FE0"],+ body: "round",+};++const register = (worker: TestWorker, environment: Env, credential: string, body: Record<string, unknown>) =>+ call(worker, environment, "/v1/installations/self/push/register", { token: credential, body: { v: 1, environment: "production", ...body } });+const push = (worker: TestWorker, environment: Env, credential: string, body: Record<string, unknown>) =>+ call(worker, environment, "/v1/installations/self/push/activity", { token: credential, body: { v: 1, activity, ...body } });++describe("Live Activities and ongoing notifications by push", () => {+ beforeEach(() => forgetFcmAccessToken());++ it("updates a registered activity through APNs liveactivity, with names and kind only", async () => {+ const environment = await pushEnv();+ const providers = fakeProviders();+ const worker = createWorker(fetch, providers.fetch);+ const credential = await installation(worker, environment, "[email protected]");+ expect((await register(worker, environment, credential, { purpose: "activity", token: ACTIVITY_TOKEN })).status).toBe(200);+ const before = Math.floor(Date.now() / 1_000);+ expect((await push(worker, environment, credential, { token: ACTIVITY_TOKEN, event: "update", activity: { ...activity, kind: "working", headline: "Scout is working" } })).status).toBe(202);++ const [sent] = providers.apns();+ expect(sent!.url).toBe(`https://api.push.apple.com/3/device/${ACTIVITY_TOKEN}`);+ expect(sent!.headers).toMatchObject({ "apns-push-type": "liveactivity", "apns-topic": "com.example.mausbot.push-type.liveactivity", "apns-priority": "5" });+ expect(sent!.headers["apns-collapse-id"]).toBeUndefined();+ const body = JSON.parse(sent!.text) as { aps: Record<string, unknown> & { "content-state": { name: string; props: string } } };+ expect(body.aps).toMatchObject({ event: "update", "content-state": { name: "BotActivity" } });+ expect(body.aps["stale-date"]).toBeGreaterThanOrEqual(before + 15 * 60);+ expect(body.aps.alert).toBeUndefined();+ expect(JSON.parse(body.aps["content-state"].props)).toEqual({+ botId: "bot_1", name: "Scout", color: "#7C5CFF", gradient: ["#7C5CFF", "#4A2FE0"], body: "round",+ mood: "working", kind: "working", headline: "Scout is working", line: "", since: 1_794_700_000_000, link: "openmausbot://chat/th_1", answers: [],+ });+ });++ it("starts one with the push-to-start token, ringing, and ends one with a dismissal date", async () => {+ const environment = await pushEnv();+ const providers = fakeProviders();+ const worker = createWorker(fetch, providers.fetch);+ const credential = await installation(worker, environment, "[email protected]");+ await register(worker, environment, credential, { purpose: "activity-start", token: START_TOKEN });+ await register(worker, environment, credential, { purpose: "activity", token: ACTIVITY_TOKEN });+ expect((await push(worker, environment, credential, { token: START_TOKEN, event: "start", alert: true })).status).toBe(202);+ expect((await push(worker, environment, credential, { token: ACTIVITY_TOKEN, event: "end" })).status).toBe(202);++ const [start, end] = providers.apns().map((one) => ({ headers: one.headers, aps: (JSON.parse(one.text) as { aps: Record<string, unknown> }).aps }));+ expect(start!.headers["apns-priority"]).toBe("10");+ expect(start!.aps).toMatchObject({ event: "start", "attributes-type": "LiveActivityAttributes", attributes: { url: "openmausbot://chat/th_1" }, alert: { title: "Scout needs you", body: "Scout", sound: "default" } });+ expect(end!.aps.event).toBe("end");+ expect(end!.aps["dismissal-date"]).toEqual(expect.any(Number));+ expect(end!.aps["stale-date"]).toBeUndefined();+ expect(end!.aps.alert).toBeUndefined();+ });++ it("sends each token only what it was registered for", async () => {+ const environment = await pushEnv();+ const providers = fakeProviders();+ const worker = createWorker(fetch, providers.fetch);+ const credential = await installation(worker, environment, "[email protected]");+ await register(worker, environment, credential, { purpose: "activity-start", token: START_TOKEN });+ await register(worker, environment, credential, { purpose: "activity", token: ACTIVITY_TOKEN });+ await register(worker, environment, credential, { token: ALERT_TOKEN });+ expect((await push(worker, environment, credential, { token: ACTIVITY_TOKEN, event: "start" })).status).toBe(404);+ expect((await push(worker, environment, credential, { token: START_TOKEN, event: "update" })).status).toBe(404);+ expect((await push(worker, environment, credential, { token: ALERT_TOKEN, event: "update" })).status).toBe(404);+ const alert = await call(worker, environment, "/v1/installations/self/push/send", {+ token: credential,+ body: { v: 1, token: ACTIVITY_TOKEN, notification: { kind: "done", title: "Scout finished", botId: "bot_1", botName: "Scout", threadId: "th_1" } },+ });+ expect(alert.status).toBe(404);+ expect(providers.calls).toEqual([]);+ expect((await register(worker, environment, credential, { platform: "fcm", purpose: "activity", token: FCM_TOKEN, environment: undefined })).status).toBe(400);+ });++ it("sends Android a data message for its ongoing notification, urgent only when the bot needs the person", async () => {+ const environment = await pushEnv();+ const providers = fakeProviders();+ const worker = createWorker(fetch, providers.fetch);+ const credential = await installation(worker, environment, "[email protected]");+ await register(worker, environment, credential, { platform: "fcm", token: FCM_TOKEN, environment: undefined });+ expect((await push(worker, environment, credential, { token: FCM_TOKEN, event: "update", alert: true })).status).toBe(202);+ expect((await push(worker, environment, credential, { token: FCM_TOKEN, event: "update", activity: { ...activity, kind: "working", headline: "Scout is working" } })).status).toBe(202);+ const [needs, working] = providers.fcm().map((one) => (JSON.parse(one.text) as { message: { data: Record<string, string>; android: { priority: string } } }).message);+ expect(needs!.data).toMatchObject({ omb_kind: "activity", event: "update", bot_id: "bot_1", bot_name: "Scout", kind: "needsYou", headline: "Scout needs you", since: "1794700000000", link: "openmausbot://chat/th_1", alert: "1" });+ expect(needs!.data.title).toBeUndefined();+ expect(needs!.android.priority).toBe("HIGH");+ expect(working!.android.priority).toBe("NORMAL");+ });++ it("refuses anything that could carry message text or an answer link", async () => {+ const environment = await pushEnv();+ const providers = fakeProviders();+ const worker = createWorker(fetch, providers.fetch);+ const credential = await installation(worker, environment, "[email protected]");+ await register(worker, environment, credential, { purpose: "activity", token: ACTIVITY_TOKEN });+ for (const body of [+ { activity: { ...activity, line: "the reply text" } },+ { activity: { ...activity, answers: [{ label: "Allow", link: "openmausbot://answer?key=secret" }] } },+ { activity: { ...activity, headline: "Scout\nneeds you" } },+ { activity: { ...activity, link: "https://example.com/phish" } },+ { activity: { ...activity, color: "red" } },+ { activity: { ...activity, kind: "done" } },+ { event: "dismiss" },+ { message: "hello" },+ ]) {+ expect((await push(worker, environment, credential, { token: ACTIVITY_TOKEN, event: "update", ...body })).status, JSON.stringify(body)).toBe(400);+ }+ expect(providers.calls).toEqual([]);+ });+});