Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(device-auth): Kimi and Grok sign out from the server through their CLI's logout
DeryFerda87396e7e010
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 8d8a209ec5..23d82a1b59 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -14,7 +14,7 @@ import { PROVIDER_CREDENTIAL_ENV, stripControlPlaneEnv, WORKSPACE_CREDENTIAL_ENVimport { openStartupModelCatalog } from "../../startup-model-catalog.ts";import { acpModelCatalog } from "./model-catalog.ts";import { decodeInjectId } from "../local-inject.ts";-import { DeviceAuthController, type DeviceSignIn } from "../device-auth.ts";+import { DeviceAuthController, deviceAuthInstanceSurface, type DeviceSignIn } from "../device-auth.ts";import { deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSessionPrompt, writePromptSplitReceipt } from "../prompt-split.ts";import type { PromptSplitReceipt } from "../prompt-split.ts";import { describeSpawnFailure, execCli, killCliTree, spawnCli } from "../../procs.ts";@@ -1672,11 +1672,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>},refreshModels: support.resolveModels ? () => refreshModels(true) : undefined,...(startupModelRefresh ? { startupModelRefresh } : {}),- ...(deviceSignIn ? {- startAuthentication: () => deviceSignIn.start(),- getAuthentication: (flowId: string) => deviceSignIn.get(flowId),- cancelAuthentication: () => deviceSignIn.cancel(),- } : {}),+ ...(support.deviceSignIn && deviceSignIn ? deviceAuthInstanceSurface(deviceSignIn, support.deviceSignIn) : {}),snapshot,adapter: {provider: DRIVER_KIND,diff --git a/server/drivers/acp/grok-device-auth.test.ts b/server/drivers/acp/grok-device-auth.test.tsindex e4a328623e..c87729ef54 100644--- a/server/drivers/acp/grok-device-auth.test.ts+++ b/server/drivers/acp/grok-device-auth.test.ts@@ -53,6 +53,14 @@ describe("Grok device prompt", () => {});});+describe("Grok sign-out from the server", () => {+ it("declares the CLI's logout command with the stored sign-in as its check", () => {+ expect(GROK_DEVICE_SIGN_IN.logoutArgs).toEqual(["logout"]);+ expect(GROK_DEVICE_SIGN_IN.signedIn).toBeTypeOf("function");+ expect(GROK_DEVICE_SIGN_IN.signInState).toBeTypeOf("function");+ });+});+describe.skipIf(process.platform === "win32")("Grok Build sign-in with a device code", () => {let home: string;let instances: ProviderInstance[];@@ -206,4 +214,16 @@ describe.skipIf(process.platform === "win32")("Grok Build sign-in with a devicewriteFileSync(join(home, ".omb-fake-grok-approved"), "approve fixture only\n");await expect.poll(async () => (await instance.getAuthentication!(start.flowId!)).phase, { timeout: 5_000 }).toBe("succeeded");});++ it("signs the stored login out through the CLI's logout", async () => {+ const instance = await grok("success");+ const start = await instance.startAuthentication!();+ await expect.poll(async () => (await instance.getAuthentication!(start.flowId!)).phase, { timeout: 5_000 }).toBe("succeeded");+ expect(existsSync(join(home, ".grok", "auth.json"))).toBe(true);+ await instance.signOut!();+ expect(existsSync(join(home, ".grok", "auth.json"))).toBe(false);+ expect(calls().filter((call) => call.args[0] === "logout")).toEqual([+ { args: ["logout"], home, grokHome: join(home, ".grok"), xaiKey: null },+ ]);+ });});diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.tsindex a1f41d2460..b04617e3b0 100644--- a/server/drivers/acp/grok.ts+++ b/server/drivers/acp/grok.ts@@ -1,13 +1,13 @@// Grok Build: the official `grok` CLI over ACP stdio (`grok … agent stdio`) on the grok.com// subscription login (~/.grok/auth.json), not the xAI API key. Verified against grok 1.0.0.-import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";import { dirname, join, resolve } from "node:path";import { setTimeout as delay } from "node:timers/promises";import { parse as parseYaml } from "yaml";import type { ModelCatalog } from "../../contracts.ts";import { harnessHome, splitCliString } from "../../env-path.ts";-import type { DeviceSignIn } from "../device-auth.ts";+import type { DeviceSignIn, DeviceSignInState } from "../device-auth.ts";import { decodeInjectId, hostApiKey, localHost, mergeLocalInject } from "../local-inject.ts";import { createAcpDriver, type AcpSupport } from "./core.ts";import type { AcpQuestionRequest } from "./question-requests.ts";@@ -35,6 +35,17 @@ export function grokSignedIn(env: Record<string, string | undefined>): boolean {return existsSync(join(grokHome(env), "auth.json"));}+/** The sign-out probe: an auth.json that cannot be read is `unknown`, so sign-out refuses instead of reporting a+ * removal that never happened. `grokSignedIn` keeps its boolean contract for turn gating. */+export function grokSignInState(env: Record<string, string | undefined>): DeviceSignInState {+ try {+ statSync(join(grokHome(env), "auth.json"));+ return "signed-in";+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === "ENOENT" ? "signed-out" : "unknown";+ }+}+function grokLoginFailure(output: string): string {if (/(unexpected argument|unrecognized (argument|option)|unknown option).*device-(auth|code)/i.test(output)) {return "This server's Grok is too old to sign in with a code. Update Grok on the server, then try again.";@@ -47,8 +58,8 @@ function grokLoginFailure(output: string): string {return "Grok sign-in did not finish. Check the server's connection, then try again.";}-/** `grok login --device-auth` on the grok.com subscription (grok 1.0.25 and 1.0.41). Grok has no- * status command, so nothing is checked first. */+/** `grok login --device-auth` / `grok logout` on the grok.com subscription (grok 1.0.25 and 1.0.41). Grok has no+ * status command, so the stored auth.json is the sign-in check. */export const GROK_DEVICE_SIGN_IN: DeviceSignIn = {provider: "grok",product: "Grok",@@ -56,9 +67,11 @@ export const GROK_DEVICE_SIGN_IN: DeviceSignIn = {homeEnv: "GROK_HOME",homeDir: ".grok",loginArgs: ["login", "--device-auth"],+ logoutArgs: ["logout"],install: "Install it with xAI's installer (https://x.ai/cli), then try again.",failure: grokLoginFailure,signedIn: grokSignedIn,+ signInState: grokSignInState,};function unquote(raw: string): string {diff --git a/server/drivers/acp/kimi-device-auth.test.ts b/server/drivers/acp/kimi-device-auth.test.tsindex fcd558adae..d5135ae40d 100644--- a/server/drivers/acp/kimi-device-auth.test.ts+++ b/server/drivers/acp/kimi-device-auth.test.ts@@ -1,5 +1,5 @@// Every process here is the offline fake kimi in a disposable HOME: no real Kimi, no Moonshot call, no credentials.-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";@@ -79,6 +79,26 @@ describe("Kimi device prompt", () => {});});+describe("Kimi sign-out from the server", () => {+ it("has no logout command to drive, so sign-out removes the stored credential files it checks", () => {+ expect(KIMI_DEVICE_SIGN_IN.logoutArgs).toBeUndefined();+ expect(KIMI_DEVICE_SIGN_IN.removeCredentials).toBeTypeOf("function");+ expect(KIMI_DEVICE_SIGN_IN.signInState).toBeTypeOf("function");+ });++ it("reports an unreadable credential folder as unknown instead of signed-out", () => {+ const scratch = mkdtempSync(join(tmpdir(), "omb-kimi-state-"));+ try {+ const env = { KIMI_CODE_HOME: scratch };+ expect(KIMI_DEVICE_SIGN_IN.signInState!(env)).toBe("signed-out");+ writeFileSync(join(scratch, "credentials"), "a file where the credentials folder would go");+ expect(KIMI_DEVICE_SIGN_IN.signInState!(env)).toBe("unknown");+ } finally {+ rmSync(scratch, { recursive: true, force: true });+ }+ });+});+describe.skipIf(process.platform === "win32")("Kimi Code sign-in with a device code", () => {let home: string;let instances: ProviderInstance[];@@ -225,4 +245,14 @@ describe.skipIf(process.platform === "win32")("Kimi Code sign-in with a device cwriteFileSync(join(home, ".omb-fake-kimi-approved"), "approve fixture only\n");await expect.poll(async () => (await instance.getAuthentication!(start.flowId!)).phase, { timeout: 5_000 }).toBe("succeeded");});++ it("signs out by removing the stored credential files, without driving a CLI command", async () => {+ const instance = await kimi("success");+ const start = await instance.startAuthentication!();+ await expect.poll(async () => (await instance.getAuthentication!(start.flowId!)).phase, { timeout: 5_000 }).toBe("succeeded");+ expect(existsSync(credential())).toBe(true);+ await instance.signOut!();+ expect(existsSync(credential())).toBe(false);+ expect(calls().every((call) => call.args[0] === "login")).toBe(true);+ });});diff --git a/server/drivers/acp/kimi.ts b/server/drivers/acp/kimi.tsindex 623fa5f024..a8d06be21a 100644--- a/server/drivers/acp/kimi.ts+++ b/server/drivers/acp/kimi.ts@@ -1,11 +1,11 @@// Kimi Code: Moonshot's `kimi acp` on the Kimi Code subscription login// (~/.kimi-code/credentials), not a Moonshot API key. Verified on kimi-code 0.29.1.-import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";import type { ModelCatalog } from "../../contracts.ts";-import type { DeviceSignIn } from "../device-auth.ts";+import type { DeviceSignIn, DeviceSignInState } from "../device-auth.ts";import { decodeInjectId, hostApiKey, LOCAL_HOSTS, localHost, mergeLocalInject } from "../local-inject.ts";import { createAcpDriver, type AcpSupport } from "./core.ts";@@ -57,6 +57,28 @@ function kimiSignedIn(env: Record<string, string | undefined>): boolean {}}+/** The sign-out probe: a credential folder that cannot be read is `unknown`, so sign-out refuses instead of+ * reporting a removal that never happened. `kimiSignedIn` keeps its boolean contract for turn gating. */+function kimiSignInState(env: Record<string, string | undefined>): DeviceSignInState {+ const credentials = join(kimiDataRoot(env), "credentials");+ let names: string[];+ try {+ names = readdirSync(credentials);+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === "ENOENT" ? "signed-out" : "unknown";+ }+ return names.some((name) => KIMI_TOKEN_FILE.test(name) && kimiTokenHeld(join(credentials, name))) ? "signed-in" : "signed-out";+}++/** Kimi Code 2.4.1 ships no logout command, so sign-out removes the credential files the login created — the same+ * cleanup the sign-out flow confirms afterwards. */+function kimiRemoveCredentials(env: Record<string, string | undefined>): void {+ const credentials = join(kimiDataRoot(env), "credentials");+ for (const name of readdirSync(credentials)) {+ if (KIMI_TOKEN_FILE.test(name)) unlinkSync(join(credentials, name));+ }+}+/** Never the CLI's own words, which may carry tokens (kimi-code 2.4.1 ends with "Login failed: …" or "Login cancelled: …",* and after 900s with "Login failed: Device authorization timed out"). */function kimiLoginFailure(output: string): string {@@ -65,7 +87,8 @@ function kimiLoginFailure(output: string): string {return "Kimi sign-in did not finish. Check the server's connection, then try again.";}-/** `kimi login`, Kimi Code's device-code login (kimi-code 2.4.1). Kimi has no status command, so nothing is checked first. */+/** `kimi login`, Kimi Code's device-code login (kimi-code 2.4.1). Kimi has no status or logout command, so the+ * stored credential files are both the sign-in check and what sign-out removes. */export const KIMI_DEVICE_SIGN_IN: DeviceSignIn = {provider: "kimi",product: "Kimi",@@ -76,6 +99,8 @@ export const KIMI_DEVICE_SIGN_IN: DeviceSignIn = {install: "Install it with Moonshot's installer (https://code.kimi.com), or from Settings when this server has npm, then try again.",failure: kimiLoginFailure,signedIn: kimiSignedIn,+ signInState: kimiSignInState,+ removeCredentials: kimiRemoveCredentials,};function quoteToml(value: string): string {diff --git a/server/drivers/device-auth.test.ts b/server/drivers/device-auth.test.tsnew file mode 100644index 0000000000..b0d04b3bfe--- /dev/null+++ b/server/drivers/device-auth.test.ts@@ -0,0 +1,125 @@+// Every subprocess here is a local fake script in a disposable HOME: no real provider, network or credentials.+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { removeTempDir } from "../testing/cleanup.ts";+import { DeviceAuthController, type DeviceSignIn } from "./device-auth.ts";++const FAKE = `#!/usr/bin/env node+import { appendFileSync, existsSync, unlinkSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+const home = process.env.HOME;+const args = process.argv.slice(2);+appendFileSync(join(home, 'calls.jsonl'), JSON.stringify({ args }) + '\\n');+if (args.join(' ') === 'logout') {+ writeFileSync(join(home, 'logout.pid'), String(process.pid));+ if (process.env.FAKE_AUTH_MODE === 'logout-fails') { console.error('error: could not remove credentials'); process.exit(1); }+ const had = existsSync(join(home, '.fake-provider', 'auth.json'));+ try { unlinkSync(join(home, '.fake-provider', 'auth.json')); } catch {}+ console.error(had ? 'Signed out' : 'Not signed in');+ process.exit(0);+}+process.exit(4);+`;++function spec(logoutArgs?: readonly string[], overrides: Partial<DeviceSignIn> = {}): DeviceSignIn {+ return {+ provider: "grok",+ product: "Fake",+ account: "Fake",+ homeEnv: "FAKE_PROVIDER_HOME",+ homeDir: ".fake-provider",+ loginArgs: ["login"],+ install: "install hint",+ failure: () => "Fake sign-in did not finish.",+ signedIn: (env) => existsSync(join(env.FAKE_PROVIDER_HOME || join(env.HOME || env.USERPROFILE || "", ".fake-provider"), "auth.json")),+ ...(logoutArgs ? { logoutArgs } : {}),+ ...overrides,+ };+}++describe("device sign-out without a status command", () => {+ let home: string;+ let cli: string;+ let controllers: DeviceAuthController[];+ const create = (logoutArgs?: readonly string[], mode?: string, overrides: Partial<DeviceSignIn> = {}) => {+ const controller = new DeviceAuthController(spec(logoutArgs, overrides), {+ cli, terminateTimeoutMs: 50,+ environment: () => ({+ ...process.env, HOME: home, USERPROFILE: home, FAKE_PROVIDER_HOME: join(home, ".fake-provider"),+ ...(mode ? { FAKE_AUTH_MODE: mode } : {}),+ }),+ });+ controllers.push(controller);+ return controller;+ };+ const calls = () => existsSync(join(home, "calls.jsonl"))+ ? readFileSync(join(home, "calls.jsonl"), "utf8").trim().split("\n").map((line) => JSON.parse(line) as { args: string[] })+ : [];+ const signedIn = () => {+ mkdirSync(join(home, ".fake-provider"), { recursive: true });+ writeFileSync(join(home, ".fake-provider", "auth.json"), "{}", { mode: 0o600 });+ };++ beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), "omb-device-signout-"));+ cli = join(home, "fake-provider.mjs");+ writeFileSync(cli, FAKE, { mode: 0o700 });+ chmodSync(cli, 0o700);+ controllers = [];+ });+ afterEach(async () => {+ await Promise.all(controllers.map((controller) => controller.dispose()));+ await removeTempDir(home);+ });++ it("reads the stored sign-in through the spec, runs the CLI's logout, and confirms it is gone", async () => {+ signedIn();+ const controller = create(["logout"]);+ await controller.signOut();+ expect(existsSync(join(home, ".fake-provider", "auth.json"))).toBe(false);+ expect(calls().map((call) => call.args)).toEqual([["logout"]]);+ await controller.signOut();+ expect(calls().map((call) => call.args)).toEqual([["logout"]]);+ });++ it("returns without running the logout when nothing is signed in", async () => {+ const controller = create(["logout"]);+ await controller.signOut();+ expect(calls()).toEqual([]);+ });++ it("says plainly when the CLI could not remove the sign-in", async () => {+ signedIn();+ const controller = create(["logout"], "logout-fails");+ await expect(controller.signOut()).rejects.toThrow("Fake could not remove the sign-in on this server.");+ expect(existsSync(join(home, ".fake-provider", "auth.json"))).toBe(true);+ });++ it("stays unavailable for a provider without a logout command", async () => {+ signedIn();+ await expect(create(undefined).signOut()).rejects.toThrow("Signing out of Fake is not available from here.");+ expect(calls()).toEqual([]);+ });++ it("removes the stored sign-in without a CLI command when the spec removes credentials itself", async () => {+ signedIn();+ const controller = create(undefined, undefined, { removeCredentials: (env) => {+ unlinkSync(join(env.FAKE_PROVIDER_HOME || join(env.HOME || env.USERPROFILE || "", ".fake-provider"), "auth.json"));+ } });+ await controller.signOut();+ expect(existsSync(join(home, ".fake-provider", "auth.json"))).toBe(false);+ expect(calls()).toEqual([]);+ });++ it("refuses to sign out when the sign-in cannot be read, instead of reporting a removal that never happened", async () => {+ signedIn();+ const controller = create(undefined, undefined, {+ removeCredentials: () => unlinkSync(join(home, ".fake-provider", "auth.json")),+ signInState: () => "unknown",+ });+ await expect(controller.signOut()).rejects.toThrow("Fake did not confirm a Fake sign-in.");+ expect(existsSync(join(home, ".fake-provider", "auth.json"))).toBe(true);+ });+});diff --git a/server/drivers/device-auth.ts b/server/drivers/device-auth.tsindex 3f1be7fa15..8479b5ac57 100644--- a/server/drivers/device-auth.ts+++ b/server/drivers/device-auth.ts@@ -44,7 +44,24 @@ export interface DeviceSignIn {status?: { args: readonly string[]; read(code: number | null, output: string): DeviceSignInState };/** Without a status command: whether the sign-in a turn uses is now there. */signedIn?(env: Env): boolean;+ /** The sign-out probe when a plain boolean is not enough: a credential folder that cannot be read is `unknown`,+ * and sign-out refuses instead of reporting a removal that never happened. */+ signInState?(env: Env): DeviceSignInState;logoutArgs?: readonly string[];+ /** Sign-out without a CLI command: remove the stored credential files the CLI reads. */+ removeCredentials?(env: Env): void | Promise<void>;+}++/** The instance surface an ACP driver exposes for its device sign-in: start/get/cancel, plus `signOut` when the spec+ * can actually perform one (a CLI logout command or a credential removal). Lives beside the controller so the+ * instance wiring stays one line in each driver. */+export function deviceAuthInstanceSurface(deviceSignIn: DeviceAuthController, spec: DeviceSignIn) {+ return {+ startAuthentication: () => deviceSignIn.start(),+ getAuthentication: (flowId: string) => deviceSignIn.get(flowId),+ cancelAuthentication: () => deviceSignIn.cancel(),+ ...((spec.logoutArgs || spec.removeCredentials) ? { signOut: () => deviceSignIn.signOut() } : {}),+ };}type Flow = {@@ -180,8 +197,9 @@ export class DeviceAuthController {}private async signOutNow(): Promise<void> {- const { product, account, status, logoutArgs } = this.spec;- if (!status || !logoutArgs) throw new Error(`Signing out of ${account} is not available from here.`);+ const { product, account, status, signedIn, signInState, logoutArgs, removeCredentials } = this.spec;+ if (!logoutArgs && !removeCredentials) throw new Error(`Signing out of ${account} is not available from here.`);+ if (!status && !signedIn && !signInState) throw new Error(`Signing out of ${account} is not available from here.`);if (this.disposed) throw new Error("This provider was removed. Refresh Settings before signing out.");if (this.flow?.status.phase === "waiting") throw new Error(`Finish or cancel the ${account} sign-in in progress before signing out.`);await this.flow?.stopping;@@ -193,16 +211,28 @@ export class DeviceAuthController {}authenticatingHomes.add(homeKey);try {- const before = await this.exec([...status.args], env, home);- const state = status.read(before.code, before.output);+ const held = async (): Promise<DeviceSignInState> => {+ if (signInState) return signInState(env);+ if (!status) return signedIn!(env) ? "signed-in" : "signed-out";+ const probe = await this.exec([...status.args], env, home);+ return status.read(probe.code, probe.output);+ };+ const state = await held();if (state === "signed-out") return;if (state !== "signed-in") {throw new Error(`${product} did not confirm a ${account} sign-in. Other authentication methods will not be removed; ask the server administrator to check the account.`);}- const logout = await this.exec([...logoutArgs], env, home);- if (logout.code !== 0) throw new Error(`${product} could not remove the sign-in on this server. Check the server's ${product} installation and try again.`);- const after = await this.exec([...status.args], env, home);- if (status.read(after.code, after.output) !== "signed-out") {+ if (logoutArgs) {+ const logout = await this.exec([...logoutArgs], env, home);+ if (logout.code !== 0) throw new Error(`${product} could not remove the sign-in on this server. Check the server's ${product} installation and try again.`);+ } else {+ try {+ await removeCredentials!(env);+ } catch {+ throw new Error(`${product} could not remove the sign-in on this server. Check the server's ${product} installation and try again.`);+ }+ }+ if (await held() !== "signed-out") {throw new Error(`${product} still reports a sign-in on this server. Update ${product} and check its login status before trying again.`);}} finally {diff --git a/server/testing/fake-grok-login-cli.ts b/server/testing/fake-grok-login-cli.tsindex 46ceae63b4..9b6c9dc281 100755--- a/server/testing/fake-grok-login-cli.ts+++ b/server/testing/fake-grok-login-cli.ts@@ -3,7 +3,7 @@// device instructions): no network, no real credential; needs explicit opt-in and a disposable HOME.// FAKE_GROK_MODE success | approve (once HOME/.omb-fake-grok-approved exists) | waiting | complete |// evil (a page on another host) | expired | denied | crash | no-credential | old (no --device-auth) | ignore-term-import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";+import { appendFileSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";import { isAbsolute, join } from "node:path";const home = process.env.HOME;@@ -49,6 +49,10 @@ if (args.join(" ") === "--version") {if (mode === "ignore-term") process.on("SIGTERM", () => {});setInterval(() => {}, 1000);}+} else if (args.join(" ") === "logout") {+ rmSync(join(grokHome, "auth.json"), { force: true });+ process.stderr.write("Signed out of Grok.\n");+ process.exit(0);} else {process.stderr.write("Unsupported offline fixture command.\n");process.exitCode = 2;