mslxdff 0.1.245 → 0.1.247

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.
Files changed (82) hide show
  1. package/package.json +1 -1
  2. package/src/autostart-health.js +65 -0
  3. package/src/autostart.js +57 -1
  4. package/src/chat-pipeline/terminal-verdict.js +4 -4
  5. package/src/cli/commands/daemon.js +9 -1
  6. package/src/cli/commands/provider/index.js +6 -1
  7. package/src/cli/commands/provider/models.js +3 -0
  8. package/src/cli/commands/provider/todaycn-login.js +121 -0
  9. package/src/cli/commands/provider/todaycn-persona.js +117 -0
  10. package/src/cli/commands/system.js +21 -5
  11. package/src/cli/help.js +4 -4
  12. package/src/cli/index.js +0 -5
  13. package/src/cli/status.js +11 -4
  14. package/src/daemon.js +3 -3
  15. package/src/providers/classify.js +1 -1
  16. package/src/providers/codearts/stream.js +17 -0
  17. package/src/providers/dispatcher.js +1 -1
  18. package/src/providers/railway-endpoints.js +192 -0
  19. package/src/providers/railway.js +111 -45
  20. package/src/providers/registry.js +8 -2
  21. package/src/providers/share-keys.js +2 -1
  22. package/src/providers/todaycn/account-store.js +169 -0
  23. package/src/providers/todaycn/chat.js +168 -0
  24. package/src/providers/todaycn/const.js +59 -0
  25. package/src/providers/todaycn/index.js +202 -0
  26. package/src/providers/todaycn/models.js +93 -0
  27. package/src/providers/todaycn/persona.js +103 -0
  28. package/src/providers/todaycn/prompt.js +194 -0
  29. package/src/providers/todaycn/session.js +107 -0
  30. package/src/providers/todaycn/sse.js +86 -0
  31. package/src/providers/todaycn/token.js +66 -0
  32. package/src/providers/todaycn.js +2 -0
  33. package/src/runtime/autostart-repair.js +108 -0
  34. package/src/runtime/bootstrap.js +1 -1
  35. package/src/runtime/proc-info.js +2 -2
  36. package/src/runtime/provider-gate.js +2 -2
  37. package/src/runtime/providers-setup.js +2 -4
  38. package/src/runtime/server-lifecycle.js +21 -48
  39. package/src/server.js +3 -3
  40. package/src/state/facade.js +1 -0
  41. package/src/state/merge.js +2 -0
  42. package/src/state/schemas/autostart.js +79 -0
  43. package/src/upstream-engine/index.js +2 -17
  44. package/src/upstream.js +1 -61
  45. package/src/cli/commands/multi-ip-pool-fetch.js +0 -173
  46. package/src/cli/commands/multi-ip-pool-test.js +0 -136
  47. package/src/cli/commands/multi-ip-pool.js +0 -83
  48. package/src/cli/commands/v6-pool.js +0 -123
  49. package/src/multi-ip-pool/config.js +0 -157
  50. package/src/multi-ip-pool/diagnose.js +0 -159
  51. package/src/multi-ip-pool/dial.js +0 -179
  52. package/src/multi-ip-pool/dispatch.js +0 -244
  53. package/src/multi-ip-pool/index.js +0 -174
  54. package/src/multi-ip-pool/nodes-fetch.js +0 -160
  55. package/src/multi-ip-pool/nodes.js +0 -205
  56. package/src/multi-ip-pool/report.js +0 -162
  57. package/src/multi-ip-pool/selftest.js +0 -168
  58. package/src/multi-ip-pool/standby.js +0 -157
  59. package/src/multi-ip-pool/tunnel.js +0 -291
  60. package/src/v6pool/claim.js +0 -157
  61. package/src/v6pool/config.js +0 -65
  62. package/src/v6pool/detect.js +0 -130
  63. package/src/v6pool/index.js +0 -157
  64. package/src/v6pool/prefix.js +0 -140
  65. package/src/v6pool/probe.js +0 -40
  66. package/src/v6pool/report.js +0 -104
  67. package/src/v6pool/rotate.js +0 -263
  68. package/src/v6pool/selftest.js +0 -178
  69. package/src/warp-pool/config.js +0 -74
  70. package/src/warp-pool/health.js +0 -106
  71. package/src/warp-pool/identity.js +0 -141
  72. package/src/warp-pool/index.js +0 -358
  73. package/src/warp-pool/keys.js +0 -29
  74. package/src/warp-pool/nodes.js +0 -95
  75. package/src/warp-pool/ports.js +0 -160
  76. package/src/warp-pool/register.js +0 -113
  77. package/src/warp-pool/report.js +0 -232
  78. package/src/warp-pool/revive.js +0 -168
  79. package/src/warp-pool/rotate.js +0 -214
  80. package/src/warp-pool/strategy.js +0 -43
  81. package/src/warp-pool/verdict.js +0 -69
  82. package/src/warp-pool/wireproxy.js +0 -162
