Repository navigation
fix: break the proxy-origin hijack chain (#405) - #514
ranxianglei wants to merge 1 commit into
Conversation
- src/proxy-origin.ts (new): shared pointer protocol — claim with liveness probe, lease sidecar (origin/pid/bootedAt/instanceId), ownership-checked release - server.ts: listen callback claims instead of clobbers; healthy existing owner keeps the pointer; /__bili/health reports instanceId; graceful shutdown releases only our own pointer - mcp.ts: async resolveLiveOrigin() probes env->file->default candidates, caches after success, invalidates on fetch failure so the next MCP call re-resolves (dead ephemeral pointer heals without restarting the host client); stderr declares rebinds - launcher.ts: ensureProxyRunning probes the preferred port first and reuses a healthy instance (no second spawn); ProxyHandle.child optional, stopProxy no-op on reused handles - plugin-install.ts: bake stable DEFAULT_PROXY_ORIGIN into claude/codex/opencode configs instead of the transiently resolved origin; explicit BILI_MCP_PROXY/--origin still honored - persist.ts: reject stale full snapshots (requests/nextBlockId rollback) when two processes share BILI_SESSIONS_DIR; throttled warn
[bot] 🏷 Picked up. Reviewing |
[bot] 🏷 Review verdict: cannot merge as-is — the branch is based on stale master and overlaps with already-merged PR #419 (instance governance). The code itself is well-built and its pre-flight claims check out; the problem is where it lands, not what it does. Details below. 1. Verification (all run locally on
|
| Fix | Status on current master | Assessment |
|---|---|---|
#1 mcp read-side liveness (resolveLiveOrigin) |
Still missing — resolveProxyOrigin() trusts the instance file blindly |
Genuinely additive. Port to current master: probe chain env → readProxyInstanceFile().origin → default, same cache/invalidation mechanics. |
#2 write-side claim/lease (proxy-origin.ts) |
Master clobbers the instance file unconditionally (registry warns on duals) | Claim semantics are a real improvement, but this PR introduces a second discovery surface (plain pointer + lease sidecar) competing with #419's JSON instance file. Should be folded into announceListening's write path operating on ProxyInstanceFile; the parallel sidecar format should not ship. |
| #3 launcher reuse | Already implemented, broader — master attaches to any healthy config-compatible instance (registry-based), plus handshake bind; stopProxy no-ops via attached flag |
Redundant. Drop it; master supersedes it. |
| #4 plugin-install stable bake | Master bakes env ?? recorded origin ?? throw | Conflicting policy. My recommendation: adopt this PR's bakedProxyOrigin() (explicit env wins, else stable :8787) — baking a possibly-ephemeral recorded origin repeats the freeze bug, and throwing mid-install is harsher than needed since the shell resolves at runtime anyway. Small, self-contained change. |
| #5 persist stale-snapshot rejection | Still missing | Genuinely additive and the concrete landing of #394 item 4. Cherry-picks onto current master essentially as-is (no dependency on the other fixes). |
So ~half the PR (fixes #1, #5, arguably #4) is net-new value that current master still lacks; half (#3, and the design of #2) collides with what just shipped.
4. Wrong issue reference (auto-close hazard)
The title, commit message, README and all code comments cite #405 — but GitHub #405 is the unrelated open ACP_PASSTHROUGH issue. The hijack-chain issue is #403 (closed/completed, folded into umbrella #417), with #394 as the persist direction. As written, a merge would auto-close the wrong issue. Every (#405) in the diff should become (#403) / (#394) where applicable.
5. Minor notes (report only, no separate issues)
_resetMcpLiveOriginForTestduplicatesforgetLiveOriginbody (test-only export, acceptable but redundant).resolveLiveOrigininvalidates the cache on network errors/timeouts but not on non-ok HTTP (e.g. 404 health) — edge case, fine to leave.- Worst-case first MCP call latency when all candidates are dead: up to 3 × 1.5 s probes before falling back to
candidates[0]. - Fix fix: address all code review findings (condense, routing, session-id, dead code) #2 edge: an instance that failed to claim loses discoverability when the claiming owner shuts down gracefully (pointer deleted, no handoff). Rare; acceptable if documented.
guardedBuildrewrites the disk payload on every stale save attempt (extra I/O while a stale copy keeps saving); warn is throttled 60 s/session, which is fine.
Recommendation
Close #514 without merging, then land a rebased branch off current master containing: fix #5 as-is, fix #1 adapted to the env→instance-file→default chain, fix #4's bake policy, and optionally fix #2's claim semantics folded into the JSON instance-file write path (drop the lease sidecar). Drop fix #3 entirely. Happy to do that rework if you confirm the scope — say the word and I'll cut the branch, port the pieces, re-run the full pre-flight, and open the new PR.
|
Reviewed against master @8496194 (v0.1.83). Verdict: do not merge as-is — 4 of the 5 fixes are superseded by the instance registry that landed on master (#394/#403/#417, Superseded by master
Still valuable — please rebase the scope down to these two
Everything else in the diff (launcher attach model, install origin policy, lease file) should be dropped rather than ported. The test claim (887/888) also predates the current baseline (1046/1048 with 2 known env fails) — the branch needs a fresh rebase pass anyway. |
|
Per the review above, this PR is now superseded and split into two focused PRs rebuilt on current master:
Fixes 2–4 (pointer lease, launcher port reuse, baked install origin) remain intentionally dropped — master's instance registry (#394/#403/#417) covers them in a richer form, and #516/#517 are built on top of it. Closing as superseded — thanks for the investigation and the rollback-guard design, which carried over almost verbatim. If you'd like to keep iterating on any of the dropped parts, the review comment above explains the overlap with master. |
ranxianglei#405, split from ranxianglei#514 fix 1) A crashed/killed proxy leaves its JSON instance record behind naming a port nothing listens on; MCP shells then dial the dead origin forever. resolveProxyOrigin now checks pid liveness (kill-0) on JSON records before trusting them and falls back to the default origin with a one-time stderr note. pid 0 (foreign record without a liveness claim) and legacy plain-URL pointers keep the old trust.
What
Fixes #405 — four independent defects in the proxy-origin lifecycle, each with its own fix + regression tests:
src/mcp.ts) — new asyncresolveLiveOrigin()probes candidatesenv → pointer file → defaultviaGET /__bili/health, caches after success, and invalidates the cache on fetch failure (incl. timeout). A dead ephemeral pointer self-heals on the next MCP call — no host-client restart. Rebinds are declared on stderr with the instance id.src/server.ts+ newsrc/proxy-origin.ts) — the listen callback now claims instead of clobbers: a different existing origin that is healthy keeps the pointer (logged); otherwise it is reclaimed. Main file format unchanged (plain URL line, old shells keep working); a new sidecar lease (proxy-origin.lease: origin/pid/bootedAt/instanceId) carries ownership proof. Graceful shutdown releases the pointer only if it still points at this instance./__bili/healthnow reportsinstanceId.src/launcher.ts) —ensureProxyRunningprobes the preferred port first and reuses a healthy one (ProxyHandle.childnow optional;stopProxyno-ops on reused handles). Warns if MITM domains were requested on a reused shared instance (domains only apply to instances started with them).src/plugin-install.ts) — all four bake sites (claude/codex/opencode) now bake the stableDEFAULT_PROXY_ORIGIN; explicitBILI_MCP_PROXY/--originstill wins. Custom-port instances keep working at runtime because the shell's env→file→default chain finds them (and dead pointers now heal per fix: keep system prompt byte-stable for prefix cache #1).src/persist.ts, the concrete landing spot for 无单实例守卫:多个 bili 代理进程并存共写 sessions 目录,伴随孤儿 ref、有注册表无 transcript、计数自相矛盾的污染簇 #394's direction) — when two processes shareBILI_SESSIONS_DIR, a stale full snapshot (monotonic signalsstats.requests/state.nextBlockIdregressing) is rejected with a throttled warn and the disk state is kept;flushSyncon a stale copy reports success so eviction drops the stale in-memory copy (self-heal).Acceptance criteria
tests/mcp-live-origin.test.ts(self-heal test); cache invalidation covers ECONNREFUSED/timeoutsbili claudewith healthy :8787 present → no second spawn, no origin rewrite —tests/launcher.test.tsreuse test +tests/proxy-origin.test.tsclaim teststests/proxy-persist.test.tsplugin installartifact bakes the stable BILI_MCP_PROXY — new test intests/plugin-agent.test.ts(pointer file holding an ephemeral port → bakes :8787; explicit env still honored)Pre-flight
npm run typecheck✅npm test: 887/888 pass. The single failure (resolveClientCommand: codex/claude resolve to themselves) is pre-existing and environment-dependent: it fails identically on clean master here because this machine has/usr/bin/codexwhile the test hardcodes a bare-name expectation forPATH=/usr/bin. Not caused by this change (reported below as a minor issue).npm run build✅ (tsup bundlesproxy-origin.tsinline intodist/index.js)E2E_CHECK=1): codex CLI + dist OK; full e2e skipped — the127.0.0.1:8199upstream is not reachable from this sandbox (expected, seetests/e2e/README.md).Notes
BILI_MCP_PROXY(or--origin) still wins at bake time — operator intent preserved; the default path (the actual bug) bakes the stable port.