Skip to content

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

fix(grok): reload grok-oauth.json when another process logs in

Jack Rudenko6a4d111df5a5
diff --git a/packages/cli/src/auth/credential-file.ts b/packages/cli/src/auth/credential-file.ts
new file mode 100644
index 00000000..547eded4
--- /dev/null
+++ b/packages/cli/src/auth/credential-file.ts
@@ -0,0 +1,159 @@
+/**
+ * This process's copy of ONE credential file, kept in step with the file on disk.
+ *
+ * A long-lived claudish (`claudish --mcp`, `serve`, a pane child) used to read its OAuth
+ * login once, in a constructor, and keep that copy for its whole life. After
+ * `claudish login grok` rewrote `~/.claudish/grok-oauth.json` in another terminal, an
+ * older MCP server kept presenting the revoked refresh token and answering `Grok token
+ * refresh failed: Refresh token has been revoked` until it was restarted
+ * (model-failures-2026-10-21.md, D1).
+ *
+ * There is no timer. The file is checked with one path `stat` at the moments a caller
+ * asks (before signing, before refreshing, before reporting a dead login), and re-read
+ * only when its stamp moved. The stamp is recorded per path, so a test seam that swaps
+ * the path always reads the new file.
+ *
+ * Four disk states, and why the fourth exists: an OLDER claudish on the same machine
+ * writes this file in place (`openSync(path, "w")`), so between its truncate and its
+ * write a reader sees a 0-byte or partial file. If that read meant "no credentials", one
+ * torn read would sign a subscription user out, and the routing chain would walk the
+ * request onto a metered provider. So a file that exists but cannot be read, parsed or
+ * validated is `unreadable`: the last good credentials are kept, the new stamp is NOT
+ * recorded (the next call reads again), and only ENOENT means `removed`.
+ *
+ * Never logs a credential value: log lines carry the label and the path only.
+ */
+import { readFileSync, statSync } from "node:fs";
+import { log } from "../logger.js";
+
+/** What identifies one version of a file without reading it. */
+export interface FileStamp {
+ ino: number;
+ size: number;
+ mtimeMs: number;
+ ctimeMs: number;
+}
+
+/**
+ * `null` = the file does not exist (ENOENT only). Any other stat error (EACCES, EIO …)
+ * is `{ error }`, which a caller treats as "unreadable", never as "removed".
+ */
+export function statCredentialFile(path: string): FileStamp | null | { error: string } {
+ try {
+ const st = statSync(path);
+ return { ino: st.ino, size: st.size, mtimeMs: st.mtimeMs, ctimeMs: st.ctimeMs };
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ if (code === "ENOENT") return null;
+ return { error: code ?? String(err) };
+ }
+}
+
+function sameStamp(a: FileStamp, b: FileStamp): boolean {
+ return a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
+}
+
+/**
+ * unchanged : same path, same stamp as the last GOOD read
+ * reloaded : the stamp moved; the file parsed and validated; `value` replaced
+ * removed : ENOENT; `value` becomes null
+ * unreadable : the file exists but cannot be read, parsed or validated; `value` keeps
+ * the last good credentials and the stamp is not recorded
+ */
+export type DiskSync = "unchanged" | "reloaded" | "removed" | "unreadable";
+
+/** Re-reads of an unreadable file before `settle()` gives up, and the pause between them. */
+const SETTLE_RETRIES = 3;
+const SETTLE_DELAY_MS = 25;
+
+export interface CredentialFileOptions<T> {
+ /** Read per call, so a test path seam works. */
+ path: () => string;
+ validate: (data: unknown) => data is T;
+ /** Log label: "GrokOAuth", "KimiOAuth". */
+ label: string;
+}
+
+export class CredentialFileState<T extends { access_token: string; refresh_token?: string }> {
+ private current: T | null = null;
+ /** The path and stamp of the last GOOD read (or of a confirmed absence). */
+ private recorded: { path: string; stamp: FileStamp | null } | null = null;
+
+ constructor(private readonly opts: CredentialFileOptions<T>) {}
+
+ /** The last GOOD credentials, or null when never loaded or removed. No I/O. */
+ get value(): T | null {
+ return this.current;
+ }
+
+ /** stat; compare with the recorded {path, stamp}; read only when either differs. */
+ syncFromDisk(): DiskSync {
+ const path = this.opts.path();
+ const label = this.opts.label;
+ const stamp = statCredentialFile(path);
+
+ if (stamp === null) {
+ if (this.current !== null) log(`[${label}] credential file removed on disk; signed out`);
+ this.current = null;
+ this.recorded = { path, stamp: null };
+ return "removed";
+ }
+ if ("error" in stamp) return this.unreadable(path);
+
+ const recorded = this.recorded;
+ if (recorded && recorded.path === path && recorded.stamp && sameStamp(recorded.stamp, stamp)) {
+ return "unchanged";
+ }
+
+ let data: unknown;
+ try {
+ data = JSON.parse(readFileSync(path, "utf-8"));
+ } catch {
+ return this.unreadable(path);
+ }
+ if (!this.opts.validate(data)) return this.unreadable(path);
+
+ const firstLoad = recorded === null || recorded.path !== path;
+ this.current = data;
+ this.recorded = { path, stamp };
+ log(
+ firstLoad
+ ? `[${label}] Loaded credentials from file`
+ : `[${label}] credential file changed on disk; reloaded`
+ );
+ return "reloaded";
+ }
+
+ /** `syncFromDisk()`, and on "unreadable" re-read up to 3 times, 25 ms apart. */
+ async settle(): Promise<DiskSync> {
+ let result = this.syncFromDisk();
+ for (let i = 0; i < SETTLE_RETRIES && result === "unreadable"; i++) {
+ await new Promise((resolve) => setTimeout(resolve, SETTLE_DELAY_MS));
+ result = this.syncFromDisk();
+ }
+ return result;
+ }
+
+ /**
+ * Hold `next` as this process's credentials after THIS process wrote it to `path`,
+ * recording the file's current stamp so our own write is not read back as a change.
+ */
+ adoptWritten(next: T): void {
+ const path = this.opts.path();
+ const stamp = statCredentialFile(path);
+ this.current = next;
+ this.recorded = stamp && !("error" in stamp) ? { path, stamp } : null;
+ }
+
+ /** Forget the in-memory credentials (a logout in this process). */
+ forget(): void {
+ this.current = null;
+ }
+
+ private unreadable(path: string): DiskSync {
+ log(
+ `[${this.opts.label}] credential file unreadable (${path}); kept the last good credentials`
+ );
+ return "unreadable";
+ }
+}
diff --git a/packages/cli/src/auth/grok-oauth.test.ts b/packages/cli/src/auth/grok-oauth.test.ts
index ab9f3998..eeee377f 100644
--- a/packages/cli/src/auth/grok-oauth.test.ts
+++ b/packages/cli/src/auth/grok-oauth.test.ts
@@ -1,5 +1,8 @@
-import { afterEach, describe, expect, mock, test } from "bun:test";
-import { GrokOAuth, type GrokOAuthCredentials } from "./grok-oauth.js";
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { GrokOAuth, type GrokOAuthCredentials, setGrokOAuthPathForTesting } from "./grok-oauth.js";
const realFetch = globalThis.fetch;
const realSetTimeout = globalThis.setTimeout;
@@ -14,7 +17,6 @@ interface DeviceAuthorizationFixture {
}
interface GrokOAuthTestInternals {
- credentials: GrokOAuthCredentials | null;
requestDeviceCode(clientId: string): Promise<DeviceAuthorizationFixture>;
saveCredentials(credentials: GrokOAuthCredentials): void;
deleteCredentials(): void;
@@ -22,18 +24,32 @@ interface GrokOAuthTestInternals {
presentAuthUrl(url: string): () => void;
}
-class HermeticGrokOAuth extends GrokOAuth {
- protected override loadCredentials(): GrokOAuthCredentials | null {
- // Constructor dispatches here, keeping tests independent of the developer's real home.
- return null;
- }
-}
+// The credential file is read lazily and re-read on change, so every test points
+// GrokOAuth at a temp file (`setGrokOAuthPathForTesting`), never at the developer's
+// real ~/.claudish/grok-oauth.json.
+class HermeticGrokOAuth extends GrokOAuth {}
+
+let credentialDir: string;
+let credentialPath: string;
+
+beforeEach(() => {
+ credentialDir = mkdtempSync(join(tmpdir(), "claudish-grok-oauth-"));
+ credentialPath = join(credentialDir, "grok-oauth.json");
+ setGrokOAuthPathForTesting(credentialPath);
+});
afterEach(() => {
globalThis.fetch = realFetch;
globalThis.setTimeout = realSetTimeout;
+ setGrokOAuthPathForTesting(null);
+ rmSync(credentialDir, { recursive: true, force: true });
});
+/** Write the login another process (or an earlier session) left on disk. */
+function seedCredentialFile(credentials: GrokOAuthCredentials): void {
+ writeFileSync(credentialPath, JSON.stringify(credentials, null, 2), { mode: 0o600 });
+}
+
function internals(oauth: GrokOAuth): GrokOAuthTestInternals {
return oauth as unknown as GrokOAuthTestInternals;
}
@@ -277,7 +293,7 @@ describe("GrokOAuth refresh", () => {
test("uses a public-client refresh form and persists a rotated refresh token", async () => {
const oauth = new HermeticGrokOAuth();
const state = internals(oauth);
- state.credentials = expiredCredentials();
+ seedCredentialFile(expiredCredentials());
const saveCredentials = mock((_credentials: GrokOAuthCredentials) => {});
state.saveCredentials = saveCredentials;
const fetchMock = mock(async (_input: RequestInfo | URL, _init?: RequestInit) =>
@@ -314,7 +330,7 @@ describe("GrokOAuth refresh", () => {
test("keeps the existing refresh token when the server does not rotate it", async () => {
const oauth = new HermeticGrokOAuth();
const state = internals(oauth);
- state.credentials = expiredCredentials();
+ seedCredentialFile(expiredCredentials());
const saveCredentials = mock((_credentials: GrokOAuthCredentials) => {});
state.saveCredentials = saveCredentials;
globalThis.fetch = mock(async () =>
@@ -330,7 +346,7 @@ describe("GrokOAuth refresh", () => {
test("names claudish login grok when refresh fails", async () => {
const oauth = new HermeticGrokOAuth();
const state = internals(oauth);
- state.credentials = expiredCredentials();
+ seedCredentialFile(expiredCredentials());
const saveCredentials = mock((_credentials: GrokOAuthCredentials) => {});
state.saveCredentials = saveCredentials;
globalThis.fetch = mock(async () =>
@@ -360,7 +376,7 @@ describe("GrokOAuth logout", () => {
test("revokes the refresh token before clearing local state", async () => {
const oauth = new HermeticGrokOAuth();
const state = internals(oauth);
- state.credentials = loggedInCredentials();
+ seedCredentialFile(loggedInCredentials());
const order: string[] = [];
const deleteCredentials = mock(() => order.push("delete"));
state.deleteCredentials = deleteCredentials;
@@ -387,7 +403,7 @@ describe("GrokOAuth logout", () => {
test("clears local state even when revocation fails", async () => {
const oauth = new HermeticGrokOAuth();
const state = internals(oauth);
- state.credentials = loggedInCredentials();
+ seedCredentialFile(loggedInCredentials());
const deleteCredentials = mock(() => {});
state.deleteCredentials = deleteCredentials;
globalThis.fetch = mock(async () => {
diff --git a/packages/cli/src/auth/grok-oauth.ts b/packages/cli/src/auth/grok-oauth.ts
index 0191be95..ce7121e1 100644
--- a/packages/cli/src/auth/grok-oauth.ts
+++ b/packages/cli/src/auth/grok-oauth.ts
@@ -28,6 +28,8 @@
* `grok login` is still picked up for free.
*/
+import { homedir } from "node:os";
+import { join } from "node:path";
import { log } from "../logger.js";
import { credentialHttpError, terminalCredentialError } from "./credentials/credential-error.js";
import { type BaseCredentials, OAuthManager } from "./oauth-manager.js";
@@ -123,6 +125,23 @@ interface TokenResponse {
/** Poll interval floor, per RFC 8628 §3.5 when the server sends none. */
const DEFAULT_POLL_INTERVAL_S = 5;
+/**
+ * Test seam for `~/.claudish/grok-oauth.json`. MANDATORY in any test that reaches
+ * `GrokOAuth`: the default is the developer's real login, and since the file is
+ * read lazily and re-read on change, a test without the seam reads (and, through a
+ * refresh, writes) the real file. The guard does not snapshot this file.
+ */
+let grokOAuthPathOverride: string | null = null;
+
+export function setGrokOAuthPathForTesting(path: string | null): void {
+ grokOAuthPathOverride = path;
+}
+
+/** claudish's OWN Grok login file, written by `claudish login grok`. */
+export function grokOAuthPath(): string {
+ return grokOAuthPathOverride ?? join(homedir(), ".claudish", "grok-oauth.json");
+}
+
export class GrokOAuth extends OAuthManager<GrokOAuthCredentials> {
protected readonly credentialFile = "grok-oauth.json";
protected readonly providerName = "GrokOAuth";
@@ -137,9 +156,13 @@ export class GrokOAuth extends OAuthManager<GrokOAuthCredentials> {
return GrokOAuth.instance;
}
- constructor() {
- super();
- this.credentials = this.loadCredentials();
+ /**
+ * claudish's own Grok login file, honouring `setGrokOAuthPathForTesting`. The
+ * readiness check (`hasClaudishGrokOAuth`) reads the same function, so a test
+ * override can never send the two to different files.
+ */
+ protected override getCredentialsPath(): string {
+ return grokOAuthPath();
}
protected validateCredentials(data: unknown): data is GrokOAuthCredentials {
@@ -239,7 +262,6 @@ export class GrokOAuth extends OAuthManager<GrokOAuthCredentials> {
client_id: current.client_id || GROK_PUBLIC_CLIENT_ID,
scope: parsed.scope ?? current.scope,
};
- this.credentials = next;
this.saveCredentials(next);
return next.access_token;
}
@@ -265,7 +287,6 @@ export class GrokOAuth extends OAuthManager<GrokOAuthCredentials> {
try {
const credentials = await this.pollForToken(auth, clientId);
- this.credentials = credentials;
this.saveCredentials(credentials);
} finally {
// Must run on the failure path too — a timed-out or declined login would
@@ -364,6 +385,8 @@ export class GrokOAuth extends OAuthManager<GrokOAuthCredentials> {
* surprising outcome of the two.
*/
async logout(): Promise<void> {
+ // Revoke the login that is on disk now, which may be newer than ours.
+ this.fileState.syncFromDisk();
const current = this.credentials;
if (current?.refresh_token) {
try {
diff --git a/packages/cli/src/auth/oauth-manager.ts b/packages/cli/src/auth/oauth-manager.ts
index f78686d5..f1cfaf6a 100644
--- a/packages/cli/src/auth/oauth-manager.ts
+++ b/packages/cli/src/auth/oauth-manager.ts
@@ -2,7 +2,9 @@
* OAuthManager — shared base class for all OAuth providers.
*
* Handles:
- * - Credential file I/O with 0600 permissions
+ * - Credential file I/O with 0600 permissions, through `CredentialFileState`: the
+ * file is re-read when another process changed it (a new login), never on a timer
+ * and never in a constructor
* - Token refresh with promise-based deduplication
* - Token validity checking with configurable margin
* - PKCE code verifier/challenge generation
@@ -12,19 +14,12 @@
import { exec } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
-import {
- closeSync,
- existsSync,
- mkdirSync,
- openSync,
- readFileSync,
- unlinkSync,
- writeSync,
-} from "node:fs";
+import { closeSync, existsSync, mkdirSync, openSync, unlinkSync, writeSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { log } from "../logger.js";
+import { CredentialFileState } from "./credential-file.js";
import { terminalCredentialError } from "./credentials/credential-error.js";
const execAsync = promisify(exec);
@@ -46,8 +41,8 @@ export interface BaseCredentials {
* - `validateCredentials(data)` — check that loaded JSON has required fields
*/
export abstract class OAuthManager<T extends BaseCredentials = BaseCredentials> {
- protected credentials: T | null = null;
private refreshPromise: Promise<string> | null = null;
+ private fileStateInstance: CredentialFileState<T> | null = null;
protected tokenRefreshMargin = 5 * 60 * 1000; // 5 minutes
/** Filename inside ~/.claudish/ (e.g. "gemini-oauth.json") */
@@ -79,22 +74,26 @@ export abstract class OAuthManager<T extends BaseCredentials = BaseCredentials>
// ── Credential File I/O ────────────────────────────────────────────────
- protected loadCredentials(): T | null {
- const credPath = this.getCredentialsPath();
- if (!existsSync(credPath)) return null;
-
- try {
- const data = JSON.parse(readFileSync(credPath, "utf-8"));
- if (!this.validateCredentials(data)) {
- log(`[${this.providerName}] Invalid credentials file structure`);
- return null;
- }
- log(`[${this.providerName}] Loaded credentials from file`);
- return data;
- } catch (e: any) {
- log(`[${this.providerName}] Failed to load credentials: ${e.message}`);
- return null;
+ /**
+ * This process's copy of the credential file (`credential-file.ts`). Created on
+ * first use, never in a constructor: the subclass's `credentialFile` and
+ * `providerName` are not set yet while the base constructor runs, and no
+ * manager reads its file before something asks for a token (lazy first load).
+ */
+ protected get fileState(): CredentialFileState<T> {
+ if (!this.fileStateInstance) {
+ this.fileStateInstance = new CredentialFileState<T>({
+ path: () => this.getCredentialsPath(),
+ validate: (data): data is T => this.validateCredentials(data),
+ label: this.providerName,
+ });
}
+ return this.fileStateInstance;
+ }
+
+ /** The last credentials read from (or written to) the file. No I/O. */
+ protected get credentials(): T | null {
+ return this.fileState.value;
}
protected saveCredentials(credentials: T): void {
@@ -106,6 +105,7 @@ export abstract class OAuthManager<T extends BaseCredentials = BaseCredentials>
} finally {
closeSync(fd);
}
+ this.fileState.adoptWritten(credentials);
log(`[${this.providerName}] Credentials saved to ${credPath}`);
}
@@ -119,8 +119,22 @@ export abstract class OAuthManager<T extends BaseCredentials = BaseCredentials>
// ── Token Lifecycle ────────────────────────────────────────────────────
+ /**
+ * Whether a login is on disk. Asks the file (one stat), so a login written by
+ * another process since this one started answers yes. An unreadable file keeps
+ * the last good credentials (`credential-file.ts`): it never answers no for a
+ * process that was signed in.
+ */
hasCredentials(): boolean {
- return this.credentials !== null && !!this.credentials.refresh_token;
+ this.fileState.syncFromDisk();
+ const current = this.credentials;
+ return current !== null && !!current.refresh_token;
+ }
+
+ protected noCredentialsError(): Error {
+ return terminalCredentialError(
+ `No ${this.providerName} credentials found. Please run \`${this.loginHint}\` first.`
+ );
}
async getAccessToken(): Promise<string> {
@@ -129,16 +143,20 @@ export abstract class OAuthManager<T extends BaseCredentials = BaseCredentials>
return this.refreshPromise;
}
- if (!this.credentials) {
- throw terminalCredentialError(
- `No ${this.providerName} credentials found. Please run \`${this.loginHint}\` first.`
- );
- }
+ // Before use: a newer login written by another process replaces ours, and a
+ // newer valid token is returned with no network call.
+ await this.fileState.settle();
+ // The settle awaited: a refresh another caller started meanwhile is joined.
+ if (this.refreshPromise) return this.refreshPromise;
+
+ const current = this.credentials;
+ if (!current) throw this.noCredentialsError();
if (this.isTokenValid()) {
- return this.credentials.access_token;
+ return current.access_token;
}
+ // Before refresh: the refresh starts from the file's credentials as just synced.
this.refreshPromise = this.doRefreshToken().finally(() => {
this.refreshPromise = null;
});
@@ -146,11 +164,23 @@ export abstract class OAuthManager<T extends BaseCredentials = BaseCredentials>
return this.refreshPromise;
}
+ /**
+ * A forced refresh (the transport's 401 retry). The token that drew the 401 is
+ * not passed in, so the proxy for it is the access token held in memory right
+ * before this call's sync: if the file now holds a different one, another
+ * process logged in or refreshed, and that token is adopted with no refresh.
+ * Otherwise the refresh runs. Accepted: a concurrent request in this process may
+ * already have synced the newer token, which costs one redundant refresh, and
+ * never adopts a token that was itself rejected.
+ */
async refreshToken(): Promise<void> {
- if (!this.credentials) {
- throw terminalCredentialError(
- `No ${this.providerName} credentials found. Please run \`${this.loginHint}\` first.`
- );
+ const before = this.credentials?.access_token;
+ await this.fileState.settle();
+ const current = this.credentials;
+ if (!current) throw this.noCredentialsError();
+ if (before !== undefined && current.access_token !== before) {
+ log(`[${this.providerName}] credential file changed on disk; using the newer login`);
+ return;
}
await this.doRefreshToken();
}
@@ -299,6 +329,6 @@ export abstract class OAuthManager<T extends BaseCredentials = BaseCredentials>
async logout(): Promise<void> {
this.deleteCredentials();
- this.credentials = null;
+ this.fileState.forget();
}
}
diff --git a/packages/cli/src/providers/grok/grok-credentials.ts b/packages/cli/src/providers/grok/grok-credentials.ts
index 878caba9..a1fb8dd9 100644
--- a/packages/cli/src/providers/grok/grok-credentials.ts
+++ b/packages/cli/src/providers/grok/grok-credentials.ts
@@ -46,7 +46,12 @@ import {
credentialHttpError,
isTransientCredentialError,
} from "../../auth/credentials/credential-error.js";
-import { GROK_PUBLIC_CLIENT_ID, GrokOAuth } from "../../auth/grok-oauth.js";
+import {
+ GROK_PUBLIC_CLIENT_ID,
+ GrokOAuth,
+ grokOAuthPath,
+ setGrokOAuthPathForTesting,
+} from "../../auth/grok-oauth.js";
import { classifyConnectionError, markOwnTimeout } from "../../handlers/shared/connection-error.js";
import { TOKEN_REFRESH_TIMEOUT_MS } from "../../handlers/shared/transient-retry.js";
@@ -93,7 +98,7 @@ export function setGrokHomeForTesting(path: string | null): void {
// Point the OAuth store at a sibling inside the SAME temp home, so a test
// that seams only `~/.grok` cannot accidentally read the developer's real
// `claudish login grok` credential and take the wrong branch.
- claudishOAuthPathOverride = path ? join(path, "claudish-grok-oauth.json") : null;
+ setGrokOAuthPathForTesting(path ? join(path, "claudish-grok-oauth.json") : null);
liveClientVersion = null;
}
@@ -185,15 +190,15 @@ export function readGrokCredential(): GrokCredential | undefined {
* happens to be logged in — the same class of machine-state dependency that
* made `setPeerLockProbe` necessary for the 1Password suite.
*/
-let claudishOAuthPathOverride: string | null = null;
-
export function setClaudishGrokOAuthPathForTesting(path: string | null): void {
- claudishOAuthPathOverride = path;
+ // ONE seam: `GrokOAuth` reads the same path, so the readiness check and the
+ // token resolver can never read two different files under a test override.
+ setGrokOAuthPathForTesting(path);
}
/** claudish's OWN OAuth store, written by `claudish login grok`. */
export function claudishGrokOAuthPath(): string {
- return claudishOAuthPathOverride ?? join(homedir(), ".claudish", "grok-oauth.json");
+ return grokOAuthPath();
}
/**