mslxdff 0.1.178 → 0.1.179

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mslxdff",
3
- "version": "0.1.178",
3
+ "version": "0.1.179",
4
4
  "description": "测试项目,请勿使用。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -7,7 +7,8 @@ import { createHealthMonitor } from "./health.js";
7
7
  import { ensureDir, loadNodes, removeNode, saveNode } from "./nodes.js";
8
8
  import { registerWarpDevice } from "./register.js";
9
9
  import { ensureBinary, probeTunnel, resolveAsset, startTunnel, writeTunnelConf } from "./wireproxy.js";
10
- import { createReviver, labelExits } from "./revive.js";
10
+ import { createReviver, labelExits, tailReason } from "./revive.js";
11
+ import { portInUse, reclaimPort } from "./ports.js";
11
12
  import { wireRotation } from "./identity.js";
12
13
 
13
14
  /** 重拨节流:连续失败指数退避。网络不通的机器绝不能让重注册把 CF 刷到 429。 */
@@ -55,11 +56,19 @@ export function createWarpPool({
55
56
  async function reviveTunnel(port) {
56
57
  if (closed) return false;
57
58
  const node = loadNodes(cfg.dir, [port])[0];
58
- if (!node) return false;
59
- await bringUp(node);
60
- return tunnels.has(port);
59
+ if (!node) {
60
+ log(`[warp-pool] :${port} 放弃复活:磁盘上没有该节点的身份(node-${port}.json 缺失或缺私钥)`);
61
+ return false;
62
+ }
63
+ try {
64
+ await bringUp(node);
65
+ } catch (e) {
66
+ log(`[warp-pool] :${port} 复活起隧道失败:${String(e?.message || e)}`);
67
+ return false;
68
+ }
69
+ return true; // 真活没活由 createReviver 在 settleMs 后用 isAlive 复查,这里不许冒充成功
61
70
  }
62
- const reviver = createReviver({ revive: reviveTunnel, log });
71
+ const reviver = createReviver({ revive: reviveTunnel, isAlive: (port) => { const t = tunnels.get(port); return !!t && t.alive !== false; }, log });
63
72
  let binPath = "";
64
73
  let closed = false;
65
74
  let lastRedialAt = 0;
@@ -74,21 +83,28 @@ export function createWarpPool({
74
83
  }
75
84
  });
76
85
 
86
+ /** 起一条隧道的完整动作:清残留 → 写 conf → 确认端口真空着 → spawn → 记表。 */
77
87
  async function bringUp(node) {
88
+ await reclaimPort({ dir: cfg.dir, port: node.port, log }); // 清上一代孤儿(daemon 被强杀时子进程不会自己退)
78
89
  writeTunnelConf(cfg.dir, node);
79
90
  if (tunnels.has(node.port)) return;
91
+ if (await portInUse(node.port)) {
92
+ throw new Error(`端口 :${node.port} 已被非本池进程占用,拒绝再起(硬起只会 bind 失败、无限重启刷屏)`);
93
+ }
80
94
  const t = start({
81
95
  binPath,
82
96
  dir: cfg.dir,
83
97
  port: node.port,
84
98
  log,
85
- onExit: ({ port, code }) => {
99
+ onExit: ({ port, code, signal, tail }) => {
86
100
  tunnels.delete(port);
87
- log(`[warp-pool] 隧道 :${port} 退出(code=${code}),尝试复活`);
101
+ const why = tailReason(tail) || "进程没留下任何输出";
102
+ log(`[warp-pool] :${port} 隧道意外退出(退出码 ${code}${signal ? `,信号 ${signal}` : ""}):${why}`);
88
103
  void reviver.onExit(port);
89
104
  },
90
105
  });
91
106
  tunnels.set(node.port, t);
107
+ log(`[warp-pool] :${node.port} 隧道已起:HTTP 代理 http://127.0.0.1:${node.port} → 经 WARP 出网(pid ${t.pid ?? "?"})`);
92
108
  }
93
109
 
94
110
  // 429 = 上游按出口 IP 计的名额耗尽 ⇒ 换一台设备的身份换出口(换身份=换桶)。
@@ -110,14 +126,14 @@ export function createWarpPool({
110
126
  const why = !cfg.bin && !resolveAsset()
111
127
  ? `本平台(${process.platform}-${process.arch})无预编译 wireproxy,如需启用请设 MSLXDFF_WARP_BIN`
112
128
  : String(e?.message || e);
113
- log(`[warp-pool] 出口池跳过:${why}`);
129
+ log(`[warp-pool] 出口池本次跳过(不启用,请求走直连):${why}`);
114
130
  return;
115
131
  }
116
132
  if (closed) return;
117
133
 
118
134
  // 1. 复用磁盘上已注册的节点
119
135
  let nodes = loadNodes(cfg.dir, cfg.ports);
120
- log(`[warp-pool] 已有节点 ${nodes.length}/${cfg.count}`);
136
+ log(`[warp-pool] 复用磁盘上已注册的身份 ${nodes.length}/${cfg.count} 个(端口 ${cfg.ports.join(", ")};缺的现场注册)`);
121
137
 
122
138
  // 2. 补足:逐个注册(拉长间隔,避免 CF 注册限流与同网段撞车)
123
139
  const used = new Set(nodes.map((n) => n.port));
@@ -131,9 +147,9 @@ export function createWarpPool({
131
147
  const node = nodeFromReg(port, reg, now);
132
148
  saveNode(cfg.dir, node);
133
149
  nodes.push(node);
134
- log(`[warp-pool] 注册节点 :${port}(v6=${reg.v6})`);
150
+ log(`[warp-pool] 注册新身份 :${port} 成功(设备 v6=${reg.v6},WireGuard 密钥对在本地生成)`);
135
151
  } catch (e) {
136
- log(`[warp-pool] 注册节点 :${port} 失败:${String(e?.message || e)}`);
152
+ log(`[warp-pool] :${port} 注册身份失败,本轮跳过这个端口:${String(e?.message || e)}`);
137
153
  }
138
154
  }
139
155
 
@@ -142,7 +158,7 @@ export function createWarpPool({
142
158
  try {
143
159
  await bringUp(n);
144
160
  } catch (e) {
145
- log(`[warp-pool] 起隧道 :${n.port} 失败:${String(e?.message || e)}`);
161
+ log(`[warp-pool] :${n.port} 起隧道失败,这个端口本轮不可用:${String(e?.message || e)}`);
146
162
  }
147
163
  }
148
164
 
@@ -152,13 +168,13 @@ export function createWarpPool({
152
168
  if (!tunnels.has(n.port)) continue;
153
169
  const r = await probe({ port: n.port, baseUrl, path: cfg.probePath });
154
170
  if (r.ok) live.push(n);
155
- else log(`[warp-pool] 节点 :${n.port} 隧道未通(${r.status || r.error || "?"}),不进池`);
171
+ else log(`[warp-pool] :${n.port} 隧道没探通(${r.status || r.error || "?"}),不进池:进池会把请求挂到超时,比直连更糟`);
156
172
  }
157
173
  if (live.length) {
158
174
  await dispatcher.setNodes(live.map((n) => ({ port: n.port, uri: `http://127.0.0.1:${n.port}` })));
159
- log(`[warp-pool] 出口池就绪:${live.length} 个节点`);
175
+ log(`[warp-pool] 出口池就绪:${live.length} 条隧道可用(选路策略 ${cfg.strategy}${cfg.rotate ? ",撞 429 会自动换身份换出口" : ""})`);
160
176
  } else {
161
- log("[warp-pool] 无可用节点,保持直连");
177
+ log("[warp-pool] 没有一条隧道探通 ⇒ 池为空,全部请求照旧直连(不影响可用性,只是没多出口)");
162
178
  }
163
179
 
164
180
  // 5. 出口取证:把每台设备的真实出口地址打进日志(免费版 WARP 的 IPv4 是共享 NAT,N 台设备很可能折叠成同一个出口)
@@ -221,6 +237,7 @@ export function createWarpPool({
221
237
  if (closed) return;
222
238
  closed = true;
223
239
  monitor.stop();
240
+ reviver.stop();
224
241
  for (const t of tunnels.values()) {
225
242
  try {
226
243
  t.stop();
@@ -0,0 +1,110 @@
1
+ // warp-pool · 端口占用与「上一代进程残留」清理(2026-10-16 组长 VPS 真机事故后新增)。
2
+ //
3
+ // 事故:daemon 被强杀(WMI TerminateProcess / taskkill /F)时 `process.once("exit")` 钩子不执行,
4
+ // wireproxy 子进程变成孤儿,继续占着 127.0.0.1:10800+ 这些端口。新 daemon 再起隧道就 bind 失败
5
+ // (wireproxy 立刻退出 code=1),而旧代码把「spawn 成功」当成「复活成功」⇒ 无限重启、日志刷屏、
6
+ // 且该端口的隧道永远起不来。治本是「起隧道前先把自家残留清掉」,并「端口被别人占着就别硬起」。
7
+ import { readFileSync, readdirSync } from "node:fs";
8
+ import { connect } from "node:net";
9
+ import { nodePaths } from "./nodes.js";
10
+
11
+ /** /proc/<pid>/cmdline 是 NUL 分隔的字节串;切成参数数组(丢掉结尾空串)。 */
12
+ export function parseCmdline(buf) {
13
+ return String(buf == null ? "" : buf).split("\0").filter((s) => s !== "");
14
+ }
15
+
16
+ /**
17
+ * 该进程是不是「正在跑我们这条 conf」的 wireproxy。
18
+ * 判据刻意收紧(argv 里得有 wireproxy 这个可执行文件名,且 conf 路径逐字相等),
19
+ * 免得误杀别人的进程。缺一不可。
20
+ */
21
+ export function isOurWireproxy(argv, conf) {
22
+ const list = Array.isArray(argv) ? argv : [];
23
+ const isBin = list.some((a) => /(^|[\\/])wireproxy(\.exe)?$/i.test(a));
24
+ return isBin && list.includes(conf);
25
+ }
26
+
27
+ function defaultPids() {
28
+ try {
29
+ return readdirSync("/proc").filter((f) => /^\d+$/.test(f)).map(Number);
30
+ } catch {
31
+ return [];
32
+ }
33
+ }
34
+
35
+ function defaultCmdline(pid) {
36
+ try {
37
+ return parseCmdline(readFileSync(`/proc/${pid}/cmdline`));
38
+ } catch {
39
+ return [];
40
+ }
41
+ }
42
+
43
+ /** 进程是否还在(信号 0 = 只做存在性检查,不真发信号)。 */
44
+ export function pidAlive(pid, kill = process.kill) {
45
+ try {
46
+ kill(pid, 0);
47
+ return true;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * 清掉「占着该端口那条 conf」的上一代 wireproxy。返回被清理的 pid 列表。
55
+ * 非 Linux 直接返回 [](读不到 /proc,别拿别的平台做危险猜测)。
56
+ * @param {{ dir: string, port: number, log?: Function, platform?: string,
57
+ * pids?: Function, cmdline?: Function, kill?: Function, sleep?: Function, waitRounds?: number }} opts
58
+ */
59
+ export async function reclaimPort({
60
+ dir,
61
+ port,
62
+ log = () => {},
63
+ platform = process.platform,
64
+ pids = defaultPids,
65
+ cmdline = defaultCmdline,
66
+ kill = process.kill,
67
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
68
+ waitRounds = 15,
69
+ } = {}) {
70
+ if (platform !== "linux") return [];
71
+ const conf = nodePaths(dir, port).conf;
72
+ const targets = pids().filter((pid) => isOurWireproxy(cmdline(pid), conf));
73
+ if (!targets.length) return [];
74
+
75
+ log(
76
+ `[warp-pool] 端口 :${port} 发现上一代 wireproxy 残留(pid ${targets.join(", ")}):` +
77
+ `daemon 被强杀时子进程不会自己退出,它会一直占着端口让新隧道 bind 失败。先清掉再起。`,
78
+ );
79
+ for (const pid of targets) {
80
+ try {
81
+ kill(pid, "SIGTERM");
82
+ } catch {}
83
+ }
84
+ for (let i = 0; i < waitRounds && targets.some((p) => pidAlive(p, kill)); i++) await sleep(100);
85
+ for (const pid of targets.filter((p) => pidAlive(p, kill))) {
86
+ try {
87
+ kill(pid, "SIGKILL");
88
+ } catch {}
89
+ }
90
+ return targets;
91
+ }
92
+
93
+ /** 该端口是否已有人在监听(TCP 连得上 = 占用;连不上/被拒 = 空闲)。 */
94
+ export function portInUse(port, { host = "127.0.0.1", timeoutMs = 800, connectFn = connect } = {}) {
95
+ return new Promise((resolve) => {
96
+ let done = false;
97
+ const sock = connectFn({ host, port });
98
+ const finish = (v) => {
99
+ if (done) return;
100
+ done = true;
101
+ try {
102
+ sock.destroy();
103
+ } catch {}
104
+ resolve(v);
105
+ };
106
+ sock.setTimeout(timeoutMs, () => finish(false));
107
+ sock.once("connect", () => finish(true));
108
+ sock.once("error", () => finish(false));
109
+ });
110
+ }
@@ -1,14 +1,14 @@
1
1
  // warp-pool · 复活与取证(真机事故后新增,2026-10-16)。
2
2
  //
3
- // 两件事,都来自组长 VPS 上暴露的缺陷:
3
+ // 三件事,都来自组长 VPS 上暴露的缺陷:
4
4
  //
5
- // 1. `revive`: 隧道进程意外退出后**必须自愈**。原先 `onExit` 只把端口从表里删掉、打一行日志就完事,
6
- // 而唯一的补拉路径 `onExhausted` 要求「全池不通」——3 条活着时探活一直成功,那条死隧道
7
- // 就**再也不会被拉起**,池静默从 4 降到 3,直到 daemon 重启。(真机::10800 死了就一直死。)
8
- // 注意:复活走**磁盘上已有的 conf**(不重新注册)——进程挂了不代表设备失效,重注册只会白烧 CF 配额。
5
+ // 1. 隧道退出后必须自愈:原先只有「全池不通」才补拉,一条死隧道会让池静默从 4 降到 3,直到 daemon 重启。
6
+ // 2. 入池后必须实测各节点真实出口:WARP 的 IPv4 出口是共享 NAT,「N 设备」很可能折叠成一个出口。
7
+ // 3. 复活必须**真的活下来**(2026-10-16 组长 VPS 事故):`tunnels.has(port)` 只证明「spawn 被调用了」,
8
+ // wireproxy 起一条死一条(端口被上一代孤儿进程占着 ⇒ bind 失败 ⇒ 退出码 1),旧逻辑次次判「已复活」
9
+ // ⇒ 下一次退出立刻再复活 ⇒ 无限重启刷屏,该端口永远起不来。
9
10
  //
10
- // 2. `labelExits`: 入池后实测各节点**真实出口地址**并标注撞车。WARP 的 IPv4 出口是共享 NAT,
11
- // 「N 设备」很可能折叠成一个出口;没有这条读数就只能靠人手工 curl 才发现。
11
+ // 复活只走**磁盘上已有的 conf**:进程挂了 ≠ 设备失效,重注册只会白烧 CF 配额。
12
12
  import { probeTunnel } from "./wireproxy.js";
13
13
 
14
14
  /** 出口取证目标:Cloudflare 自己的 trace 端点,回 `ip=` 一行(不烧上游 token)。 */
@@ -20,12 +20,20 @@ export function parseExitIp(text) {
20
20
  return m ? m[1] : "";
21
21
  }
22
22
 
23
+ /** 子进程末行输出当退出原因(wireproxy 的真实报错都在 stderr);没有输出返回 ""。 */
24
+ export function tailReason(tail, max = 300) {
25
+ const lines = String(tail || "").split("\n").map((s) => s.trim()).filter(Boolean);
26
+ return lines.length ? lines[lines.length - 1].slice(0, max) : "";
27
+ }
28
+
23
29
  /**
24
30
  * 按端口独立的退避复活器。
25
- * @param {{ revive: (port:number)=>Promise<boolean>, minGapMs?: number, maxGapMs?: number,
26
- * now?: ()=>number, log?: (s:string)=>void }} opts
31
+ * @param {{ revive: (port:number)=>Promise<boolean>, isAlive?: (port:number)=>boolean, minGapMs?: number,
32
+ * maxGapMs?: number, settleMs?: number, now?: ()=>number, sleep?: Function,
33
+ * schedule?: Function, cancel?: Function, log?: (s:string)=>void }} opts
34
+ * 复活是否算数由 `isAlive` 在 `settleMs` 后复查;失败按指数退避并**自己用定时器安排下一次重试**。
27
35
  */
28
- export function createReviver({ revive, minGapMs = 30_000, maxGapMs = 10 * 60_000, now = Date.now, log = () => {} } = {}) {
36
+ export function createReviver({ revive, isAlive, minGapMs = 30_000, maxGapMs = 10 * 60_000, settleMs = 1_200, now = Date.now, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), schedule = (fn, ms) => setTimeout(fn, ms), cancel = (h) => clearTimeout(h), log = () => {} } = {}) {
29
37
  /** @type {Map<number, {attempts:number, nextAt:number, busy:boolean}>} */
30
38
  const state = new Map();
31
39
 
@@ -38,37 +46,71 @@ export function createReviver({ revive, minGapMs = 30_000, maxGapMs = 10 * 60_00
38
46
  return s;
39
47
  }
40
48
 
49
+ /** @type {Map<number, object>} 每端口最多一个待触发的重试定时器 */
50
+ const timers = new Map();
51
+
52
+ /** 安排「到点自动重试」;没有它,日志里那句「N s 后自动再试」就是空话。 */
53
+ function armRetry(port, ms) {
54
+ if (timers.has(port)) return;
55
+ const h = schedule(() => {
56
+ timers.delete(port);
57
+ void attempt(port);
58
+ }, Math.max(0, ms));
59
+ if (h && typeof h.unref === "function") h.unref();
60
+ timers.set(port, h);
61
+ }
62
+
63
+ /**
64
+ * 复活一次:首次立即复活,失败按 30s→10min 指数退避并自己安排下一次重试。
65
+ * 复活算不算数由 `isAlive` 在 `settleMs` 后复查——不许拿「spawn 被调用了」冒充「活下来了」。
66
+ */
67
+ async function attempt(port) {
68
+ const s = entry(port);
69
+ if (s.busy) return false;
70
+ const wait = Math.max(0, s.nextAt - now());
71
+ if (wait > 0) {
72
+ log(`[warp-pool] :${port} 距上次复活不足退避间隔,${Math.ceil(wait / 1000)}s 后再试(防抖动刷屏,不是故障)`);
73
+ armRetry(port, wait);
74
+ return false;
75
+ }
76
+ s.busy = true;
77
+ s.attempts += 1;
78
+ const gap = Math.min(minGapMs * 2 ** (s.attempts - 1), maxGapMs);
79
+ let ok = false;
80
+ try {
81
+ ok = await revive(port);
82
+ } catch (e) {
83
+ log(`[warp-pool] :${port} 复活抛出异常:${String(e?.message || e)}`);
84
+ }
85
+ if (ok && isAlive) {
86
+ if (settleMs > 0) await sleep(settleMs);
87
+ ok = isAlive(port);
88
+ if (!ok) log(`[warp-pool] :${port} 复活后进程立刻又退出 —— 不认这次复活(原因见上面那条「意外退出」)`);
89
+ }
90
+ s.busy = false;
91
+ if (ok) {
92
+ const n = s.attempts;
93
+ s.attempts = 0;
94
+ s.nextAt = now() + minGapMs; // 稳定期:期间再退出先等一轮,防「起一条死一条」把日志刷爆
95
+ log(`[warp-pool] :${port} 已复活(第 ${n} 次尝试成功);${Math.round(minGapMs / 1000)}s 内若又退出会先等一轮再重启`);
96
+ return true;
97
+ }
98
+ s.nextAt = now() + gap;
99
+ const hint = s.attempts >= 3 ? ` 排查:ss -ltnp | grep :${port};或前台跑隧道二进制 -c node-${port}.conf 看真实报错` : "";
100
+ log(`[warp-pool] :${port} 复活未成功(第 ${s.attempts} 次),${Math.round(gap / 1000)}s 后自动再试。${hint}`);
101
+ armRetry(port, gap);
102
+ return false;
103
+ }
104
+
41
105
  return {
42
- /** 进程退出时调用。首次立即复活,之后按 30s→10min 指数退避。 */
43
- async onExit(port) {
44
- const s = entry(port);
45
- const wait = Math.max(0, s.nextAt - now());
46
- if (wait > 0) {
47
- log(`[warp-pool] :${port} 复活退避中(还剩 ${Math.round(wait / 1000)}s)`);
48
- return false;
49
- }
50
- if (s.busy) return false;
51
- s.busy = true;
52
- s.attempts += 1;
53
- const gap = Math.min(minGapMs * 2 ** (s.attempts - 1), maxGapMs);
54
- s.nextAt = now() + gap;
55
- let ok = false;
56
- try {
57
- ok = await revive(port);
58
- } catch (e) {
59
- log(`[warp-pool] :${port} 复活失败:${String(e?.message || e)}`);
60
- }
61
- s.busy = false;
62
- if (ok) {
63
- state.delete(port);
64
- log(`[warp-pool] :${port} 已复活`);
65
- } else {
66
- log(`[warp-pool] :${port} 复活未成功(第 ${s.attempts} 次,下次最早 ${Math.round(gap / 1000)}s 后)`);
67
- }
68
- return ok;
69
- },
70
- /** 探活成功时调用:清掉退避账,恢复正常节奏。 */
106
+ onExit: (port) => attempt(port),
107
+ /** 探活成功时调用:清掉退避账与待触发定时器,恢复正常节奏。 */
71
108
  noteHealthy(port) {
109
+ const h = timers.get(port);
110
+ if (h) {
111
+ try { cancel(h); } catch {}
112
+ timers.delete(port);
113
+ }
72
114
  state.delete(port);
73
115
  },
74
116
  stats() {
@@ -79,6 +121,15 @@ export function createReviver({ revive, minGapMs = 30_000, maxGapMs = 10 * 60_00
79
121
  cooldownMsLeft: Math.max(0, s.nextAt - now()),
80
122
  }));
81
123
  },
124
+
125
+ /** 池关闭时调用:别再有定时器去打复活。 */
126
+ stop() {
127
+ for (const h of timers.values()) {
128
+ try { cancel(h); } catch {}
129
+ }
130
+ timers.clear();
131
+ state.clear();
132
+ },
82
133
  };
83
134
  }
84
135
 
@@ -108,10 +159,10 @@ export async function labelExits({ ports = [], fetchImpl, timeoutMs = 12_000, lo
108
159
 
109
160
  const groups = [...byIp.entries()].map(([ip, nodes]) => ({ ip, nodes }));
110
161
  if (groups.length === 1) {
111
- log(`[warp-pool] ⚠ 出口不分散:${groups[0].nodes.length} 个节点共用同一个出口 ${groups[0].ip}(免费版 WARP 的 IPv4 是共享 NAT)`);
162
+ log(`[warp-pool] ⚠ 出口不分散:${groups[0].nodes.length} 条隧道同时在线只有 1 个出口地址(${groups[0].ip}):免费版 WARP 的 IPv4 是共享 NAT,多开隧道换不到多份名额;多份名额靠撞 429 时的身份轮换`);
112
163
  } else if (groups.length > 1) {
113
- log(`[warp-pool] 出口分散:${groups.length} 个不同地址 / ${groups.reduce((a, g) => a + g.nodes.length, 0)} 个节点`);
164
+ log(`[warp-pool] 出口分散:${groups.length} 个出口地址 / ${groups.reduce((a, g) => a + g.nodes.length, 0)} 条隧道同时在线(同时在线就有 ${groups.length} 份上游名额)`);
114
165
  }
115
- if (failed) log(`[warp-pool] ${failed} 个节点出口取证失败(不影响其进池)`);
166
+ if (failed) log(`[warp-pool] ${failed} 个节点出口取证失败(不影响进池,只影响轮换时「出口到底变没变」的比对)`);
116
167
  return groups;
117
168
  }