Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

test(auth): pin reloading a credential file another process rewrote

Jack Rudenkodc21ed6821b4
diff --git a/packages/cli/src/auth/credential-file.test.ts b/packages/cli/src/auth/credential-file.test.ts
new file mode 100644
index 00000000..c6df18d6
--- /dev/null
+++ b/packages/cli/src/auth/credential-file.test.ts
@@ -0,0 +1,388 @@
+import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test";
+import * as fs from "node:fs";
+import {
+ existsSync,
+ mkdtempSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ capturedLines,
+ startLogCapture,
+ stopLogCapture,
+} from "../recovery/test-helpers/capture-log";
+import {
+ CredentialFileState,
+ refreshAndCommit,
+ statCredentialFile,
+ writeCredentialFileAtomic,
+} from "./credential-file";
+
+interface Login {
+ access_token: string;
+ refresh_token: string;
+ expires_at: number;
+}
+
+const first: Login = {
+ access_token: "OPAQUE_TEST_TOKEN_abc",
+ refresh_token: "OPAQUE_TEST_TOKEN_refresh",
+ expires_at: 1,
+};
+const newer: Login = {
+ access_token: "OPAQUE_TEST_TOKEN_new_login",
+ refresh_token: "OPAQUE_TEST_TOKEN_new_lineage",
+ expires_at: Number.MAX_SAFE_INTEGER,
+};
+const rotated: Login = {
+ access_token: "OPAQUE_TEST_TOKEN_rotated",
+ refresh_token: "OPAQUE_TEST_TOKEN_rotated_refresh",
+ expires_at: Number.MAX_SAFE_INTEGER,
+};
+const opts = {
+ isValid: (login: Login) => login.expires_at > Date.now(),
+ noCredentials: () => new Error("No test credentials found"),
+};
+
+let root: string;
+let path: string;
+
+function state(
+ validate: (data: unknown) => boolean = (data: unknown) => {
+ const value = data as Partial<Login> | null;
+ return typeof value?.access_token === "string" && typeof value?.refresh_token === "string";
+ }
+) {
+ return new CredentialFileState<Login>({
+ path: () => path,
+ validate: (data: unknown): data is Login => validate(data),
+ label: "W1",
+ });
+}
+
+function replace(login: Login) {
+ const next = join(root, "new-login.json");
+ writeFileSync(next, JSON.stringify(login));
+ renameSync(next, path);
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "w1-credential-file-"));
+ path = join(root, "login.json");
+ startLogCapture();
+});
+
+afterEach(async () => {
+ try {
+ const lines = (await capturedLines()).join("\n");
+ for (const login of [first, newer, rotated]) {
+ expect(lines).not.toContain(login.access_token);
+ expect(lines).not.toContain(login.refresh_token);
+ }
+ } finally {
+ stopLogCapture();
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+describe("W1 credential file public contract", () => {
+ test("G1 1.1 lazy first load and rename replacement adopt the new login", () => {
+ const file = state();
+ expect(file.value).toBeNull();
+ writeFileSync(path, JSON.stringify(first));
+ expect(file.syncFromDisk()).toBe("reloaded");
+ expect(file.value).toEqual(first);
+ replace(newer);
+ expect(file.syncFromDisk()).toBe("reloaded");
+ expect(file.value).toEqual(newer);
+ }, 5_000);
+
+ test("G1 1.2 an in-place rewrite on the same inode is reloaded", () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ const ino = statSync(path).ino;
+ writeFileSync(path, JSON.stringify(newer));
+ expect(statSync(path).ino).toBe(ino);
+ expect(file.syncFromDisk()).toBe("reloaded");
+ expect(file.value).toEqual(newer);
+ }, 5_000);
+
+ test("G1 the stamp is keyed by path, not just the file identity", () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ const previous = path;
+ path = join(root, "other.json");
+ writeFileSync(path, JSON.stringify(newer));
+ expect(file.syncFromDisk()).toBe("reloaded");
+ expect(file.value).toEqual(newer);
+ expect(existsSync(previous)).toBe(true);
+ }, 5_000);
+
+ test("G1 1.8 only removal clears the last good credentials", () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ unlinkSync(path);
+ expect(statCredentialFile(path)).toBeNull();
+ expect(file.syncFromDisk()).toBe("removed");
+ expect(file.value).toBeNull();
+ }, 5_000);
+
+ test("G3 a non-ENOENT stat failure never signs out the last good login", () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ unlinkSync(path);
+ symlinkSync(path, path);
+ expect(statCredentialFile(path)).toMatchObject({ error: "ELOOP" });
+ expect(file.syncFromDisk()).toBe("unreadable");
+ expect(file.value).toEqual(first);
+ unlinkSync(path);
+ writeFileSync(path, JSON.stringify(newer));
+ expect(file.syncFromDisk()).toBe("reloaded");
+ expect(file.value).toEqual(newer);
+ }, 5_000);
+
+ test("G5 unchanged files skip file reads, parsing and validation", () => {
+ writeFileSync(path, JSON.stringify(first));
+ const validate = mock((value: unknown): value is Login => Boolean(value));
+ const file = state(validate);
+ expect(file.syncFromDisk()).toBe("reloaded");
+ expect(validate).toHaveBeenCalledTimes(1);
+ const reads = spyOn(fs, "readFileSync");
+ try {
+ for (let i = 0; i < 4; i++) expect(file.syncFromDisk()).toBe("unchanged");
+ expect(reads).not.toHaveBeenCalled();
+ expect(validate).toHaveBeenCalledTimes(1);
+ expect(file.value).toEqual(first);
+ } finally {
+ reads.mockRestore();
+ }
+ }, 5_000);
+
+ test("G3 1.16/1.17 unreadable files keep the value and retry the SAME stamp", () => {
+ writeFileSync(path, JSON.stringify(first));
+ let allow = true;
+ const validate = mock((value: unknown): value is Login => allow && Boolean(value));
+ const file = state(validate);
+ file.syncFromDisk();
+ writeFileSync(path, JSON.stringify(newer));
+ allow = false;
+ expect(file.syncFromDisk()).toBe("unreadable");
+ expect(file.value).toEqual(first);
+ const stamp = statCredentialFile(path);
+ allow = true;
+ expect(file.syncFromDisk()).toBe("reloaded");
+ expect(statCredentialFile(path)).toEqual(stamp);
+ expect(file.value).toEqual(newer);
+ expect(validate).toHaveBeenCalledTimes(3);
+ }, 5_000);
+
+ for (const torn of ["", '{"access_token":"OPAQUE_TEST_TOKEN_abc"']) {
+ test(`G3 1.16/1.19 torn JSON (${torn.length} bytes) keeps the last good value`, () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ writeFileSync(path, torn);
+ expect(file.syncFromDisk()).toBe("unreadable");
+ expect(file.value).toEqual(first);
+ expect(file.syncFromDisk()).toBe("unreadable");
+ writeFileSync(path, JSON.stringify(newer));
+ expect(file.syncFromDisk()).toBe("reloaded");
+ expect(file.value).toEqual(newer);
+ const fresh = state();
+ writeFileSync(path, torn);
+ expect(fresh.syncFromDisk()).toBe("unreadable");
+ expect(fresh.value).toBeNull();
+ }, 5_000);
+ }
+
+ test("G2 1.6 saveRefreshed never overwrites a newer refresh-token lineage", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ replace(newer);
+ const bytes = readFileSync(path, "utf8");
+ expect(await file.saveRefreshed(first, rotated)).toEqual({
+ outcome: "newer-on-disk",
+ onDisk: newer,
+ });
+ expect(readFileSync(path, "utf8")).toBe(bytes);
+ expect(file.value).toEqual(newer);
+ }, 5_000);
+
+ test("G2 the refresh-token lineage, not the access token, controls the commit", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ replace({ ...first, access_token: newer.access_token });
+ expect(await file.saveRefreshed(first, rotated)).toEqual({ outcome: "saved" });
+ expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(rotated);
+ }, 5_000);
+
+ test("G2 1.7/1.10b uncontended refresh writes atomically with mode 0600", async () => {
+ writeFileSync(path, JSON.stringify(first), { mode: 0o644 });
+ const file = state();
+ file.syncFromDisk();
+ const oldInode = statSync(path).ino;
+ expect(await file.saveRefreshed(first, rotated)).toEqual({ outcome: "saved" });
+ expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(rotated);
+ expect(statSync(path).ino).not.toBe(oldInode);
+ expect(statSync(path).mode & 0o777).toBe(0o600);
+ }, 5_000);
+
+ test("G2 an in-flight refresh never recreates a logout file", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ unlinkSync(path);
+ expect(await file.saveRefreshed(first, rotated)).toEqual({ outcome: "removed" });
+ expect(existsSync(path)).toBe(false);
+ }, 5_000);
+
+ test("G2 1.11 a rejected login cannot delete another writer's login", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ replace(newer);
+ const bytes = readFileSync(path, "utf8");
+ expect(await file.deleteIfUnchanged(first)).toBe("newer-on-disk");
+ expect(readFileSync(path, "utf8")).toBe(bytes);
+ expect(file.value).toEqual(newer);
+ }, 5_000);
+
+ test("G2 a rejection deletes only an unchanged login", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ expect(await file.deleteIfUnchanged(first)).toBe("deleted");
+ expect(existsSync(path)).toBe(false);
+ expect(file.value).toBeNull();
+ }, 5_000);
+
+ test("G3 1.18 an unreadable file is not overwritten by a successful refresh", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ writeFileSync(path, "");
+ expect(await file.saveRefreshed(first, rotated)).toEqual({ outcome: "unreadable" });
+ expect(readFileSync(path, "utf8")).toBe("");
+ }, 5_000);
+
+ test("G3 1.19b rejection never deletes an unreadable file", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ writeFileSync(path, "");
+ expect(await file.deleteIfUnchanged(first)).toBe("unreadable");
+ expect(existsSync(path)).toBe(true);
+ expect(readFileSync(path, "utf8")).toBe("");
+ expect(file.value).toEqual(first);
+ }, 5_000);
+
+ test("G1 1.4 a failed exchange adopts a valid login written during the exchange", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ const refresh = mock(async () => {
+ replace(newer);
+ throw new Error("Refresh token has been revoked");
+ });
+ expect(await refreshAndCommit(file, refresh, opts, "W1")).toBe(newer.access_token);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ expect(file.value).toEqual(newer);
+ }, 5_000);
+
+ test("G1 1.5 an unchanged failed exchange rethrows the SAME error, without retry", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ const failure = new Error("Refresh token has been revoked");
+ const refresh = mock(async () => {
+ throw failure;
+ });
+ await expect(refreshAndCommit(file, refresh, opts)).rejects.toBe(failure);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ expect(file.value).toEqual(first);
+ }, 5_000);
+
+ test("G2 1.6 a successful exchange returns the newer login and preserves its bytes", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ const refresh = mock(async () => {
+ replace(newer);
+ return rotated;
+ });
+ expect(await refreshAndCommit(file, refresh, opts)).toBe(newer.access_token);
+ expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(newer);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ }, 5_000);
+
+ test("G3 1.18 a successful refresh is retained in memory while the file is torn", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ const refresh = mock(async () => {
+ writeFileSync(path, "");
+ return rotated;
+ });
+ expect(await refreshAndCommit(file, refresh, opts, "W1")).toBe(rotated.access_token);
+ expect(file.value).toEqual(rotated);
+ expect(readFileSync(path, "utf8")).toBe("");
+ expect(file.syncFromDisk()).toBe("unreadable");
+ expect(file.value).toEqual(rotated);
+ replace(newer);
+ expect(file.syncFromDisk()).toBe("reloaded");
+ expect(file.value).toEqual(newer);
+ }, 5_000);
+
+ test("G3 a failed exchange on an unreadable file preserves its original error", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ const failure = new Error("Refresh token has been revoked");
+ await expect(
+ refreshAndCommit(
+ file,
+ async () => {
+ writeFileSync(path, "");
+ throw failure;
+ },
+ opts
+ )
+ ).rejects.toBe(failure);
+ expect(file.value).toEqual(first);
+ expect(readFileSync(path, "utf8")).toBe("");
+ }, 5_000);
+
+ test("G4 unreadable debug logs contain the path and label, never credential values", async () => {
+ writeFileSync(path, JSON.stringify(first));
+ const file = state();
+ file.syncFromDisk();
+ writeFileSync(path, '{"OPAQUE_TEST_TOKEN_abc":');
+ file.syncFromDisk();
+ expect((await capturedLines()).join("\n")).toContain(
+ `[W1] credential file unreadable (${path}); kept the last good credentials`
+ );
+ }, 5_000);
+
+ test("G2 atomic login writes replace the inode and use mode 0600", () => {
+ writeFileSync(path, JSON.stringify(first), { mode: 0o644 });
+ const previous = statSync(path).ino;
+ const stamp = writeCredentialFileAtomic(path, newer);
+ expect(statCredentialFile(path)).toEqual(stamp);
+ expect(statSync(path).ino).not.toBe(previous);
+ expect(statSync(path).mode & 0o777).toBe(0o600);
+ expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(newer);
+ }, 5_000);
+});
diff --git a/packages/cli/src/auth/grok-oauth.reload.test.ts b/packages/cli/src/auth/grok-oauth.reload.test.ts
new file mode 100644
index 00000000..f177b9cf
--- /dev/null
+++ b/packages/cli/src/auth/grok-oauth.reload.test.ts
@@ -0,0 +1,194 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
+import {
+ mkdtempSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ statSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ claudishGrokOAuthPath,
+ hasClaudishGrokOAuth,
+ resolveGrokAccessToken,
+ setClaudishGrokOAuthPathForTesting,
+ setGrokHomeForTesting,
+} from "../providers/grok/grok-credentials";
+import {
+ capturedLines,
+ startLogCapture,
+ stopLogCapture,
+} from "../recovery/test-helpers/capture-log";
+import { GrokOAuth, type GrokOAuthCredentials, setGrokOAuthPathForTesting } from "./grok-oauth";
+
+const first = {
+ access_token: "OPAQUE_TEST_TOKEN_abc",
+ refresh_token: "OPAQUE_TEST_TOKEN_refresh",
+ client_id: "TEST-CLIENT-ID",
+ expires_at: Number.MAX_SAFE_INTEGER,
+} satisfies GrokOAuthCredentials;
+const newer = {
+ ...first,
+ access_token: "OPAQUE_TEST_TOKEN_new_login",
+ refresh_token: "OPAQUE_TEST_TOKEN_new_lineage",
+};
+const realFetch = globalThis.fetch;
+let root: string;
+let path: string;
+let oauth: GrokOAuth;
+let fetches: ReturnType<typeof mock>;
+
+function write(login: GrokOAuthCredentials, atomic = false) {
+ if (atomic) {
+ const next = join(root, "replacement.json");
+ writeFileSync(next, JSON.stringify(login));
+ renameSync(next, path);
+ } else {
+ writeFileSync(path, JSON.stringify(login));
+ }
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "w1-grok-reload-"));
+ path = join(root, "grok-oauth.json");
+ setGrokHomeForTesting(root);
+ setGrokOAuthPathForTesting(path);
+ oauth = new GrokOAuth();
+ fetches = mock(async () => {
+ throw new Error("Unexpected network in W1 Grok reload tests");
+ });
+ globalThis.fetch = fetches as unknown as typeof fetch;
+ startLogCapture();
+});
+
+afterEach(async () => {
+ try {
+ const lines = (await capturedLines()).join("\n");
+ expect(lines).not.toContain("OPAQUE_TEST_TOKEN");
+ for (const login of [first, newer]) {
+ expect(lines).not.toContain(login.access_token);
+ expect(lines).not.toContain(login.refresh_token);
+ }
+ expect(fetches).not.toHaveBeenCalled();
+ } finally {
+ globalThis.fetch = realFetch;
+ stopLogCapture();
+ setGrokOAuthPathForTesting(null);
+ setClaudishGrokOAuthPathForTesting(null);
+ setGrokHomeForTesting(null);
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+describe("W1 Grok public reload behavior without token exchanges", () => {
+ test("G1 1.1 the next getToken adopts a renamed login without a fetch", async () => {
+ write(first);
+ expect(await oauth.getToken()).toBe(first.access_token);
+ write(newer, true);
+ expect(await oauth.getToken()).toBe(newer.access_token);
+ expect(oauth.hasCredentials()).toBe(true);
+ }, 5_000);
+
+ test("G1 1.2 the next getToken adopts an in-place login on the same inode", async () => {
+ write(first);
+ expect(await oauth.getToken()).toBe(first.access_token);
+ const ino = statSync(path).ino;
+ write(newer);
+ expect(statSync(path).ino).toBe(ino);
+ expect(await oauth.getToken()).toBe(newer.access_token);
+ }, 5_000);
+
+ test("G1 1.3 sync happens before deciding an expired cached token needs refresh", async () => {
+ write({ ...first, expires_at: 1 });
+ expect(oauth.hasCredentials()).toBe(true);
+ write(newer, true);
+ expect(await oauth.getToken()).toBe(newer.access_token);
+ }, 5_000);
+
+ test("G1 1.10 forced refresh adopts a new login instead of refreshing the stale token", async () => {
+ write(first);
+ expect(await oauth.getToken()).toBe(first.access_token);
+ write(newer, true);
+ await oauth.refreshToken();
+ expect(await oauth.getToken()).toBe(newer.access_token);
+ expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(newer);
+ }, 5_000);
+
+ test("G1 1.8 deleting the credential file signs out an already-loaded instance", async () => {
+ write(first);
+ expect(await oauth.getToken()).toBe(first.access_token);
+ unlinkSync(path);
+ await expect(oauth.getToken()).rejects.toThrow("No GrokOAuth credentials found");
+ expect(oauth.hasCredentials()).toBe(false);
+ }, 5_000);
+
+ for (const torn of ["", '{"access_token":"OPAQUE_TEST_TOKEN_abc"']) {
+ test(`G3 1.16/1.17 torn own file (${torn.length} bytes) keeps the login and retries`, async () => {
+ write(first);
+ expect(await oauth.getToken()).toBe(first.access_token);
+ writeFileSync(path, torn);
+ expect(await oauth.getToken()).toBe(first.access_token);
+ expect(oauth.hasCredentials()).toBe(true);
+ expect((await capturedLines()).join("\n")).toContain(
+ `[GrokOAuth] credential file unreadable (${path}); kept the last good credentials`
+ );
+ write(newer);
+ expect(await oauth.getToken()).toBe(newer.access_token);
+ }, 5_000);
+ }
+
+ test("G3 1.19 a corrupt first read has no last good login to return", async () => {
+ writeFileSync(path, "");
+ expect(oauth.hasCredentials()).toBe(false);
+ await expect(oauth.getToken()).rejects.toThrow("No GrokOAuth credentials found");
+ }, 5_000);
+
+ test("G4 a corrupt initial file never appears in the terminal error text", async () => {
+ writeFileSync(path, '{"access_token":"OPAQUE_TEST_TOKEN_abc"');
+ const failure: unknown = await oauth.getToken().catch((error: unknown) => error);
+ expect(failure).toBeInstanceOf(Error);
+ expect(String(failure)).toContain("No GrokOAuth credentials found");
+ expect(String(failure)).not.toContain(first.access_token);
+ expect(String(failure)).not.toContain(first.refresh_token);
+ }, 5_000);
+
+ test("G4 reload logs identify the change without printing the parsed credential", async () => {
+ write(first);
+ await oauth.getToken();
+ write(newer, true);
+ await oauth.getToken();
+ expect((await capturedLines()).join("\n")).toContain(
+ "[GrokOAuth] credential file changed on disk; reloaded"
+ );
+ }, 5_000);
+
+ test("G1 Grok own-file discovery and token use share either path override", async () => {
+ setClaudishGrokOAuthPathForTesting(path);
+ write(first);
+ expect(claudishGrokOAuthPath()).toBe(path);
+ expect(hasClaudishGrokOAuth()).toBe(true);
+ expect(await oauth.getToken()).toBe(first.access_token);
+ }, 5_000);
+
+ test("G1 the Grok CLI credential is re-read after another writer logs in", async () => {
+ const cliPath = join(root, "auth.json");
+ const scope = "https://auth.x.ai::TEST-CLIENT-ID";
+ const cli = (key: string) => ({
+ [scope]: {
+ key,
+ refresh_token: "OPAQUE_TEST_TOKEN_cli_refresh",
+ expires_at: "2999-01-01T00:00:00.000Z",
+ oidc_client_id: "TEST-CLIENT-ID",
+ oidc_issuer: "https://auth.x.ai",
+ auth_mode: "oidc",
+ },
+ });
+ writeFileSync(cliPath, JSON.stringify(cli(first.access_token)));
+ expect(await resolveGrokAccessToken()).toBe(first.access_token);
+ writeFileSync(cliPath, JSON.stringify(cli(newer.access_token)));
+ expect(await resolveGrokAccessToken()).toBe(newer.access_token);
+ }, 5_000);
+});
diff --git a/packages/cli/src/auth/kimi-oauth.reload.test.ts b/packages/cli/src/auth/kimi-oauth.reload.test.ts
new file mode 100644
index 00000000..0bc0bace
--- /dev/null
+++ b/packages/cli/src/auth/kimi-oauth.reload.test.ts
@@ -0,0 +1,223 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
+import {
+ existsSync,
+ mkdtempSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ statSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { homedir, tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+
+// Import Kimi only in the child: Bun fixes homedir() when the process starts.
+if (process.env.CLAUDISH_W1_KIMI_CHILD !== "1") {
+ test("W1 Kimi contracts run with HOME redirected before any production import", async () => {
+ const home = mkdtempSync(join(tmpdir(), "w1-kimi-home-"));
+ try {
+ const child = Bun.spawn([process.execPath, "--no-env-file", "test", import.meta.path], {
+ cwd: resolve(import.meta.dir, "../../../.."),
+ env: {
+ ...process.env,
+ HOME: home,
+ CLAUDISH_W1_KIMI_CHILD: "1",
+ CLAUDISH_DISABLE_KEYCHAIN: "1",
+ CLAUDISH_DISABLE_OP: "1",
+ CLAUDISH_DISABLE_CATALOG_WARM: "1",
+ },
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const [stdout, stderr, exit] = await Promise.all([
+ new Response(child.stdout).text(),
+ new Response(child.stderr).text(),
+ child.exited,
+ ]);
+ expect(exit, stdout + stderr).toBe(0);
+ expect(stdout + stderr).toContain("0 fail");
+ process.stdout.write(stdout + stderr);
+ expect(existsSync(join(home, ".claudish", "kimi-device-id"))).toBe(false);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 20_000);
+} else {
+ const { KimiOAuth, setKimiOAuthPathForTesting, setKimiDeviceIdPathForTesting } = await import(
+ "./kimi-oauth"
+ );
+ const { capturedLines, startLogCapture, stopLogCapture } = await import(
+ "../recovery/test-helpers/capture-log"
+ );
+ const first = {
+ access_token: "OPAQUE_TEST_TOKEN_abc",
+ refresh_token: "OPAQUE_TEST_TOKEN_refresh",
+ expires_at: Number.MAX_SAFE_INTEGER,
+ scope: "openid",
+ token_type: "Bearer",
+ };
+ const newer = {
+ ...first,
+ access_token: "OPAQUE_TEST_TOKEN_new_login",
+ refresh_token: "OPAQUE_TEST_TOKEN_new_lineage",
+ };
+ const realFetch = globalThis.fetch;
+ let root: string;
+ let path: string;
+ let devicePath: string;
+ let fetches: ReturnType<typeof mock>;
+
+ function write(login: typeof first, atomic = false) {
+ if (atomic) {
+ const next = join(root, "replacement.json");
+ writeFileSync(next, JSON.stringify(login));
+ renameSync(next, path);
+ } else {
+ writeFileSync(path, JSON.stringify(login));
+ }
+ }
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "w1-kimi-reload-"));
+ path = join(root, "kimi-oauth.json");
+ devicePath = join(root, "device", "id");
+ setKimiOAuthPathForTesting(path);
+ setKimiDeviceIdPathForTesting(devicePath);
+ KimiOAuth._resetForTests();
+ fetches = mock(async () => {
+ throw new Error("Unexpected network in W1 Kimi reload tests");
+ });
+ globalThis.fetch = fetches as unknown as typeof fetch;
+ startLogCapture();
+ });
+
+ afterEach(async () => {
+ try {
+ const lines = (await capturedLines()).join("\n");
+ for (const login of [first, newer]) {
+ expect(lines).not.toContain(login.access_token);
+ expect(lines).not.toContain(login.refresh_token);
+ }
+ expect(fetches).not.toHaveBeenCalled();
+ } finally {
+ globalThis.fetch = realFetch;
+ stopLogCapture();
+ KimiOAuth._resetForTests();
+ setKimiOAuthPathForTesting(null);
+ setKimiDeviceIdPathForTesting(null);
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ describe("W1 Kimi public reload behavior without token exchanges", () => {
+ test("G1 1.1 a long-lived singleton adopts a renamed login", async () => {
+ const oauth = KimiOAuth.getInstance();
+ write(first);
+ expect(await oauth.getAccessToken()).toBe(first.access_token);
+ write(newer, true);
+ expect(await oauth.getAccessToken()).toBe(newer.access_token);
+ expect(oauth.hasCredentials()).toBe(true);
+ }, 5_000);
+
+ test("G1 1.2 an in-place login on the same inode is reloaded", async () => {
+ const oauth = KimiOAuth.getInstance();
+ write(first);
+ expect(await oauth.getAccessToken()).toBe(first.access_token);
+ const ino = statSync(path).ino;
+ write(newer);
+ expect(statSync(path).ino).toBe(ino);
+ expect(await oauth.getAccessToken()).toBe(newer.access_token);
+ }, 5_000);
+
+ test("G1 1.3 a newer login is checked before refreshing the expired cached token", async () => {
+ const oauth = KimiOAuth.getInstance();
+ write({ ...first, expires_at: 1 });
+ expect(oauth.hasCredentials()).toBe(true);
+ write(newer, true);
+ expect(await oauth.getAccessToken()).toBe(newer.access_token);
+ }, 5_000);
+
+ test("G1 1.8 a deleted login clears both token use and credential presence", async () => {
+ const oauth = KimiOAuth.getInstance();
+ write(first);
+ expect(await oauth.getAccessToken()).toBe(first.access_token);
+ unlinkSync(path);
+ await expect(oauth.getAccessToken()).rejects.toThrow("No Kimi OAuth credentials found");
+ expect(oauth.hasCredentials()).toBe(false);
+ }, 5_000);
+
+ for (const torn of ["", '{"access_token":"OPAQUE_TEST_TOKEN_abc"']) {
+ test(`G3 1.16/1.17 a torn Kimi file (${torn.length} bytes) keeps the last good login`, async () => {
+ const oauth = KimiOAuth.getInstance();
+ write(first);
+ expect(await oauth.getAccessToken()).toBe(first.access_token);
+ writeFileSync(path, torn);
+ expect(await oauth.getAccessToken()).toBe(first.access_token);
+ expect(oauth.hasCredentials()).toBe(true);
+ expect((await capturedLines()).join("\n")).toContain(
+ `[KimiOAuth] credential file unreadable (${path}); kept the last good credentials`
+ );
+ write(newer);
+ expect(await oauth.getAccessToken()).toBe(newer.access_token);
+ }, 5_000);
+ }
+
+ test("G3 1.19 no last good login means a corrupt initial file is unauthenticated", async () => {
+ writeFileSync(path, "");
+ const oauth = KimiOAuth.getInstance();
+ expect(oauth.hasCredentials()).toBe(false);
+ await expect(oauth.getAccessToken()).rejects.toThrow("No Kimi OAuth credentials found");
+ }, 5_000);
+
+ test("G1 1.12 reset retains identity and clears the cached device id", () => {
+ const oauth = KimiOAuth.getInstance();
+ const headers = oauth.getPlatformHeaders();
+ const previous = readFileSync(devicePath, "utf8").trim();
+ expect(Object.values(headers)).toContain(previous);
+ devicePath = join(root, "another-device", "id");
+ setKimiDeviceIdPathForTesting(devicePath);
+ KimiOAuth._resetForTests();
+ expect(KimiOAuth.getInstance()).toBe(oauth);
+ const nextHeaders = oauth.getPlatformHeaders();
+ const next = readFileSync(devicePath, "utf8").trim();
+ expect(next).not.toBe(previous);
+ expect(Object.values(nextHeaders)).toContain(next);
+ expect(statSync(devicePath).mode & 0o777).toBe(0o600);
+ }, 5_000);
+
+ test("G1 1.20 importing the authority and obtaining the singleton does no home I/O", async () => {
+ expect(existsSync(join(homedir(), ".claudish"))).toBe(false);
+ await import("./credentials/authority");
+ KimiOAuth.getInstance();
+ expect(existsSync(join(homedir(), ".claudish"))).toBe(false);
+ expect(existsSync(devicePath)).toBe(false);
+ KimiOAuth.getInstance().getPlatformHeaders();
+ expect(existsSync(devicePath)).toBe(true);
+ expect(statSync(devicePath).mode & 0o777).toBe(0o600);
+ expect(existsSync(join(homedir(), ".claudish"))).toBe(false);
+ }, 5_000);
+
+ test("G4 a corrupt initial file never appears in the terminal error text", async () => {
+ writeFileSync(path, '{"access_token":"OPAQUE_TEST_TOKEN_abc"');
+ const failure: unknown = await KimiOAuth.getInstance()
+ .getAccessToken()
+ .catch((error: unknown) => error);
+ expect(failure).toBeInstanceOf(Error);
+ expect(String(failure)).toContain("No Kimi OAuth credentials found");
+ expect(String(failure)).not.toContain(first.access_token);
+ expect(String(failure)).not.toContain(first.refresh_token);
+ }, 5_000);
+
+ test("G4 reload logging contains the label without the parsed token values", async () => {
+ write(first);
+ const oauth = KimiOAuth.getInstance();
+ await oauth.getAccessToken();
+ write(newer, true);
+ await oauth.getAccessToken();
+ expect((await capturedLines()).join("\n")).toContain(
+ "[KimiOAuth] credential file changed on disk; reloaded"
+ );
+ }, 5_000);
+ });
+}
diff --git a/packages/cli/src/providers/devin/devin-credentials.reload.test.ts b/packages/cli/src/providers/devin/devin-credentials.reload.test.ts
new file mode 100644
index 00000000..dd23eb90
--- /dev/null
+++ b/packages/cli/src/providers/devin/devin-credentials.reload.test.ts
@@ -0,0 +1,113 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ capturedLines,
+ startLogCapture,
+ stopLogCapture,
+} from "../../recovery/test-helpers/capture-log";
+import {
+ DEVIN_API_KEY_ENV,
+ hasDevinCredentials,
+ readDevinApiKey,
+ setDevinCredentialsPathForTesting,
+} from "./devin-credentials";
+
+const first = "OPAQUE_TEST_TOKEN_abc";
+const newer = "OPAQUE_TEST_TOKEN_new_login";
+let root: string;
+let path: string;
+let originalKey: string | undefined;
+
+function toml(key: string) {
+ return `windsurf_api_key = "${key}"\n`;
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "w1-devin-reload-"));
+ path = join(root, "credentials.toml");
+ originalKey = process.env[DEVIN_API_KEY_ENV];
+ delete process.env[DEVIN_API_KEY_ENV];
+ setDevinCredentialsPathForTesting(path);
+ startLogCapture();
+});
+
+afterEach(async () => {
+ try {
+ const lines = (await capturedLines()).join("\n");
+ expect(lines).not.toContain(first);
+ expect(lines).not.toContain(newer);
+ } finally {
+ stopLogCapture();
+ setDevinCredentialsPathForTesting(null);
+ if (originalKey === undefined) delete process.env[DEVIN_API_KEY_ENV];
+ else process.env[DEVIN_API_KEY_ENV] = originalKey;
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+describe("W1 Devin file-backed key reload behavior", () => {
+ test("G1 1.13 an in-place CLI rewrite is visible to the next key read", () => {
+ writeFileSync(path, toml(first));
+ expect(readDevinApiKey()).toBe(first);
+ const ino = statSync(path).ino;
+ writeFileSync(path, toml(newer));
+ expect(statSync(path).ino).toBe(ino);
+ expect(readDevinApiKey()).toBe(newer);
+ }, 5_000);
+
+ test("G1 1.13 a renamed credentials.toml replaces the cached key", () => {
+ writeFileSync(path, toml(first));
+ expect(readDevinApiKey()).toBe(first);
+ const next = join(root, "next.toml");
+ writeFileSync(next, toml(newer));
+ renameSync(next, path);
+ expect(readDevinApiKey()).toBe(newer);
+ expect(hasDevinCredentials()).toBe(true);
+ }, 5_000);
+
+ for (const torn of ["", 'windsurf_api_key = "OPAQUE_TEST_TOKEN_abc']) {
+ test(`G3 unreadable TOML (${torn.length} bytes) keeps the key and retries on the next call`, () => {
+ writeFileSync(path, toml(first));
+ expect(readDevinApiKey()).toBe(first);
+ writeFileSync(path, torn);
+ expect(readDevinApiKey()).toBe(first);
+ expect(hasDevinCredentials()).toBe(true);
+ writeFileSync(path, toml(newer));
+ expect(readDevinApiKey()).toBe(newer);
+ }, 5_000);
+ }
+
+ test("G1 deleting the file removes the cached credential", () => {
+ writeFileSync(path, toml(first));
+ expect(readDevinApiKey()).toBe(first);
+ unlinkSync(path);
+ expect(readDevinApiKey()).toBeUndefined();
+ expect(hasDevinCredentials()).toBe(false);
+ }, 5_000);
+
+ test("G3 an unreadable first use has no cached credential, but is retried", () => {
+ writeFileSync(path, "");
+ expect(readDevinApiKey()).toBeUndefined();
+ writeFileSync(path, toml(newer));
+ expect(readDevinApiKey()).toBe(newer);
+ }, 5_000);
+
+ test("G4 the reload log is credential-free and unchanged reads produce no reload logs", async () => {
+ writeFileSync(path, toml(first));
+ expect(readDevinApiKey()).toBe(first);
+ writeFileSync(path, toml(newer));
+ expect(readDevinApiKey()).toBe(newer);
+ const before = (await capturedLines()).filter((line) =>
+ line.includes("[Devin] credentials file changed on disk; reloaded")
+ );
+ expect(before.length).toBeGreaterThan(0);
+ expect(readDevinApiKey()).toBe(newer);
+ expect(readDevinApiKey()).toBe(newer);
+ const after = (await capturedLines()).filter((line) =>
+ line.includes("[Devin] credentials file changed on disk; reloaded")
+ );
+ expect(after).toEqual(before);
+ }, 5_000);
+});