From dcd91019b00927eb976902dfa1ac2407af896d1a Mon Sep 17 00:00:00 2001 From: Pesres Kabo <2389400626lh@gmail.com> Date: Sat, 5 Dec 2026 10:24:15 +0800 Subject: [PATCH] fix(kimi): resolve dynamic OAuth credential filename from config.toml --- app/electron/quota/kimi.test.ts | 26 +++++ app/electron/quota/kimi.ts | 189 ++++++++++++++++++++++++++++---- src/quota/kimi.ts | 189 ++++++++++++++++++++++++++++---- tests/quota-kimi.test.ts | 186 +++++++++++++++++++++++++++++++ 4 files changed, 548 insertions(+), 42 deletions(-) create mode 100644 tests/quota-kimi.test.ts diff --git a/app/electron/quota/kimi.test.ts b/app/electron/quota/kimi.test.ts index 8338103d3..eabed3b44 100644 --- a/app/electron/quota/kimi.test.ts +++ b/app/electron/quota/kimi.test.ts @@ -157,4 +157,30 @@ describe('Kimi quota fetch', () => { expect(logged).not.toMatch(/eyJhbGciOiJFUzI1NiJ9|leak|\0/) expect(logged).toContain('[REDACTED]') }) + + it('resolves dynamic OAuth credential filenames from config.toml and falls back to kimi-code-env-*.json', async () => { + const fetchMock = vi.fn(async () => okJson(liveBody)) + const readFile = vi.fn(async (filePath: string) => + filePath.endsWith('kimi-code-env-win281.json') ? fresh : null, + ) + const fromConfig = await fetchKimiQuota({ + fetch: fetchMock, + readFile, + readConfigFile: vi.fn(async () => '[providers."managed:kimi-code".oauth]\nstorage = "file"\nkey = "oauth/kimi-code-env-win281"\n'), + listCredentialsDir: vi.fn(async () => []), + now, + }) + expect(fromConfig.quota.connection).toBe('connected') + + const fromScan = await fetchKimiQuota({ + fetch: fetchMock, + readFile: vi.fn(async (filePath: string) => + filePath.endsWith('kimi-code-env-fallback.json') ? fresh : null, + ), + readConfigFile: vi.fn(async () => null), + listCredentialsDir: vi.fn(async () => ['unrelated.json', 'kimi-code-env-fallback.json']), + now, + }) + expect(fromScan.quota.connection).toBe('connected') + }) }) diff --git a/app/electron/quota/kimi.ts b/app/electron/quota/kimi.ts index 166fe8332..c9968fbaa 100644 --- a/app/electron/quota/kimi.ts +++ b/app/electron/quota/kimi.ts @@ -6,10 +6,13 @@ // X-Msh-Device-Id). Numeric fields have shipped as both JSON numbers and // strings, and the reset stamp under several spellings, so decode leniently. // -// Credential: the Kimi CLI's own ~/.kimi-code/credentials/kimi-code.json, -// read-only. Access tokens live ~15 minutes and ONLY the Kimi CLI refreshes -// them — we never refresh and never write, so an expired or rejected token is a -// terminal state whose footer tells the user to run the Kimi CLI once. +// Credential: the Kimi CLI's OAuth file under ~/.kimi-code/credentials/ +// (resolved from ~/.kimi-code/config.toml, legacy kimi-code.json, or +// kimi-code-env-*.json), read-only. Access tokens live ~15 minutes and ONLY +// the Kimi CLI refreshes them — we never refresh and never write, so an +// expired or rejected token is a terminal state whose footer tells the user +// to run the Kimi CLI once. +import fs from 'node:fs/promises' import os from 'node:os' import path from 'node:path' @@ -18,23 +21,119 @@ import type { QuotaProvider, QuotaWindow } from './types' const USAGE_ENDPOINT = 'https://api.kimi.com/coding/v1/usages' const EXPIRED_FOOTER = ['Login expired. Run the Kimi CLI once, then refresh.'] +const CREDENTIAL_MAX_BYTES = 64 * 1024 +const CONFIG_MAX_BYTES = 64 * 1024 +const SAFE_KEY_STEM_RE = /^[A-Za-z0-9._-]+$/ +const ENV_CREDENTIAL_FILE_RE = /^kimi-code-env-[A-Za-z0-9._-]+\.json$/ +const MANAGED_OAUTH_SECTION_RE = /^providers\s*\.\s*(?:"managed:kimi-code"|'managed:kimi-code')\s*\.\s*oauth$/ -const kimiHome = process.env['KIMI_CODE_HOME'] ?? path.join(os.homedir(), '.kimi-code') +export type ReadConfigFileFn = (filePath: string) => Promise +export type ListCredentialsDirFn = (dirPath: string) => Promise export type KimiDeps = { fetch: typeof fetch - credentialPath: string + credentialPath?: string deviceIdPath: string readFile: typeof readSecureFile + readConfigFile: ReadConfigFileFn + listCredentialsDir: ListCredentialsDirFn now: () => number } -const defaults: KimiDeps = { - fetch: globalThis.fetch, - credentialPath: path.join(kimiHome, 'credentials', 'kimi-code.json'), - deviceIdPath: path.join(kimiHome, 'device_id'), - readFile: readSecureFile, - now: Date.now, +function resolveKimiHome(): string { + const envHome = process.env['KIMI_CODE_HOME']?.trim() + return envHome || path.join(os.homedir(), '.kimi-code') +} + +async function defaultReadConfigFile(filePath: string): Promise { + try { + const stat = await fs.lstat(filePath) + if (stat.isSymbolicLink() || !stat.isFile() || stat.size > CONFIG_MAX_BYTES) return null + return await fs.readFile(filePath, 'utf8') + } catch { + return null + } +} + +async function defaultListCredentialsDir(dirPath: string): Promise { + try { + return await fs.readdir(dirPath) + } catch { + return [] + } +} + +function stripTomlComment(line: string): string { + let inSingle = false + let inDouble = false + let escaped = false + for (let i = 0; i < line.length; i++) { + const ch = line[i]! + if (escaped) { escaped = false; continue } + if (inDouble && ch === '\\') { escaped = true; continue } + if (!inDouble && ch === "'") { inSingle = !inSingle; continue } + if (!inSingle && ch === '"') { inDouble = !inDouble; continue } + if (!inSingle && !inDouble && ch === '#') return line.slice(0, i) + } + return line +} + +function parseTomlStringScalar(rawValue: string): string | null { + const trimmed = rawValue.trim() + if (trimmed.length < 2) return null + if (trimmed.startsWith('"') && trimmed.endsWith('"')) { + try { + const parsed = JSON.parse(trimmed) + return typeof parsed === 'string' ? parsed : null + } catch { + return null + } + } + if (trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1) + return null +} + +/** Extracts `key` from `[providers."managed:kimi-code".oauth]`. */ +export function parseManagedOAuthKey(tomlContent: string): string | null { + let inTargetSection = false + for (const rawLine of tomlContent.split(/\r?\n/)) { + const line = stripTomlComment(rawLine).trim() + if (!line) continue + if (line.startsWith('[') && line.endsWith(']')) { + inTargetSection = MANAGED_OAUTH_SECTION_RE.test(line.slice(1, -1).trim()) + continue + } + if (!inTargetSection) continue + const eqIndex = line.indexOf('=') + if (eqIndex === -1) continue + if (line.slice(0, eqIndex).trim() !== 'key') continue + return parseTomlStringScalar(line.slice(eqIndex + 1)) + } + return null +} + +/** Converts an OAuth `key` (e.g. `"oauth/kimi-code-env-abc"`) into a safe + * single filename inside `credentials/`, rejecting path traversal. */ +export function resolveCredentialFilenameFromKey(rawKey: string): string | null { + if (!rawKey || rawKey.includes('\0') || rawKey.includes('\\')) return null + const normalized = rawKey.startsWith('oauth/') ? rawKey.slice('oauth/'.length) : rawKey + if (!normalized || normalized.includes('/') || normalized.includes('\\') || normalized.includes('..')) return null + const stem = normalized.endsWith('.json') ? normalized.slice(0, -'.json'.length) : normalized + if (!stem || stem === '.' || stem === '..' || !SAFE_KEY_STEM_RE.test(stem)) return null + return `${stem}.json` +} + +function createDeps(options: Partial = {}): KimiDeps { + const kimiHome = resolveKimiHome() + return { + fetch: options.fetch ?? globalThis.fetch, + credentialPath: options.credentialPath, + deviceIdPath: options.deviceIdPath ?? path.join(kimiHome, 'device_id'), + readFile: options.readFile ?? readSecureFile, + readConfigFile: options.readConfigFile ?? defaultReadConfigFile, + listCredentialsDir: options.listCredentialsDir ?? defaultListCredentialsDir, + now: options.now ?? Date.now, + } } function empty(connection: QuotaProvider['connection'], footerLines: string[] = []): QuotaProvider { @@ -50,17 +149,65 @@ function num(value: unknown): number | null { return null } -/** `null` = no usable credential; `'expired'` = present but past its life. */ -async function freshToken(deps: KimiDeps): Promise { - const raw = await deps.readFile(deps.credentialPath, 64 * 1024) - if (!raw) return null - const parsed = JSON.parse(raw) as Record +type TokenInspectResult = { status: 'valid'; token: string } | { status: 'expired' } | { status: 'missing' } + +async function inspectCredentialFile(filePath: string, deps: KimiDeps): Promise { + const raw = await deps.readFile(filePath, CREDENTIAL_MAX_BYTES) + if (!raw) return { status: 'missing' } + let parsed: Record + try { + parsed = JSON.parse(raw) as Record + } catch { + return { status: 'missing' } + } const token = parsed.access_token - if (typeof token !== 'string' || !token) return null + if (typeof token !== 'string' || !token) return { status: 'missing' } const expiresAt = num(parsed.expires_at) // 60s skew, matching the menubar: a token about to die is already useless. - if (expiresAt === null || expiresAt <= deps.now() / 1000 + 60) return 'expired' - return token + if (expiresAt === null || expiresAt <= deps.now() / 1000 + 60) return { status: 'expired' } + return { status: 'valid', token } +} + +/** `null` = no usable credential; `'expired'` = present but past its life. */ +async function freshToken(deps: KimiDeps): Promise { + if (deps.credentialPath) { + const res = await inspectCredentialFile(deps.credentialPath, deps) + return res.status === 'valid' ? res.token : res.status === 'expired' ? 'expired' : null + } + + const kimiHome = resolveKimiHome() + const credentialsDir = path.join(kimiHome, 'credentials') + + // 1. OAuth key configured in /config.toml. + const configRaw = await deps.readConfigFile(path.join(kimiHome, 'config.toml')) + if (configRaw) { + const oauthKey = parseManagedOAuthKey(configRaw) + const filename = oauthKey !== null ? resolveCredentialFilenameFromKey(oauthKey) : null + if (filename) { + const res = await inspectCredentialFile(path.join(credentialsDir, filename), deps) + if (res.status === 'valid') return res.token + if (res.status === 'expired') return 'expired' + } + } + + // 2. Legacy fixed filename. + const legacyRes = await inspectCredentialFile(path.join(credentialsDir, 'kimi-code.json'), deps) + if (legacyRes.status === 'valid') return legacyRes.token + if (legacyRes.status === 'expired') return 'expired' + + // 3. Fallback discovery for dynamically named kimi-code-env-*.json files. + const envFiles = (await deps.listCredentialsDir(credentialsDir)) + .filter(entry => ENV_CREDENTIAL_FILE_RE.test(entry)) + .sort() + + let sawExpired = false + for (const file of envFiles) { + const res = await inspectCredentialFile(path.join(credentialsDir, file), deps) + if (res.status === 'valid') return res.token + if (res.status === 'expired') sawExpired = true + } + + return sawExpired ? 'expired' : null } async function deviceId(deps: KimiDeps): Promise { @@ -149,7 +296,7 @@ export function decodeKimiUsage(body: unknown): QuotaProvider | null { export type KimiResult = { quota: QuotaProvider; retryAfterSeconds?: number } export async function fetchKimiQuota(options: Partial & { signal?: AbortSignal } = {}): Promise { - const deps = { ...defaults, ...options } + const deps = createDeps(options) try { const token = await freshToken(deps) if (token === null) return { quota: empty('disconnected') } diff --git a/src/quota/kimi.ts b/src/quota/kimi.ts index 407b23d55..58272e344 100644 --- a/src/quota/kimi.ts +++ b/src/quota/kimi.ts @@ -6,10 +6,13 @@ // X-Msh-Device-Id). Numeric fields have shipped as both JSON numbers and // strings, and the reset stamp under several spellings, so decode leniently. // -// Credential: the Kimi CLI's own ~/.kimi-code/credentials/kimi-code.json, -// read-only. Access tokens live ~15 minutes and ONLY the Kimi CLI refreshes -// them - we never refresh and never write, so an expired or rejected token is a -// terminal state whose footer tells the user to run the Kimi CLI once. +// Credential: the Kimi CLI's OAuth file under ~/.kimi-code/credentials/ +// (resolved from ~/.kimi-code/config.toml, legacy kimi-code.json, or +// kimi-code-env-*.json), read-only. Access tokens live ~15 minutes and ONLY +// the Kimi CLI refreshes them - we never refresh and never write, so an +// expired or rejected token is a terminal state whose footer tells the user +// to run the Kimi CLI once. +import fs from 'node:fs/promises' import os from 'node:os' import path from 'node:path' @@ -18,23 +21,119 @@ import type { QuotaProvider, QuotaWindow } from './types.js' const USAGE_ENDPOINT = 'https://api.kimi.com/coding/v1/usages' const EXPIRED_FOOTER = ['Login expired. Run the Kimi CLI once, then refresh.'] +const CREDENTIAL_MAX_BYTES = 64 * 1024 +const CONFIG_MAX_BYTES = 64 * 1024 +const SAFE_KEY_STEM_RE = /^[A-Za-z0-9._-]+$/ +const ENV_CREDENTIAL_FILE_RE = /^kimi-code-env-[A-Za-z0-9._-]+\.json$/ +const MANAGED_OAUTH_SECTION_RE = /^providers\s*\.\s*(?:"managed:kimi-code"|'managed:kimi-code')\s*\.\s*oauth$/ -const kimiHome = process.env['KIMI_CODE_HOME'] ?? path.join(os.homedir(), '.kimi-code') +export type ReadConfigFileFn = (filePath: string) => Promise +export type ListCredentialsDirFn = (dirPath: string) => Promise export type KimiDeps = { fetch: typeof fetch - credentialPath: string + credentialPath?: string deviceIdPath: string readFile: typeof readSecureFile + readConfigFile: ReadConfigFileFn + listCredentialsDir: ListCredentialsDirFn now: () => number } -const defaults: KimiDeps = { - fetch: globalThis.fetch, - credentialPath: path.join(kimiHome, 'credentials', 'kimi-code.json'), - deviceIdPath: path.join(kimiHome, 'device_id'), - readFile: readSecureFile, - now: Date.now, +function resolveKimiHome(): string { + const envHome = process.env['KIMI_CODE_HOME']?.trim() + return envHome || path.join(os.homedir(), '.kimi-code') +} + +async function defaultReadConfigFile(filePath: string): Promise { + try { + const stat = await fs.lstat(filePath) + if (stat.isSymbolicLink() || !stat.isFile() || stat.size > CONFIG_MAX_BYTES) return null + return await fs.readFile(filePath, 'utf8') + } catch { + return null + } +} + +async function defaultListCredentialsDir(dirPath: string): Promise { + try { + return await fs.readdir(dirPath) + } catch { + return [] + } +} + +function stripTomlComment(line: string): string { + let inSingle = false + let inDouble = false + let escaped = false + for (let i = 0; i < line.length; i++) { + const ch = line[i]! + if (escaped) { escaped = false; continue } + if (inDouble && ch === '\\') { escaped = true; continue } + if (!inDouble && ch === "'") { inSingle = !inSingle; continue } + if (!inSingle && ch === '"') { inDouble = !inDouble; continue } + if (!inSingle && !inDouble && ch === '#') return line.slice(0, i) + } + return line +} + +function parseTomlStringScalar(rawValue: string): string | null { + const trimmed = rawValue.trim() + if (trimmed.length < 2) return null + if (trimmed.startsWith('"') && trimmed.endsWith('"')) { + try { + const parsed = JSON.parse(trimmed) + return typeof parsed === 'string' ? parsed : null + } catch { + return null + } + } + if (trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1) + return null +} + +/** Extracts `key` from `[providers."managed:kimi-code".oauth]`. */ +export function parseManagedOAuthKey(tomlContent: string): string | null { + let inTargetSection = false + for (const rawLine of tomlContent.split(/\r?\n/)) { + const line = stripTomlComment(rawLine).trim() + if (!line) continue + if (line.startsWith('[') && line.endsWith(']')) { + inTargetSection = MANAGED_OAUTH_SECTION_RE.test(line.slice(1, -1).trim()) + continue + } + if (!inTargetSection) continue + const eqIndex = line.indexOf('=') + if (eqIndex === -1) continue + if (line.slice(0, eqIndex).trim() !== 'key') continue + return parseTomlStringScalar(line.slice(eqIndex + 1)) + } + return null +} + +/** Converts an OAuth `key` (e.g. `"oauth/kimi-code-env-abc"`) into a safe + * single filename inside `credentials/`, rejecting path traversal. */ +export function resolveCredentialFilenameFromKey(rawKey: string): string | null { + if (!rawKey || rawKey.includes('\0') || rawKey.includes('\\')) return null + const normalized = rawKey.startsWith('oauth/') ? rawKey.slice('oauth/'.length) : rawKey + if (!normalized || normalized.includes('/') || normalized.includes('\\') || normalized.includes('..')) return null + const stem = normalized.endsWith('.json') ? normalized.slice(0, -'.json'.length) : normalized + if (!stem || stem === '.' || stem === '..' || !SAFE_KEY_STEM_RE.test(stem)) return null + return `${stem}.json` +} + +function createDeps(options: Partial = {}): KimiDeps { + const kimiHome = resolveKimiHome() + return { + fetch: options.fetch ?? globalThis.fetch, + credentialPath: options.credentialPath, + deviceIdPath: options.deviceIdPath ?? path.join(kimiHome, 'device_id'), + readFile: options.readFile ?? readSecureFile, + readConfigFile: options.readConfigFile ?? defaultReadConfigFile, + listCredentialsDir: options.listCredentialsDir ?? defaultListCredentialsDir, + now: options.now ?? Date.now, + } } function empty(connection: QuotaProvider['connection'], footerLines: string[] = []): QuotaProvider { @@ -50,17 +149,65 @@ function num(value: unknown): number | null { return null } -/** `null` = no usable credential; `'expired'` = present but past its life. */ -async function freshToken(deps: KimiDeps): Promise { - const raw = await deps.readFile(deps.credentialPath, 64 * 1024) - if (!raw) return null - const parsed = JSON.parse(raw) as Record +type TokenInspectResult = { status: 'valid'; token: string } | { status: 'expired' } | { status: 'missing' } + +async function inspectCredentialFile(filePath: string, deps: KimiDeps): Promise { + const raw = await deps.readFile(filePath, CREDENTIAL_MAX_BYTES) + if (!raw) return { status: 'missing' } + let parsed: Record + try { + parsed = JSON.parse(raw) as Record + } catch { + return { status: 'missing' } + } const token = parsed.access_token - if (typeof token !== 'string' || !token) return null + if (typeof token !== 'string' || !token) return { status: 'missing' } const expiresAt = num(parsed.expires_at) // 60s skew, matching the menubar: a token about to die is already useless. - if (expiresAt === null || expiresAt <= deps.now() / 1000 + 60) return 'expired' - return token + if (expiresAt === null || expiresAt <= deps.now() / 1000 + 60) return { status: 'expired' } + return { status: 'valid', token } +} + +/** `null` = no usable credential; `'expired'` = present but past its life. */ +async function freshToken(deps: KimiDeps): Promise { + if (deps.credentialPath) { + const res = await inspectCredentialFile(deps.credentialPath, deps) + return res.status === 'valid' ? res.token : res.status === 'expired' ? 'expired' : null + } + + const kimiHome = resolveKimiHome() + const credentialsDir = path.join(kimiHome, 'credentials') + + // 1. OAuth key configured in /config.toml. + const configRaw = await deps.readConfigFile(path.join(kimiHome, 'config.toml')) + if (configRaw) { + const oauthKey = parseManagedOAuthKey(configRaw) + const filename = oauthKey !== null ? resolveCredentialFilenameFromKey(oauthKey) : null + if (filename) { + const res = await inspectCredentialFile(path.join(credentialsDir, filename), deps) + if (res.status === 'valid') return res.token + if (res.status === 'expired') return 'expired' + } + } + + // 2. Legacy fixed filename. + const legacyRes = await inspectCredentialFile(path.join(credentialsDir, 'kimi-code.json'), deps) + if (legacyRes.status === 'valid') return legacyRes.token + if (legacyRes.status === 'expired') return 'expired' + + // 3. Fallback discovery for dynamically named kimi-code-env-*.json files. + const envFiles = (await deps.listCredentialsDir(credentialsDir)) + .filter(entry => ENV_CREDENTIAL_FILE_RE.test(entry)) + .sort() + + let sawExpired = false + for (const file of envFiles) { + const res = await inspectCredentialFile(path.join(credentialsDir, file), deps) + if (res.status === 'valid') return res.token + if (res.status === 'expired') sawExpired = true + } + + return sawExpired ? 'expired' : null } async function deviceId(deps: KimiDeps): Promise { @@ -149,7 +296,7 @@ export function decodeKimiUsage(body: unknown): QuotaProvider | null { export type KimiResult = { quota: QuotaProvider; retryAfterSeconds?: number } export async function fetchKimiQuota(options: Partial & { signal?: AbortSignal } = {}): Promise { - const deps = { ...defaults, ...options } + const deps = createDeps(options) try { const token = await freshToken(deps) if (token === null) return { quota: empty('disconnected') } diff --git a/tests/quota-kimi.test.ts b/tests/quota-kimi.test.ts new file mode 100644 index 000000000..c9bee876c --- /dev/null +++ b/tests/quota-kimi.test.ts @@ -0,0 +1,186 @@ +import fs from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { + fetchKimiQuota, + parseManagedOAuthKey, + resolveCredentialFilenameFromKey, +} from '../src/quota/kimi.js' + +const liveBody = { + user: { userId: 'x', region: 'REGION_OVERSEA', membership: { level: 'LEVEL_INTERMEDIATE' } }, + usage: { limit: '100', used: '5', remaining: '95', resetTime: '2026-07-30T13:27:17.211Z' }, + limits: [ + { + window: { duration: 300, timeUnit: 'TIME_UNIT_MINUTE' }, + detail: { limit: '100', remaining: '100', resetTime: '2026-07-23T23:27:17.211Z' }, + }, + ], +} + +const nowMs = 1_700_000_000_000 +const validExpiry = nowMs / 1000 + 3600 +const expiredExpiry = nowMs / 1000 + 10 +const okJson = (value: unknown) => new Response(JSON.stringify(value), { status: 200 }) +const tokenJson = (accessToken: string, expiresAt: number) => + JSON.stringify({ access_token: accessToken, expires_at: expiresAt }) + +const originalKimiHome = process.env['KIMI_CODE_HOME'] +const tempDirs: string[] = [] + +async function makeTempKimiHome(): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'codeburn-kimi-')) + tempDirs.push(dir) + await fs.mkdir(path.join(dir, 'credentials'), { recursive: true }) + return dir +} + +async function writePrivateFile(filePath: string, content: string): Promise { + await fs.writeFile(filePath, content, { encoding: 'utf8', mode: 0o600 }) + if (process.platform !== 'win32') await fs.chmod(filePath, 0o600) +} + +afterEach(async () => { + vi.restoreAllMocks() + if (originalKimiHome === undefined) delete process.env['KIMI_CODE_HOME'] + else process.env['KIMI_CODE_HOME'] = originalKimiHome + for (const dir of tempDirs.splice(0)) { + await fs.rm(dir, { recursive: true, force: true }) + } +}) + +describe('Kimi OAuth config parsing and filename validation', () => { + it('parses double-quoted and single-quoted managed:kimi-code oauth keys', () => { + expect(parseManagedOAuthKey(` +[providers."managed:kimi-code".oauth] +storage = "file" +key = "oauth/kimi-code-env-env_12345" # inline comment +`)).toBe('oauth/kimi-code-env-env_12345') + + expect(parseManagedOAuthKey(` +[providers.'managed:kimi-code'.oauth] +key = 'kimi-code-env-env_67890' +`)).toBe('kimi-code-env-env_67890') + + expect(parseManagedOAuthKey(` +[providers."other".oauth] +key = "oauth/other-env" +`)).toBeNull() + }) + + it('rejects path traversal, separators, and NUL bytes in OAuth keys', () => { + expect(resolveCredentialFilenameFromKey('oauth/kimi-code-env-abc123')).toBe('kimi-code-env-abc123.json') + expect(resolveCredentialFilenameFromKey('kimi-code-env-abc123.json')).toBe('kimi-code-env-abc123.json') + expect(resolveCredentialFilenameFromKey('../../etc/passwd')).toBeNull() + expect(resolveCredentialFilenameFromKey('oauth/../../secret')).toBeNull() + expect(resolveCredentialFilenameFromKey('oauth/sub/dir-file')).toBeNull() + expect(resolveCredentialFilenameFromKey('oauth\\kimi-code-env-abc')).toBeNull() + expect(resolveCredentialFilenameFromKey('oauth/kimi-code-env-ok\0.json')).toBeNull() + }) +}) + +describe('Kimi dynamic credential discovery', () => { + it('resolves the credential file configured in KIMI_CODE_HOME/config.toml on disk', async () => { + const home = await makeTempKimiHome() + process.env['KIMI_CODE_HOME'] = home + + await fs.writeFile( + path.join(home, 'config.toml'), + `[providers."managed:kimi-code".oauth]\nstorage = "file"\nkey = "oauth/kimi-code-env-win281"\n`, + 'utf8', + ) + await writePrivateFile( + path.join(home, 'credentials', 'kimi-code-env-win281.json'), + tokenJson('tok_from_config', validExpiry), + ) + await writePrivateFile(path.join(home, 'device_id'), 'dev-win-1\n') + + const fetchMock = vi.fn(async () => okJson(liveBody)) + const result = await fetchKimiQuota({ fetch: fetchMock, now: () => nowMs }) + + expect(result.quota.connection).toBe('connected') + const [, init] = fetchMock.mock.calls[0]! as unknown as [string, RequestInit] + expect(init.headers).toMatchObject({ + Authorization: 'Bearer tok_from_config', + 'X-Msh-Device-Id': 'dev-win-1', + }) + }) + + it('falls back to kimi-code-env-*.json discovery when config.toml is absent and prefers fresh over expired', async () => { + const home = await makeTempKimiHome() + process.env['KIMI_CODE_HOME'] = home + + await writePrivateFile( + path.join(home, 'credentials', 'kimi-code-env-01.json'), + tokenJson('tok_expired', expiredExpiry), + ) + await writePrivateFile( + path.join(home, 'credentials', 'kimi-code-env-02.json'), + tokenJson('tok_fresh', validExpiry), + ) + + const fetchMock = vi.fn(async () => okJson(liveBody)) + const result = await fetchKimiQuota({ fetch: fetchMock, now: () => nowMs }) + + expect(result.quota.connection).toBe('connected') + const [, init] = fetchMock.mock.calls[0]! as unknown as [string, RequestInit] + expect(init.headers).toMatchObject({ Authorization: 'Bearer tok_fresh' }) + }) + + it('returns terminalFailure when all discovered kimi-code-env-*.json files are expired', async () => { + const home = await makeTempKimiHome() + process.env['KIMI_CODE_HOME'] = home + + await writePrivateFile( + path.join(home, 'credentials', 'kimi-code-env-a.json'), + tokenJson('tok_old', expiredExpiry), + ) + + const fetchMock = vi.fn() + const result = await fetchKimiQuota({ fetch: fetchMock, now: () => nowMs }) + + expect(result.quota.connection).toBe('terminalFailure') + expect(fetchMock).not.toHaveBeenCalled() + }) + + it('keeps legacy kimi-code.json working when config.toml has no oauth key', async () => { + const home = await makeTempKimiHome() + process.env['KIMI_CODE_HOME'] = home + + await writePrivateFile( + path.join(home, 'credentials', 'kimi-code.json'), + tokenJson('tok_legacy', validExpiry), + ) + + const fetchMock = vi.fn(async () => okJson(liveBody)) + const result = await fetchKimiQuota({ fetch: fetchMock, now: () => nowMs }) + + expect(result.quota.connection).toBe('connected') + const [, init] = fetchMock.mock.calls[0]! as unknown as [string, RequestInit] + expect(init.headers).toMatchObject({ Authorization: 'Bearer tok_legacy' }) + }) + + it('ignores unsafe traversal keys in config.toml and falls back safely', async () => { + const home = await makeTempKimiHome() + process.env['KIMI_CODE_HOME'] = home + + const legacyPath = path.join(home, 'credentials', 'kimi-code.json') + const readFile = vi.fn(async (filePath: string) => + filePath === legacyPath ? tokenJson('tok_safe', validExpiry) : null, + ) + const fetchMock = vi.fn(async () => okJson(liveBody)) + + const result = await fetchKimiQuota({ + fetch: fetchMock, + readFile, + readConfigFile: vi.fn(async () => '[providers."managed:kimi-code".oauth]\nkey = "oauth/../../outside"\n'), + listCredentialsDir: vi.fn(async () => []), + now: () => nowMs, + }) + + expect(result.quota.connection).toBe('connected') + expect(readFile).not.toHaveBeenCalledWith(expect.stringContaining('outside'), expect.any(Number)) + }) +})