Skip to content

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

23.6 KB
Raw Blame
/**
 * Kimi OAuth Authentication Manager
 *
 * Handles Device Authorization Grant (RFC 8628) for Kimi/Moonshot AI API access.
 * Supports:
 * - Device authorization flow with browser-based user authorization
 * - Secure credential storage with 0600 permissions
 * - Automatic token refresh with 5-minute buffer
 * - Singleton pattern for shared token management
 * - Persistent device ID for platform headers
 * - Network retry with exponential backoff
 * - API key fallback on refresh failure
 *
 * Credentials stored at: ~/.claudish/kimi-oauth.json
 * Device ID stored at: ~/.claudish/kimi-device-id
 */

import { exec } from "node:child_process";
import { randomBytes } from "node:crypto";
import {
  closeSync,
  existsSync,
  mkdirSync,
  openSync,
  readFileSync,
  unlinkSync,
  writeSync,
} from "node:fs";
import { homedir, hostname, platform, release } from "node:os";
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,
  terminalCredentialError,
} from "./credentials/credential-error.js";

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
 */
export interface KimiCredentials {
  access_token: string;
  refresh_token: string;
  expires_at: number; // Unix timestamp (ms)
  scope: string;
  token_type: string;
}

/**
 * Device authorization response
 */
interface DeviceAuthorization {
  user_code: string;
  device_code: string;
  verification_uri: string;
  verification_uri_complete: string;
  expires_in: number;
  interval: number;
}

/**
 * Token response
 */
interface TokenResponse {
  access_token: string;
  refresh_token?: string;
  expires_in: number;
  scope: string;
  token_type: string;
  error?: string;
  error_description?: string;
}

/**
 * OAuth configuration for Kimi/Moonshot AI
 */
const OAUTH_CONFIG = {
  clientId: "17e5f671-d194-4dfb-9706-5516cb48c098",
  authHost: "https://auth.kimi.com",
  deviceAuthPath: "/api/oauth/device_authorization",
  tokenPath: "/api/oauth/token",
};

/**
 * Manages OAuth authentication for Kimi/Moonshot AI API
 */
export class KimiOAuth {
  private static instance: KimiOAuth | 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
  /** Persistent device ID, loaded (or created) on first use, then cached. */
  private deviceIdCache: string | null = null;

  /**
   * Get singleton instance
   */
  static getInstance(): KimiOAuth {
    if (!KimiOAuth.instance) {
      KimiOAuth.instance = new KimiOAuth();
    }
    return KimiOAuth.instance;
  }

  private static newFileState(): CredentialFileState<KimiCredentials> {
    return new CredentialFileState<KimiCredentials>({
      path: kimiOAuthPath,
      validate: isKimiCredentials,
      label: "KimiOAuth",
    });
  }

  /**
   * 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() {}

  /**
   * 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 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.state.syncFromDisk();
    this.refreshPromise = null;
  }

  /**
   * 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 {
    this.state.syncFromDisk();
    const current = this.state.value;
    return current !== null && !!current.refresh_token;
  }

  /** 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. Called on the first request or login, then
   * cached in the instance.
   */
  private loadOrCreateDeviceId(): string {
    const deviceIdPath = kimiDeviceIdPath();
    const claudishDir = dirname(deviceIdPath);

    // Ensure directory exists
    if (!existsSync(claudishDir)) {
      mkdirSync(claudishDir, { recursive: true });
    }

    // Try to load existing device ID
    if (existsSync(deviceIdPath)) {
      try {
        const deviceId = readFileSync(deviceIdPath, "utf-8").trim();
        if (deviceId) {
          return deviceId;
        }
      } catch (e: any) {
        log(`[KimiOAuth] Failed to load device ID: ${e.message}`);
      }
    }

    // Generate new device ID (UUID v4)
    const deviceId = randomBytes(16)
      .toString("hex")
      .replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");

    // Save to file
    try {
      const fd = openSync(deviceIdPath, "w", 0o600);
      try {
        writeSync(fd, deviceId, 0, "utf-8");
      } finally {
        closeSync(fd);
      }
      log(`[KimiOAuth] New device ID created: ${deviceId}`);
    } catch (e: any) {
      log(`[KimiOAuth] Failed to save device ID: ${e.message}`);
    }

    return deviceId;
  }

  /**
   * Get version from generated version.ts
   */
  private getVersion(): string {
    return VERSION;
  }

  /**
   * Get platform headers (X-Msh-*)
   * Uses cached device ID from constructor
   */
  getPlatformHeaders(): Record<string, string> {
    return {
      "X-Msh-Platform": "claudish",
      "X-Msh-Version": this.getVersion(),
      "X-Msh-Device-Name": hostname(),
      "X-Msh-Device-Model": `${platform()}-${process.arch}`,
      "X-Msh-Os-Version": release(),
      "X-Msh-Device-Id": this.deviceId,
    };
  }