@@ -1,157 +0,0 @@
1
- // multi-ip-pool · 配置解析:env 优先,缺省值集中一处;纯函数,便于单测。
2
- //
3
- // 定位:第三.种出口源(与 v6pool 换本机源地址、warp-pool 换 WARP 出口同层)。
4
- // 思路参照 aimili-vpngate(VPNGate 免费 OpenVPN 节点当出口),但本模块是:
5
- // ① Node 实现(不再需要 Python 侧那套进程/代理);② **N 槽并行**(参照实现一次只挂 1 条隧道);
6
- // ③ 只服务 opencode 免费层(免费层按**出口 IP** 计额,见 docs/domain-notes.md §5)。
7
- import { join } from "node:path";
8
- import { logDir } from "../logs.js";
9
-
10
- /**
11
- * 缺省**开** + **只有组长建**(用户 2026-10-25 补裁):`joined` 里存在"自己当组长"的组才建池。
12
- * 组员、以及**没带任何组的单机都不建**(这种机器上要用,显式 `MSLXDFF_MULTI_IP_MODE=leader`)。
13
- * 另三条硬门:只有 Linux(tun + ip rule)、要 root、要有 openvpn 可执行文件。
14
- */
15
- export const DEFAULTS = {
16
- enabled: true,
17
- mode: "auto", // auto | leader | member
18
- count: 2, // 并行隧道数:每槽一条 openvpn + 一条策略路由表
19
- country: "", // 国家白名单(ISO 两字母,逗号分隔;空 = 不限)
20
- minScore: 1_000_000, // VPNGate Score 下限(低于它的节点基本连不动)
21
- scan: 8, // 起隧道时最多按序尝试多少个候选
22
- baseTable: 210, // 策略路由表起始号(避开通信/策略常用表)
23
- devPrefix: "mltun", // tun 设备名前缀(留足内核 15 字符上限)
24
- probeModel: "", // 「打 hi 探额度」用的免费模型(空 = 与 v6 池对照测试同款)
25
- strategy: "session", // 会话粘出口:上游按 session 做粘性路由,每请求换出口会撞冷启动
26
- standby: 5, // 备选出口上限(用户定:**不多于 5**;0 = 关备选池)
27
- standbyEveryMs: 60 * 60_000, // 备选池刷新周期(每小时重拨一批新 IP)
28
- connectTimeoutMs: 25_000, // 等 "Initialization Sequence Completed" 的上限
29
- probeTimeoutMs: 20_000, // 探活/出口取证单发超时
30
- cooldownMs: 600_000, // 槽失败冷却
31
- rotate: true, // 撞额度信号时换槽
32
- nodesTtlMs: 30 * 60_000, // 节点表缓存有效期(VPNGate 免费节点掉得快)
33
- maxTableAgeMs: 24 * 60 * 60_000, // 表龄告警阈值:镜像表超过它就 ⚠(旧表 = 一堆早下线的 IP,白拨几分钟)
34
- openvpnBin: "openvpn",
35
- authUser: "vpn", // VPNGate 公共账号(非私人凭据)
36
- authPass: "vpn",
37
- debug: false,
38
- sysctl: true, // 放宽 rp_filter(严格反向路径过滤会让隧道"活着但请求挂死")
39
- };
40
-
41
- /**
42
- * VPNGate 节点源:**官方永远在前**,第三方镜像只作兜墙。
43
- * 纠错(2026-10-26 实测):`aimili-vpngate` 的 Actions 只把新鲜快照发到 **GitHub Pages**(`openmili.github.io/aimili-vpngate/`),
44
- * **不往仓库里写表**;仓库内 `mirror/vpngate.csv` 是手工提交的死快照(2026-08-26 后未变)——此前当「每 15 分钟刷新」用 =
45
- * 拿两个月前的死 IP 白拨,真机症状与被墙一模一样。
46
- * 表只是公开节点配置 + VPNGate 公共账号(vpn/vpn);不信任镜像就 `_SOURCES` 只留官方或 `_NODES_FILE` 自带。
47
- */
48
- export const NODE_SOURCES = [
49
- "https://www.vpngate.net/api/iphone/",
50
- "http://www.vpngate.net/api/iphone/",
51
- "https://openmili.github.io/aimili-vpngate/vpngate.csv",
52
- "https://raw.githubusercontent.com/OpenMili/aimili-vpngate/main/mirror/vpngate.csv",
53
- ];
54
-
55
- const OFF = ["0", "off", "false", "no", "disable", "disabled"];
56
- const MODES = ["auto", "leader", "member"];
57
-
58
- function envBool(env, name, fallback) {
59
- const raw = env[name];
60
- if (raw === undefined || raw === null || raw === "") return fallback;
61
- return !OFF.includes(String(raw).trim().toLowerCase());
62
- }
63
-
64
- function envInt(env, name, fallback) {
65
- const v = Number(env[name]);
66
- return Number.isInteger(v) && v > 0 ? v : fallback;
67
- }
68
-
69
- function envStr(env, name, fallback) {
70
- const raw = env[name];
71
- return typeof raw === "string" && raw.trim() ? raw.trim() : fallback;
72
- }
73
-
74
- function envList(env, name, fallback = "") {
75
- return String(env[name] ?? fallback)
76
- .split(",")
77
- .map((s) => s.trim())
78
- .filter(Boolean);
79
- }
80
- /** 备选出口上限:0 = 关;**硬上限 5**(用户 2026-10-25:不多于 5 个备选 IP)。 */
81
- function standbyCount(env) {
82
- const raw = Number(env.MSLXDFF_MULTI_IP_STANDBY);
83
- if (!Number.isFinite(raw) || raw < 0) return DEFAULTS.standby;
84
- return Math.min(5, Math.floor(raw));
85
- }
86
-
87
- /** 槽 i 的 tun 设备名(内核上限 15 字符:前缀默认 6 + 序号 ≤2 位,安全)。 */
88
- export function devNameFor(prefix, i) {
89
- return `${prefix}${i}`;
90
- }
91
-
92
- /** 槽 i 的策略路由表号(每槽独立表:`ip rule from <tun 地址> lookup <table>`)。 */
93
- export function tableFor(baseTable, i) {
94
- return baseTable + i;
95
- }
96
-
97
- /**
98
- * 解析 multi-ip 出口池配置。
99
- * @param {Record<string, string|undefined>} env
100
- * @param {{ logDirFn?: () => string }} [deps] 测试可注入 logDir
101
- */
102
- export function resolveMultiIpConfig(env = process.env, { logDirFn = logDir } = {}) {
103
- const modeRaw = envStr(env, "MSLXDFF_MULTI_IP_MODE", DEFAULTS.mode).toLowerCase();
104
- // 受限网络兜墙:`MSLXDFF_MULTI_IP_NODES_FILE` 指的本地表**排在最前**(设了就一次网络都不打)。
105
- const nodesFile = envStr(env, "MSLXDFF_MULTI_IP_NODES_FILE", "");
106
- const baseSources = envList(env, "MSLXDFF_MULTI_IP_SOURCES").length
107
- ? envList(env, "MSLXDFF_MULTI_IP_SOURCES")
108
- : NODE_SOURCES;
109
- const sources = nodesFile ? [nodesFile, ...baseSources.filter((s) => s !== nodesFile)] : baseSources;
110
- return {
111
- enabled: envBool(env, "MSLXDFF_MULTI_IP_POOL", DEFAULTS.enabled),
112
- mode: MODES.includes(modeRaw) ? modeRaw : DEFAULTS.mode,
113
- count: Math.min(8, envInt(env, "MSLXDFF_MULTI_IP_COUNT", DEFAULTS.count)),
114
- countries: envList(env, "MSLXDFF_MULTI_IP_COUNTRY").map((c) => c.toUpperCase()),
115
- minScore: envInt(env, "MSLXDFF_MULTI_IP_MIN_SCORE", DEFAULTS.minScore),
116
- scan: Math.min(32, envInt(env, "MSLXDFF_MULTI_IP_SCAN", DEFAULTS.scan)),
117
- baseTable: envInt(env, "MSLXDFF_MULTI_IP_BASE_TABLE", DEFAULTS.baseTable),
118
- devPrefix: envStr(env, "MSLXDFF_MULTI_IP_DEV_PREFIX", DEFAULTS.devPrefix),
119
- probeModel: envStr(env, "MSLXDFF_MULTI_IP_PROBE_MODEL", DEFAULTS.probeModel),
120
- strategy: envStr(env, "MSLXDFF_MULTI_IP_STRATEGY", DEFAULTS.strategy) === "request" ? "request" : "session",
121
- standby: standbyCount(env),
122
- standbyEveryMs: envInt(env, "MSLXDFF_MULTI_IP_STANDBY_EVERY_MS", DEFAULTS.standbyEveryMs),
123
- connectTimeoutMs: envInt(env, "MSLXDFF_MULTI_IP_CONNECT_TIMEOUT_MS", DEFAULTS.connectTimeoutMs),
124
- probeTimeoutMs: envInt(env, "MSLXDFF_MULTI_IP_PROBE_TIMEOUT_MS", DEFAULTS.probeTimeoutMs),
125
- cooldownMs: envInt(env, "MSLXDFF_MULTI_IP_COOLDOWN_MS", DEFAULTS.cooldownMs),
126
- rotate: envBool(env, "MSLXDFF_MULTI_IP_ROTATE", DEFAULTS.rotate),
127
- nodesTtlMs: envInt(env, "MSLXDFF_MULTI_IP_NODES_TTL_MS", DEFAULTS.nodesTtlMs),
128
- maxTableAgeMs: envInt(env, "MSLXDFF_MULTI_IP_MAX_TABLE_AGE_MS", DEFAULTS.maxTableAgeMs),
129
- openvpnBin: envStr(env, "MSLXDFF_MULTI_IP_OPENVPN", DEFAULTS.openvpnBin),
130
- authUser: envStr(env, "MSLXDFF_MULTI_IP_AUTH_USER", DEFAULTS.authUser),
131
- authPass: envStr(env, "MSLXDFF_MULTI_IP_AUTH_PASS", DEFAULTS.authPass),
132
- dir: envStr(env, "MSLXDFF_MULTI_IP_DIR", join(logDirFn(), "multi-ip-pool")),
133
- sources,
134
- nodesFile,
135
- debug: envBool(env, "MSLXDFF_MULTI_IP_DEBUG", DEFAULTS.debug),
136
- sysctl: envBool(env, "MSLXDFF_MULTI_IP_SYSCTL", DEFAULTS.sysctl),
137
- };
138
- }
139
-
140
- /**
141
- * 角色门(纯函数):**只有组长建池**(用户 2026-10-25 补裁);判据与 `-group` 同口径 —— `joined` 里 `leaderUrl` 为空即本节点是组长。
142
- * 纯组员与"没带任何组的单机"都不建;确需强开设 MSLXDFF_MULTI_IP_MODE=leader。
143
- * @param {{ mode?: string, joined?: Array<{leaderUrl?: string}> }} opts
144
- * @returns {{ active: boolean, role: "leader" | "member" | "solo", why: string }}
145
- */
146
- export function resolveRole({ mode = "auto", joined = [] } = {}) {
147
- const list = Array.isArray(joined) ? joined : [];
148
- const leads = list.some((g) => g && !g.leaderUrl);
149
- const derived = list.length === 0 ? "solo" : leads ? "leader" : "member";
150
- // 显式覆盖优先于推导(escape hatch:单机/组员机器上 MSLXDFF_MULTI_IP_MODE=leader 强开)
151
- if (mode === "leader") return { active: true, role: "leader", why: "MSLXDFF_MULTI_IP_MODE=leader(显式强开)" };
152
- if (mode === "member") return { active: false, role: "member", why: "MSLXDFF_MULTI_IP_MODE=member(显式)" };
153
- const why = derived === "leader" ? "本节点是组长(自己带的组)" : derived === "solo"
154
- ? "本节点没带任何组(单机):按「只有组长启用」不建池,要启用请设 MSLXDFF_MULTI_IP_MODE=leader"
155
- : "本节点是组员,出口池只由组长建";
156
- return { active: derived === "leader", role: derived, why };
157
- }
@@ -1,159 +0,0 @@
1
- // multi-ip-pool · 诊断层:openvpn 输出归因 / 节点 TCP 预检 / 取证全程 transcript(argv 原文由 report.js:fmtArgv 出)。
2
- //
3
- // 为什么单独一份:2026-10-25 真机两轮都栽在「看得见结果、看不见环节」——openvpn 用法错误的末行恒是
4
- // `Use --help`,真凶在它上面;而 selftest 的内部步骤日志在 CLI 里被接到了空函数上。
5
- // 本文件把「哪一步出问题」变成一等信息:每一步都有编号、耗时、原文,并整份落盘可粘贴。
6
- import { mkdirSync, appendFileSync } from "node:fs";
7
- import { dirname, join } from "node:path";
8
- import net from "node:net";
9
- import { devNameFor, tableFor } from "./config.js";
10
- import { clusterOf } from "./nodes.js";
11
-
12
- /** 值得单独成行的报错关键词(openvpn 的用法/握手/认证/网络失败都在这里)。 */
13
- const ERRORISH = /options error|unrecognized|missing or extra|fatal|error:|can ?not|cannot|denied|failed|refused|reset|auth failed|tls|write udp|bind|permission/i;
14
-
15
- /**
16
- * openvpn 输出里挑「最能说明问题」的一行:用法错误的**末行恒是** `Use --help for more information.`,
17
- * 真凶(`Options error: …`)在它上面。只报末行等于把病因盖住。
18
- */
19
- export function openvpnErrorLine(text, max = 240) {
20
- const lines = String(text || "").split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
21
- if (!lines.length) return "";
22
- const pick = lines.find((l) => ERRORISH.test(l));
23
- return (pick || lines[lines.length - 1]).slice(0, max);
24
- }
25
-
26
- /**
27
- * 一行内的**多行摘要**:真凶行 + 其余最多 3 行(用 ` ‖ ` 分隔)。
28
- * 单行是为了日志文件仍可 grep;多行是为了人眼一次看完,不必再翻 openvpn 自己的输出。
29
- */
30
- export function openvpnErrorBrief(text, max = 620) {
31
- const lines = String(text || "").split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
32
- if (!lines.length) return "";
33
- const first = lines.find((l) => ERRORISH.test(l)) || "";
34
- const rest = lines.filter((l) => l !== first && !/^Use --help/i.test(l)).slice(-3);
35
- return [first || lines[lines.length - 1], ...rest].join(" ‖ ").slice(0, max);
36
- }
37
-
38
- /**
39
- * 节点 TCP 预检:拨号前先确认「这台机能不能连到 host:port」。
40
- * 判语口径:VPNGate 实测 91/97 是 `proto tcp`,TCP 连不上基本就是节点/防火墙问题;
41
- * `proto udp` 的节点这条只作参考(UDP 无握手,连不上不代表隧道必挂),**必须如实分开说**。
42
- */
43
- export function probeTcp({ host, port, timeoutMs = 6_000, connectFn } = {}) {
44
- const t0 = Date.now();
45
- return new Promise((resolve) => {
46
- const done = (ok, extra) => resolve({ ok, ms: Date.now() - t0, host, port, ...extra });
47
- if (!host || !port) return done(false, { error: "缺 host/port" });
48
- if (connectFn) {
49
- return connectFn(host, port, timeoutMs)
50
- .then((r) => done(Boolean(r?.ok), { ...(r?.error ? { error: r.error } : {}) }))
51
- .catch((e) => done(false, { error: String(e?.message || e) }));
52
- }
53
- const s = net.connect({ host, port });
54
- const timer = setTimeout(() => { s.destroy(); done(false, { error: `连接超时(${timeoutMs}ms)` }); }, timeoutMs);
55
- s.once("connect", () => { clearTimeout(timer); s.destroy(); done(true, {}); });
56
- s.once("error", (e) => { clearTimeout(timer); done(false, { error: String(e?.code || e?.message || e) }); });
57
- });
58
- }
59
-
60
- /**
61
- * 批量 TCP 预检:**限并发**探一组节点,按输入顺序返回结果(`{ node, ok, ms, error }`)。
62
- * 为什么必须成批:真机实证「同一机房整片连不上」远多于「个别节点不通」——只探 3 条会给出
63
- * 一句误导的「全部不通」,探一批才看得出**是哪一片不通、还有哪片是通的**。
64
- */
65
- export async function probeBatch({ nodes = [], timeoutMs = 6_000, concurrency = 6, probe = probeTcp } = {}) {
66
- const out = new Array(nodes.length);
67
- let next = 0;
68
- const worker = async () => {
69
- for (;;) {
70
- const i = next++;
71
- if (i >= nodes.length) return;
72
- const node = nodes[i];
73
- out[i] = { node, ...(await probe({ host: node?.host, port: node?.port, timeoutMs })) };
74
- }
75
- };
76
- const width = Math.max(1, Math.min(Math.max(1, concurrency), nodes.length || 1));
77
- await Promise.all(Array.from({ length: width }, worker));
78
- return out;
79
- }
80
-
81
- /**
82
- * 取样小结:一句「探了几条、通几条」+ **簇分布**(哪个机房整片不通,一眼看出)。
83
- * 判死口径必须分开写:`proto udp` 的节点无握手,TCP 探不通**不能**当成「这条隧道必挂」。
84
- */
85
- export function probeSummaryLines({ results = [], minScore = 0, clustersShown = 6 } = {}) {
86
- const udp = results.filter((r) => String(r.node?.proto || "").toLowerCase() === "udp");
87
- const tcp = results.filter((r) => !udp.includes(r));
88
- const tcpLive = tcp.filter((r) => r.ok);
89
- const strict = results.filter((r) => Number(r.node?.score || 0) >= minScore).length;
90
- const groups = new Map();
91
- for (const r of tcp) {
92
- const key = clusterOf(r.node);
93
- const cur = groups.get(key) || { total: 0, ok: 0 };
94
- cur.total += 1;
95
- cur.ok += r.ok ? 1 : 0;
96
- groups.set(key, cur);
97
- }
98
- const tail = udp.length ? `(另有 ${udp.length} 条 UDP 节点:无握手,不计入判死)` : "";
99
- const lines = [`取样 ${results.length} 个(Score 达下限 ${strict} 个)→ TCP 通 ${tcpLive.length}|不通 ${tcp.length - tcpLive.length}${tail}`];
100
- const shown = [...groups.entries()].slice(0, clustersShown).map(([key, v]) => `${key} ${v.ok}/${v.total} 通`);
101
- if (shown.length) lines.push(`簇分布(机房/IP 段):${shown.join("|")}${groups.size > clustersShown ? `|…共 ${groups.size} 簇` : ""}`);
102
- if (!tcpLive.length && udp.some((r) => r.ok)) lines.push("探通的都是 UDP 节点 ⇒ TCP 探不出结论,下面仍按取样顺序真拨");
103
- return lines;
104
- }
105
-
106
- /**
107
- * 取证全程 transcript:每行带 `[步骤号]` 与相对耗时,同时进屏幕与文件(0600)。
108
- * 落盘是为了「一次跑完贴一个文件给我」,不必复现;写文件失败绝不影响测试本体。
109
- */
110
- export function createTranscript({ dir, out = (s) => console.log(s), now = () => Date.now(), fs = { mkdirSync, appendFileSync }, fileName = "" } = {}) {
111
- const t0 = now();
112
- let step = 0;
113
- const file = dir ? join(dir, fileName || `test-${new Date(t0).toISOString().replace(/[:.]/g, "-")}.log`) : "";
114
- const emit = (raw) => {
115
- const line = `[${String(step).padStart(2, "0")} +${((now() - t0) / 1000).toFixed(1)}s] ${raw}`;
116
- out(line);
117
- if (file) {
118
- try { fs.appendFileSync(file, line + "\n"); } catch { /* 落盘失败只影响存档,不影响取证 */ }
119
- }
120
- };
121
- try {
122
- if (file) { fs.mkdirSync(dirname(file), { recursive: true }); fs.appendFileSync(file, `# multi-ip-pool 取证 transcript(本文件可整份粘贴)\n`); }
123
- } catch { /* 同上 */ }
124
- return {
125
- file,
126
- /** 一条步骤行(自动编号)。 */
127
- step: (text) => { step += 1; emit(text); return step; },
128
- /** 归属当前步骤的明细行(不占编号)。 */
129
- say: (text) => emit(` ${String(text).replace(/^\s+/, "")}`),
130
- /** 小节标题。 */
131
- section: (text) => { step += 1; emit(`—— ${text} ——`); return step; },
132
- };
133
- }
134
-
135
- /** 环境快照:一眼看清「机器/权限/二进制/配置/磁盘上有什么」,省掉一轮来回。 */
136
- export function envSnapshotLines({ cfg, platform, root, openvpn, files = [], argvNode = "" } = {}) {
137
- return [
138
- `node ${argvNode || process.version}|平台 ${platform}|root ${root ? "是" : "否"}`,
139
- `openvpn ${openvpn?.ok ? `可用:${openvpn.version}` : `不可用:${openvpn?.why || "?"}`}`,
140
- `配置:隧道 ${cfg?.count} 条|备胎 ${cfg?.standby} 条/每 ${Math.round((cfg?.standbyEveryMs || 0) / 60_000)} 分钟|Score 下限 ${cfg?.minScore}|国家 ${cfg?.countries?.length ? cfg.countries.join("/") : "不限"}|策略 ${cfg?.strategy}`,
141
- `目录 ${cfg?.dir}:${files.length ? files.join(" ") : "(空,本轮第一次跑)"}`,
142
- `节点源(按序):${(cfg?.sources || []).join(" → ")}`,
143
- ];
144
- }
145
-
146
- /** 每槽的「设备名/路由表/优先级」对照表:内核侧出问题时按这张表查。 */
147
- export function slotPlanLines({ cfg, nodes = [] } = {}) {
148
- return nodes.map((n, i) => ` 槽 ${i}:${n.hostName}(${n.countryShort || "?"})→ ${n.host}:${n.port}|proto ${n.proto || "?"}|设备 ${devNameFor(cfg.devPrefix, i)}|表 ${tableFor(cfg.baseTable, i)}`);
149
- }
150
-
151
- /** 跑完(尤其是中途失败)后给全善后命令:设备与路由残留必须能一眼查清。 */
152
- export function residualHints() {
153
- return [
154
- "ip -brief addr show type tun",
155
- "ip link show | grep -E 'mltun|tun'",
156
- "ip rule show | grep -E 'from (10\\.|192\\.|172\\.)' | head",
157
- "ip route show table all | grep -E 'mltun' | head",
158
- ];
159
- }
@@ -1,179 +0,0 @@
1
- // multi-ip-pool · 拨号与体检:候选队列 → 起一条隧道 → **打一个 hi 到上游要它 200** → 才算可用出口。
2
- //
3
- // 为什么"要 200"而不是"能连上就行"(用户 2026-10-25 定):
4
- // 这条池的唯一目的是**换新额度**。隧道起来了但那个 IP 已经没额度(429/403),拿它换出口等于白换——
5
- // 所以判据必须是"这个出口现在真能出活",即免费层 chat 打 `hi` 回 **200**。
6
- // 请求形状复用 `v6pool/selftest.js`(`stream:true` + 五核心工具名 + 身份四件套):缺任何一项上游回
7
- // **403 FreeTierError 而不是 429**,那测的是形状、不是额度(真机 2026-10-19 踩过)。
8
- // 拆成独立模块的原因:装配(index)、拨号(本文件)、备选池(standby)三件事各自都要单测,混一起必超 10KB 门。
9
- import { getUndici } from "../compat.js";
10
- import { DEFAULT_PROBE_MODEL, probeUpstreamFrom } from "../v6pool/selftest.js";
11
- import { loadNodeCache, materializeNode, sampleCandidates } from "./nodes.js";
12
- import { fetchNodes, probeExitIp } from "./nodes-fetch.js";
13
- import { bringUpTunnel, tearDownTunnel } from "./tunnel.js";
14
- import { AGENT_OPTIONS } from "./dispatch.js";
15
- import { fmtExitIpFail, fmtHi, fmtNodePick, fmtNodes } from "./report.js";
16
-
17
- /**
18
- * @param {{ cfg: object, baseUrl?: string, log?: Function, deps?: {
19
- * bringUpTunnel?, tearDownTunnel?, materializeNode?, fetchNodes?, loadNodeCache?, probeExitIp?,
20
- * probeHi?, agentFactory?, fetchImpl?, runCmdFn?, spawnFn?, wait?, authFile?, probeSession? } }} opts
21
- */
22
- export function createDialer({ cfg, baseUrl = "https://opencode.ai", log = () => {}, deps = {} } = {}) {
23
- const startSlot = deps.bringUpTunnel || bringUpTunnel;
24
- const stopSlot = deps.tearDownTunnel || tearDownTunnel;
25
- const materialize = deps.materializeNode || materializeNode;
26
- const probeExit = deps.probeExitIp || probeExitIp;
27
- const probeHi = deps.probeHi || probeUpstreamFrom;
28
- const { Agent } = getUndici();
29
- const agentFactory = deps.agentFactory || ((addr) => new Agent({ connect: { localAddress: addr }, ...AGENT_OPTIONS }));
30
-
31
- /** 本拨号器起过的所有隧道(含备用的):退出钩子与 close 都从这儿收,一条都不许漏。 */
32
- const tunnels = new Set();
33
- const used = new Set(); // 已试过的节点(含正在用的):绝不重复拨同一台
34
- let pending = [];
35
- let source = "(未取表)";
36
- let authFile = deps.authFile || "";
37
-
38
- function setAuthFile(f) {
39
- authFile = f || "";
40
- }
41
-
42
- /** 探额度用的免费模型(上游不同模型额度池可能独立,需要时可换)。 */
43
- function probeModel() {
44
- return cfg.probeModel || DEFAULT_PROBE_MODEL;
45
- }
46
-
47
- /**
48
- * 「打一个 hi,要 200」:一发请求同时拿两个读数——**有没有额度**(status)与**真实出口 IP**(取证)。
49
- * @returns {Promise<{ok: boolean, status: number, kind: string, ms: number, ip: string, error: string}>}
50
- */
51
- async function hiProbe(entry) {
52
- const r = await probeHi({
53
- addr: entry.tunIp,
54
- model: probeModel(),
55
- baseUrl,
56
- agentFactory,
57
- fetchImpl: deps.fetchImpl,
58
- session: deps.probeSession,
59
- });
60
- let ip = entry.exitIp || "";
61
- if (!ip) {
62
- const agent = agentFactory(entry.tunIp);
63
- try {
64
- const e = await probeExit({ agent, timeoutMs: cfg.probeTimeoutMs, fetchImpl: deps.fetchImpl });
65
- ip = e.ip || "";
66
- } finally {
67
- try {
68
- await agent.close?.();
69
- } catch {
70
- /* 一次性 Agent */
71
- }
72
- }
73
- }
74
- return { ok: Boolean(r.ok), status: Number(r.status) || 0, kind: r.kind || "", ms: Number(r.ms) || 0, ip, error: r.error || "" };
75
- }
76
-
77
- /** 取节点表 → 候选队列(Score 降序 + **按簇轮转**,剔除已用过的);`force` = 绕过缓存重取(每小时刷新备选池用)。 */
78
- async function ensureCandidates({ force = false } = {}) {
79
- if (!force && pending.length) return pending.length;
80
- let rows = [];
81
- if (!force) {
82
- const cache = (deps.loadNodeCache || loadNodeCache)({ dir: cfg.dir, ttlMs: cfg.nodesTtlMs });
83
- if (cache?.rows?.length) {
84
- rows = cache.rows;
85
- source = cache.source || "(本地缓存)";
86
- }
87
- }
88
- if (!rows.length) {
89
- const got = await (deps.fetchNodes || fetchNodes)({ sources: cfg.sources, dir: cfg.dir, timeoutMs: cfg.probeTimeoutMs, maxAgeMs: cfg.maxTableAgeMs, log });
90
- rows = got.rows;
91
- source = got.source;
92
- }
93
- // 按簇轮转(见 nodes.js sampleCandidates):免费表前列常被同一个机房霸榜,纯 Score 序会让「那一片连不上」
94
- // 变成「池永远起不来」(真机 2026-10-25:三个候选同属 219.100.37.x)。轮转不丢节点,只是把各机房摊开。
95
- pending = sampleCandidates({ rows, countries: cfg.countries, minScore: cfg.minScore, skip: used, limit: cfg.scan * (cfg.count + cfg.standby + 1) });
96
- log(fmtNodes({ source, total: rows.length, countries: cfg.countries, minScore: cfg.minScore }));
97
- return pending.length;
98
- }
99
-
100
- /** 拆一条隧道并忘掉它(先撤策略路由再收子进程,见 tunnel.js)。 */
101
- async function drop(entry, why = "") {
102
- if (!entry) return;
103
- tunnels.delete(entry);
104
- try {
105
- await stopSlot({ slot: entry, runCmdFn: deps.runCmdFn, log });
106
- } catch (e) {
107
- log(`[multi-ip-pool] ${entry.dev} 拆隧道没拆干净:${String(e?.message || e)}${why ? `(${why})` : ""}`);
108
- }
109
- }
110
-
111
- /**
112
- * 开一个出口:按序试候选,每个都走「起隧道 → hi 要 200」,**不 200 当场拆掉换下一个**。
113
- * 为什么这道闸门必须有:隧道进程活着但转不动流量、或那个 IP 早已没额度时,把它塞进池等于
114
- * 把请求挂到超时或继续 429——比直连更糟(与 WARP 池 probeGate 同一纪律)。
115
- * @returns {Promise<null | { dev, table, priority, tunIp, pid, stop, node, exitIp }>}
116
- */
117
- async function openSlot(slotIndex, { dev = "", gate = true } = {}) {
118
- for (let attempt = 1; attempt <= cfg.scan; attempt++) {
119
- if (!pending.length) {
120
- try {
121
- await ensureCandidates();
122
- } catch (e) {
123
- log(`[multi-ip-pool] 取节点表失败:${String(e?.message || e)}`);
124
- return null;
125
- }
126
- if (!pending.length) return null;
127
- }
128
- const row = pending.shift();
129
- if (!row || used.has(row.hostName)) continue;
130
- used.add(row.hostName);
131
- log(fmtNodePick({ i: attempt, n: cfg.scan, row, dev }));
132
- let slot = null;
133
- try {
134
- let node = row;
135
- if (!node.conf) {
136
- node = materialize({ dir: cfg.dir, row });
137
- if (!node) throw new Error("节点配置解不开(base64 或 remote 缺失)");
138
- }
139
- slot = await startSlot({
140
- cfg,
141
- slotIndex,
142
- node,
143
- deps: { authFile, runCmdFn: deps.runCmdFn, spawnFn: deps.spawnFn, wait: deps.wait, log, onExit: () => tunnels.delete(slot) },
144
- });
145
- tunnels.add(slot);
146
- const p = await hiProbe(slot);
147
- log(fmtHi({ dev: slot.dev, model: probeModel(), ip: p.ip, ...p }));
148
- if (!p.ip) log(fmtExitIpFail({ dev: slot.dev, error: p.error || "出口取证无响应" }));
149
- if (gate && p.status !== 200) {
150
- await drop(slot, "hi 未回 200");
151
- continue;
152
- }
153
- return { ...slot, node, exitIp: p.ip || "" };
154
- } catch (e) {
155
- await drop(slot);
156
- log(`[multi-ip-pool] ${slot?.dev || `${cfg.devPrefix}${slotIndex}`} 起隧道失败:${String(e?.message || e)}`);
157
- }
158
- }
159
- return null;
160
- }
161
-
162
- return {
163
- tunnels,
164
- agentFactory,
165
- used,
166
- setAuthFile,
167
- probeModel,
168
- hiProbe,
169
- ensureCandidates,
170
- openSlot,
171
- drop,
172
- get sourceLabel() {
173
- return source;
174
- },
175
- get pendingCount() {
176
- return pending.length;
177
- },
178
- };
179
- }