Skip to content

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

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

Jack Rudenko93efa21b38e1
diff --git a/packages/cli/src/auth/kimi-oauth.ts b/packages/cli/src/auth/kimi-oauth.ts
index 58d06718..b17fbf50 100644
--- a/packages/cli/src/auth/kimi-oauth.ts
+++ b/packages/cli/src/auth/kimi-oauth.ts
@@ -17,12 +17,21 @@
import { exec } from "node:child_process";
import { randomBytes } from "node:crypto";
-import { closeSync, existsSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
+import {
+ closeSync,
+ existsSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ unlinkSync,
+ writeSync,
+} from "node:fs";
import { homedir, hostname, platform, release } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { promisify } from "node:util";
import { log } from "../logger.js";
import { VERSION } from "../version.js";
+import { CredentialFileState, refreshAndCommit } from "./credential-file.js";
import {
credentialHttpError,
isTransientCredentialError,
@@ -31,6 +40,40 @@ import {
const execAsync = promisify(exec);
+/**
+ * Test seams for the two files this module owns. MANDATORY in any test that reaches
+ * `KimiOAuth`: the defaults are the developer's real `~/.claudish/kimi-oauth.json`
+ * and `~/.claudish/kimi-device-id`, and Bun resolves `homedir()` from the passwd
+ * entry, not from a `HOME` assigned in-process.
+ */
+let kimiOAuthPathOverride: string | null = null;
+let kimiDeviceIdPathOverride: string | null = null;
+
+export function setKimiOAuthPathForTesting(path: string | null): void {
+ kimiOAuthPathOverride = path;
+}
+
+export function setKimiDeviceIdPathForTesting(path: string | null): void {
+ kimiDeviceIdPathOverride = path;
+}
+
+/** claudish's Kimi login file, written by `claudish login kimi`. */
+export function kimiOAuthPath(): string {
+ return kimiOAuthPathOverride ?? join(homedir(), ".claudish", "kimi-oauth.json");
+}
+
+/** The persistent device id sent in the `X-Msh-Device-Id` header. */
+export function kimiDeviceIdPath(): string {
+ return kimiDeviceIdPathOverride ?? join(homedir(), ".claudish", "kimi-device-id");
+}
+
+/** The structure a Kimi credential file must have. */
+function isKimiCredentials(data: unknown): data is KimiCredentials {
+ if (!data || typeof data !== "object") return false;
+ const c = data as Partial<KimiCredentials>;
+ return !!(c.access_token && c.refresh_token && c.expires_at && c.scope && c.token_type);
+}
+
/**
* Kimi OAuth credentials structure
*/
@@ -82,10 +125,12 @@ const OAUTH_CONFIG = {
*/
export class KimiOAuth {
private static instance: KimiOAuth | null = null;
- private credentials: KimiCredentials | null = null;
+ /** This process's copy of the login file, re-read when another process changes it. */
+ private state = KimiOAuth.newFileState();
private refreshPromise: Promise<string> | null = null;
private tokenRefreshMargin = 5 * 60 * 1000; // Refresh 5 minutes before expiry
- private deviceId: string; // Persistent device ID (generated once)
+ /** Persistent device ID, loaded (or created) on first use, then cached. */
+ private deviceIdCache: string | null = null;
/**
* Get singleton instance
@@ -97,69 +142,75 @@ export class KimiOAuth {
return KimiOAuth.instance;
}
+ private static newFileState(): CredentialFileState<KimiCredentials> {
+ return new CredentialFileState<KimiCredentials>({
+ path: kimiOAuthPath,
+ validate: isKimiCredentials,
+ label: "KimiOAuth",
+ });
+ }
+
/**
- * Private constructor (singleton pattern)
- * FIX C3: Generate/load device ID in constructor (not per-request)
+ * Private constructor (singleton pattern). It does NO I/O: the singleton is built
+ * when the credential authority is imported, before a test can set a path seam, so
+ * reading here read the real login and created the real device-id file. The login
+ * loads on first use (`CredentialFileState`), the device id on first request.
*/
- private constructor() {
- // Load or create device ID
- this.deviceId = this.loadOrCreateDeviceId();
- log(`[KimiOAuth] Device ID loaded: ${this.deviceId}`);
+ private constructor() {}
- // Try to load existing credentials on startup
- this.credentials = this.loadCredentials();
+ /**
+ * Test seam: reset IN PLACE (the in-memory login, the recorded file stamp, the
+ * cached device id, an in-flight refresh). Never replaces the singleton: the
+ * credential authority's Kimi provider captured this instance at import, so a
+ * replacement would leave it holding a stale one.
+ */
+ static _resetForTests(): void {
+ const instance = KimiOAuth.getInstance();
+ instance.state = KimiOAuth.newFileState();
+ instance.refreshPromise = null;
+ instance.deviceIdCache = null;
}
/**
- * Re-read the credential file from disk into the in-memory singleton.
- *
- * The singleton loads credentials ONCE in its constructor, so a login that
- * happens in a CHILD process (e.g. the config TUI spawns `claudish login
- * kimi`) writes a fresh token file this long-lived parent never sees — its
- * request path keeps using the stale startup snapshot and fails until the
- * process is relaunched. Calling this after a login child returns picks up the
- * new token in-process, no restart needed. (Device ID is preserved.)
+ * Re-read the credential file now (the config TUI calls this after its login child
+ * returns). The request path already re-reads a changed file before every use, so
+ * this only makes the check immediate. (Device ID is preserved.)
*/
reloadCredentials(): void {
- this.credentials = this.loadCredentials();
+ this.state.syncFromDisk();
this.refreshPromise = null;
}
/**
- * Check if credentials exist (without validating expiry)
- * Use this to determine if login is needed before making requests
+ * Check if credentials exist (without validating expiry). Asks the file (one
+ * stat), so a login written by another process answers yes; an unreadable file
+ * keeps the last good login and never answers no for a process that was signed in.
*/
hasCredentials(): boolean {
- return this.credentials !== null && !!this.credentials.refresh_token;
- }
-
- /**
- * Get credentials file path
- */
- private getCredentialsPath(): string {
- const claudishDir = join(homedir(), ".claudish");
- return join(claudishDir, "kimi-oauth.json");
+ this.state.syncFromDisk();
+ const current = this.state.value;
+ return current !== null && !!current.refresh_token;
}
- /**
- * Get device ID file path
- */
- private getDeviceIdPath(): string {
- const claudishDir = join(homedir(), ".claudish");
- return join(claudishDir, "kimi-device-id");
+ /** The device id, loaded or created on first use. */
+ private get deviceId(): string {
+ if (this.deviceIdCache === null) {
+ this.deviceIdCache = this.loadOrCreateDeviceId();
+ log(`[KimiOAuth] Device ID loaded: ${this.deviceIdCache}`);
+ }
+ return this.deviceIdCache;
}
/**
- * Load or create persistent device ID
- * FIX C3: Called once in constructor, cached in instance
+ * Load or create persistent device ID. Called on the first request or login, then
+ * cached in the instance.
*/
private loadOrCreateDeviceId(): string {
- const deviceIdPath = this.getDeviceIdPath();
- const claudishDir = join(homedir(), ".claudish");
+ const deviceIdPath = kimiDeviceIdPath();
+ const claudishDir = dirname(deviceIdPath);
// Ensure directory exists
if (!existsSync(claudishDir)) {
- const { mkdirSync } = require("node:fs");
mkdirSync(claudishDir, { recursive: true });
}
@@ -253,8 +304,9 @@ export class KimiOAuth {
token_type: tokens.token_type,
};
- this.saveCredentials(credentials);
- this.credentials = credentials;
+ // A login is the user's intent: written unconditionally, atomically (0600).
+ this.state.saveLogin(credentials);
+ log(`[KimiOAuth] Credentials saved to ${kimiOAuthPath()}`);
log("[KimiOAuth] Login successful");
}
@@ -431,14 +483,14 @@ export class KimiOAuth {
* Logout - delete stored credentials
*/
async logout(): Promise<void> {
- const credPath = this.getCredentialsPath();
+ const credPath = kimiOAuthPath();
if (existsSync(credPath)) {
unlinkSync(credPath);
log("[KimiOAuth] Credentials deleted");
}
- this.credentials = null;
+ this.state.forget();
}
/**
@@ -452,21 +504,33 @@ export class KimiOAuth {
return this.refreshPromise;
}
+ // Before use: a newer login written by another process replaces ours.
+ await this.state.settle();
+ // The settle awaited: a refresh another caller started meanwhile is joined.
+ if (this.refreshPromise) return this.refreshPromise;
+
// Check if we have credentials
- if (!this.credentials) {
- throw terminalCredentialError(
- "No Kimi OAuth credentials found. Please run `claudish login kimi` first."
- );
- }
+ const current = this.state.value;
+ if (!current) throw noKimiCredentialsError();
// Check if token is still valid (with 5-minute buffer)
- if (this.isTokenValid()) {
- return this.credentials.access_token;
+ if (this.isCredentialValid(current)) {
+ return current.access_token;
}
- // Start refresh (lock to prevent duplicate refreshes)
+ // Start refresh (lock to prevent duplicate refreshes). The shared sequence
+ // commits the result without overwriting a login another process wrote, and
+ // adopts that login when this refresh fails (`credential-file.ts`).
// FIX C2: Use .finally() to ensure lock is released even on error
- this.refreshPromise = this.doRefreshToken().finally(() => {
+ this.refreshPromise = refreshAndCommit(
+ this.state,
+ (credentials) => this.doRefreshToken(credentials),
+ {
+ isValid: (credentials) => this.isCredentialValid(credentials),
+ noCredentials: noKimiCredentialsError,
+ },
+ "KimiOAuth"
+ ).finally(() => {
this.refreshPromise = null;
});
@@ -474,25 +538,19 @@ export class KimiOAuth {
}
/**
- * Check if cached token is still valid (with 5-minute buffer)
+ * Check if a token is still valid (with 5-minute buffer)
* FIX H5: Includes 5-minute buffer
*/
- private isTokenValid(): boolean {
- if (!this.credentials) return false;
- return Date.now() < this.credentials.expires_at - this.tokenRefreshMargin;
+ private isCredentialValid(credentials: KimiCredentials): boolean {
+ return Date.now() < credentials.expires_at - this.tokenRefreshMargin;
}
/**
- * Perform the actual token refresh
+ * The token exchange: refresh `current` and RETURN the next credentials. Never
+ * writes them; `refreshAndCommit` commits the result.
* FIX H4: Falls back to API key if available on failure
*/
- private async doRefreshToken(): Promise<string> {
- if (!this.credentials) {
- throw terminalCredentialError(
- "No Kimi OAuth credentials found. Please run `claudish login kimi` first."
- );
- }
-
+ private async doRefreshToken(current: KimiCredentials): Promise<KimiCredentials> {
log("[KimiOAuth] Refreshing access token");
const url = `${OAUTH_CONFIG.authHost}${OAUTH_CONFIG.tokenPath}`;
@@ -503,7 +561,7 @@ export class KimiOAuth {
const body = new URLSearchParams({
client_id: OAUTH_CONFIG.clientId,
grant_type: "refresh_token",
- refresh_token: this.credentials.refresh_token,
+ refresh_token: current.refresh_token,
});
// The request and its body are network: a failure of either keeps its cause
@@ -572,20 +630,17 @@ export class KimiOAuth {
const expiresIn = typeof tokens.expires_in === "number" ? tokens.expires_in : 3600;
const updatedCredentials: KimiCredentials = {
access_token: tokens.access_token,
- refresh_token: tokens.refresh_token || this.credentials.refresh_token,
+ refresh_token: tokens.refresh_token || current.refresh_token,
expires_at: Date.now() + expiresIn * 1000,
- scope: tokens.scope ?? this.credentials.scope,
- token_type: tokens.token_type ?? this.credentials.token_type,
+ scope: tokens.scope ?? current.scope,
+ token_type: tokens.token_type ?? current.token_type,
};
- this.saveCredentials(updatedCredentials);
- this.credentials = updatedCredentials;
-
log(
`[KimiOAuth] Token refreshed, valid until ${new Date(updatedCredentials.expires_at).toISOString()}`
);
- return updatedCredentials.access_token;
+ return updatedCredentials;
}
/**
@@ -595,11 +650,11 @@ export class KimiOAuth {
*/
private rejectLogin(failure: Error): never {
log(`[KimiOAuth] Refresh rejected: ${failure.message}`);
- const credPath = this.getCredentialsPath();
+ const credPath = kimiOAuthPath();
if (existsSync(credPath)) {
unlinkSync(credPath);
}
- this.credentials = null;
+ this.state.forget();
// The fallback SIGNAL, always, carrying the login instruction as its cause.
// WHICH key may answer is not this login's decision: one KimiOAuth serves
@@ -616,65 +671,13 @@ export class KimiOAuth {
),
});
}
+}
- /**
- * Load credentials from file
- */
- private loadCredentials(): KimiCredentials | null {
- const credPath = this.getCredentialsPath();
-
- if (!existsSync(credPath)) {
- return null;
- }
-
- try {
- const data = readFileSync(credPath, "utf-8");
- const credentials = JSON.parse(data) as KimiCredentials;
-
- // Validate structure
- if (
- !credentials.access_token ||
- !credentials.refresh_token ||
- !credentials.expires_at ||
- !credentials.scope ||
- !credentials.token_type
- ) {
- log("[KimiOAuth] Invalid credentials file structure");
- return null;
- }
-
- log("[KimiOAuth] Loaded credentials from file");
- return credentials;
- } catch (e: any) {
- log(`[KimiOAuth] Failed to load credentials: ${e.message}`);
- return null;
- }
- }
-
- /**
- * Save credentials to file with 0600 permissions
- */
- private saveCredentials(credentials: KimiCredentials): void {
- const credPath = this.getCredentialsPath();
- const claudishDir = join(homedir(), ".claudish");
-
- // Ensure directory exists
- if (!existsSync(claudishDir)) {
- const { mkdirSync } = require("node:fs");
- mkdirSync(claudishDir, { recursive: true });
- }
-
- // Atomically create file with secure permissions (0600) to prevent race condition
- const fd = openSync(credPath, "w", 0o600);
- try {
- const data = JSON.stringify(credentials, null, 2);
- writeSync(fd, data, 0, "utf-8");
- } finally {
- closeSync(fd);
- }
-
- log(`[KimiOAuth] Credentials saved to ${credPath}`);
- }
+/** The terminal error for a process with no Kimi login. */
+function noKimiCredentialsError(): Error {
+ return terminalCredentialError(
+ "No Kimi OAuth credentials found. Please run `claudish login kimi` first."
+ );
}
/**
@@ -700,7 +703,7 @@ export async function getValidKimiAccessToken(): Promise<string> {
*/
export function hasKimiOAuthCredentials(): boolean {
try {
- const credPath = join(homedir(), ".claudish", "kimi-oauth.json");
+ const credPath = kimiOAuthPath();
if (!existsSync(credPath)) return false;
const data = JSON.parse(readFileSync(credPath, "utf-8"));