  /**
   * Start OAuth login flow (Device Authorization Grant)
   */
  async login(): Promise<void> {
    log("[KimiOAuth] Starting Device Authorization Grant flow");

    // Step 1: Request device authorization
    const deviceAuth = await this.requestDeviceAuthorization();

    // Step 2: Display user code and open browser
    console.log("\n🔐 Kimi OAuth Login");
    console.log("═".repeat(60));
    console.log("\nPlease authorize this device:");
    console.log(`\n  Visit: ${deviceAuth.verification_uri_complete}`);
    console.log(`  User Code: ${deviceAuth.user_code}`);
    console.log("\nWaiting for authorization...");

    await this.openBrowser(deviceAuth.verification_uri_complete);

    // Step 3: Poll for token
    const tokens = await this.pollForToken(
      deviceAuth.device_code,
      deviceAuth.interval,
      deviceAuth.expires_in
    );

    // Step 4: Save credentials
    const credentials: KimiCredentials = {
      access_token: tokens.access_token,
      refresh_token: tokens.refresh_token!,
      expires_at: Date.now() + tokens.expires_in * 1000,
      scope: tokens.scope,
      token_type: tokens.token_type,
    };

    // 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");
  }

  /**
   * Request device authorization from Kimi OAuth server
   */
  private async requestDeviceAuthorization(): Promise<DeviceAuthorization> {
    log("[KimiOAuth] Requesting device authorization");

    const url = `${OAUTH_CONFIG.authHost}${OAUTH_CONFIG.deviceAuthPath}`;
    const headers = {
      "Content-Type": "application/x-www-form-urlencoded",
      ...this.getPlatformHeaders(),
    };

    const body = new URLSearchParams({
      client_id: OAUTH_CONFIG.clientId,
    });

    try {
      const response = await fetch(url, {
        method: "POST",
        headers,
        body,
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`Device authorization failed: ${response.status} - ${errorText}`);
      }

      const data = (await response.json()) as DeviceAuthorization;

      if (!data.device_code || !data.user_code || !data.verification_uri_complete) {
        throw new Error("Invalid device authorization response");
      }

      log(
        `[KimiOAuth] Device authorization received: ${data.user_code} (expires in ${data.expires_in}s)`
      );

      return data;
    } catch (e: any) {
      throw new Error(`Failed to request device authorization: ${e.message}`);
    }
  }

  /**
   * Poll for token (RFC 8628 compliant)
   * FIX H2: Implements slow_down backoff (+5s per occurrence)
   * FIX H3: Network retry with exponential backoff
   */
  private async pollForToken(
    deviceCode: string,
    interval: number,
    expiresIn: number
  ): Promise<TokenResponse> {
    log(`[KimiOAuth] Starting polling (interval: ${interval}s, timeout: ${expiresIn}s)`);

    const startTime = Date.now();
    const timeoutMs = expiresIn * 1000;
    let currentInterval = interval * 1000; // Convert to ms

    while (Date.now() - startTime < timeoutMs) {
      // Wait for the current interval before polling
      await new Promise((resolve) => setTimeout(resolve, currentInterval));

      // Poll with retry logic (FIX H3)
      const result = await this.pollForTokenWithRetry(deviceCode);

      // Handle different response types
      if (result.error) {
        if (result.error === "authorization_pending") {
          // User hasn't authorized yet, continue polling
          log("[KimiOAuth] Authorization pending...");
          continue;
        }
        if (result.error === "slow_down") {
          // FIX H2: RFC 8628 Section 3.5 - increase interval by 5 seconds
          currentInterval += 5000;
          log(`[KimiOAuth] Slow down requested, new interval: ${currentInterval / 1000}s`);
          continue;
        }
        if (result.error === "expired_token") {
          throw new Error("Device code expired. Please run `claudish login kimi` again.");
        }
        if (result.error === "access_denied") {
          throw new Error("Authorization denied by user.");
        }
        throw new Error(`OAuth error: ${result.error} - ${result.error_description}`);
      }

      // Success!
      if (result.access_token && result.refresh_token) {
        log("[KimiOAuth] Token received successfully");
        return result;
      }

      // Unexpected response
      throw new Error("Invalid token response (missing access_token or refresh_token)");
    }

    throw new Error(`Authorization timed out after ${expiresIn} seconds.`);
  }

