Skip to content

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

fix(phones): end access when a session is revoked

Sebastian B035101e08c0c
diff --git a/server/host/phones-revocation.test.ts b/server/host/phones-revocation.test.ts
new file mode 100644
index 0000000000..aaa5f76b13
--- /dev/null
+++ b/server/host/phones-revocation.test.ts
@@ -0,0 +1,94 @@
+import { mkdtempSync } from "node:fs";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, it } from "vitest";
+
+import { flushDecisionLog } from "../decision-log.ts";
+import { json, readBody } from "../harness/http.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { dispatchRoutes } from "../routes/table.ts";
+import { SessionRegistry } from "../sessions.ts";
+import type { BotRecord } from "../store.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import { createPhones } from "./phones.ts";
+
+const cleanups: Array<() => Promise<void>> = [];
+afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup(); });
+
+async function fixture() {
+ const dir = mkdtempSync(join(tmpdir(), "phone-session-revocation-"));
+ const sessions = new SessionRegistry({ file: join(dir, "sessions.json") });
+ const paired = sessions.exchange({ code: sessions.openPairing({ scopes: ["admin", "client"] }).credential, label: "Fixture phone", source: "127.0.0.1" });
+ if (!paired.ok) throw new Error(paired.error);
+ const session = sessions.authenticate(paired.token)!;
+ const bot = { id: "helper", name: "Helper", phoneApps: { calendar: "write" } } as BotRecord;
+ const phones = createPhones({
+ dataDir: dir, shared: false, cloudHome: true, cloudOwnerKey: "owner", loopbackTrust: "owner", sharedMembership: () => false,
+ store: { bot: () => bot, groupByThread: () => undefined, messagesFor: () => [], appendMessage: (_thread, message) => ({ ...message, id: "message-1", at: message.at ?? Date.now() }) },
+ sessions, routines: () => null, ownerOrAdmin: () => true, cloudOwnerSession: () => true,
+ cloudLendingRefusal: () => null, cloudLendingTurn: () => { throw new Error("unused on Cloud home"); },
+ originIsUser: () => true, request: () => undefined, nudge: () => {}, mint: () => "fixture-token", harnessUrl: "http://127.0.0.1:1", active: () => true,
+ });
+ let pollStarted!: () => void;
+ const polling = new Promise<void>(resolve => { pollStarted = resolve; });
+ const server = createServer(async (req, res) => {
+ const session = sessions.authenticate(req.headers.authorization?.replace(/^Bearer /, ""));
+ if (!session) return json(res, 401, { error: "Session expired" });
+ const auth: RequestAuth = { kind: "session", session, via: "bearer", scopes: session.scopes };
+ const url = new URL(req.url ?? "/", "http://localhost");
+ try {
+ const dispatched = dispatchRoutes([phones.routes], { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody });
+ if (url.pathname === "/api/phones/self/jobs") pollStarted();
+ await dispatched;
+ } catch (error) { json(res, (error as { status?: number }).status ?? 500, { error: (error as Error).message }); }
+ });
+ cleanups.push(async () => {
+ phones.close(); server.closeAllConnections();
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ await flushDecisionLog(dir); await removeTempDir(dir);
+ });
+ await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ const call = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(base + path, {
+ method, headers: { authorization: `Bearer ${paired.token}`, "content-type": "application/json" },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(3000),
+ });
+ return { status: response.status, body: await response.json() as any };
+ };
+ expect((await call("PUT", "/api/phones/self", {
+ installId: "install-0001", name: "Fixture phone", platform: "ios", appVersion: "1.0.0", timeZone: "UTC", capabilities: { calendar: "full" },
+ })).status).toBe(200);
+ const request = () => phones.handle({ method: "tools/call", params: {
+ name: "PHONE_CREATE_EVENT", arguments: { title: "Private appointment", start: "2026-10-28T10:00:00Z", end: "2026-10-28T11:00:00Z" },
+ } }, { botId: bot.id, threadId: "thread-1", generation: "gen-1" }, () => {});
+ return { phones, sessions, paired, session, call, polling, request };
+}
+
+it("revoking a session removes its phone and ends its pending poll before a later job", async () => {
+ const h = await fixture();
+ const poll = h.call("GET", "/api/phones/self/jobs");
+ await h.polling;
+ expect(h.sessions.revoke(h.paired.session.id)).toBe(true);
+ const later = h.request();
+ expect(await poll).toMatchObject({ status: 401 });
+ expect(await later).toMatchObject({ isError: true });
+ expect((await h.call("GET", "/api/phones/self")).status).toBe(401);
+ expect(h.phones.fromPhone({ kind: "session", session: h.session, via: "bearer", scopes: ["admin", "client"] })).toBe(false);
+});
+
+it("revoking a session fails both a leased job and a queued job", async () => {
+ const h = await fixture();
+ const first = h.request();
+ const { body: { job } } = await h.call("GET", "/api/phones/self/jobs");
+ expect((await h.call("POST", `/api/phones/self/jobs/${job.id}/lease`)).body).toEqual({ active: true });
+ const second = h.request();
+ h.sessions.revoke(h.paired.session.id);
+ const ended = await Promise.race([
+ Promise.all([first, second]),
+ new Promise<null>(resolve => { const timer = setTimeout(() => resolve(null), 1000); timer.unref(); }),
+ ]);
+ expect(ended).toEqual([expect.objectContaining({ isError: true }), expect.objectContaining({ isError: true })]);
+});
diff --git a/server/host/phones.test.ts b/server/host/phones.test.ts
index 274ef1fff4..e4930a3175 100644
--- a/server/host/phones.test.ts
+++ b/server/host/phones.test.ts
@@ -38,7 +38,7 @@ function world(overrides: Partial<PhonesDeps> = {}) {
const phones = createPhones({
dataDir: dir, shared: false, cloudHome: false, cloudOwnerKey: null, loopbackTrust: "owner", sharedMembership: () => false,
store: { messagesFor: () => lines, bot: () => chief, groupByThread: () => undefined, appendMessage: () => {} } as unknown as PhonesDeps["store"],
- sessions: { list: () => [] }, routines: () => null, ownerOrAdmin: (auth) => auth.scopes.includes("admin"), cloudOwnerSession: () => false,
+ sessions: { list: () => [], isLive: () => true, onSessionRevoked: () => () => {} }, routines: () => null, ownerOrAdmin: (auth) => auth.scopes.includes("admin"), cloudOwnerSession: () => false,
cloudLendingRefusal: () => null,
cloudLendingTurn: () => ({ thread: lines, request: { ...requests.get(THREAD), generations: new Set([TURN.generation]) }, generation: TURN.generation, starters: [], reportsFromOthers: false,
ownerPerson: () => true, cardAnswerer: () => undefined, routineRun: () => null }) as unknown as CloudLendingTurn,
diff --git a/server/host/phones.ts b/server/host/phones.ts
index 6eba3d675d..b57a8648f4 100644
--- a/server/host/phones.ts
+++ b/server/host/phones.ts
@@ -14,8 +14,8 @@ import { PhoneRegistry } from "../phones/registry.ts";
import { createPhoneSends } from "../phones/sends.ts";
import type { LoopbackTrust, RequestAuth } from "../request-auth.ts";
import type { Routine } from "../routines.ts";
-import { createPhoneRoutes, phoneKey } from "../routes/phones.ts";
-import type { PublicSession } from "../sessions.ts";
+import { createPhoneRoutes, PHONE_ACCESS_CHANGED, phoneKey } from "../routes/phones.ts";
+import type { SessionRegistry } from "../sessions.ts";
import type { BotRecord, Store } from "../store.ts";
import type { PromptPart } from "../system-prompt.ts";
@@ -34,7 +34,7 @@ export interface PhonesDeps {
loopbackTrust: LoopbackTrust;
sharedMembership(): boolean;
store: Pick<Store, "appendMessage" | "bot" | "groupByThread" | "messagesFor">;
- sessions: { list(): PublicSession[] };
+ sessions: Pick<SessionRegistry, "list" | "isLive" | "onSessionRevoked">;
routines(): { listRoutines(): Routine[] } | null;
ownerOrAdmin(auth: RequestAuth): boolean;
cloudOwnerSession(auth: RequestAuth): boolean;
@@ -60,6 +60,11 @@ export function createPhones(deps: PhonesDeps) {
const registry = new PhoneRegistry(join(deps.dataDir, "phones.json"));
const sends = createPhoneSends();
const jobs = new PhoneJobs((phone, id) => deps.nudge({ kind: "device.job", phone, id }));
+ const unsubscribe = deps.sessions.onSessionRevoked((id) => {
+ const key = `session:${id}`;
+ registry.remove(key);
+ jobs.drop(key, PHONE_ACCESS_CHANGED);
+ });
const ownerRoutinesFile = join(deps.dataDir, "owner-routines.json");
const routineRecordsExisted = existsSync(ownerRoutinesFile);
/** Off a Cloud home: the routines the desktop owner wrote, so their runs and reports keep the owner's phones. */
@@ -136,7 +141,7 @@ export function createPhones(deps: PhonesDeps) {
},
handle: host.handle,
toolListing: host.toolListing,
- routes: createPhoneRoutes({ registry, jobs, owner: ownerOf, isAdmin: deps.ownerOrAdmin }),
+ routes: createPhoneRoutes({ registry, jobs, owner: ownerOf, isAdmin: deps.ownerOrAdmin, live: (auth) => auth.kind !== "session" || deps.sessions.isLive(auth.session.id) }),
/** How many phones run the phone app here. */
paired: (): number => registry.list(null, () => false).length,
/** Routines written before records were kept are the owner's on a single-person desktop: record them once. */
@@ -155,6 +160,6 @@ export function createPhones(deps: PhonesDeps) {
if (!deps.ownerOrAdmin(auth)) routineAuthors.forget(routine.id);
else if (ownersAgain) routineAuthors.record(routine.id, routine);
},
- close: () => jobs.close(),
+ close: () => { unsubscribe(); jobs.close(); },
};
}
diff --git a/server/routes/phones.test.ts b/server/routes/phones.test.ts
index 398fd4152f..f3fd85ba9a 100644
--- a/server/routes/phones.test.ts
+++ b/server/routes/phones.test.ts
@@ -31,19 +31,20 @@ const registration = {
};
const fromPhone = (device = "d1") => ({ "x-openmausbot-companion": "1", "x-openmausbot-companion-device": device });
-async function setup(options: { auth?: RequestAuth; owner?: () => string | null } = {}) {
+async function setup(options: { auth?: RequestAuth; owner?: () => string | null; live?: () => boolean; afterBody?: () => void } = {}) {
const dir = mkdtempSync(join(tmpdir(), "phones-routes-"));
dirs.push(dir);
const registry = new PhoneRegistry(join(dir, "phones.json"));
const jobs = new PhoneJobs();
const auth = options.auth ?? ADMIN;
const routes = [createPhoneRoutes({
- registry, jobs, owner: options.owner ?? (() => "owner"), isAdmin: (a) => a.scopes.includes("admin"),
+ registry, jobs, owner: options.owner ?? (() => "owner"), isAdmin: (a) => a.scopes.includes("admin"), live: options.live ?? (() => true),
})];
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
try {
- const handled = await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody });
+ const handled = await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json,
+ readBody: async (request, max) => { const body = await readBody(request, max); options.afterBody?.(); return body; } });
if (!handled) json(res, 404, { from: "inline routes" });
} catch (error) {
// index.ts turns an error carrying a status into JSON.
@@ -170,6 +171,26 @@ describe("phone routes", () => {
expect(await poll).toEqual({ status: 200, body: { job: null } });
});
+ it("rechecks the session before returning a pending poll's job", async () => {
+ let live = true;
+ const { call, jobs } = await setup({ auth: clientSession("s1"), live: () => live });
+ try {
+ await call("PUT", "/api/phones/self", registration);
+ const poll = call("GET", "/api/phones/self/jobs");
+ await vi.waitFor(() => expect(jobs.polling("session:s1")).toBe(true));
+ live = false;
+ void jobs.request("session:s1", "PHONE_CREATE_EVENT", { title: "Private appointment" }, { active: () => true, timeoutMs: 10_000, offlineText: "offline", online: () => true });
+ expect(await poll).toMatchObject({ status: 401, body: { error: expect.any(String) } });
+ } finally { jobs.close(); }
+ });
+
+ it("does not register a phone if its session ends while reading the body", async () => {
+ let live = true;
+ const { call, registry } = await setup({ auth: clientSession("s1"), live: () => live, afterBody: () => { live = false; } });
+ expect((await call("PUT", "/api/phones/self", registration)).status).toBe(401);
+ expect(registry.get("session:s1")).toBeUndefined();
+ });
+
it("a team Cloud offers no phones", async () => {
// A verified phone key, so the refusal comes from there being no owner, not from a missing key.
const { call } = await setup({ auth: companion("d1"), owner: () => null });
diff --git a/server/routes/phones.ts b/server/routes/phones.ts
index e241220479..b5bbb3a871 100644
--- a/server/routes/phones.ts
+++ b/server/routes/phones.ts
@@ -27,6 +27,7 @@ export interface PhoneRouteDeps {
/** The owner this phone belongs to, or null when phones are not offered here (team Cloud, hosted workspace, guest session). */
owner: (auth: RequestAuth) => string | null;
isAdmin: (auth: RequestAuth) => boolean;
+ live: (auth: RequestAuth) => boolean;
}
export function createPhoneRoutes(deps: PhoneRouteDeps): RouteHandler {
@@ -41,6 +42,7 @@ export function createPhoneRoutes(deps: PhoneRouteDeps): RouteHandler {
}
if (path === "/api/phones/self" || path.startsWith("/api/phones/self/")) {
+ if (!deps.live(auth)) return json(res, 401, { error: "Session expired" });
const key = phoneKey(auth);
const owner = deps.owner(auth);
if (!key || !owner) return json(res, 403, { error: SELF_ONLY });
@@ -49,6 +51,7 @@ export function createPhoneRoutes(deps: PhoneRouteDeps): RouteHandler {
if (method === "PUT") {
if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) return json(res, 415, { error: "JSON required" });
const parsed = phoneRegistration.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 phone registration" });
registry.register(key, owner, parsed.data);
const [phone] = registry.list(owner, (k) => jobs.busy(k)).filter((p) => p.key === key);
@@ -63,7 +66,9 @@ export function createPhoneRoutes(deps: PhoneRouteDeps): RouteHandler {
}
if (path === "/api/phones/self/jobs" && method === "GET") {
if (!registry.get(key)) return json(res, 404, { error: "Register this phone first" });
- return json(res, 200, { job: await jobs.poll(key, responseGone(res)) });
+ const job = await jobs.poll(key, responseGone(res));
+ if (!deps.live(auth)) return json(res, 401, { error: "Session expired" });
+ return json(res, 200, { job });
}
const act = /^\/api\/phones\/self\/jobs\/([\w-]+)\/(lease|result)$/.exec(path);
if (act && method === "POST") {