Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Server: phone push for approvals, questions, sign-ins and replies, off by default (#5982)

Milind Sonicb3f62226abb
diff --git a/companion/src/routes.ts b/companion/src/routes.ts
index 198a42eeac..c0f7c926bc 100644
--- a/companion/src/routes.ts
+++ b/companion/src/routes.ts
@@ -217,6 +217,10 @@ const ALLOWED: ReadonlyArray<{ method: string; path: RegExp }> = [
{ method: "DELETE", path: /^\/api\/phones\/self$/ },
{ method: "GET", path: /^\/api\/phones\/self\/jobs$/ },
{ method: "POST", path: /^\/api\/phones\/self\/jobs\/[\w-]+\/(?:lease|result)$/ },
+ // The phone's closed-app alert registration: its own device token, never another phone's.
+ { method: "PUT", path: /^\/api\/push\/device$/ },
+ { method: "GET", path: /^\/api\/push\/device$/ },
+ { method: "DELETE", path: /^\/api\/push\/device$/ },
// The harness records only the owner's activation; a guest's is answered and
// dropped.
diff --git a/companion/test/routes.test.ts b/companion/test/routes.test.ts
index fc0ea07913..1d37c5666a 100644
--- a/companion/test/routes.test.ts
+++ b/companion/test/routes.test.ts
@@ -31,6 +31,9 @@ describe("what the app may do", () => {
["PUT", "/api/phones/self"],
["GET", "/api/phones/self/jobs"],
["POST", "/api/phones/self/jobs/j1/result"],
+ ["PUT", "/api/push/device"],
+ ["GET", "/api/push/device"],
+ ["DELETE", "/api/push/device"],
["GET", "/api/config"],
["GET", "/api/events"],
["GET", "/api/instances"],
diff --git a/electron/main.mjs b/electron/main.mjs
index f60fde77c4..28013eb606 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -100,7 +100,7 @@ import { installCloudPlanIpc } from "./cloud-plan-ipc.mjs";
import { cloudLinkOpensSheet, colorDotIcons, createCloudLook, createCloudReadyNotice, installCloudBuy, lookFile } from "./cloud-buy.mjs"; import { unreadBadgeIcon } from "./color-dot.mjs";
import { createTrialNotices } from "./cloud-trial-notice.mjs";
import { createDesktopText, DESKTOP_PORTS, jsonFile, registerDesktopPrefs, relabelDesktop } from "./desktop-prefs.mjs";
-import { createDesktopIncludedX } from "./included-x.mjs"; import { createDesktopIncludedPages } from "./included-pages.mjs"; import { createPhoneLinkFact } from "./phone-link-fact.mjs";
+import { createDesktopIncludedX } from "./included-x.mjs"; import { createDesktopIncludedPages } from "./included-pages.mjs"; import { createPhoneLinkFact } from "./phone-link-fact.mjs"; import { createPhonePushAccessSync } from "./phone-push-access.mjs";
import { cloudPageSenderAllowed, cloudPlanDisk, cloudUnreachableText, createCloudPowerGate, isCloudHomeEntry, myCloudOrigin, rememberedCloudHome, savedCloudHomeOrigin, signInCloudSession, withCloudHome } from "./cloud-home.mjs";
import { installCloudFiles } from "./cloud-sync-main.mjs";
import { createCloudEntry } from "./cloud-entry.mjs"; import { installTeamJoin } from "./team-join-main.mjs";
@@ -287,7 +287,7 @@ let companyBackupClientStateRequest = null;
let companyRestoreCommitting = false;
let companyBackupConfigurationRevision = 0;
const managedDesktopRelay = createManagedDesktopRelay();
-const includedX = createDesktopIncludedX({ account: () => cloudAccount, server: () => serverProc, log: slog }), includedPages = createDesktopIncludedPages({ account: () => cloudAccount, server: () => serverProc, log: slog }), phoneLinkFact = createPhoneLinkFact({ retired: () => companionTunnelRetired(secureCredentialState?.read() ?? secureCredentials), server: () => (serverReady ? serverProc : null), log: slog });
+const includedX = createDesktopIncludedX({ account: () => cloudAccount, server: () => serverProc, log: slog }), includedPages = createDesktopIncludedPages({ account: () => cloudAccount, server: () => serverProc, log: slog }), phoneLinkFact = createPhoneLinkFact({ retired: () => companionTunnelRetired(secureCredentialState?.read() ?? secureCredentials), server: () => (serverReady ? serverProc : null), log: slog }), phonePushAccess = createPhonePushAccessSync({ server: () => (serverReady ? serverProc : null), credentials: () => secureCredentialState?.read() ?? secureCredentials, controlPlane: () => resolveCompanionControlPlaneURL({ isPackaged: app.isPackaged, environment: process.env }), log: slog });
const cloudPower = createCloudPowerGate({ power: () => cloudAccount?.power() ?? null, wanted: () => Boolean(cloudSync?.running() || computerSharing?.lendingToCloud()) });
const utilityServerExits = new WeakMap();
const UTILITY_SERVER_STOP_TIMEOUT_MS = 6_500;
@@ -304,7 +304,7 @@ const serverSupervisor = createServerSupervisor({
serverStartConflictOnly = false;
slog(`server ready pid=${proc.pid} port=${SERVER_PORT}`);
void readCloudOfferBrand();
- syncManagedComposioCredentials(); includedX.serverStarted(); includedPages.serverStarted(); phoneLinkFact.serverStarted(); railChanged();
+ syncManagedComposioCredentials(); includedX.serverStarted(); includedPages.serverStarted(); phoneLinkFact.serverStarted(); phonePushAccess.serverStarted(); railChanged();
reportOwnListeners(proc);
orgLibrary?.runtimeReady();
if (managedDesktop) void managedDesktop.refresh().catch(() => {});
@@ -524,7 +524,7 @@ export async function updateSecureCredentialDocument(derive, afterPersist) {
try {
return await secureCredentialState.update(derive, afterPersist);
} finally {
- secureCredentials = secureCredentialState.read();
+ secureCredentials = secureCredentialState.read(); phonePushAccess.sync();
}
}
diff --git a/electron/phone-push-access.mjs b/electron/phone-push-access.mjs
new file mode 100644
index 0000000000..a7116cf93e
--- /dev/null
+++ b/electron/phone-push-access.mjs
@@ -0,0 +1,50 @@
+// Closed-app phone alerts: the server asks the push relay in the hosted control plane to wake a phone, as this
+// installation (server/phone-push.ts). The installation credential lives in the OS-encrypted credential store, which
+// only this main process reads, so main hands the server the control plane's origin and that credential over the
+// utility process's private parent port: on every server start and whenever the stored document changes (sign-in,
+// rotation, sign-out). Nothing else of the account crosses. Without a hosted sign-in the message says `access: null`.
+import { COMPANION_INSTALLATION_CREDENTIAL_FIELD, companionAccountCleanupPending } from "./companion-account-service.mjs";
+
+export const PHONE_PUSH_ACCESS_MESSAGE = "openmausbot:phone-push-access";
+const INSTALLATION_CREDENTIAL = /^omb_install_[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/;
+
+/** The message for the server, from the credential document and the control plane's origin ("" when hosted access is
+ * off in this build). */
+export function phonePushAccessMessage(credentials, controlPlane) {
+ const credential = credentials?.[COMPANION_INSTALLATION_CREDENTIAL_FIELD];
+ const usable = typeof controlPlane === "string" && controlPlane !== ""
+ && typeof credential === "string" && INSTALLATION_CREDENTIAL.test(credential)
+ && !companionAccountCleanupPending(credentials);
+ return { type: PHONE_PUSH_ACCESS_MESSAGE, access: usable ? { controlPlane, credential } : null };
+}
+
+/**
+ * @param {{ server: () => { postMessage(message: object): void } | null, credentials: () => object | null,
+ * controlPlane: () => string, log: (line: string) => void }} options
+ */
+export function createPhonePushAccessSync({ server, credentials, controlPlane, log }) {
+ let last = "";
+ const sync = () => {
+ const proc = server();
+ if (!proc) return false;
+ const message = phonePushAccessMessage(credentials(), controlPlane());
+ const serialized = JSON.stringify(message);
+ if (serialized === last) return false;
+ try {
+ proc.postMessage(message);
+ } catch (error) {
+ log(`phone push access sync failed: ${error?.message ?? error}`);
+ return false;
+ }
+ last = serialized;
+ return true;
+ };
+ return {
+ sync,
+ /** A new server child knows nothing yet. */
+ serverStarted() {
+ last = "";
+ return sync();
+ },
+ };
+}
diff --git a/electron/phone-push-access.test.mjs b/electron/phone-push-access.test.mjs
new file mode 100644
index 0000000000..75c05b4bd8
--- /dev/null
+++ b/electron/phone-push-access.test.mjs
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+import { createPhonePushAccessSync, phonePushAccessMessage, PHONE_PUSH_ACCESS_MESSAGE } from "./phone-push-access.mjs";
+
+const credential = `omb_install_${"a".repeat(22)}.${"b".repeat(43)}`;
+const controlPlane = "https://accounts.openmausbot.com";
+
+describe("phone push access on the desktop", () => {
+ it("hands over only the control plane and a well-formed installation credential", () => {
+ expect(phonePushAccessMessage({ companionInstallationCredential: credential, companionAccountToken: "secret" }, controlPlane))
+ .toEqual({ type: PHONE_PUSH_ACCESS_MESSAGE, access: { controlPlane, credential } });
+ expect(phonePushAccessMessage({ companionInstallationCredential: credential }, "")).toEqual({ type: PHONE_PUSH_ACCESS_MESSAGE, access: null });
+ expect(phonePushAccessMessage({ companionInstallationCredential: "omb_install_short" }, controlPlane).access).toBeNull();
+ expect(phonePushAccessMessage({ companionInstallationCredential: credential, companionAccountCleanupPending: true }, controlPlane).access).toBeNull();
+ expect(phonePushAccessMessage(null, controlPlane).access).toBeNull();
+ });
+
+ it("posts on each server start and on each change, never twice the same", () => {
+ const posted = [];
+ let document = {};
+ let proc = { postMessage: (message) => posted.push(message) };
+ const sync = createPhonePushAccessSync({ server: () => proc, credentials: () => document, controlPlane: () => controlPlane, log: () => {} });
+ expect(sync.serverStarted()).toBe(true);
+ expect(sync.sync()).toBe(false);
+ document = { companionInstallationCredential: credential };
+ expect(sync.sync()).toBe(true);
+ expect(sync.serverStarted()).toBe(true);
+ expect(posted.map((message) => message.access)).toEqual([null, { controlPlane, credential }, { controlPlane, credential }]);
+ proc = null;
+ document = {};
+ expect(sync.sync()).toBe(false);
+ });
+
+ it("tries again later when the server could not take the message", () => {
+ const logged = [];
+ let fail = true;
+ const posted = [];
+ const sync = createPhonePushAccessSync({
+ server: () => ({ postMessage: (message) => { if (fail) throw new Error("closed"); posted.push(message); } }),
+ credentials: () => ({}), controlPlane: () => controlPlane, log: (line) => logged.push(line),
+ });
+ expect(sync.sync()).toBe(false);
+ expect(logged).toHaveLength(1);
+ fail = false;
+ expect(sync.sync()).toBe(true);
+ expect(posted).toHaveLength(1);
+ });
+});
diff --git a/packages/phone-protocol/src/phone-push.ts b/packages/phone-protocol/src/phone-push.ts
new file mode 100644
index 0000000000..bafc6f6bfb
--- /dev/null
+++ b/packages/phone-protocol/src/phone-push.ts
@@ -0,0 +1,124 @@
+/** Closed-app phone alerts, version 1: what a paired phone sends its computer or Cloud, what that server sends the push
+ * relay in the hosted control plane (cloudflare/control-plane), and what the phone receives from Apple or Google.
+ *
+ * A push is content-free by construction: the alert's kind, a title built from the bot's and room's names, opaque ids
+ * and the phone's own tag for the computer. Never message text, a reply, a file path or a secret. The phone fetches the
+ * content from its computer when it opens. */
+
+export const PHONE_PUSH_WIRE_VERSION = 1 as const;
+
+/** The phone's own route on its computer or Cloud: `PUT` registers or updates, `GET` reads back, `DELETE` removes. Keyed
+ * by what authenticated the request (a paired session, or the device the companion vouched for), never by the body. */
+export const PHONE_PUSH_ROUTE = "/api/push/device";
+
+/** The relay's paths, under the control plane's origin. Each takes `Authorization: Bearer <omb_install_…>`. */
+export const PHONE_PUSH_RELAY_PATHS = {
+ register: "/v1/installations/self/push/register",
+ unregister: "/v1/installations/self/push/unregister",
+ send: "/v1/installations/self/push/send",
+} as const;
+
+export const PUSH_PLATFORMS = ["apns", "fcm"] as const;
+export type PushPlatform = (typeof PUSH_PLATFORMS)[number];
+export type ApnsEnvironment = "production" | "sandbox";
+
+/** An APNs device token as the phone hands it over: lowercase hex. */
+export const APNS_TOKEN = /^[0-9a-f]{64,200}$/;
+/** An FCM registration token. */
+export const FCM_TOKEN = /^[A-Za-z0-9_:-]{64,4096}$/;
+/** The phone's opaque tag for one saved computer, echoed in every push so a tap opens the right one. */
+export const PAIRING_TAG = /^[A-Za-z0-9_-]{8,64}$/;
+/** The notification identifier a push carries: at most 64 bytes, APNs' limit for `apns-collapse-id`. */
+export const PUSH_COLLAPSE_ID = /^[A-Za-z0-9._:-]{1,64}$/;
+export const PUSH_ID = /^[\w-]{1,120}$/;
+export const PUSH_NAME_MAX = 80;
+export const PUSH_TITLE_MAX = 200;
+
+/** The kinds a closed app is woken for: a bot waits on the person (approval, question, sign-in), or a reply is ready.
+ * Everything else reaches the phone only while it is connected. */
+export const PUSH_KINDS = ["approval", "question", "sign-in", "done"] as const;
+export type PushKind = (typeof PUSH_KINDS)[number];
+
+/** `PUT /api/push/device`, from the phone. */
+export interface PhonePushRegistration {
+ platform: PushPlatform;
+ token: string;
+ /** APNs only: `sandbox` for a development build. */
+ environment?: ApnsEnvironment;
+ pairing?: string;
+ /** The kinds this phone wants pushed, from its own notification switches. Absent: all of `PUSH_KINDS`. Empty: none,
+ * the registration is kept. */
+ kinds?: PushKind[];
+}
+
+/** Whether pushes can leave this server at all: `off` until the owner switches phone push on, `no-account` while it
+ * holds no installation credential to reach the relay with. */
+export type PhonePushState = "on" | "off" | "no-account";
+
+/** A registration as the phone may read it back: never the token, never another phone's. */
+export interface PublicPushDevice {
+ platform: PushPlatform;
+ environment: ApnsEnvironment;
+ pairing?: string;
+ kinds: PushKind[];
+ updatedAt: number;
+}
+
+/** What every `/api/push/device` answer carries. */
+export interface PhonePushAnswer {
+ push: PhonePushState;
+ device: PublicPushDevice | null;
+}
+
+/** What the push carries beside its title. */
+export interface PhonePushNotification {
+ kind: string;
+ title: string;
+ botId: string;
+ botName: string;
+ threadId: string;
+ roomId?: string;
+ roomName?: string;
+}
+
+export interface PushRelaySendRequest {
+ v: typeof PHONE_PUSH_WIRE_VERSION;
+ token: string;
+ pairing?: string;
+ collapseId?: string;
+ notification: PhonePushNotification;
+}
+
+/** The data the phone app reads from a push: `body` on both platforms (APNs custom key, FCM data as JSON). */
+export interface PhonePushData {
+ v: typeof PHONE_PUSH_WIRE_VERSION;
+ kind: string;
+ botId: string;
+ botName: string;
+ threadId: string;
+ roomId?: string;
+ roomName?: string;
+ pairing?: string;
+}
+
+/** The relay's error codes a server acts on. Anything else is transient. */
+export const PUSH_RELAY_ERRORS = {
+ unknownDevice: "push_device_unknown",
+ unregistered: "push_device_unregistered",
+ unavailable: "push_unavailable",
+} as const;
+
+/** `openmaus.<threadId>.<seq>`, the identifier the phone gives the notification the live stream would post for the
+ * same frame, so a push and that notification replace each other. Undefined when it would not fit. */
+export function phonePushCollapseId(threadId: string, seq: number): string | undefined {
+ const id = `openmaus.${threadId}.${seq}`;
+ return Number.isSafeInteger(seq) && seq >= 0 && PUSH_COLLAPSE_ID.test(id) ? id : undefined;
+}
+
+export function isPushKind(kind: string): kind is PushKind {
+ return (PUSH_KINDS as readonly string[]).includes(kind);
+}
+
+export function validPushToken(platform: PushPlatform, token: string): boolean {
+ return platform === "apns" ? APNS_TOKEN.test(token) : FCM_TOKEN.test(token);
+}
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index ed4fb14f6b..35d65cf6a2 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -43,8 +43,8 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_JEV_API_KEY", "OMB_LAN", "OMB_LICENSE_KEY", "OMB_LINUX_GPU", "OMB_LIVE_PROVIDER", "OMB_LOCAL_VM_UPDATE_WAIT_MS",
"OMB_LOOPBACK_TRUST", "OMB_LOOP_GUARD", "OMB_LOOP_GUARD_STOP_AT", "OMB_META_API_KEY", "OMB_MODELGO_API_KEY", "OMB_NETLIFY_API_URL", "OMB_OPENAI_API_KEY",
"OMB_OPENAI_IMAGE_KEY", "OMB_OPENAI_LIVE_KEY", "OMB_OPENAI_LIVE_URL", "OMB_OPENROUTER_API_KEY",
- "OMB_OPENROUTER_DECIDER_KEY", "OMB_PERSON_FIRST_MS", "OMB_PHONE_RELAY", "OMB_PHONE_RELAY_URL", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PORT", "OMB_SERVES_TUNNEL", "OMB_POSTIZ_API_KEY",
- "OMB_POSTIZ_CLOUD_URL", "OMB_PROCESS_ID", "OMB_PUBLIC_IPV4", "OMB_PUBLIC_URL", "OMB_QUOTA_SWITCH",
+ "OMB_OPENROUTER_DECIDER_KEY", "OMB_PERSON_FIRST_MS", "OMB_PHONE_PUSH", "OMB_PHONE_RELAY", "OMB_PHONE_RELAY_URL", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PORT", "OMB_SERVES_TUNNEL", "OMB_POSTIZ_API_KEY",
+ "OMB_POSTIZ_CLOUD_URL", "OMB_PROCESS_ID", "OMB_PUBLIC_IPV4", "OMB_PUBLIC_URL", "OMB_PUSH_CREDENTIAL", "OMB_QUOTA_SWITCH",
"OMB_REPLAY_TOOL_HISTORY", "OMB_ROOM_SESSIONS", "OMB_SAFETY_FLOOR", "OMB_SERVER_COMPILE_CACHE", "OMB_SERVER_NAME",
"OMB_SERVER_UPDATE_DIR",
"OMB_SESSION_IDLE_MIN_MS", "OMB_SESSION_IDLE_MS", "OMB_SESSION_MAX_DAYS", "OMB_SESSION_TTL_DAYS",
diff --git a/server/config.ts b/server/config.ts
index a660ff3714..b6ab9b6eef 100644
--- a/server/config.ts
+++ b/server/config.ts
@@ -244,7 +244,7 @@ const featureConfigSchema = z.object({
/** Room jobs to several members run side by side, each in a thread of its own. Off unless true. */
parallelRoomJobs: z.boolean().optional(),
acpPlanLines: z.boolean().optional(), // An ACP agent's plan as activity lines. Off unless true.
-}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional(), cloudComputerAutoReplace: z.boolean().optional() }); // cloudComputerAutoReplace: delete and replace a dead cloud computer by itself, off unless true (OMB_CLOUD_COMPUTER_AUTO_REPLACE wins); agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless true
+}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional(), cloudComputerAutoReplace: z.boolean().optional(), phonePush: z.boolean().optional() }); // cloudComputerAutoReplace: delete and replace a dead cloud computer by itself, off unless true (OMB_CLOUD_COMPUTER_AUTO_REPLACE wins); agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless true; phonePush: wake a paired phone whose app is closed through the hosted push relay, off unless true (OMB_PHONE_PUSH wins)
const onboardingConfigSchema = z.object({
completedAt: z.string().trim().max(40).optional(),
version: z.number().int().min(0).max(1000).optional(),
@@ -483,7 +483,7 @@ export interface AppConfig extends HelperConfig {
context?: { rebuildBytes?: number; compactAt?: number; autoCompact?: boolean; roomCompactAt?: number; roomSessions?: boolean; replayToolHistory?: boolean };
memory?: { captureQuietMs?: number; tidyHour?: number };
localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean; memoryGb?: number; cpus?: number };
- features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean; usbPhoneTakeover?: boolean; cloudComputerAutoReplace?: boolean };
+ features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean; usbPhoneTakeover?: boolean; cloudComputerAutoReplace?: boolean; phonePush?: boolean };
onboarding?: { completedAt?: string; version?: number; reelSeen?: boolean; hintsSeen?: string[]; firstTurnAt?: string };
browserProfiles?: BrowserProfile[];
browserEngine?: BrowserEngineConfig;
diff --git a/server/index.ts b/server/index.ts
index 9338593e2d..cf10f7bdc1 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -102,7 +102,7 @@ import { removeRetiredAppFiles } from "./retired-apps.ts"; import { createEmailR
import { createPhones } from "./host/phones.ts";
import { NOT_THE_OWNER } from "./phones/owner.ts";
import { PHONE_INTERNAL_MCP_PATH } from "./phones/rpc.ts";
-import { isLongPollPath } from "./routes/phones.ts";
+import { isLongPollPath, phoneKey } from "./routes/phones.ts"; import { createPhonePushRoutes } from "./routes/phone-push.ts"; import { PhonePush, PhonePushAccessSource, phonePushEnabled } from "./phone-push.ts"; import { DEFAULT_COMPANION_CONTROL_PLANE_URL } from "../electron/companion-account-service.mjs"; import { TUNNEL_CREDENTIALS_FILE } from "./tunnel.ts";
import { createDataRoutes } from "./data/routes.ts";
import { DataSheetRegistry } from "./data/sheet.ts";
import { DataFailure } from "./data/types.ts";
@@ -1490,7 +1490,7 @@ const browserCleanup: BrowserCleanupCoordinator = new BrowserCleanupCoordinator(
return true;
},
});
-const phoneSecrets = new PhoneSecretBridge(postDesktopPrivateMessage, undefined, undefined, DESKTOP_MANAGED);
+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 });
utilityParentPort?.on("message", (event) => {
const message = event?.data;
try {
@@ -1498,7 +1498,7 @@ utilityParentPort?.on("message", (event) => {
if (handleDesktopTrustedApprovalMessage(message)) return;
if (browserCleanup.receive(message)) return;
if (phoneSecrets.receive(message) || botLogins.receiveHandoff(message, postDesktopPrivateMessage, (what) => cloudConnections.handoff(what))) return;
- if (applyIncludedPagesMessage(message)) return; if (applyIncludedXMessage(message)) return void broadcast({ kind: "config", ...configStatus() }); if (applyPhoneLinkMessage(message)) return;
+ if (applyIncludedPagesMessage(message)) return; if (applyIncludedXMessage(message)) return void broadcast({ kind: "config", ...configStatus() }); if (applyPhoneLinkMessage(message) || phonePushAccess.receive(message)) return;
composio.applyManagedBrokerMessage(message);
} catch (error) {
console.error(`[desktop-sync] rejected private parent message: ${error instanceof Error ? error.message : String(error)}`);
@@ -4629,7 +4629,7 @@ interface SseClient {
/** On a Team Cloud, who the stream is for: its config frames carry that person's own profile. */
person?: SessionRecord;
screens: boolean;
- appWindow: boolean;
+ appWindow: boolean; /** The phone behind this stream, as routes/phones.ts keys it: while it is open, that phone gets no push. */ pushKey?: string;
/** Revoking or expiring this session must end the stream, not just future requests. */
sessionId?: string;
backpressured: boolean;
@@ -4639,7 +4639,7 @@ interface SseClient {
/** Stops the heartbeat and leaves `sseClients` before ending the response; every way a stream ends goes through it. */
close: () => void;
}
-const { streams: sseClients, ...teamPresence } = createTeamPresenceHost<SseClient>({ people: teamOwners.people, broadcast, audienceOf: (threadId) => teamHost.audienceOf(threadId), sharedWithOne: (threadId) => conversationShares.readers(threadId) !== null, store: () => store, visibleTo });
+const { streams: sseClients, ...teamPresence } = createTeamPresenceHost<SseClient>({ people: teamOwners.people, broadcast, audienceOf: (threadId) => teamHost.audienceOf(threadId), sharedWithOne: (threadId) => conversationShares.readers(threadId) !== null, store: () => store, visibleTo }); type StreamView = Pick<SseClient, "admin" | "person" | "viewer" | "seen" | "ask">; const phonePush = new PhonePush({ dataDir: DATA_DIR, access: () => phonePushAccess.current(), enabled: () => phonePushEnabled(cfg), live: (key) => [...sseClients].some((client) => client.pushKey === key), room: (notification) => { const group = (notification.groupId ? store.group(notification.groupId) : undefined) ?? store.groupByThread(notification.threadId); return group && !group.dm ? { id: group.id, name: group.name } : undefined; } });
let audienceChangedAt = 0;
function audienceChanged(): void {
@@ -4744,7 +4744,7 @@ function broadcast(payload: Record<string, unknown>, options: { adminOnly?: bool
// Members get config as configured-or-not and every bot without its server alias.
const clientPayload = options.adminOnly ? null : kind === "config" ? configForAccess(payload as ReturnType<typeof configStatus>, false) : memberFramePayload(payload);
const clientFrame = clientPayload === null ? null : clientPayload === payload ? frame : `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...clientPayload, seq })}\n\n`;
- replayBuffer.push({ seq, kind, frame, clientFrame, payload, ...(options.person ? { person: options.person } : {}) });
+ replayBuffer.push({ seq, kind, frame, clientFrame, payload, ...(options.person ? { person: options.person } : {}) }); if (kind === "notify") phonePush.offer({ notification: payload.notification, seq }, (key) => pushReaches(key, payload, seq, options));
const ownGroups: OwnGroupFrames = new Map();
for (const client of Array.from(sseClients)) {
if (!wants(client, kind) || !teamOwners.reaches(client.ask, payload) || !streamFor(client, options.person)) continue;
@@ -4762,11 +4762,18 @@ function teamConfigFrame(client: SseClient, seq: number, payload: Record<string,
return `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...own, seq })}\n\n`;
}
-const streamFor = (client: SseClient, person: string | undefined) => !person || (client.person !== undefined && personKey(client.person) === person);
+const streamFor = (client: Pick<SseClient, "person">, person: string | undefined) => !person || (client.person !== undefined && personKey(client.person) === person);
+/** What a stream for `auth` is shown; a phone with no stream open is judged by the same view (pushReaches). */
+function streamView(auth: RequestAuth, viewer: Viewer = viewerFor(auth)): StreamView { const visibleNow = visibleTo(viewer); return { admin: auth.scopes.includes("admin"), viewer, ask: teamOwners.viewer(auth), seen: viewer.kind === "all" && !visibleNow.filtersThreads ? { bots: new Set(), groups: new Set() } : { bots: new Set(store.bots.filter((bot) => visibleNow.bot(bot.id)).map((bot) => bot.id)), groups: new Set(store.groups.filter((group) => visibleNow.group(group.id)).map((group) => group.id)) }, ...(CLOUD_TEAM && auth.kind === "session" ? { person: auth.session } : {}) }; }
+/** Whether the phone behind `key` would have been sent this frame had its stream been open: broadcast's own rule. */
+function pushReaches(key: string, payload: Record<string, unknown>, seq: number, options: { adminOnly?: boolean; person?: string }): boolean {
+ const session = key.startsWith("session:") ? sessions.record(key.slice("session:".length)) : null;
+ const auth: RequestAuth | null = key.startsWith("companion:") ? { kind: "loopback", scopes: ["admin", "client"], companionDevice: key.slice("companion:".length) } : session ? { kind: "session", session, via: "bearer", scopes: session.scopes } : null;
+ const view = auth && streamView(auth); return view !== null && teamOwners.reaches(view.ask, payload) && streamFor(view, options.person) && memberFrame(view, seq, payload, view.admin || !options.adminOnly ? "" : null) !== null; }
/** `clientFrame` is the frame this client would get unnarrowed: an admin's is the admin frame, narrowed on a Team Cloud.
* `ownGroups` keeps each person's room for one frame. */
-function memberFrame(client: SseClient, seq: number, payload: Record<string, unknown>, clientFrame: string | null, ownGroups: OwnGroupFrames = new Map()): string | null {
+function memberFrame(client: StreamView, seq: number, payload: Record<string, unknown>, clientFrame: string | null, ownGroups: OwnGroupFrames = new Map()): string | null {
const own = client.person && clientFrame !== null ? personRooms.ownGroupFrame(ownGroups, personKey(client.person), payload, (mine) => `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...mine, seq })}\n\n`) : null;
if (own) { payload = own.payload; clientFrame = own.frame; }
const order = clientFrame === null ? null : botOrders?.streamFrame(client, payload); if (order) { payload = order; clientFrame = `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...order, seq })}\n\n`; }
@@ -12486,7 +12493,7 @@ const liveCalls = new LiveCallController({
},
log: (line) => console.log(line),
});
-sessions.onSessionRevoked((sessionId) => liveCalls.sessionRevoked(sessionId));
+sessions.onSessionRevoked((sessionId) => liveCalls.sessionRevoked(sessionId)); sessions.onSessionRevoked((sessionId) => phonePush.forget(`session:${sessionId}`)); ROUTES.push(createPhonePushRoutes({ push: phonePush, live: (auth) => auth.kind === "loopback" || sessions.isLive(auth.session.id) }));
ROUTES.push(createDataRoutes({
bot: (id) => store.bot(id),
engine: dataEngine,
@@ -12495,7 +12502,7 @@ ROUTES.push(createDataRoutes({
exportRoots: dataExportRoots,
}));
ROUTES.push(createLiveRoutes({
- calls: liveCalls,
+ calls: liveCalls, deviceRevoked: (device) => phonePush.forget(`companion:${device}`),
resolveTarget: (botId, threadId) => {
const bot = store.bot(botId);
if (!bot) return null;
@@ -14621,17 +14628,11 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
}
if (method === "GET" && path === "/api/events") {
- const visibleNow = visibleTo(viewer);
+ const pushKey = phoneKey(auth);
const client: SseClient = {
- res,
- admin: auth.scopes.includes("admin"),
+ res, ...streamView(auth, viewer), ...(pushKey ? { pushKey } : {}),
screens: url.searchParams.get("screens") !== "off", appWindow: url.searchParams.get("window") === "1",
backpressured: false,
- viewer, ask: teamOwners.viewer(auth),
- seen: viewer.kind === "all" && !visibleNow.filtersThreads ? { bots: new Set(), groups: new Set() } : {
- bots: new Set(store.bots.filter((bot) => visibleNow.bot(bot.id)).map((bot) => bot.id)),
- groups: new Set(store.groups.filter((group) => visibleNow.group(group.id)).map((group) => group.id)),
- },
// A comment frame keeps intermediaries from idling the connection; a data frame resets EventSource's own liveness watchdog. Heartbeats carry no id.
close: openSseHeartbeat(res, {
everyMs: SSE_HEARTBEAT_MS,
@@ -14640,7 +14641,6 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
}),
};
if (auth.kind === "session") client.sessionId = auth.session.id;
- if (CLOUD_TEAM && auth.kind === "session") client.person = auth.session;
res.writeHead(200, {
"content-type": "text/event-stream",
"cache-control": "no-cache",
diff --git a/server/phone-push.e2e.test.ts b/server/phone-push.e2e.test.ts
new file mode 100644
index 0000000000..f34b6e4718
--- /dev/null
+++ b/server/phone-push.e2e.test.ts
@@ -0,0 +1,177 @@
+// A real server in a temporary home with the fake engines and a stand-in control plane: two paired phones register for
+// closed-app alerts; a finished reply and a question reach, as content-free pushes carrying the stream's own
+// identifier, only the phone that holds no live event stream; signing a phone out unregisters its token; a phone whose
+// stream closes gets the next one. A second server with phone push left off keeps nothing and calls nobody.
+import { spawn, type ChildProcess } from "node:child_process";
+import { chmodSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { startControlPlaneStub, type ControlPlaneStub } from "./testing/control-plane-stub.ts";
+import { freePortBlock } from "./testing/ports.ts";
+import { openSse, type SseRecorder } from "./testing/sse.ts";
+
+const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
+const ROOT = join(SERVER_DIR, "..");
+const FAKE_CLAUDE = join(SERVER_DIR, "testing", "fake-claude-cli.ts");
+const FAKE_ACP = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
+const SECRET_REPLY = "PRIVATE-REPLY-TEXT see /Users/someone/payroll.csv token sk-live-abc123";
+const APNS_A = "a1".repeat(32);
+const FCM_B = `fcmPhoneB_01:APA91b${"Q".repeat(140)}`;
+
+interface Fixture { child: ChildProcess; home: string; base: string; stderr: () => string }
+
+let stub: ControlPlaneStub;
+let on: Fixture;
+let off: Fixture;
+const streams: SseRecorder[] = [];
+
+async function boot(env: Record<string, string>): Promise<Fixture> {
+ const home = mkdtempSync(join(tmpdir(), "omb-phone-push-"));
+ const data = join(home, ".openmausbot");
+ mkdirSync(data, { recursive: true });
+ writeFileSync(join(data, "config.json"), JSON.stringify({
+ features: { smartSetupChoices: false },
+ instances: {
+ quick: { driver: "claudeAgent", displayName: "Quick fixture", environment: { FAKE_CLAUDE_MODE: "happy", FAKE_CLAUDE_REPLIES: JSON.stringify(Array.from({ length: 8 }, () => SECRET_REPLY)) }, config: { cli: FAKE_CLAUDE } },
+ curious: { driver: "grokAgent", displayName: "Curious fixture", environment: { FAKE_ACP_MODE: "question" }, config: { cli: FAKE_ACP, fullAuto: true } },
+ },
+ }));
+ const port = await freePortBlock([0, 1]);
+ let stderr = "";
+ const child = spawn(process.execPath, [join(SERVER_DIR, "index.ts")], {
+ cwd: ROOT,
+ env: {
+ ...(process.env.PATH ? { PATH: process.env.PATH } : {}),
+ ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
+ HOME: home,
+ USERPROFILE: home,
+ OMB_PORT: String(port),
+ OMB_WEBHOOK_PORT: String(port + 1),
+ ...env,
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ child.stderr!.on("data", (chunk) => (stderr += chunk));
+ const base = `http://127.0.0.1:${port}`;
+ for (const deadline = Date.now() + 20_000; ;) {
+ if (child.exitCode !== null) throw new Error(`server exited ${child.exitCode}: ${stderr}`);
+ try { if ((await fetch(`${base}/api/health`)).status === 200) break; } catch {}
+ if (Date.now() >= deadline) throw new Error(`server never became healthy: ${stderr}`);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ return { child, home, base, stderr: () => stderr };
+}
+
+const api = async (fixture: Fixture, method: string, path: string, body?: unknown, token?: string) => {
+ const response = await fetch(fixture.base + path, {
+ method,
+ headers: { origin: fixture.base, ...(body === undefined ? {} : { "content-type": "application/json" }), ...(token ? { authorization: `Bearer ${token}` } : {}) },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ signal: AbortSignal.timeout(30_000),
+ });
+ return { status: response.status, body: await response.json() as any };
+};
+
+const pair = async (fixture: Fixture, label: string) => {
+ const opened = await api(fixture, "POST", "/api/auth/pairing", { label, scopes: ["admin", "client"] });
+ expect(opened.status).toBe(200);
+ const paired = await api(fixture, "POST", "/api/auth/pair", { code: opened.body.code });
+ expect(paired.body.token).toMatch(/^omb_sess_/u);
+ return paired.body as { token: string; session: { id: string } };
+};
+
+const createBot = async (fixture: Fixture, name: string, instanceId: string, model: string) => {
+ const created = (await api(fixture, "POST", "/api/bots", {})).body.bot;
+ const patched = await api(fixture, "PATCH", `/api/bots/${created.id}`, { name, notifications: true, modelSelection: { instanceId, model } });
+ expect(patched.status).toBe(200);
+ return patched.body.bot as { id: string; threadId: string };
+};
+
+const sends = () => stub.pushes.filter((push) => push.path.endsWith("/send"));
+
+beforeAll(async () => {
+ chmodSync(FAKE_CLAUDE, 0o755);
+ chmodSync(FAKE_ACP, 0o755);
+ stub = await startControlPlaneStub();
+ const credential = stub.seedInstallation("phone push fixture");
+ [on, off] = await Promise.all([
+ boot({ OMB_PHONE_PUSH: "1", OMB_CONTROL_PLANE_URL: stub.url, OMB_PUSH_CREDENTIAL: credential }),
+ boot({ OMB_CONTROL_PLANE_URL: stub.url, OMB_PUSH_CREDENTIAL: credential }),
+ ]);
+}, 60_000);
+
+afterAll(async () => {
+ for (const stream of streams) stream.close();
+ for (const fixture of [on, off]) {
+ if (!fixture) continue;
+ await waitForExit(fixture.child, { signal: "SIGTERM" });
+ await removeTempDir(fixture.home);
+ }
+ await stub?.close();
+});
+
+describe("phone push left off", () => {
+ it("answers off, keeps nothing and calls no relay", async () => {
+ const phone = await pair(off, "Off phone");
+ expect(await api(off, "PUT", "/api/push/device", { platform: "apns", token: APNS_A }, phone.token)).toEqual({ status: 200, body: { push: "off", relay: "off", device: null } });
+ expect(await api(off, "GET", "/api/push/device", undefined, phone.token)).toEqual({ status: 200, body: { push: "off", device: null } });
+ expect(stub.pushes).toEqual([]);
+ });
+});
+
+describe("phone push switched on", () => {
+ it("wakes only the phone that is not connected, without the reply's text, and stops when it signs out", async () => {
+ const phoneA = await pair(on, "Phone A");
+ const phoneB = await pair(on, "Phone B");
+ expect((await api(on, "PUT", "/api/push/device", { platform: "apns", token: APNS_A, environment: "sandbox", pairing: "pair-tag-aaaa" }, phoneA.token)).body)
+ .toMatchObject({ push: "on", relay: "registered", device: { platform: "apns", environment: "sandbox", pairing: "pair-tag-aaaa" } });
+ expect((await api(on, "PUT", "/api/push/device", { platform: "fcm", token: FCM_B, pairing: "pair-tag-bbbb" }, phoneB.token)).body)
+ .toMatchObject({ push: "on", relay: "registered", device: { platform: "fcm", environment: "production" } });
+ expect(stub.pushes.map((push) => push.body)).toEqual([
+ { v: 1, platform: "apns", token: APNS_A, environment: "sandbox" },
+ { v: 1, platform: "fcm", token: FCM_B },
+ ]);
+
+ const streamA = await openSse(`${on.base}/api/events`, { authorization: `Bearer ${phoneA.token}`, origin: on.base });
+ streams.push(streamA);
+ await streamA.until((frame) => frame.kind === "hello", 10_000);
+ const herald = await createBot(on, "Herald", "quick", "claude-sonnet-5");
+ expect((await api(on, "POST", `/api/bots/${herald.id}/messages`, { text: "how did it go?" })).status).toBe(202);
+ const done = await streamA.until((frame) => frame.kind === "notify" && frame.notification?.kind === "done" && frame.notification?.botId === herald.id, 30_000);
+ expect(done.notification.body).toContain("PRIVATE-REPLY-TEXT");
+
+ await expect.poll(() => sends().length, { timeout: 15_000 }).toBe(1);
+ expect(sends()[0]!.body).toEqual({
+ v: 1,
+ token: FCM_B,
+ pairing: "pair-tag-bbbb",
+ collapseId: `openmaus.${herald.threadId}.${done.seq}`,
+ notification: { kind: "done", title: "Herald finished", botId: herald.id, botName: "Herald", threadId: herald.threadId },
+ });
+ const raw = JSON.stringify(stub.pushes);
+ for (const secret of ["PRIVATE-REPLY-TEXT", "payroll", "sk-live", "/Users/"]) expect(raw).not.toContain(secret);
+
+ const sage = await createBot(on, "Sage", "curious", "fake-model");
+ expect((await api(on, "PATCH", `/api/bots/${sage.id}`, { approvalMode: "ask", applyToAllThreads: true })).status).toBe(200);
+ expect((await api(on, "POST", `/api/bots/${sage.id}/messages`, { text: "pick a colour for the banner" })).status).toBe(202);
+ const question = await streamA.until((frame) => frame.kind === "notify" && frame.notification?.kind === "question" && frame.notification?.botId === sage.id, 30_000);
+ await expect.poll(() => sends().length, { timeout: 15_000 }).toBe(2);
+ expect(sends()[1]!.body).toMatchObject({ token: FCM_B, collapseId: `openmaus.${question.notification.threadId}.${question.seq}`, notification: { kind: "question", title: "Sage has a question" } });
+ await api(on, "POST", `/api/bots/${sage.id}/interrupt`, {}).catch(() => undefined);
+
+ expect((await api(on, "POST", "/api/auth/logout", {}, phoneB.token)).status).toBe(200);
+ await expect.poll(() => stub.pushes.at(-1), { timeout: 10_000 }).toEqual({ path: "/v1/installations/self/push/unregister", body: { v: 1, platform: "fcm", token: FCM_B } });
+
+ streamA.close();
+ await expect.poll(async () => (await api(on, "GET", "/api/push/device", undefined, phoneA.token)).body.device?.platform, { timeout: 5_000 }).toBe("apns");
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ expect((await api(on, "POST", `/api/bots/${herald.id}/messages`, { text: "and now?" })).status).toBe(202);
+ await expect.poll(() => sends().length, { timeout: 30_000 }).toBe(3);
+ expect(sends()[2]!.body).toMatchObject({ token: APNS_A, pairing: "pair-tag-aaaa", notification: { kind: "done", title: "Herald finished" } });
+ expect(on.stderr()).not.toContain(FCM_B);
+ }, 120_000);
+});
diff --git a/server/phone-push.test.ts b/server/phone-push.test.ts
new file mode 100644
index 0000000000..2497487d01
--- /dev/null
+++ b/server/phone-push.test.ts
@@ -0,0 +1,374 @@
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { PUSH_KINDS, phonePushCollapseId } from "../shared/phone-push.ts";
+import {
+ MAX_PUSH_DEVICES,
+ PHONE_PUSH_DESKTOP_MESSAGE,
+ PHONE_PUSH_FILE,
+ PUSH_COALESCE_MS,
+ PUSH_DEVICE_WINDOW_MAX,
+ PUSH_MAX_AGE_MS,
+ PUSH_RETRY_MS,
+ PhonePush,
+ PhonePushAccessSource,
+ RELAY_UNAVAILABLE_PAUSE_MS,
+ phonePushEnabled,
+ phonePushNotification,
+ registrationSchema,
+ type PhonePushOptions,
+} from "./phone-push.ts";
+
+const CREDENTIAL = `omb_install_${"a".repeat(22)}.${"b".repeat(43)}`;
+const ACCESS = { controlPlane: "https://accounts.openmausbot.test", credential: CREDENTIAL };
+const APNS = "ab".repeat(32);
+const APNS_2 = "cd".repeat(32);
+const FCM = `fcmInstance_1:APA91b${"x".repeat(140)}`;
+const PHONE = "session:phone-1";
+const OTHER = "companion:device-2";
+
+interface RelayCall { path: string; body: Record<string, unknown>; authorization: string | null }
+
+function fakeRelay() {
+ const calls: RelayCall[] = [];
+ const answers: Array<{ status: number; error?: string; retryAfter?: number } | "unreachable"> = [];
+ const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = new URL(String(input));
+ calls.push({ path: url.pathname, body: JSON.parse(String(init?.body)), authorization: new Headers(init?.headers).get("authorization") });
+ const answer = answers.shift();
+ if (answer === "unreachable") throw new TypeError("fetch failed");
+ const status = answer?.status ?? (url.pathname.endsWith("/send") ? 202 : url.pathname.endsWith("/unregister") ? 204 : 200);
+ return new Response(answer?.error ? JSON.stringify({ error: answer.error }) : status === 204 ? null : "{}", {
+ status,
+ headers: answer?.retryAfter ? { "retry-after": String(answer.retryAfter) } : {},
+ });
+ }) as typeof fetch;
+ return { calls, answers, fetchImpl, sends: () => calls.filter((call) => call.path.endsWith("/send")) };
+}
+
+let dataDir: string;
+let clock: number;
+let timers: Array<{ run: () => void; at: number }>;
+
+beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), "omb-phone-push-"));
+ clock = 1_000_000;
+ timers = [];
+});
+afterEach(() => rmSync(dataDir, { recursive: true, force: true }));
+
+function harness(options: Partial<PhonePushOptions> & { liveKeys?: Set<string> } = {}) {
+ const relay = fakeRelay();
+ const liveKeys = options.liveKeys ?? new Set<string>();
+ let enabled = true;
+ const push = new PhonePush({
+ dataDir,
+ access: () => ACCESS,
+ enabled: () => enabled,
+ live: (key) => liveKeys.has(key),
+ room: () => undefined,
+ fetchImpl: relay.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, relay, liveKeys, setEnabled: (on: boolean) => { enabled = on; } };
+}
+
+/** Moves the clock and runs the timers that came due. */
+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 = (overrides: Record<string, unknown> = {}) => ({
+ kind: "approval",
+ botId: "bot_1",
+ botName: "Scout",
+ threadId: "th_1",
+ title: "Scout needs approval",
+ body: "PRIVATE: run `cat ~/payroll.csv` with API_KEY=sk-live-123",
+ ...overrides,
+});
+const everyone = () => true;
+
+describe("phone push switch", () => {
+ it("is off unless config or OMB_PHONE_PUSH turns it on, and the variable wins", () => {
+ expect(phonePushEnabled({}, {})).toBe(false);
+ expect(phonePushEnabled({ features: { phonePush: true } }, {})).toBe(true);
+ expect(phonePushEnabled({ features: { phonePush: true } }, { OMB_PHONE_PUSH: "0" })).toBe(false);
+ expect(phonePushEnabled({}, { OMB_PHONE_PUSH: "1" })).toBe(true);
+ expect(phonePushEnabled({ features: { phonePush: false } }, { OMB_PHONE_PUSH: "yes" })).toBe(false);
+ });
+
+ it("switched off, keeps nothing, sends nothing and says so", async () => {
+ const { push, relay, setEnabled } = harness();
+ setEnabled(false);
+ const answer = await push.register(PHONE, { platform: "apns", token: APNS, environment: "production" });
+ expect(answer).toEqual({ push: "off", device: null, relay: "off" });
+ push.offer({ notification: notification(), seq: 7 }, everyone);
+ await push.flush();
+ expect(relay.calls).toEqual([]);
+ expect(() => readFileSync(join(dataDir, PHONE_PUSH_FILE))).toThrow();
+ });
+});
+
+describe("registering a phone", () => {
+ it("keeps the token on this computer only (0600), registers it at the relay and never echoes it", async () => {
+ const { push, relay } = harness();
+ const answer = await push.register(PHONE, { platform: "apns", token: APNS, environment: "sandbox", pairing: "pair-tag-0001" });
+ expect(answer).toEqual({ push: "on", relay: "registered", device: { platform: "apns", environment: "sandbox", pairing: "pair-tag-0001", kinds: [...PUSH_KINDS], updatedAt: clock } });
+ expect(JSON.stringify(answer)).not.toContain(APNS);
+ expect(relay.calls).toEqual([{ path: "/v1/installations/self/push/register", body: { v: 1, platform: "apns", token: APNS, environment: "sandbox" }, authorization: `Bearer ${CREDENTIAL}` }]);
+ const file = join(dataDir, PHONE_PUSH_FILE);
+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);
+ expect(new PhonePush({ dataDir, access: () => ACCESS, enabled: () => true, live: () => false, room: () => undefined, fetchImpl: relay.fetchImpl, log: () => {} }).answer(PHONE).device?.environment).toBe("sandbox");
+ });
+
+ it("registers an FCM token with no environment, and says when there is no account to push with", async () => {
+ const { push, relay } = harness({ access: () => null });
+ expect(await push.register(OTHER, { platform: "fcm", token: FCM, kinds: ["approval"] })).toMatchObject({ push: "no-account", relay: "off", device: { platform: "fcm", environment: "production", kinds: ["approval"] } });
+ expect(relay.calls).toEqual([]);
+ });
+
+ it("moves a token to the newest pairing of the same phone, and unregisters a replaced token no one else uses", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ await push.register(OTHER, { platform: "apns", token: APNS });
+ expect(push.answer(PHONE).device).toBeNull();
+ expect(push.answer(OTHER).device).not.toBeNull();
+ await push.register(OTHER, { platform: "apns", token: APNS_2 });
+ expect(relay.calls.map((call) => [call.path.split("/").at(-1), call.body.token])).toEqual([
+ ["register", APNS], ["register", APNS], ["unregister", APNS], ["register", APNS_2],
+ ]);
+ });
+
+ it("forgets a phone here and at the relay when it is unpaired or removes itself", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "fcm", token: FCM });
+ push.forget(PHONE);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(push.answer(PHONE).device).toBeNull();
+ expect(relay.calls.at(-1)).toMatchObject({ path: "/v1/installations/self/push/unregister", body: { v: 1, platform: "fcm", token: FCM } });
+ expect(await push.remove(PHONE)).toBe(false);
+ });
+
+ it("caps the phones one computer keeps", async () => {
+ const { push } = harness();
+ for (let index = 0; index < MAX_PUSH_DEVICES; index += 1) {
+ await push.register(`session:p${index}`, { platform: "apns", token: index.toString(16).padStart(2, "0").repeat(32) });
+ }
+ await expect(push.register("session:one-more", { platform: "apns", token: "ef".repeat(32) })).rejects.toMatchObject({ status: 409 });
+ });
+
+ it("takes only a well-formed registration", () => {
+ expect(registrationSchema.safeParse({ platform: "apns", token: APNS.toUpperCase() }).data).toEqual({ platform: "apns", token: APNS, environment: "production" });
+ for (const body of [
+ { platform: "apns", token: FCM },
+ { platform: "fcm", token: "short" },
+ { platform: "fcm", token: FCM, environment: "sandbox" },
+ { platform: "apns", token: APNS, kinds: ["routine-failed"] },
+ { platform: "apns", token: APNS, pairing: "no spaces allowed" },
+ { platform: "apns", token: APNS, pushToken: APNS },
+ { platform: "webpush", token: FCM },
+ ]) expect(registrationSchema.safeParse(body).success, JSON.stringify(body)).toBe(false);
+ });
+});
+
+describe("offering a notify frame", () => {
+ it("pushes only to a phone with no live stream that would have seen it, content-free, with the stream's identifier", async () => {
+ const { push, relay, liveKeys } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS, pairing: "pair-tag-0001" });
+ await push.register(OTHER, { platform: "fcm", token: FCM });
+ await push.register("session:hidden", { platform: "apns", token: APNS_2 });
+ liveKeys.add(OTHER);
+ push.offer({ notification: notification(), seq: 42 }, (key) => key !== "session:hidden");
+ await push.flush();
+ expect(relay.sends()).toEqual([{
+ path: "/v1/installations/self/push/send",
+ authorization: `Bearer ${CREDENTIAL}`,
+ body: { v: 1, token: APNS, pairing: "pair-tag-0001", collapseId: "openmaus.th_1.42", notification: { kind: "approval", title: "Scout needs approval", botId: "bot_1", botName: "Scout", threadId: "th_1" } },
+ }]);
+ const raw = JSON.stringify(relay.calls);
+ for (const secret of ["PRIVATE", "payroll", "sk-live", "API_KEY"]) expect(raw).not.toContain(secret);
+ });
+
+ it("wakes the phone for approvals, questions, sign-ins and finished replies only, as the phone chose", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS, kinds: ["question", "sign-in", "done"] });
+ for (const [seq, kind] of ["approval", "question", "sign-in", "done", "mention", "routine-failed", "spend", "secret"].entries()) {
+ push.offer({ notification: notification({ kind, threadId: `th_${kind}` }), seq }, everyone);
+ }
+ await push.flush();
+ expect(relay.sends().map((call) => (call.body.notification as { kind: string; title: string }).title)).toEqual([
+ "Scout has a question", "Scout needs you to sign in to a website", "Scout finished",
+ ]);
+ });
+
+ it("names the room, and leaves a frame alone that is not a notification", async () => {
+ const { push, relay } = harness({ room: () => ({ id: "grp_1", name: "Launch\nteam" }) });
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ push.offer({ notification: notification(), seq: 1 }, everyone);
+ push.offer({ notification: { kind: "approval" }, seq: 2 }, everyone);
+ push.offer({ notification: "approval", seq: 3 }, everyone);
+ push.offer({ notification: notification({ botId: "bad id" }), seq: 4 }, everyone);
+ await push.flush();
+ expect(relay.sends().map((call) => call.body.notification)).toEqual([
+ { kind: "approval", title: "Scout in Launch team needs approval", botId: "bot_1", botName: "Scout", threadId: "th_1", roomId: "grp_1", roomName: "Launch team" },
+ ]);
+ });
+
+ it("sends one push per kind and conversation in ten seconds, then the next", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ push.offer({ notification: notification(), seq: 1 }, everyone);
+ await push.flush();
+ push.offer({ notification: notification(), seq: 2 }, everyone);
+ push.offer({ notification: notification({ kind: "question" }), seq: 3 }, everyone);
+ await push.flush();
+ clock += PUSH_COALESCE_MS;
+ push.offer({ notification: notification(), seq: 4 }, everyone);
+ await push.flush();
+ expect(relay.sends().map((call) => call.body.collapseId)).toEqual(["openmaus.th_1.1", "openmaus.th_1.3", "openmaus.th_1.4"]);
+ });
+
+ it("stops a looping bot buzzing a pocket", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ for (let seq = 0; seq < PUSH_DEVICE_WINDOW_MAX + 5; seq += 1) push.offer({ notification: notification({ threadId: `th_${seq}` }), seq }, everyone);
+ await push.flush();
+ expect(relay.sends()).toHaveLength(PUSH_DEVICE_WINDOW_MAX);
+ });
+});
+
+describe("the outbox", () => {
+ it("retries a push the relay could not take, newest content winning, and gives up after the last wait", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ relay.answers.push("unreachable", { status: 502, error: "push_failed" }, { status: 503 }, "unreachable");
+ push.offer({ notification: notification(), seq: 1 }, everyone);
+ await push.flush();
+ expect(push.pending()).toBe(1);
+ push.offer({ notification: notification(), seq: 2 }, everyone);
+ await push.flush();
+ for (const wait of PUSH_RETRY_MS) await advance(push, wait);
+ expect(relay.sends().map((call) => call.body.collapseId)).toEqual(["openmaus.th_1.1", "openmaus.th_1.2", "openmaus.th_1.2", "openmaus.th_1.2"]);
+ expect(push.pending()).toBe(0);
+ });
+
+ it("drops a waiting push once the phone connects, or once it is too old to matter", async () => {
+ const { push, relay, liveKeys } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ await push.register(OTHER, { platform: "apns", token: APNS_2 });
+ relay.answers.push("unreachable", "unreachable");
+ push.offer({ notification: notification(), seq: 1 }, everyone);
+ await push.flush();
+ liveKeys.add(PHONE);
+ clock += PUSH_MAX_AGE_MS - PUSH_RETRY_MS[0] + 1;
+ await advance(push, PUSH_RETRY_MS[0]);
+ expect(relay.sends()).toHaveLength(2);
+ expect(push.pending()).toBe(0);
+ });
+
+ it("registers again and retries once when the relay has lost the token", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "fcm", token: FCM });
+ relay.answers.push({ status: 404, error: "push_device_unknown" });
+ push.offer({ notification: notification(), seq: 1 }, everyone);
+ await push.flush();
+ expect(relay.calls.slice(1).map((call) => call.path.split("/").at(-1))).toEqual(["send", "register", "send"]);
+ expect(relay.calls[2]!.body).toEqual({ v: 1, platform: "fcm", token: FCM });
+ });
+
+ it("drops a token the provider calls dead", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ relay.answers.push({ status: 410, error: "push_device_unregistered" });
+ push.offer({ notification: notification(), seq: 1 }, everyone);
+ await push.flush();
+ expect(push.answer(PHONE).device).toBeNull();
+ expect(JSON.parse(readFileSync(join(dataDir, PHONE_PUSH_FILE), "utf8")).devices).toEqual([]);
+ });
+
+ it("leaves the relay alone for an hour when it cannot push at all, and honours Retry-After", async () => {
+ const { push, relay } = harness();
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ relay.answers.push({ status: 503, error: "push_unavailable" });
+ push.offer({ notification: notification(), seq: 1 }, everyone);
+ await push.flush();
+ push.offer({ notification: notification({ threadId: "th_2" }), seq: 2 }, everyone);
+ await advance(push, RELAY_UNAVAILABLE_PAUSE_MS - 1);
+ expect(relay.sends()).toHaveLength(1);
+ await advance(push, 1);
+ expect(relay.sends()).toHaveLength(1);
+
+ relay.answers.push({ status: 429, error: "rate_limited", retryAfter: 120 });
+ push.offer({ notification: notification({ threadId: "th_3" }), seq: 3 }, everyone);
+ await push.flush();
+ push.offer({ notification: notification({ threadId: "th_4" }), seq: 4 }, everyone);
+ await advance(push, 119_000);
+ expect(relay.sends()).toHaveLength(2);
+ await advance(push, 1_000);
+ expect(relay.sends().at(-1)!.body.collapseId).toBe("openmaus.th_4.4");
+ });
+
+ it("never throws into the server", async () => {
+ const { push } = harness({ live: () => { throw new Error("boom"); } });
+ await push.register(PHONE, { platform: "apns", token: APNS });
+ expect(() => push.offer({ notification: notification(), seq: 1 }, everyone)).not.toThrow();
+ });
+});
+
+describe("the push's identifier and title", () => {
+ it("is the stream notification's own identifier when it fits APNs' 64 bytes", () => {
+ expect(phonePushCollapseId("th_1", 9)).toBe("openmaus.th_1.9");
+ expect(phonePushCollapseId("t".repeat(60), 9)).toBeUndefined();
+ expect(phonePushCollapseId("th_1", -1)).toBeUndefined();
+ });
+
+ it("is built from names alone, clipped, never from the notification's text", () => {
+ expect(phonePushNotification({ kind: "done", botId: "b", botName: ` ${"N".repeat(100)}\u0007`, threadId: "t" })?.botName).toHaveLength(80);
+ expect(phonePushNotification({ kind: "mention", botId: "b", botName: "Scout", threadId: "t" })).toBeNull();
+ });
+});
+
+describe("where the relay credential comes from", () => {
+ const tunnelFile = () => join(dataDir, "tunnel-account.json");
+
+ it("prefers the desktop app's message, including its 'none'", () => {
+ writeFileSync(tunnelFile(), JSON.stringify({ companionInstallationCredential: CREDENTIAL }));
+ const source = new PhonePushAccessSource({ env: { OMB_PUSH_CREDENTIAL: CREDENTIAL }, tunnelFile: tunnelFile(), defaultControlPlane: "https://accounts.openmausbot.com" });
+ expect(source.receive({ type: "something-else" })).toBe(false);
+ expect(source.receive({ type: PHONE_PUSH_DESKTOP_MESSAGE, access: { controlPlane: "https://accounts.openmausbot.com/", credential: CREDENTIAL } })).toBe(true);
+ expect(source.current()).toEqual({ controlPlane: "https://accounts.openmausbot.com", credential: CREDENTIAL });
+ source.receive({ type: PHONE_PUSH_DESKTOP_MESSAGE, access: null });
+ expect(source.current()).toBeNull();
+ source.receive({ type: PHONE_PUSH_DESKTOP_MESSAGE, access: { controlPlane: "http://evil.example", credential: CREDENTIAL } });
+ expect(source.current()).toBeNull();
+ });
+
+ it("then OMB_PUSH_CREDENTIAL, a fleet's credential, then `openmausbot login`'s file", () => {
+ const at = (env: NodeJS.ProcessEnv) => new PhonePushAccessSource({ env, tunnelFile: tunnelFile(), defaultControlPlane: "https://accounts.openmausbot.com" }).current();
+ expect(at({})).toBeNull();
+ writeFileSync(tunnelFile(), JSON.stringify({ companionInstallationCredential: CREDENTIAL }));
+ expect(at({})).toEqual({ controlPlane: "https://accounts.openmausbot.com", credential: CREDENTIAL });
+ expect(at({ OMB_PUSH_CREDENTIAL: "not-a-credential" })).toBeNull();
+ expect(at({ OMB_INSTALLATION_CREDENTIAL: CREDENTIAL, OMB_CONTROL_PLANE_URL: "http://127.0.0.1:8787" })).toEqual({ controlPlane: "http://127.0.0.1:8787", credential: CREDENTIAL });
+ });
+});
diff --git a/server/phone-push.ts b/server/phone-push.ts
new file mode 100644
index 0000000000..304021bed1
--- /dev/null
+++ b/server/phone-push.ts
@@ -0,0 +1,471 @@
+// 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).
+import { mkdirSync, readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { z } from "zod";
+
+import { COMPANION_INSTALLATION_CREDENTIAL_FIELD } from "../electron/companion-account-service.mjs";
+import { normalizeControlPlaneURL } from "../electron/control-plane-client.mjs";
+import {
+ APNS_TOKEN,
+ FCM_TOKEN,
+ PAIRING_TAG,
+ PHONE_PUSH_RELAY_PATHS,
+ PHONE_PUSH_WIRE_VERSION,
+ PUSH_ID,
+ PUSH_KINDS,
+ PUSH_NAME_MAX,
+ PUSH_RELAY_ERRORS,
+ PUSH_TITLE_MAX,
+ isPushKind,
+ phonePushCollapseId,
+ validPushToken,
+ type PhonePushAnswer,
+ type PhonePushNotification,
+ type PhonePushRegistration,
+ type PhonePushState,
+ type PublicPushDevice,
+ type PushKind,
+} from "../shared/phone-push.ts";
+import { writeFileAtomic } from "./atomic.ts";
+import { conversationLanguage, serverLine, type ServerLineKey } from "./server-lines.ts";
+
+export const PHONE_PUSH_FILE = "push-devices.json";
+export const PHONE_PUSH_ENV = "OMB_PHONE_PUSH";
+/** A push-only installation credential, for a server that holds no other (a Cloud home). */
+export const PHONE_PUSH_CREDENTIAL_ENV = "OMB_PUSH_CREDENTIAL";
+export const PHONE_PUSH_DESKTOP_MESSAGE = "openmausbot:phone-push-access";
+
+const INSTALLATION_CREDENTIAL = /^omb_install_[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/;
+/** As routes/phones.ts `phoneKey` mints them. */
+export const PUSH_DEVICE_KEY = /^(companion|session):[\w-]{1,128}$/;
+export const MAX_PUSH_DEVICES = 50;
+
+/** One push per phone, kind and conversation in this window; the newest waiting one replaces an older one. */
+export const PUSH_COALESCE_MS = 10_000;
+export const PUSH_DEVICE_WINDOW_MS = 10 * 60_000;
+export const PUSH_DEVICE_WINDOW_MAX = 30;
+/** A push still undelivered after this is dropped: the phone shows the news when it next connects. */
+export const PUSH_MAX_AGE_MS = 10 * 60_000;
+/** Waits before each retry of a push the relay could not take (network, 5xx). */
+export const PUSH_RETRY_MS = [5_000, 30_000, 120_000] as const;
+/** How long the relay is left alone after it said it cannot push at all (no keys, credential refused). */
+export const RELAY_UNAVAILABLE_PAUSE_MS = 60 * 60_000;
+const RELAY_TIMEOUT_MS = 10_000;
+
+const TITLES: Record<PushKind, ServerLineKey> = {
+ approval: "server.notify.approval",
+ question: "server.notify.question",
+ "sign-in": "server.notify.signInWebsite",
+ done: "server.notify.done",
+};
+
+/** On only when switched on: OMB_PHONE_PUSH=1 or 0 wins over `features.phonePush` in config.json. */
+export function phonePushEnabled(cfg: { features?: { phonePush?: boolean } }, env: NodeJS.ProcessEnv = process.env): boolean {
+ if (env[PHONE_PUSH_ENV] === "1") return true;
+ if (env[PHONE_PUSH_ENV] === "0") return false;
+ return cfg.features?.phonePush === true;
+}
+
+const kindsSchema = z.array(z.enum(PUSH_KINDS)).max(PUSH_KINDS.length);
+
+export const registrationSchema = z.discriminatedUnion("platform", [
+ z.object({ platform: z.literal("apns"), token: z.string().trim().toLowerCase().regex(APNS_TOKEN), environment: z.enum(["production", "sandbox"]).default("production"), pairing: z.string().regex(PAIRING_TAG).optional(), kinds: kindsSchema.optional() }).strict(),
+ z.object({ platform: z.literal("fcm"), token: z.string().trim().regex(FCM_TOKEN), environment: z.literal("production").optional(), pairing: z.string().regex(PAIRING_TAG).optional(), kinds: kindsSchema.optional() }).strict(),
+]);
+
+const storedDevice = z.object({
+ key: z.string().regex(PUSH_DEVICE_KEY),
+ platform: z.enum(["apns", "fcm"]),
+ token: z.string(),
+ environment: z.enum(["production", "sandbox"]),
+ pairing: z.string().regex(PAIRING_TAG).optional(),
+ kinds: kindsSchema,
+ createdAt: z.number(),
+ updatedAt: z.number(),
+}).refine((device) => validPushToken(device.platform, device.token));
+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 {
+ controlPlane: string;
+ credential: string;
+}
+
+export type PushOutcome = "sent" | "dropped" | "stale" | "live" | "gone" | "failed" | "retry" | "paused";
+
+export interface PhonePushOptions {
+ dataDir: string;
+ access: () => PhonePushAccess | null;
+ enabled: () => boolean;
+ /** Whether this phone holds a live event stream right now. */
+ live: (key: string) => boolean;
+ /** The room a notification came out of, for its name. */
+ room: (notification: PushableNotification) => { id: string; name: string } | undefined;
+ fetchImpl?: typeof fetch;
+ now?: () => number;
+ log?: (line: string) => void;
+ timers?: { set(run: () => void, ms: number): unknown; clear(handle: unknown): void };
+}
+
+/** The fields a push reads from a `notify` frame's notification: never its `body`. */
+export interface PushableNotification {
+ kind: string;
+ botId: string;
+ botName: string;
+ threadId: string;
+ groupId?: string;
+}
+
+interface Job {
+ key: string;
+ slot: string;
+ push: PhonePushNotification;
+ collapseId?: string;
+ queuedAt: number;
+ notBefore: number;
+ attempts: number;
+}
+
+interface RelayAnswer {
+ status: number;
+ code?: string;
+ retryAfterMs?: number;
+}
+
+function clip(value: string, max: number): string {
+ const points = [...value.replace(/[\p{Cc}\u2028\u2029]/gu, " ").trim()];
+ return points.length > max ? `${points.slice(0, max - 1).join("")}…` : points.join("");
+}
+
+function pushableOf(value: unknown): PushableNotification | null {
+ if (!value || typeof value !== "object") return null;
+ const { kind, botId, botName, threadId, groupId } = value as Record<string, unknown>;
+ if (typeof kind !== "string" || typeof botId !== "string" || typeof botName !== "string" || typeof threadId !== "string") return null;
+ return { kind, botId, botName, threadId, ...(typeof groupId === "string" ? { groupId } : {}) };
+}
+
+/** The push for one notification, or null when it is not a kind a closed app is woken for or an id is not one the
+ * relay takes. Reads the kind, the ids and the names; the title is the server's own line for that kind, from names. */
+export function phonePushNotification(notification: PushableNotification, room?: { id: string; name: string }): PhonePushNotification | null {
+ if (!isPushKind(notification.kind) || !PUSH_ID.test(notification.botId) || !PUSH_ID.test(notification.threadId)) return null;
+ const botName = clip(notification.botName, PUSH_NAME_MAX) || "MausBot";
+ const roomName = room && PUSH_ID.test(room.id) ? clip(room.name, PUSH_NAME_MAX) : "";
+ const language = conversationLanguage(notification.threadId);
+ const who = roomName ? serverLine(language, "server.notify.inRoom", { bot: botName, room: roomName }) : botName;
+ return {
+ kind: notification.kind,
+ title: clip(serverLine(language, TITLES[notification.kind], { who }), PUSH_TITLE_MAX),
+ botId: notification.botId,
+ botName,
+ threadId: notification.threadId,
+ ...(room && roomName ? { roomId: room.id, roomName } : {}),
+ };
+}
+
+export class PhonePush {
+ private devices: StoredDevice[] = [];
+ private readonly file: string;
+ private readonly now: () => number;
+ private readonly fetchImpl: typeof fetch;
+ private readonly log: (line: string) => void;
+ private readonly timers: NonNullable<PhonePushOptions["timers"]>;
+ private readonly sent = new Map<string, number[]>();
+ private readonly lastBySlot = new Map<string, number>();
+ private readonly outbox = new Map<string, Job>();
+ private pausedUntil = 0;
+ private timer: unknown = null;
+ private draining: Promise<void> | null = null;
+ private readonly options: PhonePushOptions;
+
+ constructor(options: PhonePushOptions) {
+ this.options = options;
+ this.file = join(options.dataDir, PHONE_PUSH_FILE);
+ this.now = options.now ?? Date.now;
+ this.fetchImpl = options.fetchImpl ?? fetch;
+ this.log = options.log ?? ((line) => console.log(line));
+ this.timers = options.timers ?? {
+ set: (run, ms) => setTimeout(run, ms).unref(),
+ clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
+ };
+ let raw: unknown;
+ try {
+ raw = JSON.parse(readFileSync(this.file, "utf8"));
+ } catch {
+ return;
+ }
+ const parsed = storedFile.safeParse(raw);
+ if (parsed.success) this.devices = parsed.data.devices;
+ else this.log("[phone-push] the saved phone registrations could not be read; phones register again when they connect");
+ }
+
+ private persist(): void {
+ mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 });
+ writeFileAtomic(this.file, `${JSON.stringify({ version: 1, devices: this.devices }, null, 2)}\n`, { mode: 0o600 });
+ }
+
+ status(): PhonePushState {
+ if (!this.options.enabled()) return "off";
+ return this.options.access() ? "on" : "no-account";
+ }
+
+ private publicDevice(key: string): PublicPushDevice | null {
+ const device = this.devices.find((candidate) => candidate.key === key);
+ if (!device) return null;
+ return { platform: device.platform, environment: device.environment, ...(device.pairing ? { pairing: device.pairing } : {}), kinds: [...device.kinds], updatedAt: device.updatedAt };
+ }
+
+ answer(key: string): PhonePushAnswer {
+ return { push: this.status(), device: this.publicDevice(key) };
+ }
+
+ /** The phone behind `key` registers or updates its token. Switched off, nothing is kept. A token belongs to one app on
+ * one phone, so the same token under another key (a phone that paired again) moves to this key. */
+ async register(key: string, input: PhonePushRegistration): Promise<PhonePushAnswer & { relay: "registered" | "pending" | "off" }> {
+ if (!PUSH_DEVICE_KEY.test(key)) throw new Error("not a phone");
+ if (!this.options.enabled()) return { ...this.answer(key), relay: "off" };
+ const now = this.now();
+ const previous = this.devices.find((device) => device.key === key);
+ const others = this.devices.filter((device) => device.key !== key && device.token !== input.token);
+ if (!previous && others.length >= MAX_PUSH_DEVICES) {
+ throw Object.assign(new Error(`At most ${MAX_PUSH_DEVICES} phones can get alerts from this computer.`), { status: 409 });
+ }
+ const next: StoredDevice = {
+ key,
+ platform: input.platform,
+ token: input.token,
+ environment: input.platform === "apns" ? input.environment ?? "production" : "production",
+ ...(input.pairing ? { pairing: input.pairing } : {}),
+ kinds: [...new Set(input.kinds ?? PUSH_KINDS)],
+ createdAt: previous?.createdAt ?? now,
+ updatedAt: now,
+ };
+ this.devices = [...others, next];
+ this.persist();
+ if (previous && previous.token !== next.token) this.dropFromRelay(previous);
+ if (this.status() !== "on") return { ...this.answer(key), relay: "off" };
+ const answer = await this.relay(PHONE_PUSH_RELAY_PATHS.register, this.registerBody(next));
+ return { ...this.answer(key), relay: answer && answer.status < 300 ? "registered" : "pending" };
+ }
+
+ /** The phone asked to stop, or was unpaired: drop it here and at the relay. */
+ async remove(key: string): Promise<boolean> {
+ const device = this.devices.find((candidate) => candidate.key === key);
+ if (!device) return false;
+ this.devices = this.devices.filter((candidate) => candidate.key !== key);
+ this.persist();
+ for (const [slot, job] of this.outbox) if (job.key === key) this.outbox.delete(slot);
+ await this.dropFromRelay(device);
+ return true;
+ }
+
+ /** A paired phone was revoked or its session expired. */
+ forget(key: string): void {
+ void this.remove(key).catch((error) => this.log(`[phone-push] could not forget a phone: ${error instanceof Error ? error.message : String(error)}`));
+ }
+
+ private async dropFromRelay(device: StoredDevice): Promise<void> {
+ if (this.devices.some((other) => other.token === device.token)) return;
+ await this.relay(PHONE_PUSH_RELAY_PATHS.unregister, { v: PHONE_PUSH_WIRE_VERSION, platform: device.platform, token: device.token });
+ }
+
+ private registerBody(device: StoredDevice) {
+ return device.platform === "apns"
+ ? { v: PHONE_PUSH_WIRE_VERSION, platform: "apns", token: device.token, environment: device.environment }
+ : { v: PHONE_PUSH_WIRE_VERSION, platform: "fcm", token: device.token };
+ }
+
+ /**
+ * A `notify` frame left this server as frame `seq`. Each registered phone that holds no live stream, wants this kind
+ * and would have been shown the frame (`reaches`, the event stream's own audience rule) gets a push queued. Never
+ * throws, and does nothing at all while switched off.
+ */
+ offer(frame: { notification: unknown; seq: number }, reaches: (key: string) => boolean): void {
+ try {
+ if (!this.devices.length || !this.options.enabled()) return;
+ const notification = pushableOf(frame.notification);
+ if (!notification || !isPushKind(notification.kind)) return;
+ const push = phonePushNotification(notification, this.options.room(notification));
+ if (!push) return;
+ const collapseId = phonePushCollapseId(push.threadId, frame.seq);
+ const now = this.now();
+ for (const device of this.devices) {
+ if (!device.kinds.includes(notification.kind) || this.options.live(device.key) || !reaches(device.key)) continue;
+ const slot = `${device.key}|${push.kind}|${push.threadId}`;
+ const waiting = this.outbox.get(slot);
+ if (!waiting && now - (this.lastBySlot.get(slot) ?? -Infinity) < PUSH_COALESCE_MS) continue;
+ this.outbox.set(slot, { key: device.key, slot, push, ...(collapseId ? { collapseId } : {}), queuedAt: now, notBefore: waiting?.notBefore ?? now, attempts: waiting?.attempts ?? 0 });
+ }
+ this.kick();
+ } catch (error) {
+ this.log(`[phone-push] could not queue a push: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
+ /** Resolves once every push that is due has been tried. */
+ async flush(): Promise<void> {
+ while (this.draining) await this.draining;
+ }
+
+ /** Pushes waiting for a retry or the relay's pause. */
+ pending(): number {
+ return this.outbox.size;
+ }
+
+ private kick(): void {
+ if (this.draining) return;
+ this.draining = this.drain().finally(() => {
+ this.draining = null;
+ this.schedule();
+ });
+ }
+
+ private schedule(): void {
+ if (this.timer !== null) this.timers.clear(this.timer);
+ this.timer = null;
+ if (!this.outbox.size) return;
+ const due = Math.max(this.pausedUntil, Math.min(...[...this.outbox.values()].map((job) => job.notBefore)));
+ if (due <= this.now()) {
+ this.kick();
+ return;
+ }
+ this.timer = this.timers.set(() => {
+ this.timer = null;
+ this.kick();
+ }, Math.max(due - this.now(), 0));
+ }
+
+ private async drain(): Promise<void> {
+ for (;;) {
+ const now = this.now();
+ if (now < this.pausedUntil) return;
+ const job = [...this.outbox.values()].find((candidate) => candidate.notBefore <= now);
+ if (!job) return;
+ this.outbox.delete(job.slot);
+ const outcome = await this.attempt(job, now).catch((error: unknown) => {
+ this.log(`[phone-push] could not push: ${error instanceof Error ? error.message : String(error)}`);
+ return "failed" as const;
+ });
+ if (outcome === "retry") {
+ const wait = PUSH_RETRY_MS[job.attempts];
+ if (wait !== undefined && !this.outbox.has(job.slot)) this.outbox.set(job.slot, { ...job, attempts: job.attempts + 1, notBefore: this.now() + wait });
+ }
+ if (outcome === "paused") this.outbox.clear();
+ }
+ }
+
+ private async attempt(job: Job, now: number): Promise<PushOutcome> {
+ const device = this.devices.find((candidate) => candidate.key === job.key);
+ if (!device || !this.options.enabled()) return "gone";
+ if (now - job.queuedAt > PUSH_MAX_AGE_MS) return "stale";
+ // The phone connected while this waited: its stream delivers the frame itself.
+ if (this.options.live(job.key)) return "live";
+ const recent = (this.sent.get(job.key) ?? []).filter((at) => now - at < PUSH_DEVICE_WINDOW_MS);
+ if (recent.length >= PUSH_DEVICE_WINDOW_MAX) return "dropped";
+ const body = { v: PHONE_PUSH_WIRE_VERSION, token: device.token, ...(device.pairing ? { pairing: device.pairing } : {}), ...(job.collapseId ? { collapseId: job.collapseId } : {}), notification: job.push };
+ let answer = await this.relay(PHONE_PUSH_RELAY_PATHS.send, body);
+ if (answer?.status === 404 && answer.code === PUSH_RELAY_ERRORS.unknownDevice) {
+ const registered = await this.relay(PHONE_PUSH_RELAY_PATHS.register, this.registerBody(device));
+ if (registered && registered.status < 300) answer = await this.relay(PHONE_PUSH_RELAY_PATHS.send, body);
+ }
+ if (!answer) return "retry";
+ if (answer.status < 300) {
+ this.sent.set(job.key, [...recent, now]);
+ this.lastBySlot.set(job.slot, now);
+ if (this.lastBySlot.size > 2_000) this.lastBySlot.clear();
+ return "sent";
+ }
+ if (answer.status === 410 || answer.code === PUSH_RELAY_ERRORS.unregistered) {
+ this.devices = this.devices.filter((candidate) => candidate.token !== device.token);
+ this.persist();
+ return "gone";
+ }
+ if (answer.code === PUSH_RELAY_ERRORS.unavailable || answer.status === 401 || answer.status === 404) return this.pause(RELAY_UNAVAILABLE_PAUSE_MS);
+ if (answer.status === 429) return this.pause(answer.retryAfterMs ?? 60_000);
+ if (answer.status >= 500) return "retry";
+ return "failed";
+ }
+
+ private pause(ms: number): PushOutcome {
+ this.pausedUntil = Math.max(this.pausedUntil, this.now() + Math.min(Math.max(ms, 1_000), 6 * 60 * 60_000));
+ return "paused";
+ }
+
+ /** 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. */
+ private async relay(path: string, body: unknown): Promise<RelayAnswer | null> {
+ const access = this.options.access();
+ if (!access) 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 payload = await response.json().catch(() => null) as { error?: unknown } | null;
+ const retryAfter = Number(response.headers.get("retry-after"));
+ return {
+ status: response.status,
+ ...(typeof payload?.error === "string" ? { code: payload.error } : {}),
+ ...(Number.isFinite(retryAfter) && retryAfter > 0 ? { retryAfterMs: retryAfter * 1_000 } : {}),
+ };
+ } catch (error) {
+ this.log(`[phone-push] the relay could not be reached: ${error instanceof Error ? error.name : "error"}`);
+ return null;
+ }
+ }
+}
+
+/** A validated access pair, or null. */
+export function phonePushAccess(controlPlane: unknown, credential: unknown): PhonePushAccess | null {
+ const origin = typeof controlPlane === "string" ? normalizeControlPlaneURL(controlPlane) : "";
+ if (!origin || typeof credential !== "string" || !INSTALLATION_CREDENTIAL.test(credential)) return null;
+ return { controlPlane: origin, credential };
+}
+
+/** 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. */
+export class PhonePushAccessSource {
+ private desktop: PhonePushAccess | null | undefined;
+ private readonly env: NodeJS.ProcessEnv;
+ private readonly options: { tunnelFile: string; defaultControlPlane: string };
+
+ constructor(options: { env?: NodeJS.ProcessEnv; tunnelFile: string; defaultControlPlane: string }) {
+ this.env = options.env ?? process.env;
+ this.options = options;
+ }
+
+ /** The desktop app's message: true when it was one. */
+ receive(message: unknown): boolean {
+ if (!message || typeof message !== "object" || (message as { type?: unknown }).type !== PHONE_PUSH_DESKTOP_MESSAGE) return false;
+ const access = (message as { access?: unknown }).access;
+ this.desktop = access && typeof access === "object"
+ ? phonePushAccess((access as { controlPlane?: unknown }).controlPlane, (access as { credential?: unknown }).credential)
+ : null;
+ return true;
+ }
+
+ private controlPlane(): string {
+ if (Object.hasOwn(this.env, "OMB_CONTROL_PLANE_URL")) return normalizeControlPlaneURL(this.env.OMB_CONTROL_PLANE_URL ?? "");
+ return this.options.defaultControlPlane;
+ }
+
+ current(): PhonePushAccess | null {
+ if (this.desktop !== undefined) return this.desktop;
+ const fromEnv = this.env[PHONE_PUSH_CREDENTIAL_ENV]?.trim() || this.env.OMB_INSTALLATION_CREDENTIAL?.trim();
+ if (fromEnv) return phonePushAccess(this.controlPlane(), fromEnv);
+ let document: unknown;
+ try {
+ document = JSON.parse(readFileSync(this.options.tunnelFile, "utf8"));
+ } catch {
+ return null;
+ }
+ const credential = document && typeof document === "object" ? (document as Record<string, unknown>)[COMPANION_INSTALLATION_CREDENTIAL_FIELD] : undefined;
+ return phonePushAccess(this.controlPlane(), credential);
+ }
+}
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 17f5f95182..89ff128b7d 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -328,6 +328,8 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg
{ methods: ["GET", "PUT", "DELETE"], path: /^\/api\/phones\/self$/ },
{ methods: ["GET"], path: /^\/api\/phones\/self\/jobs$/ },
{ methods: ["POST"], path: /^\/api\/phones\/self\/jobs\/[\w-]+\/(?:lease|result)$/ },
+ // This phone's own closed-app alert registration, keyed by its session (routes/phone-push.ts).
+ { methods: ["GET", "PUT", "DELETE"], path: /^\/api\/push\/device$/ },
{ methods: ["GET"], path: /^\/api\/health$/ },
{ methods: ["GET"], path: /^\/api\/edition$/ },
{ methods: ["GET"], path: /^\/api\/brand$/ },
diff --git a/server/routes/live.ts b/server/routes/live.ts
index 0b20cdb32f..baea08fcd6 100644
--- a/server/routes/live.ts
+++ b/server/routes/live.ts
@@ -10,6 +10,8 @@ import { PASS, type RouteContext, type RouteHandler } from "./table.ts";
export interface LiveRouteDeps {
calls: Pick<LiveCallController, "start" | "end" | "current" | "deviceRevoked">;
+ /** The companion unpaired this phone: its closed-app alerts end too. */
+ deviceRevoked?: (device: string) => void;
resolveTarget(botId: string, threadId: string | undefined): { botId: string; botName: string; threadId: string } | null;
settings(): LiveSettings;
saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; voice?: string; geminiVoice?: string; readTypedReplies?: boolean; idleMinutes?: number }): Promise<LiveSettings>;
@@ -116,6 +118,7 @@ export function createLiveRoutes(deps: LiveRouteDeps): RouteHandler {
if (req.headers["x-openmausbot-companion"] !== "1") return json(res, 403, { error: "Only the phone companion can report an unpaired phone." });
const device = companionDevice(req);
if (!device) return json(res, 400, { error: "The unpaired phone was not named." });
+ deps.deviceRevoked?.(device);
return json(res, 200, { call: deps.calls.deviceRevoked(device) });
}
diff --git a/server/routes/phone-push.test.ts b/server/routes/phone-push.test.ts
new file mode 100644
index 0000000000..45c4e42f39
--- /dev/null
+++ b/server/routes/phone-push.test.ts
@@ -0,0 +1,98 @@
+import { mkdtempSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { json, readBody } from "../harness/http.ts";
+import { PhonePush } from "../phone-push.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import { createPhonePushRoutes } from "./phone-push.ts";
+import { dispatchRoutes } from "./table.ts";
+
+const servers: Server[] = [];
+const dirs: string[] = [];
+afterEach(async () => {
+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
+ await Promise.all(dirs.splice(0).map(removeTempDir));
+});
+
+const APNS = "ab".repeat(32);
+const session = (id: string, cookieOnly = false): RequestAuth => ({
+ kind: "session", via: "bearer", scopes: ["client"],
+ session: { id, cookieOnly } as unknown as Extract<RequestAuth, { kind: "session" }>["session"],
+});
+const companion = (device: string): RequestAuth => ({ kind: "loopback", scopes: ["admin", "client"], companionDevice: device });
+const desktop: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };
+
+async function setup(options: { enabled?: boolean; live?: boolean } = {}) {
+ const dir = mkdtempSync(join(tmpdir(), "phone-push-routes-"));
+ dirs.push(dir);
+ const push = new PhonePush({
+ dataDir: dir,
+ access: () => null,
+ enabled: () => options.enabled ?? true,
+ live: () => false,
+ room: () => undefined,
+ log: () => {},
+ });
+ let auth: RequestAuth = session("s1");
+ const routes = [createPhonePushRoutes({ push, live: () => options.live ?? true })];
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ const handled = await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody });
+ if (!handled) json(res, 404, { from: "elsewhere" });
+ });
+ servers.push(server);
+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ const call = async (method: string, path: string, body?: unknown, contentType = "application/json") => {
+ const response = await fetch(`${base}${path}`, {
+ method,
+ headers: body === undefined ? {} : { "content-type": contentType },
+ ...(body === undefined ? {} : { body: typeof body === "string" ? body : JSON.stringify(body) }),
+ });
+ return { status: response.status, body: await response.json() as Record<string, unknown> };
+ };
+ return { push, call, as: (next: RequestAuth) => { auth = next; } };
+}
+
+describe("/api/push/device", () => {
+ it("registers, reads back and removes the calling phone's own registration, never echoing the token", async () => {
+ const { call, push } = await setup();
+ const put = await call("PUT", "/api/push/device", { platform: "apns", token: APNS, pairing: "pair-tag-0001" });
+ expect(put).toEqual({ status: 200, body: { push: "no-account", relay: "off", device: expect.objectContaining({ platform: "apns", pairing: "pair-tag-0001" }) } });
+ expect(JSON.stringify(put.body)).not.toContain(APNS);
+ expect((await call("GET", "/api/push/device")).body).toMatchObject({ push: "no-account", device: { platform: "apns" } });
+ expect(push.answer("session:s1").device).not.toBeNull();
+ expect(await call("DELETE", "/api/push/device")).toEqual({ status: 200, body: { push: "no-account", device: null } });
+ });
+
+ it("keys a companion phone by the device the sidecar vouched for, and refuses anything that is not a phone", async () => {
+ const { call, as, push } = await setup();
+ as(companion("device-7"));
+ expect((await call("PUT", "/api/push/device", { platform: "apns", token: APNS })).status).toBe(200);
+ expect(push.answer("companion:device-7").device).not.toBeNull();
+ for (const who of [desktop, session("browser", true)]) {
+ as(who);
+ expect(await call("PUT", "/api/push/device", { platform: "apns", token: APNS })).toEqual({ status: 403, body: { error: expect.stringContaining("Only a paired phone") } });
+ }
+ });
+
+ it("answers off and keeps nothing while phone push is switched off", async () => {
+ const { call, push } = await setup({ enabled: false });
+ expect(await call("PUT", "/api/push/device", { platform: "apns", token: APNS })).toEqual({ status: 200, body: { push: "off", relay: "off", device: null } });
+ expect(push.answer("session:s1").device).toBeNull();
+ });
+
+ it("refuses an expired session, a body that is not JSON or not a registration, and other methods", async () => {
+ expect((await (await setup({ live: false })).call("GET", "/api/push/device")).status).toBe(401);
+ const { call } = await setup();
+ expect((await call("PUT", "/api/push/device", "token=abc", "text/plain")).status).toBe(415);
+ expect((await call("PUT", "/api/push/device", { platform: "apns", token: "nope" })).status).toBe(400);
+ expect((await call("POST", "/api/push/device", { platform: "apns", token: APNS })).status).toBe(405);
+ expect((await call("GET", "/api/push/devices")).body).toEqual({ from: "elsewhere" });
+ });
+});
diff --git a/server/routes/phone-push.ts b/server/routes/phone-push.ts
new file mode 100644
index 0000000000..45d52f5a41
--- /dev/null
+++ b/server/routes/phone-push.ts
@@ -0,0 +1,40 @@
+// /api/push/device: a paired phone registers, reads back or removes its own closed-app alert registration. The phone is
+// known by what authenticated the request (a paired session, or the device the companion vouched for), never the body.
+import { PHONE_PUSH_ROUTE } from "../../shared/phone-push.ts";
+import { registrationSchema, type PhonePush } from "../phone-push.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { phoneKey } from "./phones.ts";
+import { PASS, type RouteContext, type RouteHandler } from "./table.ts";
+
+const SELF_ONLY = "Only a paired phone can register for alerts, and only for itself.";
+
+export interface PhonePushRouteDeps {
+ push: PhonePush;
+ live: (auth: RequestAuth) => boolean;
+}
+
+export function createPhonePushRoutes(deps: PhonePushRouteDeps): RouteHandler {
+ return async ({ req, res, path, method, auth, json, readBody }: RouteContext): Promise<typeof PASS | void> => {
+ if (path !== PHONE_PUSH_ROUTE) return PASS;
+ res.setHeader("Cache-Control", "no-store");
+ if (!deps.live(auth)) return json(res, 401, { error: "Session expired" });
+ const key = phoneKey(auth);
+ if (!key) return json(res, 403, { error: SELF_ONLY });
+ if (method === "GET") return json(res, 200, deps.push.answer(key));
+ if (method === "DELETE") {
+ await deps.push.remove(key);
+ return json(res, 200, deps.push.answer(key));
+ }
+ if (method !== "PUT") return json(res, 405, { error: "Method not allowed" });
+ if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) return json(res, 415, { error: "JSON required" });
+ const parsed = registrationSchema.safeParse(await readBody(req, 16_384));
+ if (!deps.live(auth)) return json(res, 401, { error: "Session expired" });
+ if (!parsed.success) return json(res, 400, { error: "Invalid push registration" });
+ try {
+ return json(res, 200, await deps.push.register(key, parsed.data));
+ } catch (error) {
+ const status = (error as { status?: unknown }).status === 409 ? 409 : 500;
+ return json(res, status, { error: error instanceof Error ? error.message : "Could not save the registration" });
+ }
+ };
+}
diff --git a/server/sessions.ts b/server/sessions.ts
index 6a5dd74f82..24d5ce4846 100644
--- a/server/sessions.ts
+++ b/server/sessions.ts
@@ -698,6 +698,12 @@ export class SessionRegistry {
return this.sessions.some((s) => s.id === sessionId && !this.personal(s.scopes));
}
+ /** A live session by id: what a paired phone with no stream open may still be shown (server/phone-push.ts). */
+ record(sessionId: string): SessionRecord | null {
+ this.prune();
+ return this.sessions.find((s) => s.id === sessionId && s.expiresAt > this.now() && !this.personal(s.scopes)) ?? null;
+ }
+
list(): PublicSession[] {
this.prune();
return this.sessions.map(publicSession);
diff --git a/server/testing/control-plane-stub.ts b/server/testing/control-plane-stub.ts
index 55795e9c00..97eb24444a 100644
--- a/server/testing/control-plane-stub.ts
+++ b/server/testing/control-plane-stub.ts
@@ -21,6 +21,10 @@ export interface ControlPlaneStub {
connectorToken: string;
/** "METHOD /path", in order. */
calls: string[];
+ /** The bodies of the push relay's calls, in order (`/v1/installations/self/push/*`). */
+ pushes: Array<{ path: string; body: Record<string, unknown> }>;
+ /** The next push-relay answers, used in order; then 200/202/204 as the real relay answers. */
+ pushAnswers: Array<{ status: number; error?: string }>;
installations: Map<string, StubInstallation>;
/** An installation the control plane already knows (as a fleet creates one): returns its credential. */
seedInstallation(name?: string): string;
@@ -49,6 +53,9 @@ export async function startControlPlaneStub(options: { otp?: string; endpointUrl
const accountTokens = new Set<string>();
const installations = new Map<string, StubInstallation>();
const calls: string[] = [];
+ const pushes: ControlPlaneStub["pushes"] = [];
+ const pushAnswers: ControlPlaneStub["pushAnswers"] = [];
+ const pushDevices = new Map<string, Set<string>>();
const publicView = (inst: StubInstallation) => ({
id: inst.id,
clientInstanceId: inst.clientInstanceId,
@@ -142,6 +149,21 @@ export async function startControlPlaneStub(options: { otp?: string; endpointUrl
}
if (method === "DELETE") return send(204);
}
+ const push = /^\/v1\/installations\/self\/push\/(register|unregister|send)$/.exec(path);
+ if (push && method === "POST") {
+ const inst = byCredential();
+ if (!inst) return send(401, { error: "unauthorized" });
+ const body = await readJson(req);
+ pushes.push({ path, body });
+ const answer = pushAnswers.shift();
+ if (answer) return send(answer.status, answer.error ? { error: answer.error } : undefined);
+ const tokens = pushDevices.get(inst.id) ?? new Set<string>();
+ pushDevices.set(inst.id, tokens);
+ const token = String(body.token ?? "");
+ if (push[1] === "register") { tokens.add(token); return send(200, { registered: true }); }
+ if (push[1] === "unregister") { tokens.delete(token); return send(204); }
+ return tokens.has(token) ? send(202, { sent: true }) : send(404, { error: "push_device_unknown" });
+ }
const one = /^\/v1\/installations\/([^/]+)$/.exec(path);
if (one && method === "DELETE") {
if (!account) return send(401, { error: "unauthorized" });
@@ -159,6 +181,8 @@ export async function startControlPlaneStub(options: { otp?: string; endpointUrl
endpointUrl,
connectorToken,
calls,
+ pushes,
+ pushAnswers,
installations,
seedInstallation: (name = "fleet box") => {
const inst: StubInstallation = { id: randomUUID(), clientInstanceId: randomUUID(), name, platform: "linux", appVersion: null, credential: newCredential() };
diff --git a/shared/phone-push.ts b/shared/phone-push.ts
new file mode 100644
index 0000000000..e2b929b489
--- /dev/null
+++ b/shared/phone-push.ts
@@ -0,0 +1 @@
+export * from "../packages/phone-protocol/src/phone-push.ts";