Skip to content

fix(core,identity,oauth): bound session/cache maps, harden cookie/intercept/file writes, and prune dead exports - #2465

Merged
dofastted merged 1 commit into
devfrom
fix/r4-core-identity-oauth
Dec 1, 2026
Merged

dofastted merged 1 commit into
devfrom
fix/r4-core-identity-oauth

Conversation

@dofastted

@dofastted dofastted commented Dec 1, 2026 •

Copy link
Copy Markdown
Owner

变更摘要

  • 改前:
    • 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 新建测试文件)。
  • 未改 / 延后:

验收记录(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 个关联单测套件。

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 intercept set_body_field blocks 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 fileLocks keys 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.json is written via atomic JSON with 0600; native kin-oauth-auth subprocesses get timeout, 1 MiB output limits, and single-settle handling; import-commit and usage-probe use optional accountQuota calls 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.

…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 个关联单测套件。
@cursor

cursor Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Bugbot couldn't run - usage limit reached

Bugbot 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)

@dofastted

Copy link
Copy Markdown
Owner Author

验收评论(head 8705956e7f0a8155737a7e25a060120668907a4a,已合入 origin/dev 062f9abac,无冲突)

范围:核心/身份/OAuth 层的上限与写入加固(限流桶、面板会话、Codex OAuth 会话、用量缓存按上限淘汰;cookie-auth 原生 helper 加超时与输出上限;头文件改原子写 0600;import-commit 吞异常处加 warn;拦截规则 setPath 拒绝 __proto__/constructor/prototype 并改为写时复制),外加清理未使用导入。

Run:Node 22 容器 + 真实 kin-scheduler:npm run test:ci 250/250(这个 PR 的新用例并入了 security、crs-headers、usage-cache、codex-oauth、oauth-auth-url);关联 94 个文件 1792 个用例,容器内 5 个失败文件本机复跑后只剩 4 个:gemini-foundation(当时 dev 上 #2461 留下的陈旧熔断断言,现已由 #2476 修复)、oauth-binary(缺 bin/kin-oauth-auth,dev 上同样失败)、scoped-intercept-session(dev 基线红)、usage-probe-monitor(2 个失败用例,与 dev 上用例名逐条相同)。

Broken by hand(锚点唯一、还原后 sha256 一致):去掉限流桶淘汰触发 → security.test.mjs 变红;去掉用量缓存的容量判断 → usage-cache.test.mjs 变红;去掉 Codex OAuth 会话上限 → codex-oauth.test.mjs 变红。两处没被拦下,如实记:面板会话 MAX_PANEL_SESSIONS 上限没有用例(要造 1 万个会话才能触发);去掉 setPath 的 __proto__ 守卫仍然全绿——因为同一个 PR 的写时复制已经让原型污染落不到全局 Object.prototype 上,守卫是第二层,我按等价变异记,没有要求补用例。

Real use:用例走真实 createRateLimiter、createUsageCache、applyIntercept、generateCodexAuthUrl;cookie-auth 的原生 helper 超时/输出上限没有真实 helper 进程的用例(缺 helper)。没有 ph24。

Not run:原生 OAuth helper 超时与输出上限的真实进程验证;面板会话上限;全量后端测试。

@dofastted
dofastted merged commit 09fd24c into dev Dec 1, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant