Skip to content

feat: codex takeover, history sync, and embedded web UI - #73

Merged
ranxianglei merged 11 commits into
ranxianglei:masterfrom
LX666-666:2026-08-09_bundle-acp-kernel
Aug 10, 2026
Merged

ranxianglei merged 11 commits into
ranxianglei:masterfrom
LX666-666:2026-08-09_bundle-acp-kernel

Conversation

@LX666-666

Copy link
Copy Markdown
Contributor
  • Add codex-takeover module to intercept and redirect codex traffic
  • Add codex-history for persistent conversation history sync
  • Add codex-provider for active provider capture
  • Add content-encoding helpers for transparent body decoding
  • Replace monolithic src/web.ts with modular src/web/ (api/client/page/styles)
  • Refactor upstream-proxy: cleaner CONNECT handling, per-URL config
  • Update responses/server/cli/config to wire new modules
  • Add 6 new test files covering codex, web routing, content encoding

- Add codex-takeover module to intercept and redirect codex traffic
- Add codex-history for persistent conversation history sync
- Add codex-provider for active provider capture
- Add content-encoding helpers for transparent body decoding
- Replace monolithic src/web.ts with modular src/web/ (api/client/page/styles)
- Refactor upstream-proxy: cleaner CONNECT handling, per-URL config
- Update responses/server/cli/config to wire new modules
- Add 6 new test files covering codex, web routing, content encoding

Co-Authored-By: AtomCode (GLM-5.2) <noreply@atomgit.com>
@ranxianglei

Copy link
Copy Markdown
Owner

Review:「无法使用工具」根因 —— text-protocol 下 custom_tool_call 被整段丢弃

环境验证:Codex 0.144(ChatGPT 登录态)+ x-openai-internal-codex-responses-lite header + additional_tools,本分支会自动进入 text-protocol(isCodexResponsesLite 命中)。日志现象:每轮 tools=[]、acp-diag allCalls=[] realCalls=[]、output≈345(纯文本),会话 16→18→20 全是文本,模型反复说「开始执行、检查 git」却永远调不出工具。

Codex 的 code_mode 工具(shell_command/apply_patch 等)是经 additional_tools 声明的,模型调用时上游回的是 custom_tool_call 类型的 output_item,不是 function_call。而 compress loop 在 text-protocol 下恰好把 custom_tool_call 整段丢了。三处叠加:

① 事件分类只认 function_call(classifyResponsesSseEvent,src/compress-loop-responses.ts)

case "response.output_item.added": {
    const item = obj.item as Record<string, unknown> | undefined;
    if (item?.type === "function_call") {   // ← 只认 function_call
        out.fcStart = { ... }               // 进 fcByItemId 累加器
        return out;
    }
    out.yieldChunk = Buffer.from(eventStr + "\n\n", "utf8");  // custom_tool_call 走这里(只设 yieldChunk)
    return out;
}

response.function_call_arguments.delta 分支也只累加 function_call 的参数。所以 custom_tool_call 既不进 contentText(只有 output_text.delta 进),也不进 fcByItemId。

② text-protocol 的 yield 闸门把所有非 meta 事件实时吞掉(line 448)

if (d.yieldChunk && (isFirstRound || !d.isMeta) && !(textProtocol && !d.isMeta)) {
    yield d.yieldChunk;
}

text-protocol 时第 3 项 !(textProtocol && !d.isMeta) = !true = false → custom_tool_call 的 SSE 事件实时一个都不吐(这是故意的,为了先把 output_text 攒齐再扫压缩 trigger,但把 custom_tool_call 也一起误伤了)。

③ 回合末重建只吐文本,不重建 custom_tool_call(line 512-549)

if (textProtocol) {
    const extracted = extractTextTriggers(contentText);
    contentText = extracted.clean;
    ...
    if (contentText.trim()) {
        yield buildMessageItemSequence(textItemId, nextOutputIndex++, contentText); // ← 只吐清洗后的文本
    }
}
...
const allCalls = [...fcByItemId.values()]...;   // ← 只有 function_call,custom_tool_call 不在里面
const realCalls = allCalls.filter((c) => !PROXY_TOOL_NAMES.has(c.name));
if (!hasOnlyProxy) {
    for (const fc of realCalls) yield buildFunctionCallEvents(fc, oi);  // ← realCalls 为空
    yield buildCompleted(responseObj);   // ← 直接收尾
    return;
}

结果:模型那一轮的 custom_tool_call 既没实时透传、也没在末尾重建 → Codex 收到的只有一段文本 + 一个 completed,工具调用凭空消失。

为什么 function_call 工具没事、只有 code_mode 工具坏

  • 顶层 tools 里的标准工具 → 模型回 function_call → 被 line 177/202 捕获进 fcByItemId → 末尾 line 534 用 buildFunctionCallEvents 重建。✅
  • additional_tools 里的 code_mode 工具 → 模型回 custom_tool_call → 没有任何分支捕获 → 闸门吞掉、末尾也不重建。❌

而 text-protocol buffer 的本意只是「把 assistant output_text 攒齐以便扫 <acp_compress> trigger」,把 custom_tool_call 也一起 buffer 是误伤——custom_tool_call 里根本不可能有压缩 trigger。


修复建议(两选一)

方案 A(最小改动,推荐):让 custom_tool_call 事件在 text-protocol 下实时透传,不进 buffer。

  • 在 classifyResponsesSseEvent 给 custom_tool_call 相关事件(output_item.added/done 且 item.type==="custom_tool_call",以及 response.custom_tool_call.input_text.delta/done)打一个标记,比如 out.noBuffer = true。
  • line 448 改成:!(textProtocol && !d.isMeta && !d.noBuffer)。

这样 code_mode 工具调用照常实时流给 Codex,只有 output_text 仍被 buffer 用于扫 trigger。

方案 B:把 custom_tool_call 也累加、末尾和 realCalls 一起重建。

  • 在 output_item.added/output_item.done 和对应 delta 里捕获 custom_tool_call,末尾用 buildFunctionCallEvents 风格重新发 custom_tool_call 事件。
  • 改动更大,且要小心 input_text.delta/done 的事件名拼接,容易出错。

同时(无论哪个方案)建议修一下诊断:allCalls/realCalls 统计加上 custom_tool_call,否则 [acp-diag] 永远显示 realCalls=[],排查时会被误导。

如果需要,我可以按方案 A 直接提一个 patch。

Codex code_mode tools (shell_command/apply_patch, declared via
additional_tools) come back from upstream as custom_tool_call output
items, not function_call. In text-protocol mode (auto-enabled for Codex
by PR#73), the compress loop's realtime yield gate suppressed ALL
non-meta events to buffer output_text for compress-trigger scanning.
custom_tool_call items were neither captured (only function_call is) nor
re-emitted at end-of-turn (only output_text is) — so every code_mode
tool call was silently dropped, and Codex received only text. This is
the root cause of the reported '无法使用工具'.

Fix: tag custom_tool_call events with noBuffer so they bypass the
text-protocol suppression and stream to the client in realtime (the same
behavior that already works in non-text-protocol mode). output_text is
still buffered for trigger scanning. Also count custom_tool_call items
in [acp-diag] so code_mode usage is visible (allCalls is function_call
only).

Note: NOT tested against a live Codex session. Validated via:
- npm run typecheck (clean)
- npm test (202 pass, incl. new regression test that fails on the
  unpatched code and passes with this fix)

Conflict note: touches only src/compress-loop-responses.ts (PR#73-only
file, not modified by master), so it will not conflict with the
responses.ts/server.ts merge conflicts that PR#73 currently has with
master.
@ranxianglei

Copy link
Copy Markdown
Owner

已实现修复:custom_tool_call 在 text-protocol 下透传

分支:fix/codex-custom-tool-call-text-protocol(commit ed4d4c4,基于本 PR 的 97190f5)
ed4d4c4

改动(仅 2 个文件,+42/−2)

src/compress-loop-responses.ts — 采用上一条评论的方案 A:

  1. ResponsesEventDisposition 新增 noBuffer?: boolean 和 customToolCallDone?: boolean 两个字段。
  2. classifyResponsesSseEvent 里给 custom_tool_call 相关事件打 noBuffer=true:
    • response.output_item.added 且 item.type==="custom_tool_call"
    • response.output_item.done 且 item.type==="custom_tool_call"(同时置 customToolCallDone)
    • default 分支里 type.startsWith("response.custom_tool_call.") 的事件(input_text delta/done 等)
  3. yield 闸门(line 462)由 !(textProtocol && !d.isMeta) 改为 !(textProtocol && !d.isMeta && !d.noBuffer) —— custom_tool_call 实时透传,output_text 仍进 buffer 扫 trigger。
  4. [acp-diag] 日志加上 customToolCalls=N 计数(因为 allCalls 只统计 function_call,code_mode 用量原本不可见)。

tests/proxy-responses-stream.test.ts — 新增回归测试:「Codex code_mode custom_tool_call passes through in text-protocol」。该测试在未打补丁的代码上会 FAIL(custom_tool_call item reaches the client 断言不通过),打补丁后 PASS,可作为回归守卫。

验证情况(⚠️ 未做实机测试)

按要求标注:没有也无法跑真实 Codex 会话验证。以下都是静态/单测层面的验证。

  • ✅ npm run typecheck —— 干净通过
  • ✅ npm test —— 202 pass / 0 fail(原 201 + 新增 1 回归测试)
  • ✅ 回归测试在原始代码上确认 FAIL、打补丁后 PASS(双向验证测试有效)
  • ⚠️ 未验证:真实 Codex 的 SSE 事件名(response.custom_tool_call.input_text.delta 等是按 Responses API 规范推断的;若上游实际事件名不同,default 分支的 startsWith("response.custom_tool_call.") 兜底应仍能命中,但建议实机确认一次 [acp-diag] ... customToolCalls=N 是否 >0)
  • ⚠️ 未验证:output_index 乱序影响。本方案让 custom_tool_call 实时透传(在重建的 text message 之前到达客户端)。Responses API 的 output_index 本就是为乱序设计的,Codex 客户端应按 index 归位;但这点也建议实机确认。

冲突评估(本 PR 与 master)

master 在本 PR 的 merge-base 之后合并了 #71(reasoning 走压缩管线)、#72(count_tokens)、release v0.1.28。试 merge 结果:

文件 结果
README.md / README.zh-CN.md / package.json ✅ 自动合并
src/responses.ts ❌ 6 处冲突
src/server.ts ❌ 2 处冲突

性质上可解,但需人工 + 测试:冲突是 PR#73 的 layout-based 输入重建(ResponsesProjection.layout / patchResponsesInput)与 master #71 的 reasoning 压缩(droppedReasoning / shouldDropAllReasoning)在同一区域交织,两者功能正交,合的时候要同时保留 layout 字段和 droppedReasoning 字段。responses.ts line 340-417 那块最大(~77 行),需要仔细手解。建议由 PR 作者 rebase 到最新 master 后解冲突,并跑一遍 reasoning 相关测试(tests/bili-message-roundtrip.test.ts 是 master 新加的)。

好消息:本次修 custom_tool_call 的改动只在 compress-loop-responses.ts,这个文件 master 没动过,所以不会和 master 冲突,可以干净地 cherry-pick 到解完冲突后的分支上。

建议的落地顺序

  1. PR 作者把 PR#73 rebase 到 master,手解 responses.ts / server.ts 冲突(保留 layout + droppedReasoning 两套)。
  2. Cherry-pick ed4d4c4(或直接 merge fix/codex-custom-tool-call-text-protocol,它基于 97190f5,应该能干净合入)。
  3. 实机跑一次 Codex,确认 [acp-diag] ... customToolCalls=N 在调用工具时 >0、且工具能真正执行。

Ported master's reasoning-through-compression (ranxianglei#71) and count_tokens (ranxianglei#72)
features onto PR#73's layout-based patching architecture:

responses.ts:
- Removed 'reasoning' from OPAQUE_ITEM_TYPES (master: reasoning is
  conversation history, routed through compression, not preserved verbatim)
- Added droppedReasoning counter + shouldDropAllReasoning() escape hatch
  (ACP_REASONING_KEEP=none)
- Added 'reasoning' case to responsesToCore switch: creates a tracked
  BiliMessage (contentType 'reasoning', rawResponsesItem carried) so the
  kernel hides it once its turn is summarized; dropped reasoning uses
  'continue' to skip layout.push so it is fully removed
- Added reasoning re-emit to coreToResponses (assistant contentType
  'reasoning' -> push raw verbatim)
- patchOriginalItem needs no change: reasoning items are preserved via
  slot.original when their turn is live, dropped (nextById miss) when
  compressed -- correct by construction

server.ts:
- Added countTokens detection (isCountTokensRequest) + prepareCountTokens
  (read-only processTurn mirror so count_tokens reports post-compression
  count; ACP_COUNT_TOKENS_PASSTHROUGH=1 escape hatch)
- Merged prepare ternary: countTokens -> anthropic -> openai ->
  responsesCompact -> responses

Validation: typecheck clean, 216 tests pass (incl. 9 reasoning + 3
count_tokens + custom_tool_call fix), build ok.
readProviders previously read only the inline config.providers entries
without normalizeUrlKey or merging the external ACP_PROVIDERS file, so the
web UI could show a different route set than the running proxy actually
used. Delegate to loadRoutes() (already used by the /reload endpoint) so
display == runtime.
- responses.ts: route opaque call items (computer_call, file_search_call,
  web_search_call, image_generation_call, code_interpreter_call, mcp_call)
  through compression via contentType 'reasoning' with 'responses-call' kind.
  Track custom_tool_call/custom_tool_call_output fully (port master).
  Lift developer/system messages out of layout into systemParts (avoid
  duplication when re-injecting as developer message).
- server.ts: include systemParts (base instructions) in the injected
  developer message alongside the compress prompt; restore base instructions
  even when compress injection is disabled. Strip previous_response_id and
  top-level instructions (lifted into developer message).
- tests: update codex-official + proxy-responses-review for new behavior
  (instructions lifted into developer message; custom_tool_call tracked).
…viders

Custom Codex providers routinely omit requires_openai_auth and
supports_websockets (they are optional in Codex's native config).
The strict validation threw an error for any custom provider missing
them, surfacing a confusing warning on the web config page even though
the provider was fully functional.

Default both fields to false for custom providers (matching Codex's own
behavior: custom providers don't use OAuth and don't support websockets).
The builtin 'openai' provider still uses its documented defaults.
Tighten boolField to require a boolean fallback so the resolved fields
are always typed boolean.
@ranxianglei

Copy link
Copy Markdown
Owner

Code Review: PR #73 — codex takeover / history sync / embedded web UI

分支 pr-73(commit 97190f5,+3679/−1033,37 文件)。已独立验证:build ✅ · typecheck ✅ · 201/201 测试通过。

总体方向很好:web.ts 拆成模块化 web/、codex 本地路由接管的状态机设计(先写 state 再改 config、三路比较恢复、原子写)思路正确,dist 保持自包含(noExternal 打包 fzstd/acp-kernel,node-forge 经 banner shim 兼容 ESM)。但有几个真实缺陷建议合并前修复,集中在两处:① codex 配置变异路径的鲁棒性(损坏态会清空用户 config);② MITM/CONNECT 的资源与竞态。下面按优先级列出。


🔴 阻塞合并(critical / high)

1. parseState 遇损坏 state 文件直接 throw → 整个 codex 子系统瘫痪

src/codex-takeover.ts:125-143

function parseState(statePath) {
    if (!existsSync(statePath)) return undefined;
    try { /* ...schema 校验... */ } catch {}
    throw new Error(`invalid Codex route ownership state: ${statePath}`);
}

文件存在但损坏(截断/手改/磁盘错误)时抛异常,而所有入口(status/enable/disable/recover/claim/recordRequest)都裸调用、无 try/catch。此时 ~/.codex/config.toml 仍被劫持指向死代理,但 API 连状态都报不了、恢复也无路可走 → codex CLI 彻底不可用,只能手动 rm state 文件。建议损坏态降级为"视为 stale 并提供恢复",而非抛错。

2. sectionPrefixLength 无类型校验 → 清空整个 config.toml

src/codex-takeover.ts:129-138 + codex-provider.ts:319-321

parseState 校验了很多字段却漏了 sectionPrefixLength。若它是非数字(损坏/手改的 state,如 "abc"),则:

const start = Math.max(0, section.headerStart - prefixLength); // NaN
return text.slice(0, start) + text.slice(section.end);         // slice(0, NaN) === ""

sectionAdded 分支下追加段在文件末尾(section.end === text.length),结果 "" + "" → 用户整个 Codex 配置被抹掉。与 #1 的损坏态叠加触发。建议:校验该字段为非负整数,或干脆不持久化、disable 时按 before 的真实尾换行重算。

3. MITM 隧道超时不取消在途连接 → upstream socket 泄漏 + 写已销毁 socket

src/mitm.ts:101-126

const connectTimer = setTimeout(() => {
    if (!established) { clientSocket.write("504..."); clientSocket.destroy(); } // 只销毁 clientSocket
}, 15000);
connectThroughProxy(...).then((upstream) => {
    established = true;            // ← 从未被读取来 gate 后续逻辑
    clientSocket.write("200 ..."); // ← 超时后仍会写入已 destroy 的 socket
    upstream.pipe(clientSocket);   // upstream socket 无人关闭 → 泄漏

established 只用于一次性定时器,没在 .then 里判断"定时器是否已触发"。慢上游(T+16s 才连上)场景:T+15s 发 504+销毁 client,T+16s .then 再写 200、把新开的 upstream pipe 到死 socket。此前的 45ac6a1 修的是另一个 race,这个没修。建议:.then 内 if (aborted) { upstream.destroy(); return; },并让超时能取消在途连接。

4. 直连路径完全没有连接超时

src/upstream-proxy.ts:301-309

if (!proxyUrl) {
    return new Promise((resolve, reject) => {
        const socket = net.connect(port, host);
        socket.once("connect", () => resolve(socket));
        socket.once("error", reject);  // ← 无 setTimeout,依赖 OS ~127s(tcp_syn_retries)
    });
}

只有代理分支(line ~322)有 10s 握手超时。配合 #3,504 之后半开 socket 还要挂 ~2 分钟。建议像代理路径一样加超时,并返回 socket 供调用方销毁。


🟠 重要(should-fix)

5. DNS rebinding CSRF → 可改写 upstream 代理、泄漏 API key

server.ts:270-278, 296-305

isTrustedAdminOrigin 只校验 Origin.host === Host,两者都客户端可控,Host 未钉到监听地址:

function isTrustedAdminOrigin(origin, host) {
    if (!origin) return true;          // 缺省 Origin → 放行
    if (!host) return false;
    const parsed = new URL(origin);
    return (parsed.protocol === "http:" || "https:") && parsed.host === host;
}

攻击网页经 DNS rebinding(evil.com→127.0.0.1)发起 fetch:浏览器在本地 → remoteAddress 是 loopback(过门控);Host==Origin==evil.com:8787(过 origin 校验)。于是可 PUT /__bili/config 把 upstreamProxy 指向攻击者 → 后续所有模型请求的 API key/OAuth token 经攻击者代理外泄(代码注释自己也点明这个 MITM 风险)。直接 fetch('http://127.0.0.1:8787') 会被挡(Origin≠Host),但 rebinding 绕过。建议:钉死 Host 为监听地址,或加 Sec-Fetch-Site: same-origin/CSRF token。

6. PID 回收 → 永久 stale 锁

codex-takeover.ts:177-185

pidAlive 只检测 PID 是否存在,无 starttime/handshake token。bili 崩溃后 PID 被回收(容器/繁忙主机常见),recoverStaleCodexTakeover 误判"仍活着"而不恢复 → codex 永久指向死代理。EPERM 分支(其他用户进程)也会误判为 alive。建议存 pid+starttime 或随机 secret 校验。

7. recordCodexRouteRequest 每请求一次 fsync 原子写 + 与 disable 竞态

codex-takeover.ts:390-396

仅更新 lastRequestAt 时间戳却走完整 atomicWrite(temp+fsync+rename)→ 高负载写放大;且是 read-modify-write,与 disableCodexTakeover 交错时会在 disable 删掉 state 后又把它"复活"(recorder 读到旧态、disable 删文件、recorder 再写回 active:true),之后 status 报 conflict、recover 重复 disable 已恢复的配置。建议:写到独立 sidecar,或加互斥/标记。

8. 无界 per-host 证书缓存 + 同步 RSA keygen → DoS

ca.ts:84-109 + mitm.ts:142-160

isMitmHost 按后缀匹配白名单域的任意子域;每个唯一 hostname 跑一次同步 rsa.generateKeyPair({bits:2048})(~100ms 阻塞事件循环)并存入 secureContextCache(无 LRU/淘汰,仅 _resetForTest 清)。getSecureContext 在上游连接前就调用,所以 CONNECT 1.chatgpt.com … CONNECT N.chatgpt.com 即可打满 CPU + 内存,缓存 key 全攻击者可控。建议加 LRU,或每域预生成一张通配证书。

9. Responses 会话身份回退回归(影响压缩对部分客户端的有效性)

src/responses.ts:304-316(对照 master :422-443)

master 的 conversationSignalResponses 回退链:header → body.session_id → previous_response_id → 内容指纹(hashId);本 PR 的 conversationIdentityResponses 改为:… → metadata.session_id → generated-${randomUUID()}。previous_response_id 链和内容指纹都被丢掉(import 也从 hashId 换成 randomUUID)。

后果:不发送 session_id 的 Responses 客户端(普通 OpenAI SDK 用法、部分 Codex 边角)每请求新建会话 → 压缩状态无法累积(本代理的核心价值失效)+ LRU(256)快速抖动 + 每请求落一个持久化会话文件。Codex 自己发 session_id 所以没被发现,无测试覆盖回退路径。建议恢复 previous_response_id→内容指纹链。

10. hop-by-hop 头未完整剥离 → proxy-authorization 转发到上游

server.ts:63-72

UPSTREAM_HOP_HEADERS 只含 {host, content-length, connection, keep-alive, transfer-encoding, content-encoding}。客户端发给"bili 作为代理"的 Proxy-Authorization: Basic <凭据> 会被原样转发到上游模型端点(凭据泄漏);还缺 te/trailer/upgrade 以及 RFC 7230 §6.1 要求按 Connection 值剥离的命名头。属既有问题,但被新 MITM 隧道路径放大。

11. 开放转发代理(LAN 绑定时)

mitm.ts:48-127

--host 0.0.0.0 时 CONNECT 处理器无鉴权、无 loopback 门控、不限目标 → CONNECT 内网db:5432 任意 host:port 的匿名 TCP 中继(隐藏来源/打内网/CONNECT 端口扫描)。建议:除非显式 opt-in,CONNECT 也限 loopback,或限制到 MITM 白名单。


🟡 低优先

  • registry.ts:50 在 ESM 源里用 require("node:fs")(仅靠 tsup banner shim 在生产生效;dev/test 下被 try/catch 吞掉 → 24h 磁盘缓存新鲜度检查恒失效,每次启动重抓 models.dev)。改 import { statSync }。
  • codex-history.ts:197-227 rewriteSessionFile 无文件锁,仅 size+mtime TOCTOU;codex 正在追加会话时跑迁移会静默丢失新增行。
  • codex-provider.ts:295 appendCodexProviderSection 把 providerId 原样插进 [model_providers.${providerId}](当前仅内置 "openai" 可达,但导出函数是注入隐患)。
  • 路由匹配:key 带尾斜杠不匹配裸 origin(upstream-proxy.ts:226);NO_PROXY 裸 host 不匹配子域(偏离 curl 语义,:161-162);parseHostPort 解析 IPv6 CONNECT 保留方括号(mitm.ts:73-80)。
  • content-encoding.ts:24-29 deflate 回退吞掉真实 zlib 错误(bare catch),损坏体被解压两次。
  • 死的安全数据:configHashBefore(codex-takeover.ts:311)、insertedFields 计算并持久化但全程无消费者(本可用 hash 守护"启用期间配置是否被外部改动",现在没用上)。
  • 无退出清理:bili 停止/崩溃后 ~/.codex/config.toml 仍指向死代理,依赖下次启动 recoverStaleCodexTakeover(且受 fix: post-merge review fixes + per-route context window + XDG config #6 PID 回收影响)。无 SIGTERM/SIGINT 钩子。
  • affinityToken 行为有意变更但注释陈旧:session-id.ts:82-83 现仅 clientProvided 时返回值(by-design,新注释明确"生成的代理身份不转发"),但 server.ts:512-514 注释仍描述旧的 ses_<conversation> 合成 → 文档/代码不一致,且 headerless 客户端(pi 等)上游拿不到稳定 affinity key,前缀缓存池不保热(性能影响,非崩溃)。
  • 信息暴露:/__bili/stats 把会话 title(用户首条消息前 60 字符)暴露给任何本地进程;config GET 明文返回 upstreamProxy(含 user:pass,日志侧已用 redactProxyUrl,API 未脱敏)。

✅ 做得好的地方(已逐一核对)

  • dist 自包含:fzstd 经 noExternal 打包进 dist/,零运行时依赖 — 所以 fzstd 放 devDependencies 是 by-design,不是 bug。
  • Web UI XSS 处理正确:escapeHtml 覆盖 sessions 表所有 innerHTML 动态值,其余用 textContent/.value;page.ts 只插值 origin(来自 opts.host:opts.port,非请求 Host 头)和 version;无 inline handler(测试断言 addEventListener 存在且无 onclick=)。
  • 原子写配置(web/api.ts):openSync("wx", 0o600)(防 symlink 覆盖)+ 随机临时名 + fsync + 同目录 rename;state 先于 config 写入(崩溃在中途仍可恢复)。
  • 会话 ID 基于 SHA-256(protocol|upstream|apiKey|conversation),API key 哈希后用作键且从不存储/日志/转发;deriveSessionId 对匿名会话抛错而非塌缩到同一 id。
  • loopback 门控对非 rebinding 的 LAN/远程访问有效;validateHttpProxy 防自环。
  • 体积限制:config PUT 256KB,代理流量 MAX_REQUEST_BYTES→干净 413;handle() 全局 try/catch + uncaughtException 守护,bad request 不崩整个代理。

建议修复优先级

  1. fix: keep system prompt byte-stable for prefix cache #1+fix: address all code review findings (condense, routing, session-id, dead code) #2(损坏态不抛 + 校验 sectionPrefixLength)— 直接威胁用户 config.toml 数据安全,~10 行,成本极低。
  2. Use kernel renderTags:"text-only" + forbid tag echoing in prompt #3+feat: OpenAI Responses API support (/v1/responses) #4(CONNECT 超时/泄漏)— 真实资源泄漏,线上必现。
  3. feat: persistent + namespaced sessions, multi-tenant session isolation, stream robustness #5 CSRF 钉 Host / feat: self-update (auto + manual) #11 CONNECT 门控— 安全闭环。
  4. feat: release CI (npm auto-publish on release branch) #8 证书缓存 LRU / feat: bili CLI + debug in config + README rewrite #7 去掉 per-request fsync— 稳定性/性能。
  5. release v0.1.2 #9 Responses 回退链恢复— 影响核心功能(压缩)对部分客户端的有效性。
  6. 其余低优先项随迭代清理。

如果需要,我可以直接提补丁(比如 #1/#2 的 parseState 鲁棒化 + 字段校验,或 #5 的 Host 钉死 + Sec-Fetch-Site)。🤝

…URL proxy UI

- routing: rename 'Codex 路由' → '客户端接入'; Codex is one client card
  alongside Claude Code / Gemini CLI / MITM placeholders (each with
  setup instructions). Generic lead text covers both integration methods.
- upstream: default proxy mode 'direct' (was 'auto' which silently picked
  up system HTTP_PROXY env — risky for a proxy tool). Relabel modes:
  直连(默认) / 手动代理 / 自动(跟随系统).
- upstream: add '按 URL 覆盖' structured table — edit per-Provider upstream
  proxy inline (empty = inherit global). No longer buried in raw JSON.
- settings: relabel '高级设置', clarify it's for raw providers JSON
  (adding providers, model context windows, etc).
@ranxianglei

Copy link
Copy Markdown
Owner

Web 端设计评审(补充:交互 / 架构 / UX 层面)

上一条评论聚焦安全/正确性 bug,这条专门讲设计层面。底层(XSS 防护、原子写、body 限制)是对的方向 👍,这里只讲设计短板。

架构设计

1. 后端路由无抽象 —— 30+ 端点全靠 if (method===X && url===Y) 线性串联

server.ts:307-411、web/api.ts 没有路由表、没有统一响应契约(有的返回 {ok}、有的返回裸 status 对象、有的 {error})、没有统一错误处理层(每个 handler 自己 try/catch + sendError)。后果:新增端点要在长链里插、错误格式不一致、无法统一加日志/限流/鉴权。建议:抽一个 dispatch(method, url, handlers) 的小路由表 + 统一响应/错误中间件。

2. PUT /__bili/config 的 onChanged 漏刷 routes —— 契约不完整,职责甩给前端

server.ts:336-342 的 onChanged 只刷新了 upstream proxy 字段(opts.proxy/proxyMode/proxySource/proxyFallback + resetProxyCache),没动 opts.routes:

return handleConfigPut(req, res, () => {
    const fresh = loadOptions();
    opts.proxy = fresh.proxy;       // ← 只刷 proxy
    opts.proxyMode = fresh.proxyMode;
    opts.proxySource = fresh.proxySource;
    opts.proxyFallback = fresh.proxyFallback;
    resetProxyCache();
}, opts.port);                      // ← routes 没刷

所以前端 saveProviders()(client.ts)必须再追加一次 POST /__bili/config/reload 才能让 routes 生效;而 saveUpstream() 不改 routes 就不用 reload。这解释了"为什么两个保存接口行为不对称",但本质是后端没保证"保存即生效"——纯 API 调用方(非 Web UI)若只 PUT 不 reload,routes 写进了文件却对运行进程无效,且没有任何错误提示。建议:PUT 成功后后端自己刷新 routes(把 handleConfigReload 逻辑并进 onChanged),config/reload 降级为"强制重读文件"的运维端点。

3. 全量返回 + 全量覆盖 providers —— 多 tab 编辑互相覆盖,无乐观锁

handleConfigGet 返回整个 providers map;handleConfigPut(api.ts:145)在 hasProviders 时 config.providers = routes(全量覆盖,非 patch)。两个浏览器 tab 都开着 settings,A 保存后 B(持旧值)再保存会静默覆盖 A,无 ETag/version 校验。

交互 / UX 设计

4. "上游测试连接"测的是 origin HEAD,不是真实请求 —— 结果有误导性

server.ts:388-407

const targetUrl = new URL(target).origin;        // 去掉 path,如 .../v1 → 只测 host
fetchWithTimeout(targetUrl, { method: "HEAD", ...(proxy? {dispatcher} : {})}, 15_000)

不带 Authorization、不带真实 path。所以"连接成功 HTTP xxx"只代表 TCP/TLS 到 origin 通了,不代表 API key 对、不代表路由对。用户看到绿色 toast 会误以为配置正确,实则可能完全不通;UI 文案也没区分。建议:要么明确标注"仅测试网络可达性(不含鉴权)",要么带一个真实的轻量鉴权探针。

5. 危险操作的二次确认不一致 —— 方向反了

改系统配置文件(无备份)比改可备份的历史更危险,却无确认。建议:disable 前加确认,或至少展示"将恢复为:originalBaseUrl"。

6. 状态刷新策略三套并存,切页看到陈旧数据

  • 初始:Promise.all([loadConfig, loadRouting, loadUpstream, loadHistory])
  • 会话页:每 5s 轮询 /__bili/stats(仅当 active)
  • 路由/上游页:无自动刷新,只能手动点"预览/刷新"

后果:在"路由"页启用 codex,切到"上游"页看到的是启动时的旧数据;routeState 全局变量在 loadRouting pending 时若用户点 toggle,读的是旧值(无 in-flight 保护)。建议:关键状态页统一用轮询或 visibilitychange 触发刷新。

7. 错误处理风格不统一

有的弹 toast(saveUpstream、testUpstream),有的写进 DOM 文本框(loadRouting 的 route-detail.textContent = String(error)),有的两者都来(loadHistory 既 toast 又写 summary)。用户对"出错了"的感知不一致;且错误文案直接把 new Error(...).message 原文丢给用户,未友好化。

8. "概览"页是死页

landing 页只有静态文字(服务地址 + "在路由页接管…"两段说明),无动态状态、无快捷操作,作为首页价值低。建议:把 codex 路由状态徽标、上游连通性、活跃会话数等关键信号聚合到概览,让首页一眼看到健康度。

9. providers 配置是"裸 textarea 手写 JSON"(page.ts settings 页)

<textarea id="providers-json">{}</textarea>

无 schema 驱动表单、无前端校验、无字段说明(用户不知道一个 provider entry 长什么样)。点保存才在后端校验,失败靠 toast 报 "invalid provider entry: {url}"。这是"开发者工具"级 UX,README 里也没标明 provider 的字段结构。建议:要么给可编辑的列表项(每条 URL + contextWindow + proxy),要么至少加 schema 示例和 JSON 语法高亮。

数据 / 信息设计

10. config GET 返回明文 upstreamProxy(可能含 user:pass@host)并填入明文 input

api.ts:75、client.ts loadConfig。日志侧已用 redactProxyUrl 脱敏,API 没脱敏。UX 上:用户若没改密码就保存,等于把明文凭据再写回文件一次。建议:GET 时脱敏显示为 user:****@host,密码用单独字段维护。

11. /__bili/stats 把会话 title(用户首条消息前 60 字符)暴露给任何本地进程

loopback 内可接受,但多用户/共享机器有泄漏面。属于设计取舍:应在 UI/文档显式声明"本机任意进程可读会话标题"。

可维护性 / 工程化

12. client.ts 是手写压缩单行 JS 字符串嵌入

改一个交互要在单行里数分号、无 source map、无构建。测试(web-routing.test.ts)只用 new Function(WEB_CLIENT) 验证"能解析",无法验证行为。随着 UI 变复杂会越来越难维护。建议:引入轻量构建(或至少多行模板 + 一道 minify),让逻辑可读、可测。

13. CSS 纯深色,无 prefers-color-scheme,无主题切换

移动端有响应式适配 👍,但深色是强制的,白天看刺眼。

14. 无可访问性(a11y)

nav 是 button 但页面切换无 aria-current/role="tab";表单未用 <form>(Enter 不提交);toast 无 role="alert";表格无 <caption>。屏幕阅读器体验差。

安全设计(补充)

15. 无任何认证/Token,纯靠 loopback + Origin 校验

对"本地单用户开发工具"可接受,但 codex enable/disable 这种改系统配置文件的操作,设计上应有更显式的门槛(可选 PIN / 首次使用确认)。当前任何能跑在本机的进程(含恶意脚本)都能调 POST /__bili/codex/disable 或改 upstream。应在文档/UI 明确这点,别让用户以为是隔离的。


小结:web 端在 XSS 防护、原子写、body 限制这些底层是对的;主要设计短板集中在:①路由层抽象缺失、②PUT 契约不完整(onChanged 漏 routes,见 #2,这条最该先修——它让纯 API 调用方的 routes 配置静默失效)、③危险操作确认不一致、④"测试连接"误导、⑤providers 手写 JSON UX 差、⑥client.ts 可维护性。

其中 #2(改动量最小、影响最大) 和 #4/#5(直接影响用户对配置正确性的判断) 建议优先处理。

…b client

- codex-history.ts: indirect specifier so esbuild cannot rewrite the
  dynamic import('node:sqlite') into __require('sqlite'), which fails
  to resolve at runtime. Node 22.5+ resolves the native import directly.
- web/client.ts: remove byId() calls for route-codex-switch,
  upstream-global-mode, upstream-provider-override — these elements were
  removed during the routing/upstream restructure but their JS setters
  remained, causing 'Cannot set properties of null' on page load.
@ranxianglei

Copy link
Copy Markdown
Owner

测试质量评审(PR #73)

配合前两条(bug + 设计),这条专门讲测试。结论:基建和风格健康,主要可操作项是补几个覆盖空白 + 修一个名实不符的测试。本条只覆盖本 PR 新增/改动代码的测试;mitm.ts/ca.ts 等 master 既存缺陷会另开 issue。

✅ 做得好的(已逐一核对)

  • 原生 node:test + assert/strict,零测试依赖 — 干净,无 jest/vitest 这类重依赖。
  • 真正的集成测试:codex-official.test.ts、upstream-proxy-routing.test.ts、web-routing.test.ts 都起真实 http server 跑端到端(真实上游 + 真实代理 + 真实 CONNECT 隧道 + 真实 fetch),不是纯 mock。
  • 回归导向:测试注释直接引用历史 bug(Review #1、PR #67、#169),说明是踩过坑后补的护栏,这类测试价值高。
  • 字节级严谨:codex-takeover.test.ts 用 BOM(\uFEFF)+ CRLF 断言原样恢复;proxy-responses-review.test.ts 用 assert.deepEqual(patched, input) 断言无损往返(含 opaque/future item 顺序与引用相等 assert.equal(patched[0], input[0]))。
  • 隔离卫生:tmpdir fixture 带 pid+Date.now+random,finally 里 rmSync;改动的 process.env 有备份恢复。
  • 数量:codex 相关 8+2+2=12 个测试/~82 断言,web 2/28,upstream 6/27,review 8/30 — 覆盖密度合理。

❌ 覆盖空白 —— 正好对着本 PR 新代码的 bug

空白 对应 文件 说明
state 文件损坏 → throw(#1) bug #1 codex-takeover.test.ts 只测正常启停,没测损坏态;而损坏态会让整个 codex 子系统瘫痪
sectionPrefixLength 非数字 → 清空 config(#2) bug #2 同上 没测字段污染;该 bug 会抹掉用户整个 config.toml
DNS rebinding 变体(#5) bug #5 web-routing.test.ts 测的是普通跨域(origin: attacker.example→403),rebinding(Origin==Host==evil.com)未覆盖,而那才是真实攻击向量
PUT providers 不调 reload 是否生效 设计 #2 web-routing.test.ts PUT 只带 upstreamProxy,没测"PUT 带 providers 后不调 reload 是否生效" — 该契约缺陷无人守护
PID 回收 / per-request fsync 竞态 bug #6/#7 codex-takeover.test.ts stale-pid 只测了固定 2e9,没测 PID 回收场景

最关键的是前两个:codex-takeover.test.ts 把"启停往返"测得很扎实(byte-for-byte、三路比较、用户改动保留),唯独没测"state 文件本身坏了怎么办" —— 而那正是会清空用户 ~/.codex/config.toml 的路径。建议补一个:

writeFileSync(statePath, "{garbage");
assert.doesNotThrow(() => getCodexTakeoverStatus(files));  // 而非 throw

这个测试 ~15 行,能顺带把 bug #1 暴露出来。

⚠️ 名实不符的测试(本 PR 改出来的回归)

proxy-session-id.test.ts:~99 —— 测试名还叫 "affinityToken is safe to send upstream: does NOT embed the API key",但本 PR 把函数签名从 (headers, convo) 改成 ({value, source, clientProvided}),断言被替换成:

// 旧(master):真正验证"不含 key"的安全属性
const a = affinityToken(hdrs("Bearer keyA"), "hello");
const b = affinityToken(hdrs("Bearer keyB"), "hello");
assert.equal(a, b, "identical regardless of key");
// 新(PR):退化成恒等式
const token = affinityToken({ value: "client-session", source: ..., clientProvided: true });
assert.equal(token, "client-session");   // 只是验证"传入即返回"

测试名保留了"does NOT embed the API key",但断言已不再验证这件事。要么改名,要么用两个不同 key 构造输入验证输出一致。

🔎 文档化设计决策的测试(呼应 bug #9)

proxy-session-id.test.ts:131 显式断言:

test("conversationIdentityResponses: previous_response_id is not treated as a stable session", () => {
    const body = { input: ..., previous_response_id: "resp_xyz" } as never;
    const identity = conversationIdentityResponses(body, undefined);
    // → 落到 generated-<uuid>

这说明丢掉 previous_response_id 链是作者有意为之并用测试锁定的(我之前当 regression 报,措辞偏了 —— 它是 design decision)。但测试只验证了"单元契约正确",没有集成测试验证"headerless Responses 客户端跨请求能否累积压缩状态"这个后果。即:决策本身被测了,决策的代价(压缩对部分客户端失效)没被测。这是值得在 PR 讨论的点。

🟡 测试设计层面的弱点

  1. web-routing.test.ts 是一个巨型串联测试:enable → saveProxy → upstream → history → disable → 关闭时恢复,8 步串在一个 test() 里。第 3 步挂了,4-8 全跳过,无法定位。建议拆成多个 test(共享 fixture)。
  2. 全局单例泄漏:_setStoreForTest/_setRegistryForTest 在 web-routing、codex-official 里 set 了但没在 finally restore。靠 node:test 默认串行才没出事,测试顺序一变就脆。
  3. PUT config 的 routes 路径未覆盖(呼应 web 设计 fix: address all code review findings (condense, routing, session-id, dead code) #2):如上表。
  4. 无 fuzz/属性测试:TOML 解析、URL 解析(IPv6 带方括号、尾斜杠)这些边界全靠手写 case,容易漏。

小结:测试基建和风格是健康的,主要可操作项是补 4 个空白测试(#1/#2 损坏态最该先补,~15 行能守住用户 config 不被清空)+ 修掉名实不符的 affinityToken 测试。mitm.ts/ca.ts/直连超时等 master 既存缺陷(我前一条评论里的 #3/#4/#8/#10/#11)会另开 issue 处理,不 block 本 PR。

@ranxianglei

Copy link
Copy Markdown
Owner

勘误:bug 评审中 pre-existing 项的归属说明

我第一条评论(bug 评审)里,部分缺陷其实是 master 既存的(PRP #73 未引入,只是重构了周边),现已拆分成独立 issue 追踪,不 block 本 PR:

评论编号 问题 归属 Issue
#3 MITM CONNECT 隧道超时竞态 → upstream socket 泄漏 master 既存(src/mitm.ts,PR 未改此段) #76
#4 直连上游路径无连接超时(半开 socket 滞留 ~2 min) master 既存(src/upstream-proxy.ts) #78
#8 MITM 证书缓存无界 + 同步 RSA keygen → DoS master 既存(src/ca.ts,PR 未改) #79
#10 hop-by-hop 头(proxy-authorization)未剥离 → 凭据泄漏 master 既存(src/server.ts) #80
#11 绑定 0.0.0.0 时 MITM CONNECT 为开放 TCP 转发 master 既存(src/mitm.ts) #77

本 PR 范围内(代码是 PR 新增/改动,建议 PR 内修)的仍是:

依据:git diff master...pr-73 显示 src/mitm.ts 源码 0 改动、src/ca.ts 未在 diff 中;src/upstream-proxy.ts 虽大重构但直连无超时缺陷 master 就有;server.ts 的 UPSTREAM_HOP_HEADERS 集合 PR 未修。

测试评审见上一条评论,也已按此边界区分。

…efault

Routing page restructured per README:
- Category A (API-key clients, /bili/ prefix): OpenCode, Codex (API key),
  Pi, Claude Code (API key), Generic (Cursor/Aider/Continue). Each card
  shows the full prefixed URL with a copy button.
- Category B (subscription/login clients): Codex Route takeover (existing),
  Claude Code (MITM), ZCode (MITM). Shows proxy + CA cert setup.
- Removed Gemini CLI card (not in README supported list).
- Generic copy-btn handler for all static-URL cards.
- config.ts: upstream proxyMode default changed from 'auto' to 'direct'
  (bili is itself a proxy; should not chain through system HTTP_PROXY by
  default).
…eload

Review feedback from ranxianglei (PR#73 comments ranxianglei#3-ranxianglei#4):

1. [ranxianglei#9 critical] Restore Responses session-identity fallback chain
   (responses.ts): header → body.session_id → metadata.session_id →
   previous_response_id → content-fingerprint(hashId). The previous
   generated-randomUUID() broke compression for headerless clients
   (Pi, plain OpenAI SDK) — every request got a new session so
   compression state never accumulated.

2. [ranxianglei#1+ranxianglei#2 critical] parseState robustness (codex-takeover.ts): corrupted
   state file now returns undefined (treat as stale/recoverable) instead
   of throwing, which would leave Codex CLI unusable. Added
   sectionPrefixLength type validation (non-negative number) to prevent
   NaN slicing that could wipe the entire config.toml.

3. [Comment#4 ranxianglei#2] PUT /__bili/config onChanged now also refreshes routes
   (server.ts): previously only proxy fields were refreshed, so pure API
   callers (non-Web-UI) had to also POST /reload for provider config to
   take effect. Now PUT guarantees save-then-apply in one call.

4. Fix misleading context-window hint on routing page (page.ts).
…UT-reload, affinityToken

Addresses test-quality review (PR#73 comment #5234982438):
- codex-takeover: corrupted state file degrades to disabled (not throw)
- codex-takeover: non-numeric sectionPrefixLength rejected (not wipe config)
- web-routing: PUT providers takes effect without separate /reload
- proxy-session-id: affinityToken test name now matches assertion (was
  'does NOT embed API key' but only checked passthrough)
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.

2 participants