From 8705956e7f0a8155737a7e25a060120668907a4a Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 1 Dec 2026 21:49:39 +0800 Subject: [PATCH] fix(core,identity,oauth): bound session/cache maps, harden cookie/intercept/file writes, and prune dead exports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 变更摘要 - 改前: - `src/lib/core/security.mjs`:`parseCookie` 直接 `decodeURIComponent` 在畸形 `%` 编码 Cookie 下抛 `URIError` 导致 `extractPanelToken` 崩溃;`createRateLimiter` 的 `buckets` 与内存 `panelSessions` 缺少过期清理与容量上限。 - `src/lib/core/intercept.mjs`:`setPath` 未拦截 `__proto__`/`constructor`/`prototype` 段且仅浅拷贝顶层 `body`,会就地修改嵌套输入对象。 - `src/lib/oauth/oauth-auth-url.mjs` / `src/lib/oauth/codex-oauth.mjs` / `src/lib/oauth/usage-cache.mjs` / `src/lib/oauth/claude-reset-credits.mjs` / `src/lib/oauth/usage-probe-monitor.mjs`:OAuth 会话 Map、`store`/`accountEpochs`、`fileLocks` 与已失效 `backoff` 存在无上限增长或清理遗漏;`usage-probe-monitor.mjs` 与 `src/lib/oauth/import-commit.mjs` 多处裸 `catch {}` 静默吞错。 - `src/lib/oauth/cookie-auth.mjs`:`runNativeOAuthAuthService` 启动 `kin-oauth-auth` 缺进程超时、输出上限与 `stdin` `EPIPE` 防护,且含未用 `fs`/`path` 导入。 - `src/lib/identity/crs-headers.mjs`:`writeHeaderFile` 使用裸 `fs.writeFileSync`,未加 `0600` 权限且非原子写入。 - `src/lib/oauth/sub2api-account.mjs` (`panelImportFromOauth`)、`src/lib/oauth/auth-scheme.mjs` (`authSchemeOfVm`)、`src/lib/identity/claude-code-only.mjs` (`hasClaudeCodeClientHeaders`) 及 4 处文件存在确认零引用的死导出/未用导入。 - 改后: - `security.mjs` 增加安全 Cookie 解码回退、`createRateLimiter` 过期桶回收与容量上限(默认 `10_000`)、`panelSessions` 过期清理与容量上限(`10_000`);`intercept.mjs` 拦截原型污染路径段并对嵌套路径按需浅拷贝。 - `oauth-auth-url.mjs`(`MAX_OAUTH_SESSIONS = 1000`)与 `codex-oauth.mjs`(`MAX_CODEX_OAUTH_SESSIONS = 1000`)在超限时按 FIFO 淘汰最早会话;`usage-cache.mjs` 为 `store`/`accountEpochs` 增设容量回收并在全局 `clear()` 清空 `accountEpochs`;`claude-reset-credits.mjs` 在 `withFileLock` 完成后回收 `fileLocks` 键;`usage-probe-monitor.mjs` 在 `runOnce` 清理过期非目标 `backoff` 条目并经 `opts.logger?.warn` 记录回调异常;`import-commit.mjs` 补齐 `accountQuota` 可选链并将 8 处裸 `catch {}` 改为结构化告警日志。 - `cookie-auth.mjs` 为 `runNativeOAuthAuthService` 补齐超时(与 `runGuestOAuthAuthService` 对齐)、1 MiB 输出上限、`stdin` 错误处理及单次 settle 守卫,并移除未用 `fs`/`path` 导入。 - `crs-headers.mjs` 改用 `atomicWriteJson(..., { mode: 0o600 })` 原子持久化 `kin-cc-headers.json`。 - 移除经全仓 `git grep` 确认零引用的死导出与未用导入(`config.mjs`、`official-profiles.mjs`、`workstation-fingerprint.mjs`、`official-cc-bootstrap.mjs`、`claude-code-only.mjs`、`auth-scheme.mjs`、`sub2api-account.mjs`),并在 5 个既有单测文件补充回归用例(0 新建测试文件)。 - 未改 / 延后: - 避让开放 PR 碰撞文件:`src/lib/oauth/oauth-credentials.mjs`(#2457)、`src/lib/oauth/openai-quota.mjs`(#2455)、`src/lib/core/panel-2fa.mjs`(#2460)、`src/lib/core/errors.mjs`(#2441/#2453)、`src/lib/identity/{crs-persona,persona-template,system-prompt-spec}.mjs`(#2446)。 - 保留契约/规范引用文件:`src/lib/oauth/oauth-contract.mjs`(22 常量被私有 `auth.js` 引用)、`src/lib/oauth/profile-policy.mjs`(二进制契约单测)、`src/lib/identity/telemetry-env.mjs`(2.1.303 遥测对照规范)。 - 未修改任何对外错误码、加密协议或身份派生不变量。 ## 验收记录(Run) - 环境与基线:Windows + WSL2 Debian Node 22,工作树 `X:\vm2api-wt-r4-core-id`(分支 `fix/r4-core-identity-oauth`,基于 `origin/dev` `566e0c1db`)。 - 已跑命令与结果: - `npx biome format --write <22 改动 .mjs> && npx biome check <22 改动 .mjs>`: PASS(Checked 22 files, 0 error) - `find src scripts -name '*.mjs' -print0 | xargs -0 -n1 node --check`: PASS(全量语法检查 exit 0) - `KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-scheduler VM2API_TEST_CONCURRENCY=4 npm run test:ci`: PASS(13/13 文件,250 pass / 0 fail / 0 skipped) - `KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-scheduler KIN_TEST_OAUTH_AUTH_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-oauth-auth KIN_OAUTH_AUTH_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-oauth-auth VM2API_TEST_CONCURRENCY=4 node scripts/run-isolated-tests.mjs test/unit .test.mjs <50 关联单测>`: PASS(50/50 文件,841 pass / 0 fail / 8 skipped,跳过项均为基线环境条件跳过) - `node --test test/unit/security.test.mjs test/unit/oauth-auth-url.test.mjs test/unit/claude-auth-login.test.mjs test/unit/warmup-monitor.test.mjs test/unit/oauth-identity.test.mjs test/unit/proxy-cli-enabled.test.mjs test/unit/subscription-plan.test.mjs test/unit/claude-reset-quota-sync.test.mjs`: PASS(8/8 文件,83 pass / 0 fail,在 `import-commit.mjs` 最终微调后复跑) ## 回退与手破验证(Broken by hand) - 回退 `src/lib/core/security.mjs` 中 `parseCookie` 的 `decodeCookieValue(v)` 为裸 `decodeURIComponent(v)` -> `extractPanelToken tolerates malformed percent-encoding in Cookie header` FAIL(`URIError: URI malformed` at `parseCookie`)-> 恢复后 `security.test.mjs` 全部 PASS。 - 移除 `src/lib/oauth/oauth-auth-url.mjs` 中 `MAX_OAUTH_SESSIONS` 淘汰循环 -> `generateAuthUrl bounds pending sessions by evicting oldest at MAX_OAUTH_SESSIONS` FAIL(`AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: actual { ... } !== expected null`)-> 恢复后 `oauth-auth-url.test.mjs` 全部 PASS。 ## 真实使用(Real use) - 已使用真实 `kin-scheduler`(`KIN_SCHEDULER_BIN`)与真实 `kin-oauth-auth`(`KIN_TEST_OAUTH_AUTH_BIN` / `KIN_OAUTH_AUTH_BIN`)在 WSL 下通过 `test:ci` 及 `oauth-binary.test.mjs` 端到端二进制协议校验;未执行 `ph24` 线上实测(本任务规范严禁连线上生产机)。 ## 未运行项(Not run) - 全量 556 个单测套件(`npm run test:unit`)、Docker/KVM 集成 E2E、前端 `web/` 测试与构建(未改动 `web/`)及 `ph24` 线上实测:本次改动严格限定在 `src/lib/{core,identity,oauth}`,已覆盖 `test:ci`(13 套件)与全库 `git grep -l` 命中的全部 50 个关联单测套件。 --- src/lib/core/config.mjs | 1 - src/lib/core/intercept.mjs | 12 +++-- src/lib/core/security.mjs | 42 +++++++++++++-- src/lib/identity/claude-code-only.mjs | 10 +--- src/lib/identity/crs-headers.mjs | 23 ++++---- src/lib/identity/official-profiles.mjs | 4 +- src/lib/identity/workstation-fingerprint.mjs | 2 +- src/lib/oauth/auth-scheme.mjs | 9 +--- src/lib/oauth/claude-reset-credits.mjs | 13 ++--- src/lib/oauth/codex-oauth.mjs | 6 +++ src/lib/oauth/cookie-auth.mjs | 55 +++++++++++++++++--- src/lib/oauth/import-commit.mjs | 41 +++++++++++---- src/lib/oauth/oauth-auth-url.mjs | 7 ++- src/lib/oauth/official-cc-bootstrap.mjs | 16 +----- src/lib/oauth/sub2api-account.mjs | 19 ------- src/lib/oauth/usage-cache.mjs | 43 +++++++++++++-- src/lib/oauth/usage-probe-monitor.mjs | 16 ++++-- test/unit/codex-oauth.test.mjs | 16 ++++++ test/unit/crs-headers.test.mjs | 27 ++++++++++ test/unit/oauth-auth-url.test.mjs | 13 +++++ test/unit/security.test.mjs | 46 ++++++++++++++++ test/unit/usage-cache.test.mjs | 14 +++++ 22 files changed, 329 insertions(+), 106 deletions(-) diff --git a/src/lib/core/config.mjs b/src/lib/core/config.mjs index cb51ef3dd8..c03cfeca82 100644 --- a/src/lib/core/config.mjs +++ b/src/lib/core/config.mjs @@ -2,7 +2,6 @@ import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { hashKey } from './security.mjs' -import { atomicWriteJson } from '../vm/vm-file.mjs' import { loadDistillRules } from './distill-detect.mjs' const __dirname = path.dirname(fileURLToPath(import.meta.url)) diff --git a/src/lib/core/intercept.mjs b/src/lib/core/intercept.mjs index 961dc8eb96..a00539eaa9 100644 --- a/src/lib/core/intercept.mjs +++ b/src/lib/core/intercept.mjs @@ -41,12 +41,18 @@ export function applyIntercept(rules, phase, ctx) { return { ...ctx, body, headers } } +const FORBIDDEN_PATH_PARTS = new Set(['__proto__', 'constructor', 'prototype']) + function setPath(obj, path, value) { - const parts = path.split('.') + const parts = String(path).split('.') + if (parts.some((part) => !part || FORBIDDEN_PATH_PARTS.has(part))) return let cur = obj for (let i = 0; i < parts.length - 1; i++) { - if (cur[parts[i]] == null || typeof cur[parts[i]] !== 'object') cur[parts[i]] = {} - cur = cur[parts[i]] + const key = parts[i] + const next = cur[key] + if (next == null || typeof next !== 'object') cur[key] = {} + else cur[key] = Array.isArray(next) ? [...next] : { ...next } + cur = cur[key] } cur[parts[parts.length - 1]] = value } diff --git a/src/lib/core/security.mjs b/src/lib/core/security.mjs index b939dd64fe..a852ed5f68 100644 --- a/src/lib/core/security.mjs +++ b/src/lib/core/security.mjs @@ -58,14 +58,29 @@ export function extractApiKey(req) { return '' } +const MAX_RATE_LIMIT_BUCKETS = 10_000 + /** Simple token bucket per key; non-positive capacity or refill disables throttling. */ -export function createRateLimiter({ capacity = 60, refillPerSec = 1 } = {}) { +export function createRateLimiter({ capacity = 60, refillPerSec = 1, maxKeys = MAX_RATE_LIMIT_BUCKETS } = {}) { if (!(capacity > 0) || !(refillPerSec > 0)) return () => true + const cap = Number.isInteger(maxKeys) && maxKeys > 0 ? maxKeys : MAX_RATE_LIMIT_BUCKETS const buckets = new Map() + const sweep = (now) => { + for (const [k, entry] of buckets) { + const refilled = entry.tokens + ((now - entry.updated) / 1000) * refillPerSec + if (refilled >= capacity) buckets.delete(k) + } + while (buckets.size >= cap) { + const oldest = buckets.keys().next().value + if (oldest === undefined) break + buckets.delete(oldest) + } + } return function allow(key) { const now = Date.now() let b = buckets.get(key) if (!b) { + if (buckets.size >= cap) sweep(now) b = { tokens: capacity, updated: now } buckets.set(key, b) } @@ -87,6 +102,7 @@ export function getPanelAdmin() { } const SESSION_TTL_MS = 7 * 24 * 3600 * 1000 +const MAX_PANEL_SESSIONS = 10_000 const panelSessions = new Map() // sha256(token) -> { user, role, exp } let _authenticateUser = null let _lookupRole = null @@ -137,12 +153,24 @@ function loadSessions() { } } +function prunePanelSessions(now = Date.now()) { + for (const [token, s] of panelSessions.entries()) { + if (!s || s.exp <= now) panelSessions.delete(token) + } + while (panelSessions.size > MAX_PANEL_SESSIONS) { + const oldest = panelSessions.keys().next().value + if (oldest === undefined) break + panelSessions.delete(oldest) + } +} + function saveSessions() { try { const f = sessionFile() fs.mkdirSync(path.dirname(f), { recursive: true }) - const obj = {} const now = Date.now() + prunePanelSessions(now) + const obj = {} for (const [token, s] of panelSessions.entries()) { if (s.exp > now) obj[token] = s } @@ -240,6 +268,14 @@ export function verifyPanelLogin(username, password) { return { username: admin.username, role: 'admin', id: null, source: 'env' } } +function decodeCookieValue(raw) { + try { + return decodeURIComponent(raw) + } catch { + return raw + } +} + function parseCookie(header) { const out = {} if (!header) return out @@ -248,7 +284,7 @@ function parseCookie(header) { if (i < 0) continue const k = part.slice(0, i).trim() const v = part.slice(i + 1).trim() - if (k) out[k] = decodeURIComponent(v) + if (k) out[k] = decodeCookieValue(v) } return out } diff --git a/src/lib/identity/claude-code-only.mjs b/src/lib/identity/claude-code-only.mjs index 2c2587626c..a1515e97e4 100644 --- a/src/lib/identity/claude-code-only.mjs +++ b/src/lib/identity/claude-code-only.mjs @@ -5,7 +5,7 @@ */ import { makeError, ErrorType, ErrorCode } from '../core/errors.mjs' import { detectProxiedOfficialCcFromRouting } from './crs-persona.mjs' -import { verifyDirectClaudeCodeHeaders, verifyOfficialClaudeCode } from './official-cc-verifier.mjs' +import { verifyOfficialClaudeCode } from './official-cc-verifier.mjs' export function claudeCodeOnlyFromRouting(routing) { return routing?.compatibility?.claude_code_only === true @@ -15,14 +15,6 @@ function headerText(headers, key) { return String(headers?.[key] ?? '').trim() } -/** - * Complete direct Claude Code header bundle (strict UA + x-app + anthropic-version + - * browser-access + all 8 Stainless JS headers + UUIDv4 session header + optional beta). - */ -export function hasClaudeCodeClientHeaders(headers = {}, { requireCodeBeta = true } = {}) { - return verifyDirectClaudeCodeHeaders(headers, { requireCodeBeta }).ok -} - /** * Claude Desktop's fixed gateway sign-in check (4.4212.0): Electron UA, `anthropic-version`, * one user turn `.`, `max_tokens` 1 (a local gateway may raise it to 16), no diff --git a/src/lib/identity/crs-headers.mjs b/src/lib/identity/crs-headers.mjs index 343659473a..77a39d6753 100644 --- a/src/lib/identity/crs-headers.mjs +++ b/src/lib/identity/crs-headers.mjs @@ -1,5 +1,6 @@ import { applyBetaPolicyToHeader, shouldPassContext1mByPolicy } from '../protocol/model-policy.mjs' import { CONTEXT_1M_BETA, hasClaudeCode1mSuffix } from '../protocol/context-1m.mjs' +import { atomicWriteJson } from '../vm/vm-file.mjs' import { OFFICIAL_CLAUDE_CLI_UA, OFFICIAL_STAINLESS } from './vm-identity.mjs' import { isOfficialClaudeUa } from './official-claude-ua.mjs' @@ -184,18 +185,16 @@ function readHeaderFile(homeDir) { } function writeHeaderFile(homeDir, headers, extra = {}) { - fs.mkdirSync(path.dirname(headerFile(homeDir)), { recursive: true }) - fs.writeFileSync( - headerFile(homeDir), - JSON.stringify( - { - headers, - updated_at: extra.updated_at || new Date().toISOString(), - ...extra, - }, - null, - 2, - ), + const file = headerFile(homeDir) + fs.mkdirSync(path.dirname(file), { recursive: true }) + atomicWriteJson( + file, + { + headers, + updated_at: extra.updated_at || new Date().toISOString(), + ...extra, + }, + { mode: 0o600 }, ) } diff --git a/src/lib/identity/official-profiles.mjs b/src/lib/identity/official-profiles.mjs index 45eeaa1e81..e1a7d6bb7c 100644 --- a/src/lib/identity/official-profiles.mjs +++ b/src/lib/identity/official-profiles.mjs @@ -5,8 +5,8 @@ * Named official presets use 2.1.303. Empty and legacy presets retain 2.1.296. */ import { createRequire } from 'node:module' -import { OFFICIAL_SLOT_CWD, officialProjectSlug, sanitizeInboundCwd } from './official-cc-system-2.1.241.mjs' -import { OFFICIAL_303_PRESET, normalizePersonaPreset } from './persona-template.mjs' +import { officialProjectSlug, sanitizeInboundCwd } from './official-cc-system-2.1.241.mjs' +import { OFFICIAL_303_PRESET } from './persona-template.mjs' const require = createRequire(import.meta.url) const FIXTURE_303 = require('./official-cc-system-2.1.303.json') diff --git a/src/lib/identity/workstation-fingerprint.mjs b/src/lib/identity/workstation-fingerprint.mjs index 3bc9e78b3a..5d9f6debf3 100644 --- a/src/lib/identity/workstation-fingerprint.mjs +++ b/src/lib/identity/workstation-fingerprint.mjs @@ -5,7 +5,7 @@ import crypto from 'node:crypto' import fs from 'node:fs' import path from 'node:path' -import { US_TIMEZONES, validTimezone } from '../core/timezone.mjs' +import { validTimezone } from '../core/timezone.mjs' import { isValidSlotUsername } from '../vm/slot-identity.mjs' import { workstationFamily, workstationKernel, workstationSkuId } from './workstation-profile.mjs' diff --git a/src/lib/oauth/auth-scheme.mjs b/src/lib/oauth/auth-scheme.mjs index 42ff37e92b..6b319d220d 100644 --- a/src/lib/oauth/auth-scheme.mjs +++ b/src/lib/oauth/auth-scheme.mjs @@ -5,7 +5,7 @@ * Defaults: OAuth / official setup-token → Bearer (Claude Console accepts * sk-ant-oat01-… this way). Console API key → x-api-key. */ -import { credentialModeOfVm, normalizeCredentialMode } from './credential-mode.mjs' +import { normalizeCredentialMode } from './credential-mode.mjs' export const AUTH_SCHEME_X_API_KEY = 'x_api_key' export const AUTH_SCHEME_BEARER = 'authorization_bearer' @@ -41,10 +41,3 @@ export function resolveAuthScheme({ mode, auth_scheme, authScheme, extra } = {}) ) return explicit || defaultAuthScheme(mode) } - -export function authSchemeOfVm(vm = {}) { - return resolveAuthScheme({ - mode: credentialModeOfVm(vm), - auth_scheme: vm.auth_scheme || vm.claude?.auth_scheme, - }) -} diff --git a/src/lib/oauth/claude-reset-credits.mjs b/src/lib/oauth/claude-reset-credits.mjs index d1ff45d3fd..757d8c6457 100644 --- a/src/lib/oauth/claude-reset-credits.mjs +++ b/src/lib/oauth/claude-reset-credits.mjs @@ -295,13 +295,14 @@ function statePath(projectRoot) { function withFileLock(key, fn) { const prev = fileLocks.get(key) || Promise.resolve() const run = prev.then(fn, fn) - fileLocks.set( - key, - run.then( - () => {}, - () => {}, - ), + const settled = run.then( + () => {}, + () => {}, ) + const tail = settled.finally(() => { + if (fileLocks.get(key) === tail) fileLocks.delete(key) + }) + fileLocks.set(key, tail) return run } diff --git a/src/lib/oauth/codex-oauth.mjs b/src/lib/oauth/codex-oauth.mjs index 84d62dd294..57bb1eb4bf 100644 --- a/src/lib/oauth/codex-oauth.mjs +++ b/src/lib/oauth/codex-oauth.mjs @@ -16,6 +16,7 @@ import { import { resolveSlotOAuthProxy } from '../vm/proxy-resolve.mjs' export const CODEX_OAUTH_SESSION_TTL_MS = 10 * 60 * 1000 +export const MAX_CODEX_OAUTH_SESSIONS = 1000 const SURFACE_STABLE_ID_DOMAIN = Buffer.from('openai/codex-desktop/surface-stable-id/v1\0') const sessions = new Map() @@ -115,6 +116,11 @@ export function generateCodexAuthUrl({ vmId, proxyUrl, installationId } = {}) { const sessionId = crypto.randomBytes(16).toString('hex') const createdAt = Date.now() const install = String(installationId || crypto.randomUUID()) + while (sessions.size >= MAX_CODEX_OAUTH_SESSIONS) { + const oldest = sessions.keys().next().value + if (oldest === undefined) break + sessions.delete(oldest) + } sessions.set(sessionId, { state, codeVerifier, diff --git a/src/lib/oauth/cookie-auth.mjs b/src/lib/oauth/cookie-auth.mjs index ef53c65e89..952baba38b 100644 --- a/src/lib/oauth/cookie-auth.mjs +++ b/src/lib/oauth/cookie-auth.mjs @@ -4,8 +4,6 @@ * macOS path is unchanged; auth.js is loaded only by fetch test seams. */ import { spawn } from 'node:child_process' -import fs from 'node:fs' -import path from 'node:path' import { resolvePackagedBin } from '../vm/vm-file.mjs' import { CAI_AUTHORIZE_URL, @@ -33,21 +31,60 @@ function serviceFailure(code, message) { return error } +const MAX_NATIVE_OAUTH_OUTPUT_BYTES = 1024 * 1024 + function runNativeOAuthAuthService(payload) { const bin = findOAuthAuthBin() if (!bin) return Promise.reject(serviceFailure('oauth_auth_bin_missing', 'kin-oauth-auth not found')) + const reqTimeout = Number(payload?.timeout_ms) + const timeoutMs = + Number.isFinite(reqTimeout) && reqTimeout > 0 + ? Math.max(reqTimeout * 9, 120_000) + : Math.max(OAUTH_REQUEST_TIMEOUT_MS * 9, 120_000) return new Promise((resolve, reject) => { const child = spawn(bin, [], { env: process.env, stdio: ['pipe', 'pipe', 'pipe'] }) let stdout = '' let stderr = '' + let outputExceeded = false + let settled = false + const finish = (err, value) => { + if (settled) return + settled = true + clearTimeout(timer) + if (err) reject(err) + else resolve(value) + } + const timer = setTimeout(() => { + try { + child.kill('SIGKILL') + } catch { + /* child already exited */ + } + finish(serviceFailure('oauth_auth_timeout', 'Native OAuth helper timed out')) + }, timeoutMs) + timer.unref?.() + child.stdin.on('error', () => {}) child.stdout.on('data', (chunk) => { + if (stdout.length + chunk.length > MAX_NATIVE_OAUTH_OUTPUT_BYTES) { + outputExceeded = true + try { + child.kill('SIGKILL') + } catch { + /* child already exited */ + } + finish(serviceFailure('oauth_auth_output_invalid', 'Native OAuth helper exceeded its output limit')) + return + } stdout += chunk.toString('utf8') }) child.stderr.on('data', (chunk) => { - stderr += chunk.toString('utf8') + if (stderr.length < MAX_NATIVE_OAUTH_OUTPUT_BYTES) { + stderr += chunk.toString('utf8').slice(0, MAX_NATIVE_OAUTH_OUTPUT_BYTES - stderr.length) + } }) - child.on('error', (error) => reject(serviceFailure('oauth_auth_spawn_failed', error.message))) + child.on('error', (error) => finish(serviceFailure('oauth_auth_spawn_failed', error.message))) child.on('close', (code) => { + if (outputExceeded) return const lines = stdout .split(/\r?\n/) .map((line) => line.trim()) @@ -55,18 +92,20 @@ function runNativeOAuthAuthService(payload) { let result = null try { result = lines.length ? JSON.parse(lines[lines.length - 1]) : null - } catch {} + } catch { + /* handled by null check below */ + } if (!result || typeof result !== 'object') { - reject(serviceFailure('oauth_auth_output_invalid', stderr.trim().slice(0, 300) || `service exited ${code}`)) + finish(serviceFailure('oauth_auth_output_invalid', stderr.trim().slice(0, 300) || `service exited ${code}`)) return } if (result.ok !== true) { - reject( + finish( serviceFailure(result.error?.code || 'oauth_auth_failed', result.error?.message || 'OAuth service failed'), ) return } - resolve(result.credential) + finish(null, result.credential) }) child.stdin.end(JSON.stringify(payload) + '\n') }) diff --git a/src/lib/oauth/import-commit.mjs b/src/lib/oauth/import-commit.mjs index 87b0dae4fd..28e52c8eff 100644 --- a/src/lib/oauth/import-commit.mjs +++ b/src/lib/oauth/import-commit.mjs @@ -37,6 +37,11 @@ import { slotHost } from '../vm/slot-host.mjs' import { finishOAuthImport } from './guest-oauth-helper.mjs' export function createImportCommit(ctx) { + const warn = (stage, err) => { + const logger = ctx.logger || console + logger.warn?.(`[import-commit] ${stage} failed: ${err?.message || err}`) + } + function routing() { return typeof ctx.getRoutingConfig === 'function' ? ctx.getRoutingConfig() : ctx.routingConfig } @@ -44,7 +49,7 @@ export function createImportCommit(ctx) { function rebindOauthAccount(vm) { const uuid = vm?.claude?.account_uuid if (!uuid || !vm?.id) return - ctx.accountQuota.rebindToVm(uuid, vm.id, { email: vm.claude?.email || null }) + ctx.accountQuota?.rebindToVm?.(uuid, vm.id, { email: vm.claude?.email || null }) } function requireSlotProxy(existing, body = {}) { @@ -132,7 +137,9 @@ export function createImportCommit(ctx) { ...(accountId === initialAccountId && resetGenerations ? { resetGenerations } : {}), }, ) - } catch {} + } catch (err) { + warn(`ingestOAuthUsage(${vmId})`, err) + } } if ( (stats?.account_tier === 'pro' || stats?.account_tier === 'max') && @@ -141,10 +148,14 @@ export function createImportCommit(ctx) { const source = stats.account_tier_source === 'profile' ? 'profile' : 'usage' try { ctx.accountQuota.setAccountTier(accountId, stats.account_tier, { source }) - } catch {} + } catch (err) { + warn(`setAccountTier(${vmId})`, err) + } try { persistAccountTier(ctx.cfg.paths.project, vmId, stats.account_tier, { source }) - } catch {} + } catch (err) { + warn(`persistAccountTier(${vmId})`, err) + } try { const vm = getVm(ctx.cfg.paths.project, vmId) if (vm && !vm.policy?.concurrencyOverride) { @@ -157,7 +168,9 @@ export function createImportCommit(ctx) { ctx.applyVmConcurrency(vmId, next, { override: false }) } } - } catch {} + } catch (err) { + warn(`applyVmConcurrency(${vmId})`, err) + } } } } @@ -256,13 +269,17 @@ export function createImportCommit(ctx) { ) try { const accountId = importedCredential.account_uuid || existing.claude?.account_uuid || vmId - ctx.accountQuota.clearGrantRevokeLeftover(accountId) + ctx.accountQuota?.clearGrantRevokeLeftover?.(accountId) ctx.poolScheduler?.clearAuthCooldownFor?.(vmId, accountId) ctx.poolScheduler?.clearGrantRevokeCooldownFor?.(vmId, accountId) - } catch {} + } catch (err) { + warn(`clearCooldown(${vmId})`, err) + } try { rebindOauthAccount({ ...existing, ...JSON.parse(fs.readFileSync(vmPath, 'utf8')), id: vmId }) - } catch {} + } catch (err) { + warn(`rebindOauthAccount(${vmId})`, err) + } // Warm-up onboarding: a fresh or swapped Claude account starts (or restarts) // the rpm ramp when routing.warmup.enabled is true. Same-account credential // refreshes (nextUuid === prevUuid) leave an in-flight warm-up untouched. @@ -280,7 +297,9 @@ export function createImportCommit(ctx) { } warmupStarted = true } - } catch {} + } catch (err) { + warn(`startWarmup(${vmId})`, err) + } const refreshed = JSON.parse(fs.readFileSync(vmPath, 'utf8')) if (name && refreshed.name !== name) { const written = patchVmRecord(ctx.cfg.paths.project, vmId, { name }) @@ -293,7 +312,9 @@ export function createImportCommit(ctx) { try { const rt = typeof ctx.getSchedulerRuntime === 'function' ? ctx.getSchedulerRuntime() : ctx.schedulerRuntime await rt?.syncConfigNow?.('warmup_start') - } catch {} + } catch (err) { + warn(`syncConfigNow(${vmId})`, err) + } } const clientSync = await syncClaudeClientCredentials(workerExec) if (!clientSync.ok) return clientSync diff --git a/src/lib/oauth/oauth-auth-url.mjs b/src/lib/oauth/oauth-auth-url.mjs index 34bda85bac..e79835fa47 100644 --- a/src/lib/oauth/oauth-auth-url.mjs +++ b/src/lib/oauth/oauth-auth-url.mjs @@ -13,6 +13,7 @@ import { carryOAuthAttempt } from './guest-oauth-helper.mjs' export const CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e' export const SESSION_TTL_MS = 30 * 60 * 1000 +export const MAX_OAUTH_SESSIONS = 1000 export const OAUTH_FLAVORS = Object.freeze({ cai: { @@ -128,6 +129,11 @@ export function generateAuthUrl({ vmId, proxyUrl, flavor } = {}) { const codeChallenge = generateCodeChallenge(codeVerifier) const sessionId = generateSessionId() const createdAt = Date.now() + while (sessions.size >= MAX_OAUTH_SESSIONS) { + const oldest = sessions.keys().next().value + if (oldest === undefined) break + sessions.delete(oldest) + } sessions.set(sessionId, { state, codeVerifier, @@ -174,7 +180,6 @@ async function exchangeCodeForToken(authCode, codeVerifier, state, session, opti }) } - /** * The helper already ran the README's post-token sequence (profile → eval → * roles → first token date → eval → bootstrap), so its reply carries diff --git a/src/lib/oauth/official-cc-bootstrap.mjs b/src/lib/oauth/official-cc-bootstrap.mjs index 1f2a0de72d..f0aa40f49f 100644 --- a/src/lib/oauth/official-cc-bootstrap.mjs +++ b/src/lib/oauth/official-cc-bootstrap.mjs @@ -20,25 +20,13 @@ import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' -import { - parseVmIndex, - containerName, - officialCcUidGid, - syncNativeTelemetry, - isSlotProxyDesynced, -} from '../vm/vm-runtime.mjs' +import { containerName, officialCcUidGid, syncNativeTelemetry, isSlotProxyDesynced } from '../vm/vm-runtime.mjs' import { slotMemory } from '../vm/machine-spec.mjs' import { isKvmRuntime } from '../vm/runtime-kind.mjs' import { isCustomKvmMode } from '../vm/custom-os-runtime.mjs' import { slotExecArgv } from '../vm/slot-exec.mjs' import { reloadSlotReady } from '../vm/slot-runtime.mjs' -import { - hasAccessPresence, - hasRefreshPresence, - needsRefresh, - readWorkerCredentialFile, - ensureOfficialCredentialLink, -} from './oauth-credentials.mjs' +import { needsRefresh, readWorkerCredentialFile, ensureOfficialCredentialLink } from './oauth-credentials.mjs' import { canOfficialCc, credentialModeOfVm } from './credential-mode.mjs' import { ensureWorkerCredential } from '../transport/go-worker-client.mjs' import { inferTierFromOfficialStats, parseOfficialCcStats, tierFromOauthProfile } from './official-cc-stats.mjs' diff --git a/src/lib/oauth/sub2api-account.mjs b/src/lib/oauth/sub2api-account.mjs index 991f8f0fc0..77ff33ee46 100644 --- a/src/lib/oauth/sub2api-account.mjs +++ b/src/lib/oauth/sub2api-account.mjs @@ -77,25 +77,6 @@ export function isSub2apiAccountExport(doc) { return false } -export function panelImportFromOauth(oauth, existing = {}) { - const n = normalizeOauth(oauth) - const scopes = Array.isArray(oauth.scopes) - ? oauth.scopes.filter(Boolean) - : String(n.scope || '') - .split(/\s+/) - .filter(Boolean) - return { - access_token: n.access_token, - refresh_token: n.refresh_token || null, - expires_at: n.expires_at || null, - email: n.email || existing.claude?.email || null, - account_uuid: n.account_uuid || existing.claude?.account_uuid || null, - org_uuid: n.org_uuid || existing.claude?.org_uuid || null, - scopes, - source: n.source || oauth.source || null, - } -} - function oauthScopes(cred = {}, n = {}) { return Array.isArray(cred.scopes) ? cred.scopes.filter(Boolean) diff --git a/src/lib/oauth/usage-cache.mjs b/src/lib/oauth/usage-cache.mjs index 05a8f7f5f0..820bece71d 100644 --- a/src/lib/oauth/usage-cache.mjs +++ b/src/lib/oauth/usage-cache.mjs @@ -11,6 +11,7 @@ import { isOfficialUsageRateLimited } from './crs-usage-probe.mjs' export const API_CACHE_TTL_MS = 3 * 60_000 export const API_ERROR_CACHE_TTL_MS = 60_000 export const API_QUERY_MAX_JITTER_MS = 800 +const MAX_USAGE_CACHE_ENTRIES = 4096 const USAGE_FETCH_META = Symbol('usage_fetch_meta') @@ -49,7 +50,13 @@ function isFailureResult(result) { return true } -export function createUsageCache({ now = () => Date.now(), random = Math.random, jitter = true } = {}) { +export function createUsageCache({ + now = () => Date.now(), + random = Math.random, + jitter = true, + maxEntries = MAX_USAGE_CACHE_ENTRIES, +} = {}) { + const cap = Number.isInteger(maxEntries) && maxEntries > 0 ? maxEntries : MAX_USAGE_CACHE_ENTRIES const store = new Map() const flights = new Map() const accountEpochs = new Map() @@ -66,6 +73,19 @@ export function createUsageCache({ now = () => Date.now(), random = Math.random, upstream_failures: 0, } + const pruneStore = (observedAt) => { + if (store.size < cap) return + for (const [k, entry] of store) { + const ttl = entry.kind === 'ok' ? API_CACHE_TTL_MS : API_ERROR_CACHE_TTL_MS + if (observedAt - entry.at >= ttl) store.delete(k) + } + while (store.size >= cap) { + const oldest = store.keys().next().value + if (oldest === undefined) break + store.delete(oldest) + } + } + const peek = (accountId) => { const id = String(accountId || '') if (!id) return null @@ -82,11 +102,17 @@ export function createUsageCache({ now = () => Date.now(), random = Math.random, } const rememberOk = (id, result) => { - store.set(id, { kind: 'ok', result, error: null, at: now() }) + const observedAt = now() + if (!store.has(id)) pruneStore(observedAt) + else store.delete(id) + store.set(id, { kind: 'ok', result, error: null, at: observedAt }) } const rememberError = (id, error, result = null) => { - store.set(id, { kind: 'error', result, error, at: now() }) + const observedAt = now() + if (!store.has(id)) pruneStore(observedAt) + else store.delete(id) + store.set(id, { kind: 'error', result, error, at: observedAt }) } const load = async (accountId, fetcher, { force = false, skipJitter = false } = {}) => { @@ -156,9 +182,18 @@ export function createUsageCache({ now = () => Date.now(), random = Math.random, globalEpoch += 1 store.clear() flights.clear() + accountEpochs.clear() } else { const id = String(accountId) - accountEpochs.set(id, (accountEpochs.get(id) || 0) + 1) + if (flights.has(id)) { + accountEpochs.set(id, (accountEpochs.get(id) || 0) + 1) + if (accountEpochs.size > cap) { + for (const key of accountEpochs.keys()) { + if (!flights.has(key)) accountEpochs.delete(key) + if (accountEpochs.size <= cap) break + } + } + } store.delete(id) flights.delete(id) } diff --git a/src/lib/oauth/usage-probe-monitor.mjs b/src/lib/oauth/usage-probe-monitor.mjs index 75592acbd0..6239e68be5 100644 --- a/src/lib/oauth/usage-probe-monitor.mjs +++ b/src/lib/oauth/usage-probe-monitor.mjs @@ -62,9 +62,7 @@ export function isUsageProbeTarget(vm) { if (!hasRefreshPresence(vm.claude) && !vm.has_refresh && !vm.has_token) return false const grantErr = String(vm.claude?.refresh_error || vm.refresh_error || '') // Skip probing revoked grants: the usage call would just 401 upstream on a dead token. - if ( - /invalid_grant|refresh token not found|oauth_revoked|token_revoked|invalidated oauth token/i.test(grantErr) - ) + if (/invalid_grant|refresh token not found|oauth_revoked|token_revoked|invalidated oauth token/i.test(grantErr)) return false // A parked org-disabled slot never recovers on its own (operator-only): stop // probing it — each hop would just burn an upstream 403 on a dead token and @@ -286,6 +284,10 @@ export function createUsageProbeMonitor(opts = {}) { inflight = (async () => { const started = nowFn() const targets = listTargets() + const targetIds = new Set(targets.map((vm) => vm.id)) + for (const [id, entry] of backoff) { + if (!targetIds.has(id) && (!entry || entry.until <= started)) backoff.delete(id) + } const items = [] const due = [] const staleMs = config.stale_sec * 1000 @@ -294,13 +296,17 @@ export function createUsageProbeMonitor(opts = {}) { if (typeof opts.reconcile === 'function') { try { opts.reconcile(vm, account) - } catch {} + } catch (err) { + opts.logger?.warn?.(`[usage-probe] reconcile failed for ${vm.id}: ${err?.message || err}`) + } } let active = false if (typeof opts.isActive === 'function') { try { active = !!opts.isActive(vm, account) - } catch {} + } catch (err) { + opts.logger?.warn?.(`[usage-probe] isActive failed for ${vm.id}: ${err?.message || err}`) + } } const decision = isUsageProbeDue(account || {}, { now: nowFn(), staleMs, active }) if (!decision.due || typeof opts.probeOne !== 'function') { diff --git a/test/unit/codex-oauth.test.mjs b/test/unit/codex-oauth.test.mjs index 249a55291a..372e25ea53 100644 --- a/test/unit/codex-oauth.test.mjs +++ b/test/unit/codex-oauth.test.mjs @@ -1,7 +1,9 @@ import test from 'node:test' import assert from 'node:assert/strict' import { + MAX_CODEX_OAUTH_SESSIONS, deriveCodexSurfaceStableId, + exchangeCodexAuthCode, generateCodexAuthUrl, parseCodexOAuthCallback, resetCodexAuthUrlSessions, @@ -37,3 +39,17 @@ test('deriveCodexSurfaceStableId is stable UUID', () => { assert.equal(a, b) assert.match(a, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) }) + +test('generateCodexAuthUrl bounds pending sessions by evicting oldest at MAX_CODEX_OAUTH_SESSIONS', async () => { + resetCodexAuthUrlSessions() + const first = generateCodexAuthUrl({ vmId: 'vm-codex-01', proxyUrl: '' }) + let last = first + for (let i = 0; i < MAX_CODEX_OAUTH_SESSIONS; i++) { + last = generateCodexAuthUrl({ vmId: 'vm-codex-01', proxyUrl: '' }) + } + await assert.rejects(() => exchangeCodexAuthCode({ sessionId: first.session_id, code: 'abc' }), { + code: 'session_expired', + }) + await assert.rejects(() => exchangeCodexAuthCode({ sessionId: last.session_id, code: '' }), { code: 'code_required' }) + resetCodexAuthUrlSessions() +}) diff --git a/test/unit/crs-headers.test.mjs b/test/unit/crs-headers.test.mjs index 73eb5a706a..d0800c0661 100644 --- a/test/unit/crs-headers.test.mjs +++ b/test/unit/crs-headers.test.mjs @@ -489,3 +489,30 @@ test('official agent ids pass through and are not stored', () => { assert.equal(unofficial['x-claude-code-parent-agent-id'], undefined) fs.rmSync(dir, { recursive: true, force: true }) }) + +test('storeAccountHeaders persists kin-cc-headers.json atomically with 0600 permissions', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-cc-mode-')) + try { + const res = storeAccountHeaders( + dir, + { + 'user-agent': 'claude-cli/2.1.321 (external, cli)', + 'anthropic-version': '2023-06-01', + 'anthropic-beta': 'oauth-2025-04-20,claude-code-20250219', + }, + { officialTraffic: true }, + ) + assert.equal(res.stored, true) + assert.equal(res.wrote, true) + const file = path.join(dir, '.claude', 'kin-cc-headers.json') + if (process.platform !== 'win32') { + assert.equal(fs.statSync(file).mode & 0o777, 0o600) + } + assert.deepEqual( + fs.readdirSync(path.join(dir, '.claude')).filter((name) => name.includes('.tmp')), + [], + ) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/test/unit/oauth-auth-url.test.mjs b/test/unit/oauth-auth-url.test.mjs index 55552e2812..2738d551cf 100644 --- a/test/unit/oauth-auth-url.test.mjs +++ b/test/unit/oauth-auth-url.test.mjs @@ -12,6 +12,7 @@ import { REDIRECT_URI, SCOPE_OAUTH, OAUTH_FLAVORS, + MAX_OAUTH_SESSIONS, linkCredentialFromToken, } from '../../src/lib/oauth/oauth-auth-url.mjs' @@ -164,3 +165,15 @@ test('link exchange derives identity from the token when the helper sent none', assert.equal(credential.refresh_token, '') assert.equal(credential.flavor, 'cai') }) + +test('generateAuthUrl bounds pending sessions by evicting oldest at MAX_OAUTH_SESSIONS', () => { + resetAuthUrlSessions() + const first = generateAuthUrl({ vmId: 'vm-01', proxyUrl: '' }) + let last = first + for (let i = 0; i < MAX_OAUTH_SESSIONS; i++) { + last = generateAuthUrl({ vmId: 'vm-01', proxyUrl: '' }) + } + assert.equal(peekAuthUrlSession(first.session_id), null) + assert.ok(peekAuthUrlSession(last.session_id)) + resetAuthUrlSessions() +}) diff --git a/test/unit/security.test.mjs b/test/unit/security.test.mjs index a04990541e..a2e6b5fdf5 100644 --- a/test/unit/security.test.mjs +++ b/test/unit/security.test.mjs @@ -201,3 +201,49 @@ test('loadConfig distinguishes explicit KIN_RATE_CAP=0 from default rate limits' else process.env.KIN_RATE_REFILL = prevRefill } }) + +test('extractPanelToken tolerates malformed percent-encoding in Cookie header', async () => { + const { extractPanelToken } = await import(`../../src/lib/core/security.mjs?badcookie=${Date.now()}`) + const token = extractPanelToken({ + headers: { cookie: 'bad=%E0%A4%A; kin_panel_token=kin-panel-abc123; raw=100%' }, + }) + assert.equal(token, 'kin-panel-abc123') +}) + +test('createRateLimiter bounds bucket map size when rotating keys hit maxKeys', async () => { + const { createRateLimiter } = await import(`../../src/lib/core/security.mjs?bound=${Date.now()}`) + const allow = createRateLimiter({ capacity: 1, refillPerSec: 0.001, maxKeys: 3 }) + assert.equal(allow('k1'), true) + assert.equal(allow('k1'), false) + assert.equal(allow('k2'), true) + assert.equal(allow('k3'), true) + // Adding k4 evicts oldest entry k1; k1 is treated as fresh again while k3 remains throttled. + assert.equal(allow('k4'), true) + assert.equal(allow('k3'), false) + assert.equal(allow('k1'), true) +}) + +test('applyIntercept blocks prototype pollution and avoids mutating nested input body', async () => { + const { applyIntercept } = await import('../../src/lib/core/intercept.mjs') + const original = { nested: { keep: 1 } } + const rules = [ + { + id: 'sec', + enabled: true, + phase: 'before_upstream', + action: { + set_body_field: { + '__proto__.polluted': 'yes', + 'constructor.prototype.polluted2': 'yes', + 'nested.added': 2, + }, + }, + }, + ] + const out = applyIntercept(rules, 'before_upstream', { body: original, headers: {} }) + assert.equal({}.polluted, undefined) + assert.equal({}.polluted2, undefined) + assert.equal(out.body.nested.added, 2) + assert.equal(out.body.nested.keep, 1) + assert.equal(original.nested.added, undefined) +}) diff --git a/test/unit/usage-cache.test.mjs b/test/unit/usage-cache.test.mjs index 8ec6e53a08..25f9741bdd 100644 --- a/test/unit/usage-cache.test.mjs +++ b/test/unit/usage-cache.test.mjs @@ -156,3 +156,17 @@ test('thrown upstream errors are negatively cached and counted once', async () = assert.equal(stats.upstream_fetches, 1) assert.equal(stats.upstream_failures, 1) }) + +test('createUsageCache bounds store size by sweeping stale entries then oldest', async () => { + const t = clock() + const cache = createUsageCache({ now: t.now, jitter: false, maxEntries: 2 }) + await cache.load('acc-1', async () => ({ ok: true })) + t.advance(1000) + await cache.load('acc-2', async () => ({ ok: true })) + t.advance(1000) + await cache.load('acc-3', async () => ({ ok: true })) + assert.equal(cache.size(), 2) + assert.equal(cache.peek('acc-1'), null) + assert.equal(cache.peek('acc-2')?.hit, 'ok') + assert.equal(cache.peek('acc-3')?.hit, 'ok') +})