Skip to content

Commit aae873f

Browse files
committed
fix(tui): guest 验证码 SDK 报错不再终止 TUI
现场报告(v4.5.5,多次复现,间隔十几到二十几分钟): zcode-proxy: tui crashed: ReferenceError: moveBy is not defined at tE (https://g.alicdn.com/captcha-frontend/FeiLin/1.5.1/feilin008….js:1:169658) Bun 下 happy-dom 的 VM 隔离不生效,Aliyun/FeiLin 脚本直接运行在宿主 realm, 因此从它们的回调里逃逸的异常会以进程级 uncaughtException 到达,与我们自己的 故障无从区分。serve 模式早已划清这条界线(captcha-happy.ts 记录后继续运行, 单次求解失败由池重试);TUI 的处理器却对一切 exit(1),把一个可恢复故障放大成 了整个代理进程死亡。 新增 runtime/guest-error.ts 按抛出帧的来源判定归属:仅当栈/sourceURL/message 中出现 SDK 的 CDN 主机才算 guest。判据锚定在 URL authority 上并要求分隔符 收尾,所以 `evil-alicdn.com.attacker.net` 与 `?ref=alicdn.com` 都不算证据; 同时跟随 cause 链(带自引用保护)。取证不足一律判为宿主故障——沉默地吞掉真实 崩溃比误杀更糟。 TUI 据此放行 guest 报错并写入日志面板,其余仍照旧 cleanup + exit(1)。 验证:把现场那条栈注入 stock captcha-happy,TUI 存活且面板出现 "ReferenceError: moveBy is not defined (tE (feilin008….js))";真实内部故障 仍然退出。
1 parent 1e4dddd commit aae873f

3 files changed

Lines changed: 162 additions & 0 deletions

File tree

‎src/runtime/guest-error.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import { describe, expect, test } from "bun:test";
2+
import { describeGuestError, isGuestOriginError } from "./guest-error.js";
3+
4+
/** The exact stack from the field crash report (v4.5.5, TUI mode). */
5+
function fieldCrash(): Error {
6+
const err = new ReferenceError("moveBy is not defined");
7+
err.stack =
8+
"ReferenceError: moveBy is not defined\n" +
9+
" at tE (https://g.alicdn.com/captcha-frontend/FeiLin/1.5.1/" +
10+
"feilin008.489f1fe42772a97d510f162902b33c35c004ce7746ca3f4696c42f8d1f677670.js:1:169658)";
11+
return err;
12+
}
13+
14+
function withStack(message: string, stack: string): Error {
15+
const err = new Error(message);
16+
err.stack = stack;
17+
return err;
18+
}
19+
20+
describe("guest-origin classification", () => {
21+
test("the captcha SDK crash that killed the TUI is attributed to the guest", () => {
22+
expect(isGuestOriginError(fieldCrash())).toBe(true);
23+
});
24+
25+
test("host faults stay fatal", () => {
26+
// The v4.5.2 crash shape: a Bun-internal timer stripped of `.unref()`.
27+
// It is a real proxy defect and must never be swallowed as guest noise.
28+
const unref = withStack(
29+
"setTimeout(() => {}, 0).unref is not a function",
30+
"TypeError: …unref is not a function\n at node:_http_server:512:9",
31+
);
32+
expect(isGuestOriginError(unref)).toBe(false);
33+
expect(
34+
isGuestOriginError(withStack("boom", "Error: boom\n at buildFrame (/app/src/tui/frame.ts:88:3)")),
35+
).toBe(false);
36+
});
37+
38+
test("an unattributable error is treated as a host fault", () => {
39+
// No evidence must never mean "assume guest": that would silently mask
40+
// genuine crashes behind a log line.
41+
expect(isGuestOriginError(new Error("no stack recorded"))).toBe(false);
42+
expect(isGuestOriginError({ message: "not even an Error" })).toBe(false);
43+
expect(isGuestOriginError(undefined)).toBe(false);
44+
});
45+
46+
test("lookalike hosts are not guest evidence", () => {
47+
expect(
48+
isGuestOriginError(withStack("x", "at f (https://evil-alicdn.com.attacker.net/x.js:1:1)")),
49+
).toBe(false);
50+
expect(
51+
isGuestOriginError(withStack("x", "at f (https://cdn.example.com/p?ref=alicdn.com)")),
52+
).toBe(false);
53+
});
54+
55+
test("every host serving the SDK counts, including subdomains and cause chains", () => {
56+
expect(isGuestOriginError(withStack("x", "at https://o.alicdn.com/captcha-frontend/a.js:1:1"))).toBe(true);
57+
expect(isGuestOriginError(withStack("x", "at https://captcha.ap-southeast-1.aliyuncs.com/x.js:1:1"))).toBe(true);
58+
const wrapped = withStack("wrapper", "Error: wrapper\n at host (/app/x.ts:1:1)");
59+
(wrapped as { cause?: unknown }).cause = fieldCrash();
60+
expect(isGuestOriginError(wrapped)).toBe(true);
61+
});
62+
63+
test("a self-referential cause chain terminates", () => {
64+
const a = withStack("a", "at /app/a.ts:1:1");
65+
const b = withStack("b", "at /app/b.ts:1:1");
66+
(a as { cause?: unknown }).cause = b;
67+
(b as { cause?: unknown }).cause = a;
68+
expect(isGuestOriginError(a)).toBe(false);
69+
});
70+
71+
test("the log line names the error and the bundle, without the content hash", () => {
72+
const line = describeGuestError(fieldCrash());
73+
expect(line).toContain("ReferenceError: moveBy is not defined");
74+
expect(line).toContain("feilin008");
75+
expect(line).not.toContain("https://");
76+
});
77+
});

‎src/runtime/guest-error.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* guest-error.ts — provenance test for errors thrown by third-party captcha
3+
* SDK code ("guest" scripts) running inside the in-process happy-dom solver.
4+
*
5+
* Under Bun the guest scripts execute in the HOST realm (happy-dom's VM
6+
* isolation is a no-op there), so an error escaping a guest callback reaches
7+
* process-level `uncaughtException` exactly like an error from our own code.
8+
* The two must not share a fate: a rotated pe/FeiLin bundle tripping over an
9+
* emulation gap must fail that one solve — the pool retries — while a genuine
10+
* fault in the proxy still terminates loudly.
11+
*
12+
* `serve` mode already draws that line (captcha-happy.ts logs and continues).
13+
* The TUI's own uncaughtException handler used to exit(1) for everything,
14+
* which turned a recoverable guest error into a dead proxy:
15+
*
16+
* zcode-proxy: tui crashed: ReferenceError: moveBy is not defined
17+
* at tE (https://g.alicdn.com/captcha-frontend/FeiLin/1.5.1/feilin008…js)
18+
*
19+
* Evidence is the source URL of the throwing frame: guest bundles are served
20+
* from Aliyun CDN/API hosts and carry those URLs in their stack frames (and,
21+
* for generated code, in the `//# sourceURL` we preserve when evaluating).
22+
*/
23+
24+
// CDN/API hosts serving the Aliyun captcha SDK bundles. Anchored at the URL
25+
// authority (`scheme://`, optional userinfo) and terminated by a port/path/
26+
// delimiter, so the domain must be the real host — `evil-alicdn.com.bad.net`
27+
// and `…?ref=alicdn.com` are not guest evidence.
28+
const GUEST_SCRIPT_HOST =
29+
/https?:\/\/(?:[^/\s@]*@)?(?:[a-z0-9-]+\.)*(?:alicdn\.com|aliyuncs\.com)(?=[:/?#]|\s|$)/i;
30+
31+
/** Follows `cause` chains without looping on self-referential errors. */
32+
function* errorChain(err: unknown, depth = 4): Generator<object> {
33+
const seen = new Set<unknown>();
34+
let current = err;
35+
for (let i = 0; i < depth; i++) {
36+
if (!current || typeof current !== "object" || seen.has(current)) return;
37+
seen.add(current);
38+
yield current as object;
39+
current = (current as { cause?: unknown }).cause;
40+
}
41+
}
42+
43+
/**
44+
* True when `err` originates in third-party captcha SDK code.
45+
*
46+
* Deliberately conservative: only a guest source URL counts as evidence. A
47+
* missing/truncated stack yields `false`, so an unattributable error keeps the
48+
* strict (fatal) treatment.
49+
*/
50+
export function isGuestOriginError(err: unknown): boolean {
51+
for (const link of errorChain(err)) {
52+
const e = link as { stack?: unknown; sourceURL?: unknown; message?: unknown };
53+
if (typeof e.stack === "string" && GUEST_SCRIPT_HOST.test(e.stack)) return true;
54+
// Bun/JSC attach the throwing script's URL directly on the error.
55+
if (typeof e.sourceURL === "string" && GUEST_SCRIPT_HOST.test(e.sourceURL)) return true;
56+
if (typeof e.message === "string" && GUEST_SCRIPT_HOST.test(e.message)) return true;
57+
}
58+
return false;
59+
}
60+
61+
/** One-line render of a guest error for the log pane / stderr. */
62+
export function describeGuestError(err: unknown): string {
63+
const e = err as { name?: unknown; message?: unknown; stack?: unknown } | null;
64+
const name = typeof e?.name === "string" ? e.name : "Error";
65+
const message = typeof e?.message === "string" ? e.message : String(err);
66+
const frame =
67+
typeof e?.stack === "string"
68+
? (e.stack.split("\n").find((line) => GUEST_SCRIPT_HOST.test(line)) ?? "").trim()
69+
: "";
70+
// Bundle URLs carry a 64-char content hash — keep the readable filename only.
71+
const source = frame.replace(/^at\s+/, "").replace(/https?:\/\/[^\s)]*\/([^/\s)]+)/, "$1");
72+
return source ? `${name}: ${message} (${source})` : `${name}: ${message}`;
73+
}

‎src/tui/app.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { ZaiOAuthClient, BigmodelOAuthClient, LOGIN_TIMEOUT_MS, parsePastedCallb
2323
import { KeyResolver } from "../auth/resolver.js";
2424
import { openBrowser } from "../runtime/open-browser.js";
2525
import { pasteLoginInstructions, readPastedLine, boldIfTTY } from "../runtime/paste-login.js";
26+
import { isGuestOriginError, describeGuestError } from "../runtime/guest-error.js";
2627
import { ensureDeviceMidInConfig, VERSION, type ServeArgs } from "../index.js";
2728
import { writeFileSync, existsSync, appendFileSync } from "node:fs";
2829
import type { ProxyConfig } from "../config/types.js";
@@ -636,7 +637,18 @@ export async function runTui(args: ServeArgs): Promise<void> {
636637
process.on("SIGTERM", quit);
637638
process.on("exit", restore);
638639
stdout.on("resize", scheduleRender);
640+
// Guest captcha-SDK errors must NOT kill the TUI. Under Bun the Aliyun/
641+
// FeiLin bundles run in the HOST realm, so an error escaping one of their
642+
// stray callbacks arrives here exactly like an internal fault. `serve` mode
643+
// already logs-and-continues (captcha-happy.ts); the TUI used to exit(1) for
644+
// everything, turning a retryable solve failure into a dead proxy (field
645+
// report: "tui crashed: ReferenceError: moveBy is not defined" from
646+
// feilin008.js). The pool retries the solve; the proxy keeps serving.
639647
process.on("uncaughtException", (err: Error) => {
648+
if (isGuestOriginError(err)) {
649+
emit(`[warn] captcha SDK error (ignored): ${describeGuestError(err)}`, "warn");
650+
return;
651+
}
640652
cleanup();
641653
origError(`zcode-proxy: tui crashed: ${err.stack ?? String(err)}`);
642654
process.exit(1);

0 commit comments

Comments
 (0)