Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions app/electron/quota/kimi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})
})
189 changes: 168 additions & 21 deletions app/electron/quota/kimi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand All @@ -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<string | null>
export type ListCredentialsDirFn = (dirPath: string) => Promise<string[]>

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<string | null> {
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<string[]> {
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> = {}): 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 {
Expand All @@ -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<string | null | 'expired'> {
const raw = await deps.readFile(deps.credentialPath, 64 * 1024)
if (!raw) return null
const parsed = JSON.parse(raw) as Record<string, unknown>
type TokenInspectResult = { status: 'valid'; token: string } | { status: 'expired' } | { status: 'missing' }

async function inspectCredentialFile(filePath: string, deps: KimiDeps): Promise<TokenInspectResult> {
const raw = await deps.readFile(filePath, CREDENTIAL_MAX_BYTES)
if (!raw) return { status: 'missing' }
let parsed: Record<string, unknown>
try {
parsed = JSON.parse(raw) as Record<string, unknown>
} 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<string | null | 'expired'> {
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 <kimiHome>/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<string | null> {
Expand Down Expand Up @@ -149,7 +296,7 @@ export function decodeKimiUsage(body: unknown): QuotaProvider | null {
export type KimiResult = { quota: QuotaProvider; retryAfterSeconds?: number }

export async function fetchKimiQuota(options: Partial<KimiDeps> & { signal?: AbortSignal } = {}): Promise<KimiResult> {
const deps = { ...defaults, ...options }
const deps = createDeps(options)
try {
const token = await freshToken(deps)
if (token === null) return { quota: empty('disconnected') }
Expand Down
Loading