Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(companion): finish a sign-in that never stored its installation credential (#7589)
CI fixture53122f56f72f
diff --git a/electron/companion-account-service.mjs b/electron/companion-account-service.mjsindex cd1a474511..8b02ca54bb 100644--- a/electron/companion-account-service.mjs+++ b/electron/companion-account-service.mjs@@ -770,7 +770,12 @@ export function createCompanionAccountService({// Waiting: the control plane ended the address or had no room. Asked again on every watchdog tick while an// old phone still needs it, as a desktop that kept its address does.const waiting = document[COMPANION_TUNNEL_WAITING_FIELD] === true;- if ((!savedAddress(document) && !waiting) || autoRetryTimer !== null) return null;+ if ((!savedAddress(document) && !waiting) || autoRetryTimer !== null) {+ // A sign-in that stored the account but never its installation credential stays that way on its own, and the+ // relay token keeps answering signed_out without it: finish the provisioning, like a stored address does.+ if (autoRetryTimer === null && !storedAccount(document).installationCredential) return retryWork();+ return null;+ }return (await currentNeed()) === true ? retryWork() : null;}const need = await currentNeed();diff --git a/electron/companion-account-service.test.mjs b/electron/companion-account-service.test.mjsindex b606320cf6..7ce2cf73c3 100644--- a/electron/companion-account-service.test.mjs+++ b/electron/companion-account-service.test.mjs@@ -1574,6 +1574,68 @@ describe("Companion account on demand", () => {}});+ it("finishes a sign-in that stored no installation credential, so the relay token can be asked for again", async () => {+ const unfinished = signedCredentials();+ for (const field of [...ADDRESS_FIELDS, COMPANION_INSTALLATION_ID_FIELD, COMPANION_INSTALLATION_CREDENTIAL_FIELD, COMPANION_INSTALLATION_EXPIRY_FIELD]) {+ delete unfinished[field];+ }+ const installationChanged = vi.fn();+ const f = onDemandFixture({ initial: unfinished, installationChanged });++ // The relay token's fetch reads this field (electron/companion-e2e-desktop.mjs, server/phone-relay.ts):+ // until it exists, every fetch answers signed_out.+ expect(f.store.read()[COMPANION_INSTALLATION_CREDENTIAL_FIELD]).toBeUndefined();+ await expect(f.service.restore()).resolves.toMatchObject({ status: "ready", email: "[email protected]" });+ expect(f.client.ensureInstallation).toHaveBeenCalledOnce();+ expect(f.client.ensureEndpoint).not.toHaveBeenCalled();+ expect(f.store.read()[COMPANION_INSTALLATION_ID_FIELD]).toBe(INSTALLATION_ID);+ expect(f.store.read()[COMPANION_INSTALLATION_CREDENTIAL_FIELD]).toBe(INSTALLATION_CREDENTIAL);+ // A new credential is what the relay token service waits for: it fetches again without a restart.+ expect(installationChanged).toHaveBeenCalledOnce();++ // Once stored, nothing re-provisions: the watchdog's ticks leave the healed state alone.+ for (let tick = 0; tick < 3; tick += 1) {+ f.clock.now += HOUR_MS;+ await f.watchdog();+ }+ expect(f.client.ensureInstallation).toHaveBeenCalledOnce();+ f.service.dispose();+ });++ it("keeps finishing an unfinished sign-in on the watchdog until the installation credential is stored", async () => {+ const unfinished = signedCredentials();+ for (const field of [...ADDRESS_FIELDS, COMPANION_INSTALLATION_ID_FIELD, COMPANION_INSTALLATION_CREDENTIAL_FIELD]) {+ delete unfinished[field];+ }+ let attempts = 0;+ const client = readyClient({+ ensureInstallation: vi.fn(async () => {+ attempts += 1;+ if (attempts === 1) throw new ControlPlaneError("network_unavailable", 503);+ return {+ installation: { id: INSTALLATION_ID, clientInstanceId: UUID, name: "Test Mac", platform: "darwin" },+ credential: INSTALLATION_CREDENTIAL,+ credentialExpiresAt: LAUNCH_AT + 10_000,+ };+ }),+ });+ const f = onDemandFixture({ initial: unfinished, client });++ await f.service.restore();+ expect(attempts).toBe(1);+ // The transient failure scheduled a retry; the watchdog does not stomp on a pending one.+ await f.watchdog();+ expect(attempts).toBe(1);+ // The scheduled retry gives up (no saved address to keep serving); the next tick finishes the provisioning.+ await f.retryTimer();+ expect(attempts).toBe(1);+ await f.watchdog();+ expect(attempts).toBe(2);+ expect(f.store.read()[COMPANION_INSTALLATION_CREDENTIAL_FIELD]).toBe(INSTALLATION_CREDENTIAL);+ expect(await f.service.state()).toMatchObject({ status: "ready", email: "[email protected]" });+ f.service.dispose();+ });+it("gives an address nothing needs back one to four hours later, connector first", async () => {for (const [random, delay] of [[0, HOUR_MS], [0.5, 2.5 * HOUR_MS], [1, 4 * HOUR_MS]]) {const f = onDemandFixture({ random: () => random });diff --git a/server/phone-relay.test.ts b/server/phone-relay.test.tsindex 8da2d05092..a2c22e1818 100644--- a/server/phone-relay.test.ts+++ b/server/phone-relay.test.ts@@ -2,10 +2,10 @@// are the phones, and every relayed request reaches the handler as a remote one.import { generateKeyPairSync, randomBytes } from "node:crypto";import { mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";-import type { IncomingMessage, ServerResponse } from "node:http";+import { createServer, type IncomingMessage, type ServerResponse } from "node:http";import { tmpdir } from "node:os";import { join } from "node:path";-import type { Socket } from "node:net";+import type { AddressInfo, Socket } from "node:net";import { afterEach, describe, expect, it } from "vitest";import { WebSocket, WebSocketServer, type RawData } from "ws";@@ -24,6 +24,7 @@ import { SessionRegistry } from "./sessions.ts";const SERVER_VERSION = (JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version;const signingKey = generateKeyPairSync("ed25519").privateKey;+const secondSigningKey = generateKeyPairSync("ed25519").privateKey;const keys = new Map([["k1", ed25519RawPublicKey(signingKey)]]);const NODE = "relay1.openmausbot.com";@@ -410,6 +411,62 @@ describe("phones through MausBot Relay on a server", () => {}});+ it("asks for its token from the credential document a sign-in writes, and re-reads it when the relay refuses the old one", async () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-phone-relay-doc-"));+ cleanup.push(() => removeTempDir(dir));+ const sessions = new SessionRegistry({ file: join(dir, "sessions.json") });+ cleanup.push(() => sessions.close());+ const hostId = randomBytes(16);+ let credential = `omb_install_${randomBytes(16).toString("base64url")}.${randomBytes(32).toString("base64url")}`;+ let signing = signingKey;+ const requests: Array<{ credential: string; body: Record<string, unknown> }> = [];+ const controlPlane = createServer(async (req, res) => {+ let raw = "";+ for await (const chunk of req) raw += chunk;+ const given = (req.headers.authorization ?? "").slice("Bearer ".length);+ if (req.method !== "POST" || req.url !== "/v1/installations/self/relay-token" || given !== credential) {+ return void res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: "unauthorized" }));+ }+ requests.push({ credential: given, body: JSON.parse(raw) });+ const iat = Math.floor(Date.now() / 1000);+ const token = mintRelayToken({ v: 1, kid: "k1", hid: b64u(hostId), iid: "test-install", iat, exp: iat + 43_200 }, signing);+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({+ token, hostId: b64u(hostId), nodes: [NODE], expiresAt: (iat + 43_200) * 1000, refreshAfter: (iat + 3_600) * 1000,+ }));+ });+ await new Promise<void>((resolve) => controlPlane.listen(0, "127.0.0.1", resolve));+ cleanup.push(() => new Promise<void>((resolve) => controlPlane.close(() => resolve())));+ // What `openmausbot login --relay` leaves behind: the installation credential, and no tunnel address.+ writeFileSync(join(dir, "tunnel-account.json"), JSON.stringify({ companionInstallationCredential: credential }), { mode: 0o600 });++ const relay = await startFakeRelay({ keys });+ cleanup.push(() => relay.close());+ const upgrades = createUpgrades();+ cleanup.push(() => upgrades.close());+ const phoneRelay = startPhoneRelay({+ env: { OMB_PHONE_RELAY: "1", OMB_PHONE_RELAY_URL: relay.url, OMB_CONTROL_PLANE_URL: `http://127.0.0.1:${(controlPlane.address() as AddressInfo).port}` },+ dataDir: dir, sessions, handle: () => {}, upgrades,+ serverName: () => "VPS", publicOrigin: () => null, version: SERVER_VERSION, refusal: null,+ log: () => {},+ })!;+ cleanup.push(() => phoneRelay.stop());+ await waitFor(() => phoneRelay.status().relay === "connected", 5_000);+ expect(phoneRelay.status().grant).toBe("ok");+ expect(requests).toEqual([{ credential, body: { appVersion: SERVER_VERSION, devices: { e2e: 0, legacy: 0 }, kind: "server" } }]);++ // Signing in again rotates the credential; the relay refuses the token it holds, and the next fetch re-reads+ // the document, so a sign-in needs no restart of the server or the relay to be serving phones again.+ credential = `omb_install_${randomBytes(16).toString("base64url")}.${randomBytes(32).toString("base64url")}`;+ signing = secondSigningKey;+ keys.set("k1", ed25519RawPublicKey(secondSigningKey));+ cleanup.push(() => keys.set("k1", ed25519RawPublicKey(signingKey)));+ writeFileSync(join(dir, "tunnel-account.json"), JSON.stringify({ companionInstallationCredential: credential }), { mode: 0o600 });+ relay.restart();+ await waitFor(() => phoneRelay.status().relay === "connected" && requests.length === 2, 5_000);+ expect(requests[1]).toMatchObject({ credential });+ expect(phoneRelay.status().grant).toBe("ok");+ });+it("pairs only with the QR's credential: a typed code and the browser's pairing route are refused", async () => {const server = await startServer();await connected(server);