Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy
Rust
kimi: scaffold provider with device-code login and token refresh
Raine Virta9286e9f65fe1
diff --git a/src/providers/kimi/auth/constants.ts b/src/providers/kimi/auth/constants.tsnew file mode 100644index 0000000..32d5d3d--- /dev/null+++ b/src/providers/kimi/auth/constants.ts@@ -0,0 +1,7 @@+export const CLIENT_ID = "17e5f671-d194-4dfb-9706-5516cb48c098"+export const OAUTH_HOST = process.env.KIMI_OAUTH_HOST ?? "https://auth.kimi.com"+export const API_BASE_URL = process.env.KIMI_BASE_URL ?? "https://api.kimi.com/coding/v1"+// Masquerade as kimi-cli so the server accepts us. Bumping this in lockstep+// with kimi-cli releases may become necessary.+export const KIMI_CLI_VERSION = "1.37.0"+export const REFRESH_MARGIN_MS = 5 * 60 * 1000diff --git a/src/providers/kimi/auth/device-id.ts b/src/providers/kimi/auth/device-id.tsnew file mode 100644index 0000000..f42ac7d--- /dev/null+++ b/src/providers/kimi/auth/device-id.ts@@ -0,0 +1,22 @@+import { mkdir, readFile, writeFile, chmod } from "node:fs/promises"+import { dirname, join } from "node:path"+import { homedir } from "node:os"++const PATH = join(homedir(), ".config", "claude-code-proxy", "kimi", "device_id")++export async function getDeviceId(): Promise<string> {+ try {+ const raw = await readFile(PATH, "utf8")+ const trimmed = raw.trim()+ if (trimmed) return trimmed+ } catch (err: any) {+ if (err?.code !== "ENOENT") throw err+ }+ const id = crypto.randomUUID().replace(/-/g, "")+ await mkdir(dirname(PATH), { recursive: true })+ await writeFile(PATH, id, { encoding: "utf8", mode: 0o600 })+ try {+ await chmod(PATH, 0o600)+ } catch {}+ return id+}diff --git a/src/providers/kimi/auth/headers.ts b/src/providers/kimi/auth/headers.tsnew file mode 100644index 0000000..bebdf60--- /dev/null+++ b/src/providers/kimi/auth/headers.ts@@ -0,0 +1,30 @@+import { hostname, release, arch, platform } from "node:os"+import { KIMI_CLI_VERSION } from "./constants.ts"+import { getDeviceId } from "./device-id.ts"++function deviceModel(): string {+ const a = arch()+ const p = platform()+ if (p === "darwin") return `macOS ${release()} ${a}`.trim()+ if (p === "win32") return `Windows ${release()} ${a}`.trim()+ return `${p} ${release()} ${a}`.trim()+}++function asciiOnly(value: string, fallback = "unknown"): string {+ // Strip non-ASCII, which would be rejected as an HTTP header value.+ const cleaned = value.replace(/[^\x20-\x7e]/g, "").trim()+ return cleaned || fallback+}++export async function commonHeaders(): Promise<Record<string, string>> {+ const deviceId = await getDeviceId()+ return {+ "X-Msh-Platform": "kimi_cli",+ "X-Msh-Version": KIMI_CLI_VERSION,+ "X-Msh-Device-Name": asciiOnly(hostname()),+ "X-Msh-Device-Model": asciiOnly(deviceModel()),+ "X-Msh-Os-Version": asciiOnly(release()),+ "X-Msh-Device-Id": deviceId,+ "User-Agent": `KimiCLI/${KIMI_CLI_VERSION}`,+ }+}diff --git a/src/providers/kimi/auth/jwt.ts b/src/providers/kimi/auth/jwt.tsnew file mode 100644index 0000000..c606998--- /dev/null+++ b/src/providers/kimi/auth/jwt.ts@@ -0,0 +1,23 @@+interface KimiClaims {+ user_id?: string+ device_id?: string+ scope?: string+ exp?: number+ iat?: number+}++export function decodeClaims(jwt: string): KimiClaims | undefined {+ const parts = jwt.split(".")+ if (parts.length < 2) return undefined+ try {+ const payload = parts[1]!.replace(/-/g, "+").replace(/_/g, "/")+ const padded = payload + "=".repeat((4 - (payload.length % 4)) % 4)+ return JSON.parse(Buffer.from(padded, "base64").toString("utf8")) as KimiClaims+ } catch {+ return undefined+ }+}++export function extractUserId(accessToken: string): string | undefined {+ return decodeClaims(accessToken)?.user_id+}diff --git a/src/providers/kimi/auth/login.ts b/src/providers/kimi/auth/login.tsnew file mode 100644index 0000000..48a8901--- /dev/null+++ b/src/providers/kimi/auth/login.ts@@ -0,0 +1,75 @@+import { CLIENT_ID, OAUTH_HOST } from "./constants.ts"+import { commonHeaders } from "./headers.ts"++export interface TokenResponse {+ access_token: string+ refresh_token: string+ expires_in: number+ scope: string+ token_type: string+}++interface DeviceAuth {+ user_code: string+ device_code: string+ verification_uri?: string+ verification_uri_complete: string+ expires_in?: number+ interval: number+}++const GRANT_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code"+const POLL_SAFETY_MARGIN_MS = 500++export async function runDeviceLogin(): Promise<TokenResponse> {+ const headers = await commonHeaders()++ const initResp = await fetch(`${OAUTH_HOST}/api/oauth/device_authorization`, {+ method: "POST",+ headers: { ...headers, "Content-Type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({ client_id: CLIENT_ID }).toString(),+ })+ if (!initResp.ok) {+ throw new Error(`Device authorization failed: ${initResp.status} ${await initResp.text()}`)+ }+ const auth = (await initResp.json()) as DeviceAuth+ const intervalMs = Math.max(auth.interval || 5, 1) * 1000++ console.log(`\nVisit: ${auth.verification_uri_complete}`)+ console.log(`Code: ${auth.user_code}\n`)++ while (true) {+ const resp = await fetch(`${OAUTH_HOST}/api/oauth/token`, {+ method: "POST",+ headers: { ...headers, "Content-Type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({+ client_id: CLIENT_ID,+ device_code: auth.device_code,+ grant_type: GRANT_DEVICE_CODE,+ }).toString(),+ })++ if (resp.status === 200) {+ return (await resp.json()) as TokenResponse+ }++ // Pending / slow_down / expired come back as non-200 with a JSON error payload.+ const body = (await resp.json().catch(() => ({}))) as {+ error?: string+ error_description?: string+ }+ const error = body.error ?? `http_${resp.status}`++ if (error === "expired_token") {+ throw new Error("Device code expired. Run login again.")+ }+ if (error !== "authorization_pending" && error !== "slow_down") {+ throw new Error(+ `Device token poll failed (${resp.status}): ${error}${+ body.error_description ? ` — ${body.error_description}` : ""+ }`,+ )+ }+ await new Promise((r) => setTimeout(r, intervalMs + POLL_SAFETY_MARGIN_MS))+ }+}diff --git a/src/providers/kimi/auth/manager.ts b/src/providers/kimi/auth/manager.tsnew file mode 100644index 0000000..bd148b3--- /dev/null+++ b/src/providers/kimi/auth/manager.ts@@ -0,0 +1,136 @@+import { CLIENT_ID, OAUTH_HOST, REFRESH_MARGIN_MS } from "./constants.ts"+import { commonHeaders } from "./headers.ts"+import { extractUserId } from "./jwt.ts"+import type { TokenResponse } from "./login.ts"+import { clearAuth, loadAuth, saveAuth, type StoredAuth } from "./token-store.ts"+import { createLogger } from "../../../log.ts"++const log = createLogger("kimi.auth")++const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504])+const MAX_REFRESH_ATTEMPTS = 3++let cached: StoredAuth | undefined+let inflight: Promise<StoredAuth> | undefined++export class KimiAuthUnauthorizedError extends Error {+ constructor(message: string) {+ super(message)+ this.name = "KimiAuthUnauthorizedError"+ }+}++export async function getAuth(): Promise<StoredAuth> {+ if (!cached) {+ const stored = await loadAuth()+ if (!stored) throw new Error("Not authenticated. Run: claude-code-proxy kimi auth login")+ cached = stored+ }+ if (cached.expires - REFRESH_MARGIN_MS > Date.now()) {+ return cached+ }+ if (inflight) return inflight+ inflight = refreshNow(cached).finally(() => {+ inflight = undefined+ })+ return inflight+}++export async function forceRefresh(): Promise<StoredAuth> {+ if (!cached) {+ const stored = await loadAuth()+ if (!stored) throw new Error("Not authenticated")+ cached = stored+ }+ if (inflight) return inflight+ inflight = refreshNow(cached).finally(() => {+ inflight = undefined+ })+ return inflight+}++export async function persistInitialTokens(tokens: TokenResponse): Promise<StoredAuth> {+ const auth = tokensToStored(tokens)+ await saveAuth(auth)+ cached = auth+ return auth+}++export function resetCache(): void {+ cached = undefined+}++function tokensToStored(tokens: TokenResponse): StoredAuth {+ return {+ access: tokens.access_token,+ refresh: tokens.refresh_token,+ expires: Date.now() + (tokens.expires_in ?? 900) * 1000,+ scope: tokens.scope,+ userId: extractUserId(tokens.access_token),+ }+}++async function refreshNow(current: StoredAuth): Promise<StoredAuth> {+ if (!current.refresh) {+ throw new KimiAuthUnauthorizedError("No refresh token stored; re-authenticate")+ }+ const headers = await commonHeaders()++ let lastErr: unknown+ for (let attempt = 0; attempt < MAX_REFRESH_ATTEMPTS; attempt++) {+ let resp: Response+ try {+ resp = await fetch(`${OAUTH_HOST}/api/oauth/token`, {+ method: "POST",+ headers: { ...headers, "Content-Type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({+ client_id: CLIENT_ID,+ grant_type: "refresh_token",+ refresh_token: current.refresh,+ }).toString(),+ })+ } catch (err) {+ lastErr = err+ log.warn("refresh network error", { attempt, err: String(err) })+ await backoff(attempt)+ continue+ }++ if (resp.status === 200) {+ const tokens = (await resp.json()) as TokenResponse+ const next: StoredAuth = {+ ...tokensToStored(tokens),+ refresh: tokens.refresh_token || current.refresh,+ userId: extractUserId(tokens.access_token) || current.userId,+ }+ await saveAuth(next)+ cached = next+ return next+ }++ if (resp.status === 401 || resp.status === 403) {+ // Refresh token is dead; clear local state so the next login is clean.+ cached = undefined+ await clearAuth().catch(() => undefined)+ const body = (await resp.json().catch(() => ({}))) as { error_description?: string }+ throw new KimiAuthUnauthorizedError(+ body.error_description || `Token refresh unauthorized (${resp.status})`,+ )+ }++ if (!RETRYABLE_STATUSES.has(resp.status)) {+ const text = await resp.text().catch(() => "")+ throw new Error(`Token refresh failed: ${resp.status} ${text}`)+ }++ lastErr = new Error(`Token refresh failed: ${resp.status}`)+ log.warn("refresh retryable error", { attempt, status: resp.status })+ await backoff(attempt)+ }+ throw new Error(`Token refresh failed after ${MAX_REFRESH_ATTEMPTS} attempts: ${lastErr}`)+}++function backoff(attempt: number): Promise<void> {+ const ms = 2 ** attempt * 1000+ return new Promise((r) => setTimeout(r, ms))+}diff --git a/src/providers/kimi/auth/token-store.ts b/src/providers/kimi/auth/token-store.tsnew file mode 100644index 0000000..cf7878e--- /dev/null+++ b/src/providers/kimi/auth/token-store.ts@@ -0,0 +1,109 @@+import { mkdir, readFile, writeFile, chmod, unlink, rename } from "node:fs/promises"+import { dirname, join } from "node:path"+import { homedir } from "node:os"++export interface StoredAuth {+ access: string+ refresh: string+ expires: number+ scope?: string+ userId?: string+}++const DIR = join(homedir(), ".config", "claude-code-proxy", "kimi")+const FILE = join(DIR, "auth.json")+const KEYCHAIN_SERVICE = "claude-code-proxy.kimi"+const KEYCHAIN_ACCOUNT = "auth"++export async function loadAuth(): Promise<StoredAuth | undefined> {+ if (process.platform === "darwin") {+ const raw = await readKeychain().catch((err: Error & { code?: number }) => {+ if (err.code === 44) return undefined+ throw err+ })+ if (!raw) return undefined+ return JSON.parse(raw) as StoredAuth+ }++ try {+ const raw = await readFile(FILE, "utf8")+ return JSON.parse(raw) as StoredAuth+ } catch (err: any) {+ if (err?.code === "ENOENT") return undefined+ throw err+ }+}++export async function saveAuth(auth: StoredAuth): Promise<void> {+ if (process.platform === "darwin") {+ await runSecurity([+ "add-generic-password",+ "-U",+ "-a",+ KEYCHAIN_ACCOUNT,+ "-s",+ KEYCHAIN_SERVICE,+ "-w",+ JSON.stringify(auth),+ ])+ return+ }++ await mkdir(dirname(FILE), { recursive: true })+ const tmp = `${FILE}.${process.pid}.${Date.now()}.tmp`+ await writeFile(tmp, JSON.stringify(auth, null, 2), { encoding: "utf8", mode: 0o600 })+ try {+ await chmod(tmp, 0o600)+ } catch {}+ await rename(tmp, FILE)+}++export async function clearAuth(): Promise<void> {+ if (process.platform === "darwin") {+ await runSecurity(["delete-generic-password", "-a", KEYCHAIN_ACCOUNT, "-s", KEYCHAIN_SERVICE]).catch(+ (err: Error & { code?: number }) => {+ if (err.code !== 44) throw err+ },+ )+ return+ }++ try {+ await unlink(FILE)+ } catch (err: any) {+ if (err?.code !== "ENOENT") throw err+ }+}++export function authPath(): string {+ return process.platform === "darwin" ? "macOS Keychain" : FILE+}++async function readKeychain(): Promise<string> {+ const { stdout } = await runSecurity([+ "find-generic-password",+ "-w",+ "-a",+ KEYCHAIN_ACCOUNT,+ "-s",+ KEYCHAIN_SERVICE,+ ])+ return stdout.trim()+}++async function runSecurity(args: string[]): Promise<{ stdout: string; stderr: string }> {+ const proc = Bun.spawn(["security", ...args], { stdout: "pipe", stderr: "pipe" })+ const [stdout, stderr, exitCode] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ proc.exited,+ ])+ if (exitCode !== 0) {+ const err = new Error(stderr.trim() || `security exited with ${exitCode}`) as Error & {+ code?: number+ }+ err.code = exitCode+ throw err+ }+ return { stdout, stderr }+}diff --git a/src/providers/kimi/index.ts b/src/providers/kimi/index.tsnew file mode 100644index 0000000..1621ea0--- /dev/null+++ b/src/providers/kimi/index.ts@@ -0,0 +1,51 @@+import type { Provider, CliHandlers, RequestContext } from "../types.ts"+import type { AnthropicRequest } from "../../anthropic/schema.ts"+import { runDeviceLogin } from "./auth/login.ts"+import { persistInitialTokens } from "./auth/manager.ts"+import { loadAuth, clearAuth, authPath } from "./auth/token-store.ts"++function notImplemented(_body: AnthropicRequest, _ctx: RequestContext): Promise<Response> {+ return Promise.resolve(+ new Response(+ JSON.stringify({+ type: "error",+ error: { type: "api_error", message: "kimi provider: chat not implemented yet" },+ }),+ { status: 501, headers: { "content-type": "application/json" } },+ ),+ )+}++const cli: CliHandlers = {+ async login() {+ const tokens = await runDeviceLogin()+ const saved = await persistInitialTokens(tokens)+ console.log(`Auth saved in ${authPath()}`)+ if (saved.userId) console.log(`User: ${saved.userId}`)+ const secs = Math.floor((saved.expires - Date.now()) / 1000)+ console.log(`Expires in ${secs}s`)+ },+ async status() {+ const auth = await loadAuth()+ if (!auth) {+ console.log("Not authenticated")+ process.exit(1)+ }+ const ms = auth.expires - Date.now()+ console.log(`User: ${auth.userId ?? "(none)"}`)+ console.log(`Expires: ${new Date(auth.expires).toISOString()} (in ${Math.floor(ms / 1000)}s)`)+ console.log(`Scope: ${auth.scope ?? "(none)"}`)+ console.log(`Storage: ${authPath()}`)+ },+ async logout() {+ await clearAuth()+ console.log("Logged out")+ },+}++export const kimiProvider: Provider = {+ name: "kimi",+ handleMessages: notImplemented,+ handleCountTokens: notImplemented,+ cli,+}diff --git a/src/providers/registry.ts b/src/providers/registry.tsindex bbcb39b..f2860da 100644--- a/src/providers/registry.ts+++ b/src/providers/registry.ts@@ -1,8 +1,10 @@import type { Provider } from "./types.ts"import { codexProvider } from "./codex/index.ts"+import { kimiProvider } from "./kimi/index.ts"const PROVIDERS: Record<string, Provider> = {codex: codexProvider,+ kimi: kimiProvider,}export function getProvider(name?: string): Provider {