Repository navigation
fix(core,identity,oauth): bound session/cache maps, harden cookie/intercept/file writes, and prune dead exports - #2465
Conversation
…ercept/file writes, and prune dead exports
## 变更摘要
- 改前:
- `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 个关联单测套件。
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: 845b85fd-9531-4f87-b997-6c3e8bcbb421) |
验收评论(head
|
变更摘要
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缺进程超时、输出上限与stdinEPIPE防护,且含未用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 新建测试文件)。src/lib/oauth/oauth-credentials.mjs(fix(account): unify account RW mirror, temp-park SSOT, and sorted PG UNNEST writes #2457)、src/lib/oauth/openai-quota.mjs(fix(scheduler): converge sticky, codex holds, and Claude circuit state onto Rust SSOT #2455)、src/lib/core/panel-2fa.mjs(fix(panel,db): align PG pre-agg metrics, async reprice, query shapes, N+1, locks, and cache invalidation #2460)、src/lib/core/errors.mjs(feat(quota): add Anthropic daily VM session creation gate #2441/fix(gemini): align Antigravity model format policy, capability SSOT, ACP 503/409 handling, and pin CRAGGemini 0.6.3 #2453)、src/lib/identity/{crs-persona,persona-template,system-prompt-spec}.mjs(fix(prompt): align zero-inject preset parsing, WS pool SSOT, and panel copy #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)
X:\vm2api-wt-r4-core-id(分支fix/r4-core-identity-oauth,基于origin/dev566e0c1db)。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 headerFAIL(URIError: URI malformedatparseCookie)-> 恢复后security.test.mjs全部 PASS。src/lib/oauth/oauth-auth-url.mjs中MAX_OAUTH_SESSIONS淘汰循环 ->generateAuthUrl bounds pending sessions by evicting oldest at MAX_OAUTH_SESSIONSFAIL(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)
npm run test:unit)、Docker/KVM 集成 E2E、前端web/测试与构建(未改动web/)及ph24线上实测:本次改动严格限定在src/lib/{core,identity,oauth},已覆盖test:ci(13 套件)与全库git grep -l命中的全部 50 个关联单测套件。Note
Medium Risk
Touches authentication/session parsing, intercept body mutation, and OAuth import commit paths where new caps or logging could affect edge-case behavior, but changes are defensive and covered by added unit tests.
Overview
Hardens core security and intercept behavior: cookie parsing no longer throws on bad
%encoding, rate-limiter and in-memory panel session maps get expiry sweep and caps (10k), and interceptset_body_fieldblocks prototype-pollution path segments while cloning nested body objects instead of mutating caller input.Adds bounded in-memory state across OAuth and usage paths: pending browser OAuth / Codex authorize sessions cap at 1000 with FIFO eviction, usage cache entries cap at 4096, Claude reset
fileLockskeys drop after settle, and usage-probe backoff entries for VMs that left the target set are cleaned up.Improves operability and durability:
kin-cc-headers.jsonis written via atomic JSON with0600; nativekin-oauth-authsubprocesses get timeout, 1 MiB output limits, and single-settle handling; import-commit and usage-probe use optionalaccountQuotacalls and structured warnings instead of silent empty catches. Unused exports/imports are pruned across identity/oauth modules, with unit tests for the new bounds and hardening.Reviewed by Cursor Bugbot for commit 8705956. Configure here.