Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phone push for Cloud homes: the control plane's machine routes and the home's Admin transport, off by default (#7170)
Milind Sonia6c853426284
diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.mdindex 344c71bc67..7f5377b22a 100644--- a/cloudflare/control-plane/README.md+++ b/cloudflare/control-plane/README.md@@ -319,6 +319,43 @@ tokens. D1 stores, per row, the installation id, the token, its SHA-256, theplatform, the purpose, the environment and timestamps (`migrations/0008`, `0017`,`0018`).+**Cloud homes** (`src/push-cloud-homes.ts`; the design in `docs/phone-push.md`,+"Cloud homes"). A MausBot Cloud home has no installation credential; the Admin+that runs it checks the home's own signature and relays its calls here, keyed+by the home's machine id:++- `POST /v1/cloud-homes/<machine id>/push/register`, `unregister`, `send` and+ `activity` take exactly the installation routes' bodies, schemas, answers and+ limits (50 tokens, 120 registrations, 600 sends and 60 per token an hour,+ each per machine), and send through the same path to APNs and FCM. A send+ reaches only a token registered under the same machine id (`404+ push_device_unknown` otherwise), never an installation's.+- `POST /v1/cloud-homes/<machine id>/push/forget` deletes every token and rate+ window of that machine: the Admin calls it when it retires or deletes the+ Cloud. `204`, also when there was nothing.+- The machine id is in the path, `[A-Za-z0-9][A-Za-z0-9_-]{2,127}`, never in+ the body; a body that carries one is `400 invalid_request`.+- Authentication is `Authorization: Bearer <CLOUD_HOME_PUSH_SECRET>`, the one+ secret the Admin and this Worker share (or `CLOUD_HOME_PUSH_SECRET_PREVIOUS`+ during a rotation), compared in constant time as SHA-256 digests. Neither set+ (or under 32 characters): `503 push_unavailable`; anything else: `401+ unauthorized`. An installation credential is not accepted here, nor this+ secret on the installation routes.+- Because that secret can name any machine id, the machine routes also share+ a fleet-wide window: 20,000 sends and 6,000 registrations an hour across every+ machine (`CLOUD_HOME_FLEET_SEND_LIMIT`, `CLOUD_HOME_FLEET_REGISTER_LIMIT`), so+ a leaked secret stays bounded. Rotate it by setting the current value as+ `CLOUD_HOME_PUSH_SECRET_PREVIOUS`, a new one as `CLOUD_HOME_PUSH_SECRET`, the+ new one in the Admin (`OMB_CLOUD_PUSH_RELAY_SECRET`), then deleting+ `CLOUD_HOME_PUSH_SECRET_PREVIOUS`.+- D1: `machine_push_devices` (the shape of `installation_push_devices`, with+ `machine_id` and no foreign key) and `machine_push_rate_limits` (the fleet's+ row has machine id `*`), `migrations/0019`. A token APNs or FCM calls dead is+ deleted from both tables.+- `test/fixtures/cloud-home-push.json` lists bodies these routes accept and+ refuse and the home's request signature; the Admin holds the same file byte+ for byte and checks its forwarded bodies against it.+**Secrets the maintainer sets** (all with `wrangler secret put <NAME>--config wrangler.jsonc`; none belongs in `vars`, this file, or CI output):@@ -329,11 +366,13 @@ platform, the purpose, the environment and timestamps (`migrations/0008`, `0017`| `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. |+| `CLOUD_HOME_PUSH_SECRET` | Optional. A random value of at least 32 characters, the same as the Admin's `OMB_CLOUD_PUSH_RELAY_SECRET`: the Admin's key to the Cloud homes' routes. Unset: those routes answer `503 push_unavailable`. |+| `CLOUD_HOME_PUSH_SECRET_PREVIOUS` | Optional, during a rotation only: the value before `CLOUD_HOME_PUSH_SECRET`. Delete it once the Admin has the new one. || `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 completewithout them, with phone push off, until the keys exist. Apply-`migrations/0008`, `0017` and `0018` before deploying the Worker that uses them. For+`migrations/0008`, `0017`, `0018` and `0019` 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.diff --git a/cloudflare/control-plane/migrations/0019_cloud_home_push.sql b/cloudflare/control-plane/migrations/0019_cloud_home_push.sqlnew file mode 100644index 0000000000..a774807225--- /dev/null+++ b/cloudflare/control-plane/migrations/0019_cloud_home_push.sql@@ -0,0 +1,35 @@+-- Phone push for Cloud homes (README "Phone push relay", "Cloud homes"). A+-- Cloud home has no installation: the Admin relays its pushes, keyed by the+-- home's machine id, with the one secret it shares with this Worker. Same+-- shape as installation_push_devices, with machine_id for installation_id and+-- no foreign key (a machine lives in the Admin, not here). Additive: nothing+-- an installation reads or writes changes.+CREATE TABLE machine_push_devices (+ machine_id TEXT NOT NULL CHECK (length(machine_id) BETWEEN 3 AND 128),+ 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')),+ purpose TEXT NOT NULL DEFAULT 'alert' CHECK (purpose IN ('alert', 'activity', 'activity-start')),+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ last_sent_at INTEGER,+ PRIMARY KEY (machine_id, token_hash)+);++CREATE INDEX machine_push_devices_token_idx+ ON machine_push_devices(token_hash);++-- The same hourly windows as installation_action_rate_limits, per machine.+-- The row with machine_id '*' (no machine id can be '*') is the whole fleet's.+CREATE TABLE machine_push_rate_limits (+ machine_id TEXT NOT NULL,+ action TEXT NOT NULL,+ window_started_at INTEGER NOT NULL,+ attempts INTEGER NOT NULL CHECK (attempts >= 1),+ updated_at INTEGER NOT NULL,+ PRIMARY KEY (machine_id, action)+);++CREATE INDEX machine_push_rate_limits_updated_idx+ ON machine_push_rate_limits(updated_at);diff --git a/cloudflare/control-plane/src/index.ts b/cloudflare/control-plane/src/index.tsindex bf7d3c4a5f..f35440c08f 100644--- a/cloudflare/control-plane/src/index.ts+++ b/cloudflare/control-plane/src/index.ts@@ -14,6 +14,7 @@ import {} from "./endpoints";import { registerPushDevice, sendPush, unregisterPushDevice } from "./push";import { sendActivityPush } from "./push-activity";+import { CLOUD_HOME_PUSH_ROUTE, routeCloudHomePush } from "./push-cloud-homes";import { issueRelayToken, relayAdoption } from "./relay";import { releaseTunnels, tunnelReleaseHealth } from "./tunnel-release";import { capacityHealth, reportEndpointAccountProblems, scanTunnelCapacity } from "./tunnel-capacity";@@ -152,6 +153,12 @@ async function route(return sendActivityPush(request, env, pushFetch, requestId);}+ // A Cloud home's push calls, relayed by the Admin (push-cloud-homes.ts): its shared secret, not an installation.+ const cloudHome = url.pathname.match(CLOUD_HOME_PUSH_ROUTE);+ if (cloudHome) {+ return routeCloudHomePush(request, env, pushFetch, requestId, cloudHome[1]!, cloudHome[2]!);+ }+const rotate = url.pathname.match(ROTATE_ROUTE);if (request.method === "POST" && rotate) {return rotateInstallationCredential(request, rotate[1], env, auth);diff --git a/cloudflare/control-plane/src/push-activity.ts b/cloudflare/control-plane/src/push-activity.tsindex 430635e8a8..94a255d679 100644--- a/cloudflare/control-plane/src/push-activity.ts+++ b/cloudflare/control-plane/src/push-activity.ts@@ -5,7 +5,7 @@ import { z } from "zod";import { errorResponse } from "./http";import { FCM_TTL } from "./push-fcm";-import { sendToRegistered, type PlannedDelivery } from "./push";+import { sendToRegistered, type DeviceRow, type PlannedDelivery, type PushConfig } 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";@@ -28,7 +28,7 @@ function oneLine(max: number) {});}-const activitySchema = z.strictObject({+export const activitySchema = z.strictObject({v: z.literal(1),token: z.string().regex(TOKEN),event: z.enum(["start", "update", "end"]),@@ -134,17 +134,20 @@ export function activityFcmPayload(request: ActivitySendRequest, now: number) {};}+/** A Live Activity start, update or end on iPhone, or Android's ongoing notification. */+export async function planActivity(body: ActivitySendRequest, row: DeviceRow, config: PushConfig, now: number): 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.event === "start" ? 10 : 5;+ return { kind: "apns", config: config.apns, pushType: "liveactivity", priority, expiresInSeconds: ACTIVITY_EXPIRATION_SECONDS, payload: liveActivityPayload(body, now) };+}+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.event === "start" ? 10 : 5;- return { kind: "apns", config: config.apns, pushType: "liveactivity", priority, expiresInSeconds: ACTIVITY_EXPIRATION_SECONDS, payload: liveActivityPayload(body, now) };- });+ return sendToRegistered(request, env, pushFetch, requestId, activitySchema, planActivity);}diff --git a/cloudflare/control-plane/src/push-cloud-homes.ts b/cloudflare/control-plane/src/push-cloud-homes.tsnew file mode 100644index 0000000000..1298f9add2--- /dev/null+++ b/cloudflare/control-plane/src/push-cloud-homes.ts@@ -0,0 +1,98 @@+// Phone push for Cloud homes (README "Phone push relay", "Cloud homes"; docs/phone-push.md "Cloud homes"). A Cloud home+// has no installation credential, so the Admin that runs it relays its push calls here: the same bodies as the+// installation routes, keyed by the home's machine id (in the path, never the body), authenticated by one secret only+// the Admin and this Worker hold. The Admin checks the home's own signature and derives the machine id from it; this+// Worker trusts the Admin for that, and bounds what a leaked secret could do with a fleet-wide limit.+import { timingSafeEqual } from "node:crypto";++import { errorResponse, HTTPError } from "./http";+import {+ MACHINE_PUSH_STORE,+ registerFor,+ sendAs,+ sendSchema,+ planAlert,+ unregisterFor,+ type DeviceRow,+ type PushLimit,+ type PushSender,+} from "./push";+import { activitySchema, planActivity } from "./push-activity";++/** `POST /v1/cloud-homes/<machine id>/push/<action>`. The machine id is the Admin's (`OMB_CLOUD_MACHINE_ID` on the home). */+export const CLOUD_HOME_PUSH_ROUTE = /^\/v1\/cloud-homes\/([A-Za-z0-9][A-Za-z0-9_-]{2,127})\/push\/(register|unregister|send|activity|forget)$/;+/** The Admin's secret, and the one before it while a rotation is under way. */+export const CLOUD_HOME_PUSH_SECRET_NAMES = ["CLOUD_HOME_PUSH_SECRET", "CLOUD_HOME_PUSH_SECRET_PREVIOUS"] as const;+const SECRET_MIN_LENGTH = 32;+/** The fleet's row in machine_push_rate_limits: no machine id can be `*`. */+export const FLEET_ID = "*";+/** Across every Cloud home in an hour. A leaked Admin secret can name any machine id, so the per-machine limits alone+ * would not bound it; these do. They sit well above what the fleet sends today (each home's own limits are 600 sends+ * and 120 registrations an hour) and are the owner's to change. */+export const CLOUD_HOME_FLEET_SEND_LIMIT = 20_000;+export const CLOUD_HOME_FLEET_REGISTER_LIMIT = 6_000;++const FLEET_SENDS: PushLimit = { owner: FLEET_ID, action: "push_send", limit: CLOUD_HOME_FLEET_SEND_LIMIT };+const FLEET_REGISTERS: PushLimit = { owner: FLEET_ID, action: "push_register", limit: CLOUD_HOME_FLEET_REGISTER_LIMIT };++export function cloudHomePushSecrets(env: Env): string[] {+ const vars = env as unknown as Partial<Record<string, unknown>>;+ return CLOUD_HOME_PUSH_SECRET_NAMES+ .map((name) => vars[name])+ .filter((value): value is string => typeof value === "string" && value.trim().length >= SECRET_MIN_LENGTH)+ .map((value) => value.trim());+}++async function digest(value: string): Promise<Uint8Array> {+ return new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)));+}++/** The Admin's bearer, compared in constant time with each configured secret (every one is compared). No secret set:+ * `503 push_unavailable`, so the Admin and its homes back off; a wrong one: `401 unauthorized`. */+export async function requireCloudHomeRelay(request: Request, env: Env): Promise<void> {+ const secrets = cloudHomePushSecrets(env);+ if (!secrets.length) throw new HTTPError(503, "push_unavailable");+ const bearer = request.headers.get("authorization")?.match(/^Bearer\s+([^\s]+)$/i)?.[1] ?? "";+ const given = await digest(bearer);+ let matched = false;+ for (const secret of secrets) matched = timingSafeEqual(given, await digest(secret)) || matched;+ if (!bearer || !matched) throw new HTTPError(401, "unauthorized");+}++function sender(request: Request, env: Env, machineId: string): PushSender {+ return {+ store: MACHINE_PUSH_STORE,+ fleet: [FLEET_SENDS],+ authenticate: async (read) => {+ await requireCloudHomeRelay(request, env);+ const row = read ? await read(machineId).first<DeviceRow>() : null;+ return { ownerId: machineId, row: row ?? null };+ },+ };+}++/** Every token and window of one machine: the Admin deleted or retired that Cloud. Idempotent. */+async function forget(env: Env, machineId: string): Promise<Response> {+ await env.DB.batch([+ env.DB.prepare("DELETE FROM machine_push_devices WHERE machine_id = ?").bind(machineId),+ env.DB.prepare("DELETE FROM machine_push_rate_limits WHERE machine_id = ?").bind(machineId),+ ]);+ return new Response(null, { status: 204, headers: { "cache-control": "no-store" } });+}++export async function routeCloudHomePush(+ request: Request,+ env: Env,+ pushFetch: typeof fetch,+ requestId: string,+ machineId: string,+ action: string,+): Promise<Response> {+ if (request.method !== "POST") return errorResponse(405, "method_not_allowed");+ if (action === "send") return sendAs(request, env, pushFetch, requestId, sendSchema, planAlert, sender(request, env, machineId));+ if (action === "activity") return sendAs(request, env, pushFetch, requestId, activitySchema, planActivity, sender(request, env, machineId));+ await requireCloudHomeRelay(request, env);+ if (action === "register") return registerFor(request, env, MACHINE_PUSH_STORE, machineId, [FLEET_REGISTERS]);+ if (action === "unregister") return unregisterFor(request, env, MACHINE_PUSH_STORE, machineId);+ return forget(env, machineId);+}diff --git a/cloudflare/control-plane/src/push.ts b/cloudflare/control-plane/src/push.tsindex 97ac1720e0..ee8233c1a9 100644--- a/cloudflare/control-plane/src/push.ts+++ b/cloudflare/control-plane/src/push.ts@@ -77,7 +77,7 @@ function oneLine(max: number) {});}-const registerSchema = z.union([+export const registerSchema = z.union([z.strictObject({v: z.literal(1),platform: z.literal("apns").optional(),@@ -92,12 +92,12 @@ const registerSchema = z.union([environment: z.literal("production").optional(),}),]);-const unregisterSchema = z.strictObject({+export const unregisterSchema = z.strictObject({v: z.literal(1),platform: z.enum(["apns", "fcm"]).optional(),token: z.string().regex(ANY_TOKEN),});-const sendSchema = z.strictObject({+export const sendSchema = z.strictObject({v: z.literal(1),token: z.string().regex(ANY_TOKEN),pairing: z.string().regex(PAIRING).optional(),@@ -269,22 +269,60 @@ function rateLimited(retryAfterSeconds: number): Response {return response;}-function limitStatement(env: Env, installationId: string, action: string, limit: number, now: number) {+/** Where a caller's push tokens and rate windows live: an installation's (the original tables), or a Cloud home's, which+ * the Admin relays for, keyed by its machine id (push-cloud-homes.ts). Table and column names are constants, never input. */+export interface PushStore {+ devices: "installation_push_devices" | "machine_push_devices";+ limits: "installation_action_rate_limits" | "machine_push_rate_limits";+ owner: "installation_id" | "machine_id";+}+export const INSTALLATION_PUSH_STORE: PushStore = { devices: "installation_push_devices", limits: "installation_action_rate_limits", owner: "installation_id" };+export const MACHINE_PUSH_STORE: PushStore = { devices: "machine_push_devices", limits: "machine_push_rate_limits", owner: "machine_id" };++/** One hourly window to take from: `owner` is the caller's id, or the fleet's row for a Cloud home's fleet limit. */+export interface PushLimit {+ owner: string;+ action: string;+ limit: number;+}++function limitStatement(env: Env, store: PushStore, ownerId: string, action: string, limit: number, now: number) {const cutoff = now - HOUR_MS;return env.DB.prepare(- `INSERT INTO installation_action_rate_limits- (installation_id, action, window_started_at, attempts, updated_at)+ `INSERT INTO ${store.limits}+ (${store.owner}, action, window_started_at, attempts, updated_at)VALUES (?, ?, ?, 1, ?)- ON CONFLICT(installation_id, action) DO UPDATE SET+ ON CONFLICT(${store.owner}, action) DO UPDATE SETwindow_started_at = CASE WHEN window_started_at <= ? THEN excluded.window_started_at ELSE window_started_at END,attempts = CASE WHEN window_started_at <= ? THEN 1 ELSE attempts + 1 END,updated_at = excluded.updated_atWHERE window_started_at <= ? OR attempts < ?`,- ).bind(installationId, action, now, now, cutoff, cutoff, cutoff, limit);+ ).bind(ownerId, action, now, now, cutoff, cutoff, cutoff, limit);+}++/** Takes one from every window, or from none: with several, all are read before any is taken, so a request refused by one+ * limit does not spend another. */+async function takeLimits(env: Env, store: PushStore, limits: PushLimit[], now: number): Promise<boolean> {+ if (limits.length > 1) {+ const full = await env.DB.prepare(+ `SELECT COUNT(*) AS full FROM ${store.limits}+ WHERE window_started_at > ? AND (${limits.map(() => `(${store.owner} = ? AND action = ? AND attempts >= ?)`).join(" OR ")})`,+ ).bind(now - HOUR_MS, ...limits.flatMap(({ owner, action, limit }) => [owner, action, limit]))+ .first<{ full: number }>();+ if (full?.full) return false;+ }+ const taken = await env.DB.batch(limits.map(({ owner, action, limit }) => limitStatement(env, store, owner, action, limit, now)));+ return !taken.some((result) => result.meta.changes === 0);}export async function registerPushDevice(request: Request, env: Env): Promise<Response> {const installation = await requireInstallation(request, env);+ return registerFor(request, env, INSTALLATION_PUSH_STORE, installation.installation_id, []);+}++/** Stores a device token for one owner, the caller already authenticated. `fleet`: more windows to take from (a Cloud+ * home's fleet-wide limit). */+export async function registerFor(request: Request, env: Env, store: PushStore, ownerId: string, fleet: PushLimit[]): Promise<Response> {const config = readPushConfig(env) ?? unavailable();const body = await parse(request, registerSchema);const platform: PushPlatform = body.platform ?? "apns";@@ -296,21 +334,20 @@ export async function registerPushDevice(request: Request, env: Env): Promise<Reif (!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);+ if (!await takeLimits(env, store, [{ owner: ownerId, action: "push_register", limit: PUSH_REGISTER_LIMIT }, ...fleet], now)) return rateLimited(60);const tokenHash = await sha256(body.token);const [updated, inserted] = await env.DB.batch([env.DB.prepare(- `UPDATE installation_push_devices SET platform = ?, environment = ?, purpose = ?, updated_at = ?- WHERE installation_id = ? AND token_hash = ?`,- ).bind(platform, environment, purpose, now, installation.installation_id, tokenHash),+ `UPDATE ${store.devices} SET platform = ?, environment = ?, purpose = ?, updated_at = ?+ WHERE ${store.owner} = ? AND token_hash = ?`,+ ).bind(platform, environment, purpose, now, ownerId, tokenHash),env.DB.prepare(- `INSERT INTO installation_push_devices- (installation_id, token_hash, platform, token, environment, purpose, created_at, updated_at)+ `INSERT INTO ${store.devices}+ (${store.owner}, 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, purpose, now, now, installation.installation_id, PUSH_DEVICE_LIMIT),+ WHERE (SELECT COUNT(*) FROM ${store.devices} WHERE ${store.owner} = ?) < ?+ ON CONFLICT(${store.owner}, token_hash) DO NOTHING`,+ ).bind(ownerId, tokenHash, platform, body.token, environment, purpose, now, now, ownerId, PUSH_DEVICE_LIMIT),]);if (updated?.meta.changes === 0 && inserted?.meta.changes === 0) throw new HTTPError(409, "push_device_limit");return json({ registered: true });@@ -318,9 +355,13 @@ export async function registerPushDevice(request: Request, env: Env): Promise<Reexport async function unregisterPushDevice(request: Request, env: Env): Promise<Response> {const installation = await requireInstallation(request, env);+ return unregisterFor(request, env, INSTALLATION_PUSH_STORE, installation.installation_id);+}++export async function unregisterFor(request: Request, env: Env, store: PushStore, ownerId: string): Promise<Response> {const body = await parse(request, unregisterSchema);- await env.DB.prepare("DELETE FROM installation_push_devices WHERE installation_id = ? AND token_hash = ?")- .bind(installation.installation_id, await sha256(body.token))+ await env.DB.prepare(`DELETE FROM ${store.devices} WHERE ${store.owner} = ? AND token_hash = ?`)+ .bind(ownerId, await sha256(body.token)).run();return new Response(null, { status: 204, headers: { "cache-control": "no-store" } });}@@ -337,16 +378,29 @@ 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 };+/** An alert to an `alert` token: APNs `alert` or an FCM data message. */+export async function planAlert(body: PushSendRequest, row: DeviceRow, config: PushConfig): Promise<PlannedDelivery | Response> {+ 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");+}+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");- });+ return sendToRegistered(request, env, pushFetch, requestId, sendSchema, planAlert);+}++type Plan<T> = (body: T, row: DeviceRow, config: PushConfig, now: number) => Promise<PlannedDelivery | Response>;++/** Who is sending: authenticates (an optional read of its own device row riding along) and names its windows. */+export interface PushSender {+ store: PushStore;+ authenticate(read: ((ownerId: string) => D1PreparedStatement) | null): Promise<{ ownerId: string; row: DeviceRow | null }>;+ /** More windows than the owner's own two (a Cloud home's fleet-wide limit). */+ fleet: PushLimit[];}/**@@ -359,8 +413,29 @@ export async function sendToRegistered<T extends { token: string }>(pushFetch: typeof fetch,requestId: string,schema: z.ZodType<T>,- plan: (body: T, row: DeviceRow, config: PushConfig, now: number) => Promise<PlannedDelivery | Response>,+ plan: Plan<T>,): Promise<Response> {+ return sendAs(request, env, pushFetch, requestId, schema, plan, {+ store: INSTALLATION_PUSH_STORE,+ fleet: [],+ authenticate: async (read) => {+ const { installation, row } = await requireInstallationAndRead<DeviceRow>(request, env, read);+ return { ownerId: installation.installation_id, row };+ },+ });+}++/** `sendToRegistered` for any sender: an installation, or a Cloud home through the Admin. */+export async function sendAs<T extends { token: string }>(+ request: Request,+ env: Env,+ pushFetch: typeof fetch,+ requestId: string,+ schema: z.ZodType<T>,+ plan: Plan<T>,+ sender: PushSender,+): Promise<Response> {+ const { store } = sender;let body: T | null = null;let parseError: HTTPError | null = null;try {@@ -370,10 +445,10 @@ export async function sendToRegistered<T extends { token: string }>(parseError = error;}const tokenHash = body ? await sha256(body.token) : "";- const { installation, row } = await requireInstallationAndRead<DeviceRow>(request, env, body- ? (installationId) => env.DB.prepare(- "SELECT token, platform, environment, purpose FROM installation_push_devices WHERE installation_id = ? AND token_hash = ?",- ).bind(installationId, tokenHash)+ const { ownerId, row } = await sender.authenticate(body+ ? (id) => env.DB.prepare(+ `SELECT token, platform, environment, purpose FROM ${store.devices} WHERE ${store.owner} = ? AND token_hash = ?`,+ ).bind(id, tokenHash): null);const config = readPushConfig(env) ?? unavailable();if (parseError || !body) throw parseError ?? new HTTPError(400, "invalid_request");@@ -383,37 +458,30 @@ export async function sendToRegistered<T extends { token: string }>(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 },- { action: `push_send:${tokenHash.slice(0, 32)}`, limit: PUSH_DEVICE_SEND_LIMIT },+ { owner: ownerId, action: "push_send", limit: PUSH_SEND_LIMIT },+ { owner: ownerId, action: `push_send:${tokenHash.slice(0, 32)}`, limit: PUSH_DEVICE_SEND_LIMIT },+ ...sender.fleet,];- const full = await env.DB.prepare(- `SELECT COUNT(*) AS full FROM installation_action_rate_limits- WHERE installation_id = ? AND window_started_at > ? AND ((action = ? AND attempts >= ?) OR (action = ? AND attempts >= ?))`,- ).bind(installation.installation_id, now - HOUR_MS, limits[0]!.action, limits[0]!.limit, limits[1]!.action, limits[1]!.limit)- .first<{ full: number }>();- if (full?.full) return rateLimited(60);- 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);+ if (!await takeLimits(env, store, limits, now)) return rateLimited(60);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)+ await env.DB.prepare(`UPDATE ${store.devices} SET last_sent_at = ? WHERE ${store.owner} = ? AND token_hash = ?`)+ .bind(now, ownerId, tokenHash).run();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. 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();+ // a token for its one project. Dead for every caller that registered it: the sender's table first, then the other+ // (which may not exist yet on a database without migration 0019, so its failure is ignored).+ const invalidSince = Math.min(outcome.invalidSince ?? now, now);+ await forgetDeadToken(env, store, row, tokenHash, invalidSince);+ const other = store === MACHINE_PUSH_STORE ? INSTALLATION_PUSH_STORE : MACHINE_PUSH_STORE;+ await forgetDeadToken(env, other, row, tokenHash, invalidSince).catch(() => undefined);return errorResponse(410, "push_device_unregistered");}console.error(JSON.stringify({ message: `${row.platform} push failed`, requestId, status: outcome.status, reason: outcome.reason }));@@ -422,6 +490,14 @@ export async function sendToRegistered<T extends { token: string }>(return errorResponse(502, "push_failed");}+function forgetDeadToken(env: Env, store: PushStore, row: DeviceRow, tokenHash: string, invalidSince: number) {+ return (row.platform === "fcm"+ ? env.DB.prepare(`DELETE FROM ${store.devices} WHERE token_hash = ? AND platform = 'fcm'`).bind(tokenHash)+ : env.DB.prepare(`DELETE FROM ${store.devices} WHERE token_hash = ? AND platform = 'apns' AND environment = ? AND updated_at <= ?`)+ .bind(tokenHash, row.environment, invalidSince)+ ).run();+}+type Delivery =| { kind: "sent" }| { kind: "dead"; invalidSince?: number }diff --git a/cloudflare/control-plane/test/fixtures/cloud-home-push.json b/cloudflare/control-plane/test/fixtures/cloud-home-push.jsonnew file mode 100644index 0000000000..5387555564--- /dev/null+++ b/cloudflare/control-plane/test/fixtures/cloud-home-push.json@@ -0,0 +1,360 @@+{+ "about": "Shared by OpenMausBot (cloudflare/control-plane/test/fixtures/cloud-home-push.json) and the Admin (tests/fixtures/cloud-home-push.json), byte for byte: the bodies a Cloud home's push routes accept and refuse at the Admin and at the control plane's machine routes, and the home's request signature. Change both copies together.",+ "signature": {+ "secret": "home-bootstrap-secret-0123456789abcdefghijklmnopq",+ "machineId": "cm_fixture",+ "action": "send",+ "timestamp": "1700000000",+ "nonce": "nonce-0123456789abcdef",+ "body": "{\"v\":1,\"token\":\"a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1\",\"collapseId\":\"openmaus.th_1.7\",\"notification\":{\"kind\":\"approval\",\"title\":\"Scout in Launch needs approval\",\"botId\":\"bot_1\",\"botName\":\"Scout\",\"threadId\":\"th_1\",\"roomId\":\"grp_1\",\"roomName\":\"Launch\"}}",+ "expected": "EZygRqHh-KpmISJhENeyTC12RticqJ9V8jZ_lcQ7XB4"+ },+ "accept": {+ "register": [+ {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "environment": "production"+ },+ {+ "v": 1,+ "platform": "apns",+ "purpose": "activity",+ "token": "c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3",+ "environment": "sandbox"+ },+ {+ "v": 1,+ "platform": "fcm",+ "token": "fcm-instance_1:APA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91b"+ }+ ],+ "unregister": [+ {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1"+ },+ {+ "v": 1,+ "platform": "fcm",+ "token": "fcm-instance_1:APA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91bAPA91b"+ }+ ],+ "send": [+ {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "pairing": "pair_tag_01",+ "collapseId": "openmaus.th_1.7",+ "notification": {+ "kind": "approval",+ "title": "Scout in Launch needs approval",+ "botId": "bot_1",+ "botName": "Scout",+ "threadId": "th_1",+ "roomId": "grp_1",+ "roomName": "Launch"+ }+ },+ {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "notification": {+ "kind": "done",+ "title": "Scout finished",+ "botId": "bot_1",+ "botName": "Scout",+ "threadId": "th_1"+ }+ }+ ],+ "activity": [+ {+ "v": 1,+ "token": "c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3",+ "event": "update",+ "activity": {+ "version": 1,+ "ask": "approval",+ "status": "Needs your approval",+ "waiting": 1,+ "botId": "bot_1",+ "botName": "Scout",+ "kind": "needsYou",+ "headline": "Scout needs you",+ "since": 1700000000000,+ "link": "openmausbot://chat/th_1",+ "color": "#5b8def",+ "gradient": [+ "#5b8def",+ "#9b6bff"+ ],+ "body": "maus"+ }+ },+ {+ "v": 1,+ "token": "c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3",+ "event": "end",+ "activity": {+ "botId": "bot_1",+ "botName": "Scout",+ "kind": "working",+ "headline": "Scout is working",+ "since": 1700000000000,+ "link": "openmausbot://chat/th_1",+ "color": "#5b8def",+ "gradient": [+ "#5b8def"+ ],+ "body": "maus"+ }+ }+ ]+ },+ "refuse": {+ "register": [+ {+ "why": "a name beside the token",+ "body": {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "environment": "production",+ "name": "Ada's iPhone"+ }+ },+ {+ "why": "a machine id in the body",+ "body": {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "environment": "production",+ "machineId": "cm_other"+ }+ },+ {+ "why": "an upper-case APNs token",+ "body": {+ "v": 1,+ "token": "A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1A1",+ "environment": "production"+ }+ }+ ],+ "unregister": [+ {+ "why": "a message",+ "body": {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "message": "bye"+ }+ }+ ],+ "send": [+ {+ "why": "message text in the notification",+ "body": {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "notification": {+ "kind": "approval",+ "title": "Scout in Launch needs approval",+ "botId": "bot_1",+ "botName": "Scout",+ "threadId": "th_1",+ "roomId": "grp_1",+ "roomName": "Launch",+ "body": "Delete every file in the repo?"+ }+ }+ },+ {+ "why": "a message beside the notification",+ "body": {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "message": "Delete every file in the repo?",+ "notification": {+ "kind": "approval",+ "title": "Scout in Launch needs approval",+ "botId": "bot_1",+ "botName": "Scout",+ "threadId": "th_1",+ "roomId": "grp_1",+ "roomName": "Launch"+ }+ }+ },+ {+ "why": "a text field",+ "body": {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "text": "hello",+ "notification": {+ "kind": "approval",+ "title": "Scout in Launch needs approval",+ "botId": "bot_1",+ "botName": "Scout",+ "threadId": "th_1",+ "roomId": "grp_1",+ "roomName": "Launch"+ }+ }+ },+ {+ "why": "a machine id in the body",+ "body": {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "machineId": "cm_other",+ "notification": {+ "kind": "approval",+ "title": "Scout in Launch needs approval",+ "botId": "bot_1",+ "botName": "Scout",+ "threadId": "th_1",+ "roomId": "grp_1",+ "roomName": "Launch"+ }+ }+ },+ {+ "why": "a title over two lines",+ "body": {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "notification": {+ "kind": "approval",+ "title": "Scout needs approval\nrm -rf /",+ "botId": "bot_1",+ "botName": "Scout",+ "threadId": "th_1",+ "roomId": "grp_1",+ "roomName": "Launch"+ }+ }+ },+ {+ "why": "a title over 200 characters",+ "body": {+ "v": 1,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "notification": {+ "kind": "approval",+ "title": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",+ "botId": "bot_1",+ "botName": "Scout",+ "threadId": "th_1",+ "roomId": "grp_1",+ "roomName": "Launch"+ }+ }+ },+ {+ "why": "another wire version",+ "body": {+ "v": 2,+ "token": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",+ "notification": {+ "kind": "approval",+ "title": "Scout in Launch needs approval",+ "botId": "bot_1",+ "botName": "Scout",+ "threadId": "th_1",+ "roomId": "grp_1",+ "roomName": "Launch"+ }+ }+ }+ ],+ "activity": [+ {+ "why": "an alert on an update",+ "body": {+ "v": 1,+ "token": "c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3",+ "event": "update",+ "alert": true,+ "activity": {+ "version": 1,+ "ask": "approval",+ "status": "Needs your approval",+ "waiting": 1,+ "botId": "bot_1",+ "botName": "Scout",+ "kind": "needsYou",+ "headline": "Scout needs you",+ "since": 1700000000000,+ "link": "openmausbot://chat/th_1",+ "color": "#5b8def",+ "gradient": [+ "#5b8def",+ "#9b6bff"+ ],+ "body": "maus"+ }+ }+ },+ {+ "why": "a line of text in the activity",+ "body": {+ "v": 1,+ "token": "c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3",+ "event": "update",+ "activity": {+ "version": 1,+ "ask": "approval",+ "status": "Needs your approval",+ "waiting": 1,+ "botId": "bot_1",+ "botName": "Scout",+ "kind": "needsYou",+ "headline": "Scout needs you",+ "since": 1700000000000,+ "link": "openmausbot://chat/th_1",+ "color": "#5b8def",+ "gradient": [+ "#5b8def",+ "#9b6bff"+ ],+ "body": "maus",+ "line": "Running rm -rf /"+ }+ }+ },+ {+ "why": "an answer in the activity",+ "body": {+ "v": 1,+ "token": "c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3",+ "event": "update",+ "activity": {+ "version": 1,+ "ask": "approval",+ "status": "Needs your approval",+ "waiting": 1,+ "botId": "bot_1",+ "botName": "Scout",+ "kind": "needsYou",+ "headline": "Scout needs you",+ "since": 1700000000000,+ "link": "openmausbot://chat/th_1",+ "color": "#5b8def",+ "gradient": [+ "#5b8def",+ "#9b6bff"+ ],+ "body": "maus",+ "answers": [+ {+ "label": "Allow"+ }+ ]+ }+ }+ }+ ]+ }+}diff --git a/cloudflare/control-plane/test/migrations.test.ts b/cloudflare/control-plane/test/migrations.test.tsindex 5094e59909..6c248762ad 100644--- a/cloudflare/control-plane/test/migrations.test.ts+++ b/cloudflare/control-plane/test/migrations.test.ts@@ -96,3 +96,28 @@ describe("migration 0018", () => {).bind("f".repeat(64), "ab".repeat(32)).run()).rejects.toThrow();});});++describe("migration 0019", () => {+ it("adds the Cloud homes' push tables beside the installations' and leaves those as they were", async () => {+ expect(migrationIndex("0019_")).toBeGreaterThan(migrationIndex("0018_"));+ expect(await schemaNames(env.DB, "machine_push_%")).toEqual([+ { type: "index", name: "machine_push_devices_token_idx" },+ { type: "index", name: "machine_push_rate_limits_updated_idx" },+ { type: "table", name: "machine_push_devices" },+ { type: "table", name: "machine_push_rate_limits" },+ ]);+ expect(await schemaNames(env.DB, "installation_push_devices%")).toEqual([+ { type: "index", name: "installation_push_devices_token_idx" },+ { type: "table", name: "installation_push_devices" },+ ]);+ // No foreign key to installations: a machine id is the Admin's, not an installation's.+ await env.DB.prepare(+ `INSERT INTO machine_push_devices (machine_id, token_hash, platform, token, environment, purpose, created_at, updated_at)+ VALUES ('cm_1', ?, 'apns', ?, 'production', 'alert', 1, 1)`,+ ).bind("e".repeat(64), "ab".repeat(32)).run();+ await expect(env.DB.prepare(+ `INSERT INTO machine_push_devices (machine_id, token_hash, platform, token, environment, purpose, created_at, updated_at)+ VALUES ('cm_1', ?, 'apns', ?, 'production', 'chat', 1, 1)`,+ ).bind("f".repeat(64), "ab".repeat(32)).run()).rejects.toThrow();+ });+});diff --git a/cloudflare/control-plane/test/push-cloud-homes.test.ts b/cloudflare/control-plane/test/push-cloud-homes.test.tsnew file mode 100644index 0000000000..8c76811a02--- /dev/null+++ b/cloudflare/control-plane/test/push-cloud-homes.test.ts@@ -0,0 +1,232 @@+import { env } from "cloudflare:workers";+import { createExecutionContext, waitOnExecutionContext } from "cloudflare:test";+import { describe, expect, it } from "vitest";++import { createAuth } from "../src/auth";+import { readConfig } from "../src/config";+import { createWorker } from "../src/index";+import { PUSH_DEVICE_LIMIT, PUSH_DEVICE_SEND_LIMIT, PUSH_REGISTER_LIMIT } from "../src/push";+import { CLOUD_HOME_FLEET_SEND_LIMIT, FLEET_ID } from "../src/push-cloud-homes";+import fixture from "./fixtures/cloud-home-push.json";++const BASE_URL = "https://auth.openmausbot.test";+const SECRET = "admin-push-relay-secret-0123456789abcdef";+const PREVIOUS = "admin-push-relay-secret-before-rotation-0123";+const TOKEN_A = "a1".repeat(32);+const TOKEN_B = "b2".repeat(32);+const MACHINE = "cm_home_one";+const OTHER = "cm_home_two";++type TestWorker = ReturnType<typeof createWorker>;+type Body = Record<string, unknown>;++function fakeApns(answers: Array<{ status: number; reason?: string }> = []) {+ const calls: string[] = [];+ const fetchImpl = (async (input: RequestInfo | URL) => {+ calls.push(new Request(input).url);+ const answer = answers.shift() ?? { status: 200 };+ return new Response(answer.reason ? JSON.stringify({ reason: answer.reason }) : null, { status: answer.status });+ }) as typeof fetch;+ return { calls, fetch: fetchImpl };+}++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(extra: Record<string, string> = {}): Promise<Env> {+ const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-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", pair.privateKey) as ArrayBuffer),+ APNS_ENVIRONMENTS: "production,sandbox",+ CLOUD_HOME_PUSH_SECRET: SECRET,+ ...extra,+ } as unknown as Env;+}++async function call(worker: TestWorker, testEnv: Env, path: string, options: { body?: unknown; token?: string; method?: 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: options.method ?? "POST",+ headers,+ body: options.body === undefined ? undefined : JSON.stringify(options.body),+ }), testEnv, ctx);+ await waitOnExecutionContext(ctx);+ return response;+}++const home = (worker: TestWorker, testEnv: Env, machine: string, action: string, body: unknown, token = SECRET) =>+ call(worker, testEnv, `/v1/cloud-homes/${machine}/push/${action}`, { token, body });++const notification = { kind: "approval", title: "Scout needs approval", botId: "bot_1", botName: "Scout", threadId: "th_1" };+const registration = (token = TOKEN_A) => ({ v: 1, token, environment: "production" });+const alert = (token = TOKEN_A) => ({ v: 1, token, notification });++async function installationCredential(worker: TestWorker, testEnv: 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, testEnv, "/api/auth/sign-in/email-otp", { body: { email, name: "Push owner", otp } });+ const created = await call(worker, testEnv, "/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 count = async (sql: string, ...bind: unknown[]) => (await env.DB.prepare(sql).bind(...bind).first<{ n: number }>())?.n;++describe("phone push for Cloud homes (the Admin's machine routes)", () => {+ it("refuses every action until the Admin's secret is set, and any other bearer after", async () => {+ const apns = fakeApns();+ const worker = createWorker(fetch, apns.fetch);+ const unset = await pushEnv({ CLOUD_HOME_PUSH_SECRET: "" });+ for (const action of ["register", "unregister", "send", "activity", "forget"]) {+ const response = await home(worker, unset, MACHINE, action, {});+ expect(response.status).toBe(503);+ expect(await response.json()).toEqual({ error: "push_unavailable" });+ }+ // A secret too short to be one is the same as none.+ expect((await home(worker, await pushEnv({ CLOUD_HOME_PUSH_SECRET: "short" }), MACHINE, "register", registration(), "short")).status).toBe(503);++ const testEnv = await pushEnv();+ expect((await home(worker, testEnv, MACHINE, "register", registration(), "")).status).toBe(401);+ expect((await home(worker, testEnv, MACHINE, "register", registration(), `${SECRET}x`)).status).toBe(401);+ expect((await home(worker, testEnv, MACHINE, "send", alert(), "wrong-secret-of-the-same-length-0123456")).status).toBe(401);+ expect((await home(worker, testEnv, MACHINE, "forget", {}, PREVIOUS)).status).toBe(401);+ // An installation credential is not the Admin's secret, nor the other way round.+ const credential = await installationCredential(worker, testEnv, "[email protected]");+ expect((await home(worker, testEnv, MACHINE, "register", registration(), credential)).status).toBe(401);+ expect((await call(worker, testEnv, "/v1/installations/self/push/register", { token: SECRET, body: registration() })).status).toBe(401);+ // GET is not a route.+ expect((await call(worker, testEnv, `/v1/cloud-homes/${MACHINE}/push/send`, { method: "GET", token: SECRET })).status).toBe(405);+ expect(apns.calls).toEqual([]);+ });++ it("takes the previous secret beside the current one during a rotation", async () => {+ const worker = createWorker(fetch, fakeApns().fetch);+ const rotating = await pushEnv({ CLOUD_HOME_PUSH_SECRET: SECRET, CLOUD_HOME_PUSH_SECRET_PREVIOUS: PREVIOUS });+ expect((await home(worker, rotating, MACHINE, "register", registration(), PREVIOUS)).status).toBe(200);+ expect((await home(worker, rotating, MACHINE, "send", alert(), SECRET)).status).toBe(202);+ // The rotation is over once the previous one is removed.+ expect((await home(worker, await pushEnv(), MACHINE, "send", alert(), PREVIOUS)).status).toBe(401);+ });++ it("sends only to a token the same machine registered, never another machine's or an installation's", async () => {+ const apns = fakeApns();+ const worker = createWorker(fetch, apns.fetch);+ const testEnv = await pushEnv();+ expect((await home(worker, testEnv, MACHINE, "register", registration(TOKEN_A))).status).toBe(200);+ const foreign = await home(worker, testEnv, OTHER, "send", alert(TOKEN_A));+ expect(foreign.status).toBe(404);+ expect(await foreign.json()).toEqual({ error: "push_device_unknown" });+ const credential = await installationCredential(worker, testEnv, "[email protected]");+ expect((await call(worker, testEnv, "/v1/installations/self/push/send", { token: credential, body: alert(TOKEN_A) })).status).toBe(404);+ expect(apns.calls).toEqual([]);++ const sent = await home(worker, testEnv, MACHINE, "send", alert(TOKEN_A));+ expect(sent.status).toBe(202);+ expect(await sent.json()).toEqual({ sent: true });+ expect(apns.calls).toEqual([`https://api.push.apple.com/3/device/${TOKEN_A}`]);+ // Stored under the machine, beside (never in) the installations' table.+ expect(await count("SELECT COUNT(*) AS n FROM machine_push_devices WHERE machine_id = ? AND last_sent_at IS NOT NULL", MACHINE)).toBe(1);+ expect(await count("SELECT COUNT(*) AS n FROM installation_push_devices")).toBe(0);+ });++ it("accepts every body the shared fixture accepts and refuses every one it refuses, before Apple is asked", async () => {+ const apns = fakeApns();+ const worker = createWorker(fetch, apns.fetch);+ const testEnv = await pushEnv();+ for (const [action, bodies] of Object.entries(fixture.accept) as [string, Body[]][]) {+ for (const body of bodies) {+ const response = await home(worker, testEnv, MACHINE, action, body);+ expect(response.status, `${action} ${JSON.stringify(body)}`).not.toBe(400);+ }+ }+ const before = apns.calls.length;+ for (const [action, cases] of Object.entries(fixture.refuse) as [string, { why: string; body: Body }[]][]) {+ for (const { why, body } of cases) {+ const response = await home(worker, testEnv, MACHINE, action, body);+ expect(response.status, `${action}: ${why}`).toBe(400);+ expect(await response.json()).toEqual({ error: "invalid_request" });+ }+ }+ expect(apns.calls.length).toBe(before);+ });++ it("limits each machine and each phone as an installation is limited, and the whole fleet", async () => {+ const worker = createWorker(fetch, fakeApns().fetch);+ const testEnv = await pushEnv();+ expect((await home(worker, testEnv, MACHINE, "register", registration())).status).toBe(200);+ for (let index = 1; index < PUSH_DEVICE_SEND_LIMIT; index += 1) await home(worker, testEnv, MACHINE, "send", alert());+ expect((await home(worker, testEnv, MACHINE, "send", alert())).status).toBe(202);+ const limited = await home(worker, testEnv, MACHINE, "send", alert());+ expect(limited.status).toBe(429);+ expect(limited.headers.get("retry-after")).toBe("60");++ // Registrations: 120 an hour per machine.+ await env.DB.prepare("UPDATE machine_push_rate_limits SET attempts = ? WHERE machine_id = ? AND action = 'push_register'").bind(PUSH_REGISTER_LIMIT, MACHINE).run();+ expect((await home(worker, testEnv, MACHINE, "register", registration(TOKEN_B))).status).toBe(429);++ // The fleet: every machine's sends together. A send the fleet refuses spends none of the machine's own window.+ expect((await home(worker, testEnv, OTHER, "register", registration(TOKEN_B))).status).toBe(200);+ const now = Date.now();+ await env.DB.prepare("UPDATE machine_push_rate_limits SET attempts = ?, window_started_at = ? WHERE machine_id = ? AND action = 'push_send'")+ .bind(CLOUD_HOME_FLEET_SEND_LIMIT, now, FLEET_ID).run();+ expect((await home(worker, testEnv, OTHER, "send", alert(TOKEN_B))).status).toBe(429);+ expect(await count("SELECT COUNT(*) AS n FROM machine_push_rate_limits WHERE machine_id = ? AND action = 'push_send'", OTHER)).toBe(0);+ });++ it("keeps at most 50 tokens a machine, as for an installation", async () => {+ const worker = createWorker(fetch, fakeApns().fetch);+ const testEnv = await pushEnv();+ const token = (index: number) => index.toString(16).padStart(2, "0").repeat(32);+ for (let index = 0; index < PUSH_DEVICE_LIMIT; index += 1) expect((await home(worker, testEnv, MACHINE, "register", registration(token(index)))).status).toBe(200);+ const full = await home(worker, testEnv, MACHINE, "register", registration(token(99)));+ expect(full.status).toBe(409);+ expect(await full.json()).toEqual({ error: "push_device_limit" });+ expect((await home(worker, testEnv, OTHER, "register", registration(token(99)))).status).toBe(200);+ });++ it("forgets every token of a machine the Admin deleted, and only that machine's", async () => {+ const worker = createWorker(fetch, fakeApns().fetch);+ const testEnv = await pushEnv();+ await home(worker, testEnv, MACHINE, "register", registration(TOKEN_A));+ await home(worker, testEnv, MACHINE, "register", registration(TOKEN_B));+ await home(worker, testEnv, OTHER, "register", registration(TOKEN_A));+ expect((await home(worker, testEnv, MACHINE, "unregister", { v: 1, token: TOKEN_B })).status).toBe(204);+ expect(await count("SELECT COUNT(*) AS n FROM machine_push_devices WHERE machine_id = ?", MACHINE)).toBe(1);++ const forgot = await home(worker, testEnv, MACHINE, "forget", {});+ expect(forgot.status).toBe(204);+ expect(await count("SELECT COUNT(*) AS n FROM machine_push_devices WHERE machine_id = ?", MACHINE)).toBe(0);+ expect(await count("SELECT COUNT(*) AS n FROM machine_push_rate_limits WHERE machine_id = ?", MACHINE)).toBe(0);+ expect(await count("SELECT COUNT(*) AS n FROM machine_push_devices WHERE machine_id = ?", OTHER)).toBe(1);+ expect((await home(worker, testEnv, MACHINE, "send", alert(TOKEN_A))).status).toBe(404);+ // Again: nothing left, still 204.+ expect((await home(worker, testEnv, MACHINE, "forget", {})).status).toBe(204);+ });++ it("drops a token Apple says is dead for machines and installations alike", async () => {+ const worker = createWorker(fetch, fakeApns([{ status: 410, reason: "Unregistered" }]).fetch);+ const testEnv = await pushEnv();+ const credential = await installationCredential(worker, testEnv, "[email protected]");+ expect((await call(worker, testEnv, "/v1/installations/self/push/register", { token: credential, body: registration(TOKEN_A) })).status).toBe(200);+ await home(worker, testEnv, MACHINE, "register", registration(TOKEN_A));+ const dead = await home(worker, testEnv, MACHINE, "send", alert(TOKEN_A));+ expect(dead.status).toBe(410);+ expect(await dead.json()).toEqual({ error: "push_device_unregistered" });+ expect(await count("SELECT COUNT(*) AS n FROM machine_push_devices WHERE token_hash IS NOT NULL")).toBe(0);+ expect(await count("SELECT COUNT(*) AS n FROM installation_push_devices")).toBe(0);+ });+});diff --git a/cloudflare/control-plane/test/setup.ts b/cloudflare/control-plane/test/setup.tsindex cbccd86616..89385c0840 100644--- a/cloudflare/control-plane/test/setup.ts+++ b/cloudflare/control-plane/test/setup.ts@@ -32,6 +32,8 @@ afterEach(async () => {env.DB.prepare("DELETE FROM installation_action_rate_limits"),env.DB.prepare("DELETE FROM installation_endpoints"),env.DB.prepare("DELETE FROM installation_push_devices"),+ env.DB.prepare("DELETE FROM machine_push_devices"),+ env.DB.prepare("DELETE FROM machine_push_rate_limits"),// A missing row reads as an empty snapshot (never scanned, never refused).env.DB.prepare("DELETE FROM managed_endpoint_account_capacity"),env.DB.prepare("DELETE FROM managed_endpoint_reclaim_preview"),diff --git a/docs/phone-push.md b/docs/phone-push.mdindex 069534b4bd..e4cab33f71 100644--- a/docs/phone-push.md+++ b/docs/phone-push.md@@ -27,8 +27,10 @@ until the owner supplies the keys and turns it on (see "Switching it on").token changes, and whenever the person changes a notification switch.3. **The server registers the token with the control plane**(`POST /v1/installations/self/push/register`), using the installation- credential it already holds for the hosted transport. The control plane- holds the APNs key and the Firebase service account; servers never do.+ credential it already holds for the hosted transport. A Cloud home, which+ has none, asks its Admin to relay the same call (see "Cloud homes"). The+ control plane holds the APNs key and the Firebase service account; servers+ and the Admin never do.4. **Something happens that would notify the person.** The server emits its`notify` frame as today. For each registered phone, it checks:- is phone push switched on;@@ -121,12 +123,20 @@ the frames it missed, or the stream closes just as an alert is sent.## Privacy and threat model**What the control plane learns.** For each registered phone: the installation-that registered it, the device token, its platform and APNs environment, and+that registered it (for a Cloud home: the home's machine id), the device token, its platform and APNs environment, andwhen it last got a push. For each send: the kind, the title, the bot's androom's names and ids, the thread id and the phone's pairing tag. It never seesmessage text, files or credentials. It logs only the request id, the platformand the provider's status and reason, never the token or the payload.+**What the Admin learns (Cloud homes only).** Which of its machines asked, when,+and the action; and, in memory for the length of the call, the body it+forwards: the device token, its platform and environment, and for a send the+same names, ids and title as the control plane. It stores none of it: no token+in its database or logs (its per-phone limit counts a hash keyed with a random+key that dies with the process), and it logs only the machine, the action and+a status.+**What Apple and Google learn.** The same names, ids and title, the devicetoken, and when MausBot pushed to the phone. Not the content of anyconversation.@@ -134,7 +144,9 @@ conversation.**Where tokens are kept.** On the computer or Cloud, in`<data dir>/push-devices.json` (mode 0600), beside the other paired-devicerecords. In the control plane, in the D1 table `installation_push_devices`-(token and its SHA-256). The phone app never sends the token anywhere else.+(token and its SHA-256), or for a Cloud home in `machine_push_devices` (the+same, keyed by the home's machine id). The phone app never sends the token+anywhere else.`GET /api/push/device` never echoes it.**Revocation.** A registration ends when:@@ -147,7 +159,10 @@ records. In the control plane, in the D1 table `installation_push_devices`- the same phone pairs again (the token moves to the new pairing);- Apple or Google say the token is dead (`410`), which deletes it everywhere;- the installation is revoked in the control plane, which deletes all its- tokens.+ tokens;+- for a Cloud home, the Admin retires or deletes the Cloud: it asks the control+ plane to delete every token of that machine (`.../push/forget`), and keeps+ asking until it answers.Known gap: a phone that removes a computer it cannot reach (the computer isoff) leaves its registration there until one of the other events happens. The@@ -157,7 +172,9 @@ nothing, because the computer is no longer saved.**Rate limits.** On the server: one push per phone, kind and conversation in10 seconds, 30 per phone in 10 minutes. In the control plane: 600 sends perinstallation and 60 per token per hour, 120 registrations per hour, 50 tokens-per installation.+per installation; the same per Cloud home, plus 20,000 sends and 6,000+registrations an hour across every Cloud home together. The Admin applies the+same per-home and fleet limits before it forwards anything.**Replay and forgery.** Every relay call needs the installation credential.A send reaches only a token that the same installation registered, so a@@ -169,36 +186,73 @@ duplicate alert at most, replaced on screen by the collapse id. A paired phonecan register only for itself; a phone that registered somebody else's tokenwould only send that person the same names and ids it can already read.+A Cloud home signs each call to its Admin with its own bootstrap secret, over+the machine id, the action, a timestamp (5 minutes), a nonce (once) and the+body. The Admin takes the machine id from that signature, never from the body,+so a compromised home can register and push only under its own machine id,+which reaches only the tokens its own phones registered; it cannot reach+another customer's phone. The Admin reaches the control plane with one secret+shared only between the two. Whoever held that secret could push content-free+alerts to any Cloud home's registered phones by naming machine ids, bounded by+the per-token and fleet limits above, but could not read a token back or reach+an installation's phones. It is rotated without downtime: the control plane+accepts a previous secret beside the current one.+## Cloud homesA desktop has an installation credential once its owner turns on "Use yourphone anywhere", and `openmausbot serve` has one after `openmausbot account login` or-from `OMB_INSTALLATION_CREDENTIAL`. A Cloud home has none, so today it cannot-send.--The server code already reads a push-only credential from-`OMB_PUSH_CREDENTIAL`, so the smallest change on the home itself is nothing-but that variable. The open question is who issues it. Installation-credentials last 90 days and are rotated with an account session, which a-Cloud home does not have. Two ways:--1. **Recommended: the Admin relays for its homes.** The home already talks to- the Admin with its bootstrap secret (as `/api/cloud/machines/woke` does).- Add `POST /api/cloud/machines/push/{register,unregister,send}` to the Admin,- signed the same way, with the same strict body as the control plane. The- Admin forwards to a matching control-plane route family that it reaches- with one Worker secret shared only between the two, keyed by the home's- machine id instead of an installation. No credential lives on the home, no- 90-day rotation, and deleting a home in the Admin deletes its tokens. Cost:- a small Admin route, a control-plane route family beside the installation- one, and a second relay transport in `server/phone-push.ts`.-2. The Admin mints an installation per home under a service account and- passes it as `OMB_PUSH_CREDENTIAL`. No new code on the home or in the- control plane, but the Admin must keep a control-plane account session- alive to rotate every home's credential every 90 days.--Neither is built yet. Until one is, a Cloud home answers `push: "no-account"`-and its phones keep today's behaviour.+from `OMB_INSTALLATION_CREDENTIAL` (or a push-only `OMB_PUSH_CREDENTIAL`). A+Cloud home has none. So **the Admin relays for its homes**: built, and off+until switched on.++- **The home** (`server/phone-push-admin.ts`): when the server runs as a Cloud+ home and has no installation credential, every relay call goes to its Admin+ instead, `POST <admin>/api/cloud/machines/push/{register,unregister,send,activity}`,+ with the very same body, signed with the bootstrap secret it already holds+ (headers `x-omb-cloud-machine`, `x-omb-cloud-timestamp`, `x-omb-cloud-nonce`,+ `x-omb-cloud-signature: v1=<HMAC-SHA256 over "omb-phone-push-v1", the machine+ id, the action, the timestamp, the nonce and the body's SHA-256>`). Same+ outbox, retries and back-off: `503 push_unavailable`, a `401` or a `404` (an+ Admin with its switch off, or an older one) leaves it alone for an hour. Still+ gated by `features.phonePush` / `OMB_PHONE_PUSH`, off by default.+- **The Admin** checks the signature, takes the machine id from it, checks the+ body against the control plane's own strict schemas (no field for message+ text), applies the limits, and forwards the parsed body. Its switch is+ `OMB_CLOUD_PHONE_PUSH` (off by default); it forwards to+ `OMB_CLOUD_PUSH_RELAY_URL` with `OMB_CLOUD_PUSH_RELAY_SECRET`. Retiring or+ deleting a Cloud deletes its tokens at the control plane, switch on or off.+- **The control plane** has the matching routes,+ `POST /v1/cloud-homes/<machine id>/push/{register,unregister,send,activity,forget}`+ (`src/push-cloud-homes.ts`), beside the installation ones and with the same+ bodies, limits, storage shape (`machine_push_devices`, migration `0019`) and+ send path, plus a fleet-wide limit. They take only the Admin's secret,+ `CLOUD_HOME_PUSH_SECRET` (and `CLOUD_HOME_PUSH_SECRET_PREVIOUS` during a+ rotation), compared in constant time; with neither set they answer+ `503 push_unavailable`. Nothing changes for installation callers.++The bodies both sides accept and refuse, and the home's signature, are one+fixture, `cloudflare/control-plane/test/fixtures/cloud-home-push.json`, which+the Admin holds byte for byte and checks with the same SHA-256.++No credential lives on the home beyond the bootstrap secret it already had,+nothing needs rotating every 90 days, and the Admin keeps no device token.++**Switching it on for Cloud homes**, after steps 1 to 10 of "Switching it on",+in order:++1. Apply the control plane's migration `0019_cloud_home_push.sql`.+2. Set the control plane's `CLOUD_HOME_PUSH_SECRET` (random, 32 characters or+ more) and deploy it.+3. Ship an Admin image with the relay, then set the same value as the Admin's+ `OMB_CLOUD_PUSH_RELAY_SECRET`, and `OMB_CLOUD_PUSH_RELAY_URL` to the control+ plane's origin, and restart the Admin.+4. Ship a Cloud home image with this code.+5. Turn phone push on in one test Cloud's home: `features.phonePush: true` in+ its `config.json` (its owner's `PUT /api/config`; an `OMB_PHONE_PUSH` set by+ hand in a home's environment is rewritten by the Admin at its next update),+ then `OMB_CLOUD_PHONE_PUSH` on in the Admin's Cloud operations → Switches.+6. Run "Test plan on real devices" against that Cloud, then widen.## Always-on and the grace period@@ -374,7 +428,8 @@ What the owner provides and does, in order. Nothing here has been done.`features.phonePush: true` is in `config.json`, or `OMB_PHONE_PUSH=1` is set(`OMB_PHONE_PUSH=0` forces it off). This is the rollout flag: turn it onfor one machine first, then flip the default in a release.-11. For Cloud homes, build one of the two options under "Cloud homes".+11. For Cloud homes, follow "Switching it on for Cloud homes" under "Cloud+ homes".Deploy order: migration and secrets, then the control plane, then a serverwith phone push on for one test machine, then a phone build with the switch on,@@ -418,7 +473,7 @@ has "Use your phone anywhere" on and `features.phonePush: true`.- **Nothing arrives if the computer is off or asleep,** or offline. Thecomputer is what notices the event and asks for the push; a sleeping Macnotices nothing. A Cloud runs all the time, so a Cloud's phones get pushes- whenever its bots work (once a Cloud home can send, see "Cloud homes").+ whenever its bots work (once its Admin relays for it, see "Cloud homes").- **No push for other kinds** (mentions, routine failures, waits, notices).They arrive as today while the app is connected.- **No badge counts from push.** The badge is updated when the app runs.diff --git a/server/index.ts b/server/index.tsindex 684908ee71..e8a0b63a98 100644--- a/server/index.ts+++ b/server/index.ts@@ -1465,7 +1465,7 @@ const browserCleanup: BrowserCleanupCoordinator = new BrowserCleanupCoordinator(return true;},});-const phoneSecrets = new PhoneSecretBridge(postDesktopPrivateMessage, undefined, undefined, DESKTOP_MANAGED); const phonePushAccess = new PhonePushAccessSource({ tunnelFile: join(DATA_DIR, TUNNEL_CREDENTIALS_FILE), defaultControlPlane: DEFAULT_COMPANION_CONTROL_PLANE_URL });+const phoneSecrets = new PhoneSecretBridge(postDesktopPrivateMessage, undefined, undefined, DESKTOP_MANAGED); const phonePushAccess = new PhonePushAccessSource({ tunnelFile: join(DATA_DIR, TUNNEL_CREDENTIALS_FILE), defaultControlPlane: DEFAULT_COMPANION_CONTROL_PLANE_URL, cloudHome: CLOUD_HOME });utilityParentPort?.on("message", (event) => {const message = event?.data;try {diff --git a/server/phone-push-admin.test.ts b/server/phone-push-admin.test.tsnew file mode 100644index 0000000000..d6a31fc144--- /dev/null+++ b/server/phone-push-admin.test.ts@@ -0,0 +1,205 @@+import { createHash, timingSafeEqual } from "node:crypto";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { PHONE_ACTIVITY_RELAY_PATH, PHONE_PUSH_RELAY_PATHS } from "../shared/phone-push.ts";+import { CLOUD_HOME_PUSH_ACTIONS, cloudHomePushAccess, cloudHomePushRequest, cloudHomePushSignature } from "./phone-push-admin.ts";+import { PhonePush, PhonePushAccessSource, RELAY_UNAVAILABLE_PAUSE_MS, type PhonePushOptions } from "./phone-push.ts";++/** The bodies and the signature vector the Admin's tests read from their own copy of this file (openmaus-cloud+ * tests/fixtures/cloud-home-push.json): both copies must hash to this. */+const FIXTURE_FILE = new URL("../cloudflare/control-plane/test/fixtures/cloud-home-push.json", import.meta.url);+const FIXTURE_SHA256 = "1cac2c96498e57fb2527813f84be74d453f77d058a4499674afab69f5c3da47d";++const ADMIN = "https://cloud.mausbot.test";+const SECRET = "home-bootstrap-secret-0123456789abcdefghijklmnopq";+const MACHINE = "cm_home_one";+const HOME = { adminOrigin: ADMIN, machineId: MACHINE, bootstrapSecret: SECRET };+const APNS = "ab".repeat(32);+const PHONE = "session:phone-1";+const CREDENTIAL = `omb_install_${"a".repeat(22)}.${"b".repeat(43)}`;++interface AdminCall { url: string; body: string; headers: Headers }++function fakeAdmin() {+ const calls: AdminCall[] = [];+ const answers: Array<{ status: number; error?: string }> = [];+ const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {+ const url = String(input);+ calls.push({ url, body: String(init?.body), headers: new Headers(init?.headers) });+ const answer = answers.shift();+ const status = answer?.status ?? (url.endsWith("/send") ? 202 : url.endsWith("/unregister") ? 204 : 200);+ return new Response(answer?.error ? JSON.stringify({ error: answer.error }) : status === 204 ? null : "{}", { status });+ }) as typeof fetch;+ return { calls, answers, fetchImpl, sends: () => calls.filter((call) => call.url.endsWith("/send")) };+}++let dataDir: string;+let clock: number;+let timers: Array<{ run: () => void; at: number }>;+beforeEach(() => {+ dataDir = mkdtempSync(join(tmpdir(), "omb-phone-push-admin-"));+ clock = 1_700_000_000_000;+ timers = [];+});+afterEach(() => rmSync(dataDir, { recursive: true, force: true }));++function harness(options: Partial<PhonePushOptions> = {}) {+ const admin = fakeAdmin();+ let enabled = true;+ const push = new PhonePush({+ dataDir,+ access: () => cloudHomePushAccess(HOME),+ enabled: () => enabled,+ live: () => false,+ room: () => undefined,+ fetchImpl: admin.fetchImpl,+ now: () => clock,+ log: () => {},+ timers: {+ set: (run, ms) => { const timer = { run, at: clock + ms }; timers.push(timer); return timer; },+ clear: (handle) => { timers = timers.filter((timer) => timer !== handle); },+ },+ ...options,+ });+ return { push, admin, setEnabled: (on: boolean) => { enabled = on; } };+}++async function advance(push: PhonePush, ms: number) {+ clock += ms;+ for (const timer of timers.filter((one) => one.at <= clock)) {+ timers = timers.filter((one) => one !== timer);+ timer.run();+ }+ await push.flush();+}++const notification = (threadId = "th_1") => ({ kind: "approval", botId: "bot_1", botName: "Scout", threadId, body: "PRIVATE: the message text" });+const everyone = () => true;++/** Checks a request as the Admin does: the signature over machine, action, time, nonce and body, in constant time. */+function signedByHome(call: AdminCall, action: string): boolean {+ const presented = /^v1=([A-Za-z0-9_-]{43})$/.exec(call.headers.get("x-omb-cloud-signature") ?? "")?.[1];+ if (!presented) return false;+ const expected = cloudHomePushSignature(SECRET, call.headers.get("x-omb-cloud-machine") ?? "", action, call.headers.get("x-omb-cloud-timestamp") ?? "", call.headers.get("x-omb-cloud-nonce") ?? "", call.body);+ return timingSafeEqual(Buffer.from(presented, "base64url"), Buffer.from(expected, "base64url"));+}++describe("the shared contract with the Admin", () => {+ it("is the fixture both repositories hold, byte for byte", () => {+ // As LF text, so a Windows checkout with CRLF line ends hashes the same.+ expect(createHash("sha256").update(readFileSync(FIXTURE_FILE, "utf8").replace(/\r\n/g, "\n")).digest("hex")).toBe(FIXTURE_SHA256);+ });++ it("signs exactly as the fixture's vector says the Admin checks", () => {+ const { signature } = JSON.parse(readFileSync(FIXTURE_FILE, "utf8")) as { signature: Record<string, string> };+ expect(cloudHomePushSignature(signature.secret!, signature.machineId!, signature.action!, signature.timestamp!, signature.nonce!, signature.body!)).toBe(signature.expected);+ });++ it("relays every installation route, Live Activities included, and nothing else", () => {+ expect(CLOUD_HOME_PUSH_ACTIONS).toEqual({+ [PHONE_PUSH_RELAY_PATHS.register]: "register",+ [PHONE_PUSH_RELAY_PATHS.unregister]: "unregister",+ [PHONE_PUSH_RELAY_PATHS.send]: "send",+ [PHONE_ACTIVITY_RELAY_PATH]: "activity",+ });+ expect(cloudHomePushRequest(cloudHomePushAccess(HOME)!, "/v1/installations/self/relay-token", {}, clock)).toBeNull();+ });+});++describe("a Cloud home's pushes through its Admin", () => {+ it("signs each call with its bootstrap secret and sends the installation routes' bodies unchanged", async () => {+ const { push, admin } = harness();+ const answer = await push.register(PHONE, { platform: "apns", token: APNS, environment: "production", pairing: "pair-tag-0001" });+ expect(answer).toMatchObject({ push: "on", relay: "registered" });+ push.offer({ notification: notification(), seq: 7 }, everyone);+ await push.flush();++ expect(admin.calls.map((call) => call.url)).toEqual([`${ADMIN}/api/cloud/machines/push/register`, `${ADMIN}/api/cloud/machines/push/send`]);+ const [register, send] = admin.calls;+ expect(JSON.parse(register!.body)).toEqual({ v: 1, platform: "apns", token: APNS, environment: "production" });+ expect(JSON.parse(send!.body)).toEqual({ v: 1, token: APNS, pairing: "pair-tag-0001", collapseId: "openmaus.th_1.7",+ notification: { kind: "approval", title: "Scout needs approval", botId: "bot_1", botName: "Scout", threadId: "th_1" } });+ expect(signedByHome(register!, "register")).toBe(true);+ expect(signedByHome(send!, "send")).toBe(true);+ // Signed for one route, it is not valid for another; the machine id rides in a header the signature covers.+ expect(signedByHome(send!, "activity")).toBe(false);+ for (const call of admin.calls) {+ expect(call.headers.get("x-omb-cloud-machine")).toBe(MACHINE);+ expect(call.headers.get("x-omb-cloud-timestamp")).toBe(String(Math.floor(clock / 1000)));+ expect(call.headers.get("authorization")).toBeNull();+ expect(`${call.body}${JSON.stringify([...call.headers])}`).not.toContain(SECRET);+ expect(call.body).not.toContain("PRIVATE");+ expect(call.body).not.toContain(MACHINE);+ }+ expect(admin.calls[0]!.headers.get("x-omb-cloud-nonce")).not.toBe(admin.calls[1]!.headers.get("x-omb-cloud-nonce"));+ });++ it("backs off an hour when the Admin or the control plane says push is unavailable, as an installation does", async () => {+ const { push, admin } = harness();+ await push.register(PHONE, { platform: "apns", token: APNS });+ admin.answers.push({ status: 503, error: "push_unavailable" });+ push.offer({ notification: notification("th_1"), seq: 1 }, everyone);+ await push.flush();+ expect(admin.sends()).toHaveLength(1);+ push.offer({ notification: notification("th_2"), seq: 2 }, everyone);+ await advance(push, RELAY_UNAVAILABLE_PAUSE_MS - 1);+ expect(admin.sends()).toHaveLength(1);+ await advance(push, 1);+ push.offer({ notification: notification("th_3"), seq: 3 }, everyone);+ await push.flush();+ expect(admin.sends()).toHaveLength(2);+ });++ it("backs off the same way from an Admin with the switch off (404) or one that refuses its signature (401)", async () => {+ for (const refusal of [{ status: 404, error: "Not found." }, { status: 401, error: "unauthorized" }]) {+ const { push, admin } = harness();+ await push.register(PHONE, { platform: "apns", token: APNS });+ admin.answers.push(refusal);+ push.offer({ notification: notification("th_1"), seq: 1 }, everyone);+ await push.flush();+ push.offer({ notification: notification("th_2"), seq: 2 }, everyone);+ await advance(push, 60_000);+ expect(admin.sends()).toHaveLength(1);+ rmSync(join(dataDir, "push-devices.json"), { force: true });+ }+ });++ it("registers again and retries once when the control plane has lost the token", async () => {+ const { push, admin } = harness();+ await push.register(PHONE, { platform: "apns", token: APNS });+ admin.answers.push({ status: 404, error: "push_device_unknown" });+ push.offer({ notification: notification(), seq: 1 }, everyone);+ await push.flush();+ expect(admin.calls.slice(1).map((call) => call.url.split("/").at(-1))).toEqual(["send", "register", "send"]);+ });++ it("switched off, keeps nothing and asks the Admin nothing", async () => {+ const { push, admin, setEnabled } = harness();+ setEnabled(false);+ expect(await push.register(PHONE, { platform: "apns", token: APNS })).toEqual({ push: "off", device: null, relay: "off" });+ push.offer({ notification: notification(), seq: 1 }, everyone);+ await push.flush();+ expect(admin.calls).toEqual([]);+ });+});++describe("which transport a server uses", () => {+ const tunnelFile = () => join(dataDir, "tunnel-account.json");+ const source = (env: NodeJS.ProcessEnv, cloudHome: typeof HOME | null) =>+ new PhonePushAccessSource({ env, tunnelFile: tunnelFile(), defaultControlPlane: "https://accounts.openmausbot.com", cloudHome }).current();++ it("is the Admin only for a Cloud home with no installation credential", () => {+ expect(source({}, null)).toBeNull();+ expect(source({}, HOME)).toEqual({ admin: ADMIN, machineId: MACHINE, secret: SECRET });+ expect(source({}, { ...HOME, adminOrigin: `${ADMIN}/` })).toEqual({ admin: ADMIN, machineId: MACHINE, secret: SECRET });+ // An installation credential wins, from the environment or `openmausbot login`'s file.+ expect(source({ OMB_PUSH_CREDENTIAL: CREDENTIAL }, HOME)).toEqual({ controlPlane: "https://accounts.openmausbot.com", credential: CREDENTIAL });+ writeFileSync(tunnelFile(), JSON.stringify({ companionInstallationCredential: CREDENTIAL }));+ expect(source({}, HOME)).toEqual({ controlPlane: "https://accounts.openmausbot.com", credential: CREDENTIAL });+ writeFileSync(tunnelFile(), JSON.stringify({}));+ expect(source({}, HOME)).toEqual({ admin: ADMIN, machineId: MACHINE, secret: SECRET });+ });+});diff --git a/server/phone-push-admin.ts b/server/phone-push-admin.tsnew file mode 100644index 0000000000..816e99fa50--- /dev/null+++ b/server/phone-push-admin.ts@@ -0,0 +1,61 @@+// The second transport for closed-app phone push (docs/phone-push.md "Cloud homes"). A Cloud home holds no installation+// credential, so it asks the Admin that runs it, signed with the bootstrap secret it already has (as its wake notice is,+// server/cloud-woke.ts). The Admin checks the signature, takes the machine id from it (never from the body), checks the+// same strict body the control plane does, and forwards it to the control plane's machine routes. The bodies are the+// installation routes' bodies exactly; only the address and the signature differ.+import { createHash, createHmac, randomBytes } from "node:crypto";++import { PHONE_ACTIVITY_RELAY_PATH, PHONE_PUSH_RELAY_PATHS } from "../shared/phone-push.ts";++/** What a Cloud home signs with: its Admin, its machine id and its bootstrap secret (server/cloud-home.ts). */+export interface CloudHomePushAccess {+ admin: string;+ machineId: string;+ secret: string;+}++/** Each control-plane installation route, and the Admin route that relays it for a Cloud home. */+export const CLOUD_HOME_PUSH_ACTIONS: Readonly<Record<string, "register" | "unregister" | "send" | "activity">> = {+ [PHONE_PUSH_RELAY_PATHS.register]: "register",+ [PHONE_PUSH_RELAY_PATHS.unregister]: "unregister",+ [PHONE_PUSH_RELAY_PATHS.send]: "send",+ [PHONE_ACTIVITY_RELAY_PATH]: "activity",+};+export const CLOUD_HOME_PUSH_ADMIN_PATH = "/api/cloud/machines/push/";++/** Must match the Admin's `cloudHomePushSignature` (openmaus-cloud server/cloud-push.ts): the action is signed, so a+ * request signed for one route is never accepted by another. */+export function cloudHomePushSignature(secret: string, machineId: string, action: string, timestamp: string, nonce: string, body: string): string {+ const bodyHash = createHash("sha256").update(body).digest("hex");+ return createHmac("sha256", secret).update(`omb-phone-push-v1\n${machineId}\n${action}\n${timestamp}\n${nonce}\n${bodyHash}`).digest("base64url");+}++/** The access a Cloud home has, or null when this server is not one. */+export function cloudHomePushAccess(home: { adminOrigin: string; machineId: string; bootstrapSecret: string } | null | undefined): CloudHomePushAccess | null {+ if (!home?.adminOrigin || !home.machineId || !home.bootstrapSecret) return null;+ return { admin: home.adminOrigin.replace(/\/+$/, ""), machineId: home.machineId, secret: home.bootstrapSecret };+}++/** The Admin request for one relay call, or null for a path the Admin does not relay. The secret never leaves this+ * process: only the signature does. */+export function cloudHomePushRequest(access: CloudHomePushAccess, path: string, body: unknown, now: number): { url: string; init: RequestInit } | null {+ const action = CLOUD_HOME_PUSH_ACTIONS[path];+ if (!action) return null;+ const raw = JSON.stringify(body);+ const timestamp = String(Math.floor(now / 1000)), nonce = randomBytes(18).toString("base64url");+ return {+ url: `${access.admin}${CLOUD_HOME_PUSH_ADMIN_PATH}${action}`,+ init: {+ method: "POST",+ body: raw,+ headers: {+ accept: "application/json",+ "content-type": "application/json",+ "x-omb-cloud-machine": access.machineId,+ "x-omb-cloud-timestamp": timestamp,+ "x-omb-cloud-nonce": nonce,+ "x-omb-cloud-signature": `v1=${cloudHomePushSignature(access.secret, access.machineId, action, timestamp, nonce, raw)}`,+ },+ },+ };+}diff --git a/server/phone-push.ts b/server/phone-push.tsindex d622015d69..e71284d5f2 100644--- a/server/phone-push.ts+++ b/server/phone-push.ts@@ -1,7 +1,8 @@// Closed-app phone alerts. A paired phone registers its APNs or FCM device token here; when an approval, a question, a// sign-in request or a finished reply would reach a phone that holds no live event stream, this asks the push relay in-// the hosted control plane to wake it, with the installation credential this server already has. The push is-// content-free: kind, a title from names alone, opaque ids. Off unless `features.phonePush` (or OMB_PHONE_PUSH=1).+// the hosted control plane to wake it, with the installation credential this server already has; a Cloud home, which has+// none, asks its Admin to relay instead (phone-push-admin.ts). The push is content-free: kind, a title from names alone,+// opaque ids. Off unless `features.phonePush` (or OMB_PHONE_PUSH=1).import { mkdirSync, readFileSync } from "node:fs";import { dirname, join } from "node:path";import { z } from "zod";@@ -30,6 +31,7 @@ import {type PushKind,} from "../shared/phone-push.ts";import { writeFileAtomic } from "./atomic.ts";+import { cloudHomePushAccess, cloudHomePushRequest, type CloudHomePushAccess } from "./phone-push-admin.ts";import { conversationLanguage, serverLine, type ServerLineKey } from "./server-lines.ts";export const PHONE_PUSH_FILE = "push-devices.json";@@ -89,10 +91,12 @@ const storedDevice = z.object({const storedFile = z.object({ version: z.literal(1), devices: z.array(storedDevice).max(MAX_PUSH_DEVICES) });type StoredDevice = z.infer<typeof storedDevice>;-export interface PhonePushAccess {+export interface InstallationPushAccess {controlPlane: string;credential: string;}+/** The control plane with an installation credential, or (a Cloud home) its Admin with its bootstrap secret. */+export type PhonePushAccess = InstallationPushAccess | CloudHomePushAccess;export type PushOutcome = "sent" | "dropped" | "stale" | "live" | "gone" | "failed" | "retry" | "paused";@@ -409,18 +413,17 @@ export class PhonePush {}/** One POST to the relay; null when it could not be reached. The credential travels only in the Authorization header,- * to the control plane's own origin, and is never logged. */+ * to the control plane's own origin, and is never logged. A Cloud home's goes to its Admin, signed with its bootstrap+ * secret, which never leaves this process: the same body, the same answers. */private async relay(path: string, body: unknown): Promise<RelayAnswer | null> {const access = this.options.access();if (!access) return null;+ const request = "credential" in access+ ? { url: `${access.controlPlane}${path}`, init: { method: "POST", headers: { authorization: `Bearer ${access.credential}`, "content-type": "application/json" }, body: JSON.stringify(body) } }+ : cloudHomePushRequest(access, path, body, this.now());+ if (!request) return null;try {- const response = await this.fetchImpl(`${access.controlPlane}${path}`, {- method: "POST",- headers: { authorization: `Bearer ${access.credential}`, "content-type": "application/json" },- body: JSON.stringify(body),- redirect: "error",- signal: AbortSignal.timeout(RELAY_TIMEOUT_MS),- });+ const response = await this.fetchImpl(request.url, { ...request.init, redirect: "error", signal: AbortSignal.timeout(RELAY_TIMEOUT_MS) });const payload = await response.json().catch(() => null) as { error?: unknown } | null;const retryAfter = Number(response.headers.get("retry-after"));return {@@ -436,7 +439,7 @@ export class PhonePush {}/** A validated access pair, or null. */-export function phonePushAccess(controlPlane: unknown, credential: unknown): PhonePushAccess | null {+export function phonePushAccess(controlPlane: unknown, credential: unknown): InstallationPushAccess | null {const origin = typeof controlPlane === "string" ? normalizeControlPlaneURL(controlPlane) : "";if (!origin || typeof credential !== "string" || !INSTALLATION_CREDENTIAL.test(credential)) return null;return { controlPlane: origin, credential };@@ -444,15 +447,18 @@ export function phonePushAccess(controlPlane: unknown, credential: unknown): Pho/** Where this server's control-plane access comes from, first match wins: the desktop app's private message (its* credential lives in the OS store this process cannot read), OMB_PUSH_CREDENTIAL, a fleet's- * OMB_INSTALLATION_CREDENTIAL, `openmausbot login`'s tunnel-account.json. OMB_CONTROL_PLANE_URL overrides the origin. */+ * OMB_INSTALLATION_CREDENTIAL, `openmausbot login`'s tunnel-account.json. OMB_CONTROL_PLANE_URL overrides the origin.+ * Last, a Cloud home (server/cloud-home.ts) with none of those: its Admin relays, signed with its bootstrap secret. */export class PhonePushAccessSource {- private desktop: PhonePushAccess | null | undefined;+ private desktop: InstallationPushAccess | null | undefined;private readonly env: NodeJS.ProcessEnv;private readonly options: { tunnelFile: string; defaultControlPlane: string };+ private readonly cloudHome: CloudHomePushAccess | null;- constructor(options: { env?: NodeJS.ProcessEnv; tunnelFile: string; defaultControlPlane: string }) {+ constructor(options: { env?: NodeJS.ProcessEnv; tunnelFile: string; defaultControlPlane: string; cloudHome?: { adminOrigin: string; machineId: string; bootstrapSecret: string } | null }) {this.env = options.env ?? process.env;this.options = options;+ this.cloudHome = cloudHomePushAccess(options.cloudHome);}/** The desktop app's message: true when it was one. */@@ -478,9 +484,9 @@ export class PhonePushAccessSource {try {document = JSON.parse(readFileSync(this.options.tunnelFile, "utf8"));} catch {- return null;+ return this.cloudHome;}const credential = document && typeof document === "object" ? (document as Record<string, unknown>)[COMPANION_INSTALLATION_CREDENTIAL_FIELD] : undefined;- return phonePushAccess(this.controlPlane(), credential);+ return phonePushAccess(this.controlPlane(), credential) ?? this.cloudHome;}}