  /**
   * Poll for token with network retry (FIX H3)
   * Max 3 retries with exponential backoff (1s, 2s, 4s)
   */
  private async pollForTokenWithRetry(deviceCode: string, retryCount = 0): Promise<TokenResponse> {
    const maxRetries = 3;
    const backoffMs = 2 ** retryCount * 1000; // 1s, 2s, 4s

    try {
      const url = `${OAUTH_CONFIG.authHost}${OAUTH_CONFIG.tokenPath}`;
      const headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        ...this.getPlatformHeaders(),
      };

      const body = new URLSearchParams({
        client_id: OAUTH_CONFIG.clientId,
        device_code: deviceCode,
        grant_type: "urn:ietf:params:oauth:grant-type:device_code",
      });

      const response = await fetch(url, {
        method: "POST",
        headers,
        body,
      });

      // Parse response (could be success or error)
      const data = (await response.json()) as TokenResponse;
      return data;
    } catch (e: any) {
      // Network error - retry if not exhausted
      if (retryCount < maxRetries) {
        log(
          `[KimiOAuth] Network error during polling (attempt ${retryCount + 1}/${maxRetries}), retrying in ${backoffMs}ms...`
        );
        await new Promise((resolve) => setTimeout(resolve, backoffMs));
        return this.pollForTokenWithRetry(deviceCode, retryCount + 1);
      }

      throw new Error(`Network error during token polling: ${e.message}`);
    }
  }

  /**
   * Open URL in default browser
   * FIX M4: Catch errors silently, always show URL
   */
  private async openBrowser(url: string): Promise<void> {
    const currentPlatform = platform();

    try {
      if (currentPlatform === "darwin") {
        await execAsync(`open "${url}"`);
      } else if (currentPlatform === "win32") {
        await execAsync(`start "${url}"`);
      } else {
        // Linux/Unix
        await execAsync(`xdg-open "${url}"`);
      }
    } catch (e: any) {
      // Silently catch browser open errors (URL already displayed to user)
      log(`[KimiOAuth] Failed to open browser: ${e.message}`);
    }
  }

  /**
   * Logout - delete stored credentials
   */
  async logout(): Promise<void> {
    const credPath = kimiOAuthPath();

    if (existsSync(credPath)) {
      unlinkSync(credPath);
      log("[KimiOAuth] Credentials deleted");
    }

    this.state.forget();
  }

  /**
   * Get valid access token, refreshing if needed
   * FIX C2: Promise caching with .finally() cleanup
   */
  async getAccessToken(): Promise<string> {
    // If refresh already in progress, wait for it
    if (this.refreshPromise) {
      log("[KimiOAuth] Waiting for in-progress refresh");
      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
    const current = this.state.value;
    if (!current) throw noKimiCredentialsError();

    // Check if token is still valid (with 5-minute buffer)
    if (this.isCredentialValid(current)) {
      return current.access_token;
    }

    // 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 = refreshAndCommit(
      this.state,
      (credentials) => this.doRefreshToken(credentials),
      {
        isValid: (credentials) => this.isCredentialValid(credentials),
        noCredentials: noKimiCredentialsError,
      },
      "KimiOAuth"
    ).finally(() => {
      this.refreshPromise = null;
    });

    return this.refreshPromise;
  }

  /**
   * Check if a token is still valid (with 5-minute buffer)
   * FIX H5: Includes 5-minute buffer
   */
  private isCredentialValid(credentials: KimiCredentials): boolean {
    return Date.now() < credentials.expires_at - this.tokenRefreshMargin;
  }

  /**
   * 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(current: KimiCredentials): Promise<KimiCredentials> {
    log("[KimiOAuth] Refreshing access token");

    const url = `${OAUTH_CONFIG.authHost}${OAUTH_CONFIG.tokenPath}`;
    const headers = {
      "Content-Type": "application/x-www-form-urlencoded",
      ...this.getPlatformHeaders(),
    };
    const body = new URLSearchParams({
      client_id: OAUTH_CONFIG.clientId,
      grant_type: "refresh_token",
      refresh_token: current.refresh_token,
    });

    // The request and its body are network: a failure of either keeps its cause
    // and the endpoint, so connection recovery classifies it, and the login on
    // disk is left alone (the grok-oauth.ts split).
    let response: Response;
    let text: string;
    try {
      response = await fetch(url, { method: "POST", headers, body });
      text = await response.text();
    } catch (e) {
      log(`[KimiOAuth] Could not reach ${url}: ${(e as Error).message}`);
      throw Object.assign(
        new Error(`Could not reach ${url} to refresh the Kimi token: ${(e as Error).message}`, {
          cause: e,
        }),
        { claudishEndpoint: url }
      );
    }

    if (!response.ok) {
      const failure = credentialHttpError(
        `Token refresh failed: ${response.status} - ${text}`,
        response.status
      );
      // A token host that is down or busy (429, 5xx) says nothing about the
      // login: keep it, and let the request retry.
      if (isTransientCredentialError(failure)) throw failure;
      // A CLASSIFIED rejection of the grant is the only case that deletes the
      // stored login: 401/403, or a 400 whose body names `invalid_grant` (the
      // grok-oauth.ts rule). Any other status (a 404/405/407/408 from a proxy
      // in front of the token host, a 400 about something else) is terminal
      // for this request but proves nothing about the login, so it stays.
      const status = response.status;
      const grantRejected =
        status === 401 || status === 403 || (status === 400 && text.includes("invalid_grant"));
      if (!grantRejected) throw failure;
      return await this.rejectLogin(failure, current);
    }

    // A 2xx that is not JSON is a gateway answering for the token host:
    // retryable, and the login stays. A 2xx JSON with no access token does not
    // show the login is dead either: retryable (503), with nothing persisted
    // and nothing deleted.
    let tokens: Partial<TokenResponse>;
    try {
      tokens = JSON.parse(text) as Partial<TokenResponse>;
    } catch {
      throw Object.assign(
        new Error(
          "Kimi token refresh answered with a body that is not JSON; retrying will usually work."
        ),
        { transient: true as const, upstreamStatus: 503 }
      );
    }
    if (typeof tokens?.access_token !== "string" || tokens.access_token.length === 0) {
      throw Object.assign(
        new Error(
          "The Kimi token host answered without an access token; nothing was saved. Retrying will usually work; run `claudish login kimi` if this persists."
        ),
        { transient: true as const, upstreamStatus: 503 }
      );
    }

    // Update credentials (keep existing refresh token if new one not provided)
    const expiresIn = typeof tokens.expires_in === "number" ? tokens.expires_in : 3600;
    const updatedCredentials: KimiCredentials = {
      access_token: tokens.access_token,
      refresh_token: tokens.refresh_token || current.refresh_token,
      expires_at: Date.now() + expiresIn * 1000,
      scope: tokens.scope ?? current.scope,
      token_type: tokens.token_type ?? current.token_type,
    };

    log(
      `[KimiOAuth] Token refreshed, valid until ${new Date(updatedCredentials.expires_at).toISOString()}`
    );

    return updatedCredentials;
  }

  /**
   * The token host REJECTED the grant (401/403, or 400 `invalid_grant`): the stored
   * login cannot recover, so it is deleted, and the caller gets the fallback
   * signal or the login instruction.
   */
  private async rejectLogin(failure: Error, rejected: KimiCredentials): Promise<never> {
    log(`[KimiOAuth] Refresh rejected: ${failure.message}`);
    // Delete only the login that was rejected. If another process logged in since
    // (`claudish login kimi` in another terminal), its file is kept, and
    // refreshAndCommit adopts it after this throw instead of answering with the
    // fallback. An unreadable file (possibly that login mid-write) is kept too.
    await this.state.deleteIfUnchanged(rejected);

    // The fallback SIGNAL, always, carrying the login instruction as its cause.
    // WHICH key may answer is not this login's decision: one KimiOAuth serves
    // both kimi@ (Moonshot, metered) and kc@ (the Coding Plan), and each
    // composite owns its own product's key (kimi-credential.ts). The composite
    // falls back only when ITS key is present, and otherwise throws the cause:
    // a kc@ user with no KIMI_CODING_API_KEY sees "run `claudish login kimi`",
    // and MOONSHOT_API_KEY never signs kc@.
    log("[KimiOAuth] Login rejected; the product's own API key may answer instead");
    throw new Error("OAuth_FALLBACK_TO_API_KEY", {
      cause: terminalCredentialError(
        `Your Kimi login was rejected (${failure.message}). Run \`claudish login kimi\` to sign in again.`,
        (failure as { upstreamStatus?: number }).upstreamStatus
      ),
    });
  }
}

/** 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."
  );
}

/**
 * Get the shared KimiOAuth instance
 */
export function getKimiOAuth(): KimiOAuth {
  return KimiOAuth.getInstance();
}

/**
 * Get a valid access token (refreshing if needed)
 * Helper function for handlers to use
 */
export async function getValidKimiAccessToken(): Promise<string> {
  const oauth = KimiOAuth.getInstance();
  return oauth.getAccessToken();
}

/**
 * Check if Kimi OAuth credentials are available AND valid (sync check)
 * CRITICAL: Includes expiry check with 5-minute buffer
 * This is called by the provider resolver AFTER checking for API key env vars (FR5 priority)
 */
export function hasKimiOAuthCredentials(): boolean {
  try {
    const credPath = kimiOAuthPath();
    if (!existsSync(credPath)) return false;

    const data = JSON.parse(readFileSync(credPath, "utf-8"));
    // Check if token exists and is not expired (with 5-minute buffer)
    const now = Date.now();
    const bufferMs = 5 * 60 * 1000; // 5 minutes
    return !!(
      data.access_token &&
      data.refresh_token &&
      data.expires_at &&
      data.expires_at > now + bufferMs
    );
  } catch {
    return false;
  }
}