Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Re-pairing a phone replaces its own device instead of adding one (#6028)
Milind Soni5553edd9f121
diff --git a/companion/README.md b/companion/README.mdindex c54f4891e9..b83973b619 100644--- a/companion/README.md+++ b/companion/README.md@@ -29,7 +29,7 @@ upstream hardened its loopback gate.| | ||---|---|-| **Pairing** | A high-entropy QR credential plus a six-digit manual fallback, valid two minutes and single-use. Redeeming either returns a device token stored only as a SHA-256 digest. |+| **Pairing** | A high-entropy QR credential plus a six-digit manual fallback, valid two minutes and single-use. Redeeming either returns a device token stored only as a SHA-256 digest. A phone re-pairing may send the token it already holds (`replacesToken`): that device is replaced, not added to, and the new one starts with a fresh pairing's grants. At 20 devices a new pairing is refused with `pairing_device_limit`. || **Authorisation** | Every request needs that token. Computer access — the cloud desktop, and seeing or taking control of the Local VM — is a separate per-device capability, off by default. A rebinding page cannot obtain either. || **The allowlist** | Default deny, per method and path (`src/routes.ts`). Bot PATCH accepts only reading state, pins, colour, mascot and avatar image or framing fields; the harness rejects other fields before applying any change. A new bot may carry only its name, profile, look and model; asking for anything else (approval level, computer, folder, Chief of Staff, peers, tools, department, preset) is refused and no bot is made. General room PATCH stays closed, and approval grants use narrow verbs. A new harness route stays closed to devices until it is explicitly listed. || **Scrubbing** | `resumeCursors` — the harness's own provider session ids — never reach a device, whether or not the harness still sends them. |diff --git a/companion/src/devices.ts b/companion/src/devices.tsindex 3dd9bce479..a7bbbfb722 100644--- a/companion/src/devices.ts+++ b/companion/src/devices.ts@@ -121,6 +121,7 @@ export class DeviceRegistry {/** Paired in this run and not yet used; a restart forgets these, and such a device then stays until removed. */private unconfirmed = new Map<string, ReturnType<typeof setTimeout>>();private droppedListeners = new Set<(id: string) => void>();+ private replacedListeners = new Set<(id: string) => void>();private window: PairingWindow | null = null;/** The window a renewal replaced: still valid until its own expiry, so a phone mid-scan never misses. */private previousWindow: PairingWindow | null = null;@@ -277,12 +278,29 @@ export class DeviceRegistry {this.replayExpiryTimer = null;}+ /** A device replaced by a re-pairing, after the save that removed it. */+ onReplaced(listener: (id: string) => void): void {+ this.replacedListeners.add(listener);+ }++ private deviceWithToken(token: unknown): DeviceRecord | undefined {+ if (typeof token !== "string" || !token) return undefined;+ const hash = sha256(token);+ return this.devices.find((d) => sameDigest(d.tokenHash, hash));+ }+/** A client that supplies a request id may repeat the same redemption until- * the window's original expiry. There is no general token-read endpoint. */+ * the window's original expiry. There is no general token-read endpoint.+ *+ * `replacesToken`: the token this phone already holds here. Its device is removed in the same save, so re-pairing+ * never grows the list. Security: it acts only after a valid pairing credential, and only for a holder of that+ * token, who could already use everything that device can; the new device starts with a fresh pairing's grants.+ * An unknown token is ignored and the reply is the same either way. */redeem(credential: string,name: unknown,pairRequestId?: unknown,+ replacesToken?: unknown,): { device: PublicDevice; token: string } | PairingRefusal {const presented = String(credential ?? "");const requestId =@@ -314,7 +332,10 @@ export class DeviceRegistry {}// After the code check: a full fleet must not answer wrong guesses, which// would leak state and cost no attempts.- if (this.devices.length >= MAX_DEVICES) return { error: "too many paired devices — remove one first", code: "pairing_device_limit" };+ const replaced = this.deviceWithToken(replacesToken);+ if (this.devices.length - (replaced ? 1 : 0) >= MAX_DEVICES) {+ return { error: "too many paired devices — remove an old phone on your computer first", code: "pairing_device_limit" };+ }// Consume every open window without clearing a replay; `closePairing` clears both.this.window = null;this.previousWindow = null;@@ -328,18 +349,25 @@ export class DeviceRegistry {lastSeenAt: Date.now(),cloudDesktopAccess: false,browserControlAccess: false,- routes: "any",+ // The owner's restriction carries over; a grant never does.+ routes: replaced?.routes ?? "any",};- this.devices.push(device);+ const previous = this.devices;+ this.devices = [...previous.filter((d) => d !== replaced), device];// Unlike lastSeenAt, a failed write rolls the registration back: a device// only in memory is paired until the next restart, then silently is not.try {this.persist();} catch (e) {- this.devices.pop();+ this.devices = previous;return { error: `could not save the pairing: ${(e as Error).message}`, code: "pairing_failed" };}+ if (replaced) {+ this.lastSeenWrites.delete(replaced.id);+ this.confirm(replaced.id);+ }this.changed();+ if (replaced) for (const listener of this.replacedListeners) listener(replaced.id);const unconfirmed = setTimeout(() => {this.unconfirmed.delete(device.id);try {diff --git a/companion/src/index.ts b/companion/src/index.tsindex 02f7d13875..d863c3fbf3 100755--- a/companion/src/index.ts+++ b/companion/src/index.ts@@ -154,7 +154,7 @@ const proxy = createProxyHandler({mutationToken: parentPort ? () => mutationToken : undefined,// Also stamps lastSeenAt.authenticate: (token) => devices.authenticate(token),- redeem: (code, deviceName, pairRequestId) => devices.redeem(code, deviceName, pairRequestId),+ redeem: (code, deviceName, pairRequestId, replacesToken) => devices.redeem(code, deviceName, pairRequestId, replacesToken),serverName: machineName,version: process.env.OMB_APP_VERSION,hosts: () => hostCandidates(),@@ -234,6 +234,25 @@ devices.onDropped((deviceId) => {console.log("companion: dropped a paired device its phone never used");});+function disconnectDevice(deviceId: string): void {+ connectedDevices.disconnect(deviceId);+ proxy.disconnectDevice(deviceId);+}++// The harness hears a phone as this computer, so only the sidecar can tell+// it the phone lost access and end the Live call that phone holds.+function deviceRevoked(deviceId: string): void {+ e2e.closeDevice(deviceId);+ if (parentPort && !mutationToken) return;+ void notifyDeviceRevoked({ harnessPort: HARNESS_PORT, deviceId, mutationToken: mutationToken ?? undefined });+}++// After the pairing reply is written: until then the session carrying it may still belong to the replaced device.+devices.onReplaced((deviceId) => setImmediate(() => {+ disconnectDevice(deviceId);+ deviceRevoked(deviceId);+}));+const control = createControlServer({devices,controlToken: () => controlToken,@@ -245,17 +264,8 @@ const control = createControlServer({},discovery: () => ({ advertising: mdns.advertising, name: service().name }),connectedDeviceIds: connectedDevices.ids,- disconnectDevice: (deviceId) => {- connectedDevices.disconnect(deviceId);- proxy.disconnectDevice(deviceId);- },- // The harness hears a phone as this computer, so only the sidecar can tell- // it the phone lost access and end the Live call that phone holds.- revoked: (deviceId) => {- e2e.closeDevice(deviceId);- if (parentPort && !mutationToken) return;- void notifyDeviceRevoked({ harnessPort: HARNESS_PORT, deviceId, mutationToken: mutationToken ?? undefined });- },+ disconnectDevice,+ revoked: deviceRevoked,setDirectRoutes: (body) => {const next = body && typeof body === "object" ? (body as Record<string, unknown>) : null;if (!next || typeof next.wifi !== "boolean" || typeof next.tailscale !== "boolean") return false;diff --git a/companion/src/proxy.ts b/companion/src/proxy.tsindex 0ac13168dd..12b717ffc5 100644--- a/companion/src/proxy.ts+++ b/companion/src/proxy.ts@@ -38,6 +38,7 @@ export interface ProxyOptions {code: string,deviceName: unknown,pairRequestId?: unknown,+ replacesToken?: unknown,) => { token: string; device: unknown } | PairingRefusal;serverName: () => string;/** The desktop app's version: told only to a paired device. */@@ -461,6 +462,7 @@ export function createProxyHandler(options: ProxyOptions) {String(credential ?? ""),body.deviceName,body.pairRequestId,+ body.replacesToken,);if ("error" in result) return sendJson(res, 401, { error: result.error, code: result.code } satisfies PairingRefusal);const pairedId = (result.device as { id?: unknown } | null)?.id;diff --git a/companion/test/devices.test.ts b/companion/test/devices.test.tsindex 932d5f25b8..29416835bf 100644--- a/companion/test/devices.test.ts+++ b/companion/test/devices.test.ts@@ -7,6 +7,7 @@ import {bearerToken,cleanDeviceName,DeviceRegistry,+ MAX_DEVICES,MAX_PAIRING_ATTEMPTS,PAIRING_TTL_MS,UNCONFIRMED_DEVICE_MS,@@ -470,3 +471,120 @@ describe("browser control capability", () => {expect(registry.setBrowserControlAccess("nobody", true)).toBe(false);});});++describe("re-pairing with the token a phone already holds", () => {+ beforeEach(() => {+ rmSync(DATA_DIR, { recursive: true, force: true });+ });++ const repair = (registry: DeviceRegistry, replacesToken?: unknown, name = "iPhone") => {+ const { token: credential } = registry.openPairing();+ const result = registry.redeem(credential, name, undefined, replacesToken);+ if ("error" in result) throw new Error(`pairing failed: ${result.error}`);+ return result;+ };+ const savedIds = () => (JSON.parse(readFileSync(join(DATA_DIR, "devices.json"), "utf8")).devices as Array<{ id: string }>).map((d) => d.id);++ it("replaces that device in the same save: the count stays and the old token stops working", () => {+ const registry = new DeviceRegistry();+ const replaced: string[] = [];+ registry.onReplaced((id) => replaced.push(id));+ const other = pair(registry, "iPad");+ const first = pair(registry);+ const second = repair(registry, first.token);++ expect(registry.count()).toBe(2);+ expect(registry.authenticate(first.token)).toBeNull();+ expect(registry.authenticate(second.token)?.id).toBe(second.device.id);+ expect(registry.authenticate(other.token)?.id).toBe(other.device.id);+ expect(second.device.id).not.toBe(first.device.id);+ expect(savedIds()).toEqual([other.device.id, second.device.id]);+ expect(replaced).toEqual([first.device.id]);+ });++ it("starts the new device with a fresh pairing's grants, keeping only a route restriction", () => {+ const registry = new DeviceRegistry();+ const first = pair(registry);+ registry.setCloudDesktopAccess(first.device.id, true);+ registry.setBrowserControlAccess(first.device.id, true);+ registry.setRoutes(first.device.id, "local");+ registry.markE2E(first.device.id);++ const { device } = repair(registry, first.token);+ expect(device).toMatchObject({ cloudDesktopAccess: false, browserControlAccess: false, routes: "local" });+ expect(device).not.toHaveProperty("e2eAt");+ });++ it("ignores an unknown or malformed token, with the same reply as a pairing without one", () => {+ const registry = new DeviceRegistry();+ const kept = pair(registry);+ const replaced: string[] = [];+ registry.onReplaced((id) => replaced.push(id));+ const plain = repair(registry);+ for (const unknown of [`omb_${"A".repeat(43)}`, "", 42, { token: kept.token }, null]) {+ const result = repair(registry, unknown);+ expect(Object.keys(result).sort()).toEqual(Object.keys(plain).sort());+ expect(Object.keys(result.device).sort()).toEqual(Object.keys(plain.device).sort());+ }+ expect(registry.count()).toBe(7);+ expect(registry.authenticate(kept.token)?.id).toBe(kept.device.id);+ expect(replaced).toEqual([]);+ });++ it("does nothing without a valid pairing credential: the device stays and the attempt is spent", () => {+ const registry = new DeviceRegistry();+ const first = pair(registry);+ registry.openPairing();+ expect(registry.redeem("omb_pair_wrong", "Thief", undefined, first.token)).toMatchObject({ code: "pairing_code_wrong" });+ expect(registry.pairing()?.attemptsLeft).toBe(MAX_PAIRING_ATTEMPTS - 1);+ expect(registry.authenticate(first.token)?.id).toBe(first.device.id);+ registry.closePairing();+ expect(registry.redeem("123456", "Thief", undefined, first.token)).toMatchObject({ code: "pairing_not_open" });+ expect(registry.count()).toBe(1);+ });++ it("never reaches the device cap however often the same phone re-pairs", () => {+ const registry = new DeviceRegistry();+ for (let i = 0; i < MAX_DEVICES - 1; i++) pair(registry, `Phone ${i}`);+ let current = pair(registry, "Re-pairing phone");+ for (let i = 0; i < 25; i++) current = repair(registry, current.token, "Re-pairing phone");+ expect(registry.count()).toBe(MAX_DEVICES);+ expect(registry.authenticate(current.token)?.id).toBe(current.device.id);+ });++ it("still refuses a new phone at the cap with a code the phone can show", () => {+ const registry = new DeviceRegistry();+ for (let i = 0; i < MAX_DEVICES; i++) pair(registry, `Phone ${i}`);+ const { token: credential } = registry.openPairing();+ expect(registry.redeem(credential, "One too many")).toEqual({+ error: "too many paired devices — remove an old phone on your computer first",+ code: "pairing_device_limit",+ });+ expect(registry.redeem(credential, "One too many", undefined, `omb_${"B".repeat(43)}`)).toMatchObject({ code: "pairing_device_limit" });+ expect(registry.count()).toBe(MAX_DEVICES);+ });++ it("replays a lost reply without replacing again", () => {+ const registry = new DeviceRegistry();+ const first = pair(registry);+ const { token: credential } = registry.openPairing();+ const requestId = "4c825d5b-cf40-4db7-aac5-2455f805a8ec";+ const once = registry.redeem(credential, "iPhone", requestId, first.token);+ const again = registry.redeem(credential, "iPhone", requestId, first.token);+ expect(again).toEqual(once);+ expect(registry.count()).toBe(1);+ });++ it("keeps the old device when the save fails", () => {+ const registry = new DeviceRegistry();+ const first = pair(registry);+ const writable = registry as unknown as { persist: () => void };+ writable.persist = () => {+ throw new Error("ENOSPC: no space left on device");+ };+ const { token: credential } = registry.openPairing();+ expect(registry.redeem(credential, "iPhone", undefined, first.token)).toMatchObject({ code: "pairing_failed" });+ expect(registry.count()).toBe(1);+ expect(registry.authenticate(first.token)?.id).toBe(first.device.id);+ });+});diff --git a/companion/test/e2e/sidecar.test.ts b/companion/test/e2e/sidecar.test.tsindex 5da1ea0914..692505a623 100644--- a/companion/test/e2e/sidecar.test.ts+++ b/companion/test/e2e/sidecar.test.ts@@ -83,6 +83,30 @@ describe("the sidecar's end-to-end connection, through the real relay", () => {session.shutdown();});+ it("re-pairs a phone in place: the old device and its sessions go, the count stays", async () => {+ const before = await pairViaRelay(rig);+ before.session.shutdown();+ const count = (await state()).devices.length;+ const oldSession = await rig.direct(await state(), before.token);+ const pairing = await rig.control("POST", "/pairing");+ const res = await fetch(`http://127.0.0.1:${rig.companionPort}/api/pair`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ credential: pairing.token, deviceName: "Test Phone", replacesToken: before.token }),+ });+ expect(res.status).toBe(201);+ const after = (await res.json()) as { token: string; device: { id: string } };+ expect(await oldSession.closed).toBe(4001);+ const devices = (await state()).devices.map((device) => device.id);+ expect(devices).toHaveLength(count);+ expect(devices).toContain(after.device.id);+ expect(devices).not.toContain(before.id);+ expect((await fetch(`http://127.0.0.1:${rig.companionPort}/api/bots`, { headers: { authorization: `Bearer ${before.token}` } })).status).toBe(401);+ const fresh = await rig.direct(await state(), after.token);+ expect(json(await http(fresh, "GET", "/api/health", { token: after.token }))).toEqual({ app: "openmausbot" });+ fresh.shutdown();+ });+it(`waits ${LONG ? 105 : 35} s for headers without a deadline of its own`, async () => {rig.harness.provideWaitMs = LONG ? 104_000 : 35_000;const session = await rig.viaRelay(await state(), deviceToken);diff --git a/packages/phone-protocol/src/pairing-code.ts b/packages/phone-protocol/src/pairing-code.tsindex eb1ca78a79..5c8129b9fe 100644--- a/packages/phone-protocol/src/pairing-code.ts+++ b/packages/phone-protocol/src/pairing-code.ts@@ -61,7 +61,7 @@ export type PairingErrorCode =| "pairing_script_key"/** Through the encrypted relay only the QR code's credential pairs, never a typed code. */| "pairing_qr_only"- /** A computer already has as many paired devices as it allows. */+ /** A computer already has as many paired devices as it allows: the person removes an old phone on that computer. */| "pairing_device_limit"/** A personal Cloud pairs only its owner's devices. */| "cloud_personal"diff --git a/packages/phone-protocol/src/responses.ts b/packages/phone-protocol/src/responses.tsindex 8890bd2d5d..3c2696ffed 100644--- a/packages/phone-protocol/src/responses.ts+++ b/packages/phone-protocol/src/responses.ts@@ -29,6 +29,20 @@ export interface PairedDevice {e2eAt?: number;}+/** POST /api/pair's body. A computer, a server and a Cloud all accept it; fields one does not know are ignored. */+export interface PairRequest {+ /** The QR's `omb_pair_` credential or the typed code. */+ credential: string;+ deviceName: string;+ /** Lets the same request, retried through another address within the pairing window, get the same reply. */+ pairRequestId?: string;+ /** The device token this phone already holds for this same computer. A computer removes that device as it pairs+ * the new one, so re-pairing never adds to its list; the new device starts with a fresh pairing's grants but keeps a+ * Wi-Fi-and-Tailscale-only restriction. A token it does not know changes nothing, and the reply never says which.+ * A server or Cloud ignores it. */+ replacesToken?: string;+}+/** POST /api/pair: 201 from a computer's companion, 200 from a server or Cloud. */export interface PairResponse {token: string;diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex 0a6b47f65c..0f08975de7 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -41,7 +41,7 @@ export const SHARED_CHAT_TITLE = "Shared chat";export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveElevenLabsSession, LiveElevenLabsTransport, LiveEndReason, LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveFishTransport, LiveGeminiSession, LiveGeminiTransport, LiveKeySource, LiveProvider, LiveSettings } from "./live-call-wire.ts";export type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts";-export type { AuthPairResponse, AuthSessionResponse, BotCreateResponse, BotsResponse, BotUpdateResponse, CompanionE2EDescriptor, CompanionEndpointsSnapshot, InstancesResponse, LoopbackSessionResponse, PairedDevice, PairedSession, PairResponse, RoomCreateResponse, RoomTaskCreateResponse, RoomTaskUpdateResponse, RoomUpdateResponse, SearchHit, SearchResponse, SignedInSessionResponse, TaskResponse, WireComputerControl, WireInstance, WireMessagePage, WireModelOption } from "./responses.ts";+export type { AuthPairResponse, AuthSessionResponse, BotCreateResponse, BotsResponse, BotUpdateResponse, CompanionE2EDescriptor, CompanionEndpointsSnapshot, InstancesResponse, LoopbackSessionResponse, PairedDevice, PairedSession, PairRequest, PairResponse, RoomCreateResponse, RoomTaskCreateResponse, RoomTaskUpdateResponse, RoomUpdateResponse, SearchHit, SearchResponse, SignedInSessionResponse, TaskResponse, WireComputerControl, WireInstance, WireMessagePage, WireModelOption } from "./responses.ts";/** Reasoning-effort levels, ascending: a union of what any engine accepts;* each driver declares the subset its CLI will take. */