lynx-proxy 0.0.1 → 0.0.2
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/README.md +50 -1
- package/dist/index.d.mts +1 -11
- package/dist/index.mjs +4436 -2442
- package/dist/tui.d.mts +8 -0
- package/dist/tui.mjs +4415 -0
- package/dist/web-assets/assets/index-CW9fIDIC.js +9 -0
- package/dist/web-assets/assets/index-D-xo-2WP.css +1 -0
- package/dist/web-assets/index.html +13 -0
- package/dist/web.d.mts +1 -0
- package/dist/web.mjs +2633 -0
- package/package.json +28 -14
- package/CLI.md +0 -259
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs.map +0 -1
package/dist/web.mjs
ADDED
|
@@ -0,0 +1,2633 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execFile, spawn } from "node:child_process";
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
import { existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { dirname, extname, join, normalize, resolve, sep } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { dump, load } from "js-yaml";
|
|
9
|
+
import axios from "axios";
|
|
10
|
+
import { createConnection } from "node:net";
|
|
11
|
+
import { promisify } from "node:util";
|
|
12
|
+
//#region src/web/sse-hub.ts
|
|
13
|
+
const HEARTBEAT_MS = 25e3;
|
|
14
|
+
var SseHub = class {
|
|
15
|
+
clients = /* @__PURE__ */ new Map();
|
|
16
|
+
nextId = 1;
|
|
17
|
+
heartbeat;
|
|
18
|
+
/** 注册一个新的 SSE 客户端,写入响应头并返回其 id 与注销函数。 */
|
|
19
|
+
add(res) {
|
|
20
|
+
const id = this.nextId++;
|
|
21
|
+
res.writeHead(200, {
|
|
22
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
23
|
+
"Cache-Control": "no-cache, no-transform",
|
|
24
|
+
Connection: "keep-alive",
|
|
25
|
+
"X-Accel-Buffering": "no"
|
|
26
|
+
});
|
|
27
|
+
res.write(": connected\n\n");
|
|
28
|
+
this.clients.set(id, res);
|
|
29
|
+
this.ensureHeartbeat();
|
|
30
|
+
const close = () => {
|
|
31
|
+
this.remove(id);
|
|
32
|
+
};
|
|
33
|
+
res.on("close", close);
|
|
34
|
+
res.on("error", close);
|
|
35
|
+
return {
|
|
36
|
+
id,
|
|
37
|
+
close
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
remove(id) {
|
|
41
|
+
this.clients.delete(id);
|
|
42
|
+
if (this.clients.size === 0) this.stopHeartbeat();
|
|
43
|
+
}
|
|
44
|
+
get size() {
|
|
45
|
+
return this.clients.size;
|
|
46
|
+
}
|
|
47
|
+
/** 向所有客户端广播一条事件;写失败的客户端被摘除。 */
|
|
48
|
+
broadcast(event, data) {
|
|
49
|
+
if (this.clients.size === 0) return;
|
|
50
|
+
const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
51
|
+
for (const [id, res] of this.clients) try {
|
|
52
|
+
res.write(frame);
|
|
53
|
+
} catch {
|
|
54
|
+
this.remove(id);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
ensureHeartbeat() {
|
|
58
|
+
if (this.heartbeat !== void 0) return;
|
|
59
|
+
this.heartbeat = setInterval(() => {
|
|
60
|
+
if (this.clients.size === 0) {
|
|
61
|
+
this.stopHeartbeat();
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
for (const [id, res] of this.clients) try {
|
|
65
|
+
res.write(": ping\n\n");
|
|
66
|
+
} catch {
|
|
67
|
+
this.remove(id);
|
|
68
|
+
}
|
|
69
|
+
}, HEARTBEAT_MS);
|
|
70
|
+
if (typeof this.heartbeat.unref === "function") this.heartbeat.unref();
|
|
71
|
+
}
|
|
72
|
+
stopHeartbeat() {
|
|
73
|
+
if (this.heartbeat !== void 0) {
|
|
74
|
+
clearInterval(this.heartbeat);
|
|
75
|
+
this.heartbeat = void 0;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
stop() {
|
|
79
|
+
this.stopHeartbeat();
|
|
80
|
+
for (const [, res] of this.clients) try {
|
|
81
|
+
res.end();
|
|
82
|
+
} catch {}
|
|
83
|
+
this.clients.clear();
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
//#endregion
|
|
87
|
+
//#region src/config/models.ts
|
|
88
|
+
var ConfigError = class extends Error {
|
|
89
|
+
constructor(message) {
|
|
90
|
+
super(message);
|
|
91
|
+
this.name = "ConfigError";
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
/** 从 unknown 错误值中提取可读消息,替代散落各处的 instanceof 三元表达式。 */
|
|
95
|
+
function errorMessage(error) {
|
|
96
|
+
return error instanceof Error ? error.message : String(error);
|
|
97
|
+
}
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region src/config/profile-paths.ts
|
|
100
|
+
/**
|
|
101
|
+
* Lynx 主目录:~/.lynx-proxy/
|
|
102
|
+
*/
|
|
103
|
+
function getLynxHome() {
|
|
104
|
+
return join(homedir(), ".lynx-proxy");
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Profile 索引文件路径:~/.lynx-proxy/profiles.yaml
|
|
108
|
+
*/
|
|
109
|
+
function getProfilesYamlPath() {
|
|
110
|
+
return join(getLynxHome(), "profiles.yaml");
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* mihomo 运行时配置文件路径:~/.lynx-proxy/config.yaml
|
|
114
|
+
* 由 Lynx 在生成 Profile 后写入,mihomo 启动时读取。
|
|
115
|
+
*/
|
|
116
|
+
function getMihomoConfigPath() {
|
|
117
|
+
return join(getLynxHome(), "config.yaml");
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/config/lynx-config.ts
|
|
121
|
+
/** lynx.json 完整路径。 */
|
|
122
|
+
function getConfigPath() {
|
|
123
|
+
return join(getLynxHome(), "lynx.json");
|
|
124
|
+
}
|
|
125
|
+
/** 加载 lynx.json。不存在时创建默认配置。 */
|
|
126
|
+
function loadLynxConfig() {
|
|
127
|
+
const path = getConfigPath();
|
|
128
|
+
if (!existsSync(path)) {
|
|
129
|
+
const config = getDefaultConfig();
|
|
130
|
+
writeLynxConfig(config);
|
|
131
|
+
return config;
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
const raw = readFileSync(path, "utf8");
|
|
135
|
+
return applyDefaults(JSON.parse(raw));
|
|
136
|
+
} catch (error) {
|
|
137
|
+
throw new ConfigError(`Failed to load lynx.json: ${errorMessage(error)}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** 写入 lynx.json。 */
|
|
141
|
+
function writeLynxConfig(config) {
|
|
142
|
+
mkdirSync(getLynxHome(), { recursive: true });
|
|
143
|
+
writeFileSync(getConfigPath(), `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
144
|
+
}
|
|
145
|
+
/** 创建默认配置。 */
|
|
146
|
+
function getDefaultConfig() {
|
|
147
|
+
return {
|
|
148
|
+
version: 1,
|
|
149
|
+
listen: "127.0.0.1:7890",
|
|
150
|
+
mihomo: {
|
|
151
|
+
"mixed-port": 7891,
|
|
152
|
+
"external-controller": "127.0.0.1:9090",
|
|
153
|
+
"auto-update": true
|
|
154
|
+
},
|
|
155
|
+
"system-proxy": false,
|
|
156
|
+
log: {
|
|
157
|
+
level: "info",
|
|
158
|
+
access: true
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function applyDefaults(parsed) {
|
|
163
|
+
const mihomo = parsed.mihomo ?? {};
|
|
164
|
+
const subscriptionUa = parsed.subscription?.user_agent;
|
|
165
|
+
const subscription = {};
|
|
166
|
+
if (typeof subscriptionUa === "string") subscription.user_agent = subscriptionUa;
|
|
167
|
+
return {
|
|
168
|
+
version: 1,
|
|
169
|
+
listen: parsed.listen ?? "127.0.0.1:7890",
|
|
170
|
+
mihomo: {
|
|
171
|
+
"mixed-port": mihomo["mixed-port"] ?? 7891,
|
|
172
|
+
"external-controller": mihomo["external-controller"] ?? "127.0.0.1:9090",
|
|
173
|
+
"auto-update": mihomo["auto-update"] ?? true,
|
|
174
|
+
...mihomo.secret !== void 0 ? { secret: mihomo.secret } : {},
|
|
175
|
+
...mihomo["bin-dir"] !== void 0 ? { "bin-dir": mihomo["bin-dir"] } : {},
|
|
176
|
+
...mihomo.kernel !== void 0 ? { kernel: mihomo.kernel } : {},
|
|
177
|
+
...typeof mihomo.ipv6 === "boolean" ? { ipv6: mihomo.ipv6 } : {},
|
|
178
|
+
...isMode(mihomo.mode) ? { mode: mihomo.mode } : {}
|
|
179
|
+
},
|
|
180
|
+
"system-proxy": parsed["system-proxy"] ?? false,
|
|
181
|
+
log: parsed.log ?? {
|
|
182
|
+
level: "info",
|
|
183
|
+
access: true
|
|
184
|
+
},
|
|
185
|
+
...Object.keys(subscription).length > 0 ? { subscription } : {}
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
const MODES = [
|
|
189
|
+
"rule",
|
|
190
|
+
"global",
|
|
191
|
+
"direct",
|
|
192
|
+
"script"
|
|
193
|
+
];
|
|
194
|
+
function isMode(value) {
|
|
195
|
+
return typeof value === "string" && MODES.includes(value);
|
|
196
|
+
}
|
|
197
|
+
//#endregion
|
|
198
|
+
//#region src/config/profiles.ts
|
|
199
|
+
/**
|
|
200
|
+
* 加载 profiles.yaml。文件不存在时返回空配置。
|
|
201
|
+
*/
|
|
202
|
+
function loadProfiles() {
|
|
203
|
+
const path = getProfilesYamlPath();
|
|
204
|
+
if (!existsSync(path)) return {};
|
|
205
|
+
try {
|
|
206
|
+
const parsed = load(readFileSync(path, "utf8"));
|
|
207
|
+
if (parsed === void 0 || parsed === null) return {};
|
|
208
|
+
if (typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("profiles.yaml root must be a mapping");
|
|
209
|
+
return normalizeProfiles(parsed);
|
|
210
|
+
} catch (error) {
|
|
211
|
+
if (error instanceof ConfigError) throw error;
|
|
212
|
+
throw new ConfigError(`Failed to load profiles.yaml: ${errorMessage(error)}`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* 写入 profiles.yaml。
|
|
217
|
+
*/
|
|
218
|
+
function saveProfiles(config) {
|
|
219
|
+
const path = getProfilesYamlPath();
|
|
220
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
221
|
+
writeFileSync(path, `# Profiles Config for LynxProxy\n${dump(config, {
|
|
222
|
+
indent: 2,
|
|
223
|
+
lineWidth: 120,
|
|
224
|
+
noRefs: true,
|
|
225
|
+
sortKeys: false
|
|
226
|
+
})}`, "utf8");
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* 获取当前激活的 Profile。
|
|
230
|
+
*/
|
|
231
|
+
function getCurrentProfile(config) {
|
|
232
|
+
if (config.current === void 0) return void 0;
|
|
233
|
+
return (config.items ?? []).find((item) => item.uid === config.current);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* 切换当前 Profile。
|
|
237
|
+
*/
|
|
238
|
+
function setCurrentProfile(config, uid) {
|
|
239
|
+
if (!(config.items ?? []).some((item) => item.uid === uid)) return false;
|
|
240
|
+
config.current = uid;
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* 读取某 Profile 的代理组预选(返回空 map 表示无记录)。
|
|
245
|
+
*/
|
|
246
|
+
function getProfileSelections(profile) {
|
|
247
|
+
return profile?.selections ?? {};
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* 设置(或删除)某 Profile 中某个组的预选节点。
|
|
251
|
+
* 仅修改传入的 config 对象,调用方负责 saveProfiles() 落盘。
|
|
252
|
+
*
|
|
253
|
+
* @param node 节点名;传空串/undefined 表示删除该组的预选
|
|
254
|
+
* @returns 是否发生了实际变更
|
|
255
|
+
*/
|
|
256
|
+
function setProfileSelection(config, uid, group, node) {
|
|
257
|
+
const item = (config.items ?? []).find((it) => it.uid === uid);
|
|
258
|
+
if (item === void 0) return false;
|
|
259
|
+
const current = item.selections?.[group];
|
|
260
|
+
if (node === void 0 || node.length === 0) {
|
|
261
|
+
if (current === void 0) return false;
|
|
262
|
+
if (item.selections !== void 0) delete item.selections[group];
|
|
263
|
+
return true;
|
|
264
|
+
}
|
|
265
|
+
if (current === node) return false;
|
|
266
|
+
if (item.selections === void 0) item.selections = {};
|
|
267
|
+
item.selections[group] = node;
|
|
268
|
+
return true;
|
|
269
|
+
}
|
|
270
|
+
function normalizeProfiles(raw) {
|
|
271
|
+
const result = {};
|
|
272
|
+
if (typeof raw["current"] === "string") result.current = raw["current"];
|
|
273
|
+
if (Array.isArray(raw["items"])) result.items = raw["items"].map((entry, index) => {
|
|
274
|
+
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) throw new ConfigError(`profiles.yaml items[${index}] must be a mapping`);
|
|
275
|
+
return normalizeItem(entry);
|
|
276
|
+
});
|
|
277
|
+
return result;
|
|
278
|
+
}
|
|
279
|
+
function normalizeItem(raw) {
|
|
280
|
+
const uid = raw["uid"];
|
|
281
|
+
const type = raw["type"];
|
|
282
|
+
const name = raw["name"];
|
|
283
|
+
const file = raw["file"];
|
|
284
|
+
if (typeof uid !== "string" || uid.length === 0) throw new ConfigError("profile item uid must be a non-empty string");
|
|
285
|
+
if (type !== "remote" && type !== "local" && type !== "merge" && type !== "script" && type !== "decoder") throw new ConfigError(`profile item type must be remote|local|merge|script|decoder, got: ${String(type)}`);
|
|
286
|
+
if (typeof name !== "string" || name.length === 0) throw new ConfigError("profile item name must be a non-empty string");
|
|
287
|
+
if (typeof file !== "string" || file.length === 0) throw new ConfigError("profile item file must be a non-empty string");
|
|
288
|
+
const item = {
|
|
289
|
+
uid,
|
|
290
|
+
type,
|
|
291
|
+
name,
|
|
292
|
+
file
|
|
293
|
+
};
|
|
294
|
+
if (typeof raw["url"] === "string") item.url = raw["url"];
|
|
295
|
+
if (typeof raw["updated"] === "number") item.updated = raw["updated"];
|
|
296
|
+
if (typeof raw["desc"] === "string") item.desc = raw["desc"];
|
|
297
|
+
if (Array.isArray(raw["selected"])) item.selected = raw["selected"].map((s, i) => {
|
|
298
|
+
if (typeof s !== "object" || s === null) throw new ConfigError(`selected[${i}] must be a mapping`);
|
|
299
|
+
const obj = s;
|
|
300
|
+
return {
|
|
301
|
+
name: String(obj["name"] ?? ""),
|
|
302
|
+
now: String(obj["now"] ?? "")
|
|
303
|
+
};
|
|
304
|
+
});
|
|
305
|
+
if (typeof raw["selections"] === "object" && raw["selections"] !== null && !Array.isArray(raw["selections"])) {
|
|
306
|
+
const map = raw["selections"];
|
|
307
|
+
const selections = {};
|
|
308
|
+
for (const [group, node] of Object.entries(map)) if (typeof node === "string" && node.length > 0) selections[group] = node;
|
|
309
|
+
if (Object.keys(selections).length > 0) item.selections = selections;
|
|
310
|
+
}
|
|
311
|
+
if (typeof raw["extra"] === "object" && raw["extra"] !== null && !Array.isArray(raw["extra"])) {
|
|
312
|
+
const e = raw["extra"];
|
|
313
|
+
const extra = {};
|
|
314
|
+
if (typeof e["upload"] === "number") extra.upload = e["upload"];
|
|
315
|
+
if (typeof e["download"] === "number") extra.download = e["download"];
|
|
316
|
+
if (typeof e["total"] === "number") extra.total = e["total"];
|
|
317
|
+
if (typeof e["expire"] === "number") extra.expire = e["expire"];
|
|
318
|
+
item.extra = extra;
|
|
319
|
+
}
|
|
320
|
+
if (typeof raw["option"] === "object" && raw["option"] !== null && !Array.isArray(raw["option"])) item.option = normalizeOption(raw["option"]);
|
|
321
|
+
return item;
|
|
322
|
+
}
|
|
323
|
+
/** 是否已经打印过 decoder 字段弃用警告。同一进程只打一次。 */
|
|
324
|
+
let decoderDeprecationWarned = false;
|
|
325
|
+
function warnDecoderDeprecationOnce(legacy) {
|
|
326
|
+
if (decoderDeprecationWarned) return;
|
|
327
|
+
decoderDeprecationWarned = true;
|
|
328
|
+
process.stderr.write(`[lynx] profile option.decoder="${legacy}" 已弃用,自动迁移到 decoder_plugin: D_xxyun。新写法:lynx profile add ... --decoder-plugin D_xxyun。
|
|
329
|
+
`);
|
|
330
|
+
}
|
|
331
|
+
function normalizeOption(raw) {
|
|
332
|
+
const opt = {};
|
|
333
|
+
if (typeof raw["user_agent"] === "string") opt.user_agent = raw["user_agent"];
|
|
334
|
+
if (typeof raw["with_proxy"] === "boolean") opt.with_proxy = raw["with_proxy"];
|
|
335
|
+
if (typeof raw["self_proxy"] === "boolean") opt.self_proxy = raw["self_proxy"];
|
|
336
|
+
if (typeof raw["update_interval"] === "number") opt.update_interval = raw["update_interval"];
|
|
337
|
+
if (typeof raw["timeout_seconds"] === "number") opt.timeout_seconds = raw["timeout_seconds"];
|
|
338
|
+
if (typeof raw["danger_accept_invalid_certs"] === "boolean") opt.danger_accept_invalid_certs = raw["danger_accept_invalid_certs"];
|
|
339
|
+
if (typeof raw["allow_auto_update"] === "boolean") opt.allow_auto_update = raw["allow_auto_update"];
|
|
340
|
+
if (typeof raw["merge"] === "string") opt.merge = raw["merge"];
|
|
341
|
+
if (typeof raw["script"] === "string") opt.script = raw["script"];
|
|
342
|
+
if (typeof raw["decoder"] === "string") {
|
|
343
|
+
const legacy = raw["decoder"];
|
|
344
|
+
if (legacy === "xxyun" || legacy === "D_xxyun") {
|
|
345
|
+
opt.decoder_plugin = "D_xxyun";
|
|
346
|
+
warnDecoderDeprecationOnce(legacy);
|
|
347
|
+
} else throw new ConfigError(`Unknown legacy decoder: "${legacy}". xxyun has been migrated to plugin D_xxyun; for custom decoders, use "lynx profile decoder add".`);
|
|
348
|
+
}
|
|
349
|
+
if (typeof raw["decoder_plugin"] === "string") opt.decoder_plugin = raw["decoder_plugin"];
|
|
350
|
+
if (typeof raw["decoder_key"] === "string") opt.decoder_key = raw["decoder_key"];
|
|
351
|
+
return opt;
|
|
352
|
+
}
|
|
353
|
+
//#endregion
|
|
354
|
+
//#region src/mihomo/mihomo-api.ts
|
|
355
|
+
var MihomoApiError = class extends Error {
|
|
356
|
+
status;
|
|
357
|
+
data;
|
|
358
|
+
constructor(message, status, data) {
|
|
359
|
+
super(message);
|
|
360
|
+
this.name = "MihomoApiError";
|
|
361
|
+
this.status = status;
|
|
362
|
+
this.data = data;
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
/**
|
|
366
|
+
* mihomo REST API 客户端。
|
|
367
|
+
* 完整封装 mihomo 外部控制器 HTTP 端点,使用 Bearer token 认证。
|
|
368
|
+
*
|
|
369
|
+
* 所有公共方法返回具体类型,错误统一抛 {@link MihomoApiError}。
|
|
370
|
+
*
|
|
371
|
+
* WebSocket 端点(/traffic, /logs)不在此类中,需另行实现 WebSocket 连接。
|
|
372
|
+
*/
|
|
373
|
+
var MihomoApiClient = class {
|
|
374
|
+
baseUrl;
|
|
375
|
+
secret;
|
|
376
|
+
/** 默认请求超时(毫秒) */
|
|
377
|
+
timeout;
|
|
378
|
+
constructor(host, port, secret, timeout = 5e3) {
|
|
379
|
+
this.baseUrl = `http://${host}:${port}`;
|
|
380
|
+
this.secret = secret;
|
|
381
|
+
this.timeout = timeout;
|
|
382
|
+
}
|
|
383
|
+
/** 健康检查:GET /version */
|
|
384
|
+
async isReady() {
|
|
385
|
+
try {
|
|
386
|
+
await this.request("/version", "GET");
|
|
387
|
+
return true;
|
|
388
|
+
} catch {
|
|
389
|
+
return false;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
/** 获取 mihomo 版本信息:GET /version */
|
|
393
|
+
async getVersion() {
|
|
394
|
+
return this.request("/version", "GET");
|
|
395
|
+
}
|
|
396
|
+
/** 重载配置:PUT /configs?force=true */
|
|
397
|
+
async reloadConfig() {
|
|
398
|
+
await this.request("/configs?force=true", "PUT", { path: "" });
|
|
399
|
+
}
|
|
400
|
+
/** 重启 mihomo:POST /restart */
|
|
401
|
+
async restart() {
|
|
402
|
+
await this.request("/restart", "POST");
|
|
403
|
+
}
|
|
404
|
+
/** 获取所有代理和组状态:GET /proxies */
|
|
405
|
+
async getProxies() {
|
|
406
|
+
return this.request("/proxies", "GET");
|
|
407
|
+
}
|
|
408
|
+
/** 获取单个代理或组详情:GET /proxies/{name} */
|
|
409
|
+
async getProxy(name) {
|
|
410
|
+
return this.request(`/proxies/${encodeURIComponent(name)}`, "GET");
|
|
411
|
+
}
|
|
412
|
+
/** 设置代理组选中的节点:PUT /proxies/{groupName} */
|
|
413
|
+
async selectProxy(groupName, proxyName) {
|
|
414
|
+
await this.request(`/proxies/${encodeURIComponent(groupName)}`, "PUT", { name: proxyName });
|
|
415
|
+
}
|
|
416
|
+
/** 测试节点延迟:GET /proxies/{name}/delay?url=...&timeout=... */
|
|
417
|
+
async getProxyDelay(name, url = "http://www.gstatic.com/generate_204", timeout = 5e3) {
|
|
418
|
+
const params = new URLSearchParams({
|
|
419
|
+
url,
|
|
420
|
+
timeout: String(timeout)
|
|
421
|
+
});
|
|
422
|
+
return this.request(`/proxies/${encodeURIComponent(name)}/delay?${params.toString()}`, "GET");
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* 获取所有代理组详情:GET /groups
|
|
426
|
+
*
|
|
427
|
+
* 与 /proxies 不同,/groups 只返回代理组(Selector / URLTest / Fallback 等),
|
|
428
|
+
* 不包含普通代理节点。
|
|
429
|
+
*/
|
|
430
|
+
async getGroups() {
|
|
431
|
+
return (await this.request("/groups", "GET")).groups;
|
|
432
|
+
}
|
|
433
|
+
/** 获取所有活跃连接及累计流量:GET /connections */
|
|
434
|
+
async getConnections() {
|
|
435
|
+
return this.request("/connections", "GET");
|
|
436
|
+
}
|
|
437
|
+
/** 断开所有连接:DELETE /connections */
|
|
438
|
+
async closeConnections() {
|
|
439
|
+
await this.request("/connections", "DELETE");
|
|
440
|
+
}
|
|
441
|
+
/** 断开指定连接:DELETE /connections/{id} */
|
|
442
|
+
async closeConnection(id) {
|
|
443
|
+
await this.request(`/connections/${encodeURIComponent(id)}`, "DELETE");
|
|
444
|
+
}
|
|
445
|
+
/** 获取当前运行配置:GET /configs */
|
|
446
|
+
async getConfigs() {
|
|
447
|
+
return this.request("/configs", "GET");
|
|
448
|
+
}
|
|
449
|
+
/** 更新运行配置(如 mode):PATCH /configs */
|
|
450
|
+
async patchConfigs(patch) {
|
|
451
|
+
await this.request("/configs", "PATCH", patch);
|
|
452
|
+
}
|
|
453
|
+
/** 获取规则匹配统计:GET /rules */
|
|
454
|
+
async getRules() {
|
|
455
|
+
return this.request("/rules", "GET");
|
|
456
|
+
}
|
|
457
|
+
/** 获取所有 proxy provider:GET /providers/proxies */
|
|
458
|
+
async getProxyProviders() {
|
|
459
|
+
return this.request("/providers/proxies", "GET");
|
|
460
|
+
}
|
|
461
|
+
/** 刷新单个 proxy provider:PUT /providers/proxies/{name} */
|
|
462
|
+
async refreshProxyProvider(name) {
|
|
463
|
+
await this.request(`/providers/proxies/${encodeURIComponent(name)}`, "PUT");
|
|
464
|
+
}
|
|
465
|
+
/** 获取所有 rule provider:GET /providers/rules */
|
|
466
|
+
async getRuleProviders() {
|
|
467
|
+
return this.request("/providers/rules", "GET");
|
|
468
|
+
}
|
|
469
|
+
/** 刷新单个 rule provider:PUT /providers/rules/{name} */
|
|
470
|
+
async refreshRuleProvider(name) {
|
|
471
|
+
await this.request(`/providers/rules/${encodeURIComponent(name)}`, "PUT");
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* DNS 查询:GET /dns/query?name={name}&type={type}
|
|
475
|
+
* @param name 要查询的域名
|
|
476
|
+
* @param type 记录类型(如 "A", "AAAA", "TXT"),默认 "A"
|
|
477
|
+
*/
|
|
478
|
+
async dnsQuery(name, type = "A") {
|
|
479
|
+
const params = new URLSearchParams({
|
|
480
|
+
name,
|
|
481
|
+
type
|
|
482
|
+
});
|
|
483
|
+
return this.request(`/dns/query?${params.toString()}`, "GET");
|
|
484
|
+
}
|
|
485
|
+
/** 获取 FakeIP 缓存:GET /cache/fakeip */
|
|
486
|
+
async getFakeIpCache() {
|
|
487
|
+
return this.request("/cache/fakeip", "GET");
|
|
488
|
+
}
|
|
489
|
+
/** 清空 FakeIP 缓存:DELETE /cache/fakeip */
|
|
490
|
+
async flushFakeIpCache() {
|
|
491
|
+
await this.request("/cache/fakeip", "DELETE");
|
|
492
|
+
}
|
|
493
|
+
/** 获取当前日志级别:GET /logs/level */
|
|
494
|
+
async getLogLevel() {
|
|
495
|
+
return this.request("/logs/level", "GET");
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* 设置日志级别:PATCH /logs/level
|
|
499
|
+
* @param level 日志级别 "debug" | "info" | "warn" | "error"
|
|
500
|
+
*/
|
|
501
|
+
async setLogLevel(level) {
|
|
502
|
+
await this.request("/logs/level", "PATCH", { level });
|
|
503
|
+
}
|
|
504
|
+
/** 获取内存使用统计:GET /memory */
|
|
505
|
+
async getMemory() {
|
|
506
|
+
return this.request("/memory", "GET");
|
|
507
|
+
}
|
|
508
|
+
/** 升级 mihomo 内核:PUT /upgrade */
|
|
509
|
+
async upgradeCore() {
|
|
510
|
+
return this.request("/upgrade", "PUT");
|
|
511
|
+
}
|
|
512
|
+
/** 升级 Geo 数据库:PUT /upgrade/geo */
|
|
513
|
+
async upgradeGeo() {
|
|
514
|
+
return this.request("/upgrade/geo", "PUT");
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* 获取 pprof 性能分析数据:GET /debug/pprof/{name}
|
|
518
|
+
*
|
|
519
|
+
* 返回原始二进制数据(ArrayBuffer),适用于:
|
|
520
|
+
* - goroutine — 协程栈
|
|
521
|
+
* - heap — 堆分配
|
|
522
|
+
* - allocs — 分配统计
|
|
523
|
+
* - threadcreate — 线程创建
|
|
524
|
+
* - block — 阻塞分析
|
|
525
|
+
* - mutex — 互斥锁
|
|
526
|
+
* - profile — CPU 分析(配合 seconds 参数)
|
|
527
|
+
* - trace — 执行追踪(配合 seconds 参数)
|
|
528
|
+
*
|
|
529
|
+
* @param name 分析类型名称,如 "heap", "goroutine", "profile"
|
|
530
|
+
* @param seconds CPU profile / trace 的采样时长(秒)
|
|
531
|
+
*/
|
|
532
|
+
async getPprof(name, seconds) {
|
|
533
|
+
let path = `/debug/pprof/${encodeURIComponent(name)}`;
|
|
534
|
+
if (seconds !== void 0) path += `?seconds=${seconds}`;
|
|
535
|
+
const config = {
|
|
536
|
+
method: "GET",
|
|
537
|
+
url: `${this.baseUrl}${path}`,
|
|
538
|
+
headers: { Authorization: `Bearer ${this.secret}` },
|
|
539
|
+
timeout: (seconds ?? 30) * 1e3 + 5e3,
|
|
540
|
+
responseType: "arraybuffer"
|
|
541
|
+
};
|
|
542
|
+
try {
|
|
543
|
+
return (await axios(config)).data;
|
|
544
|
+
} catch (error) {
|
|
545
|
+
if (axios.isAxiosError(error)) {
|
|
546
|
+
const status = error.response?.status;
|
|
547
|
+
throw new MihomoApiError(`pprof error (${status ?? "unknown"}): ${error.message}`, status);
|
|
548
|
+
}
|
|
549
|
+
throw new MihomoApiError(`pprof request failed: ${String(error)}`);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* 统一 HTTP 请求底层方法(JSON 响应)。
|
|
554
|
+
* - 自动注入 Bearer token
|
|
555
|
+
* - 错误统一抛 {@link MihomoApiError}
|
|
556
|
+
* - 返回解析后的 JSON 响应体
|
|
557
|
+
*/
|
|
558
|
+
async request(path, method, body) {
|
|
559
|
+
const config = {
|
|
560
|
+
method,
|
|
561
|
+
url: `${this.baseUrl}${path}`,
|
|
562
|
+
headers: { Authorization: `Bearer ${this.secret}` },
|
|
563
|
+
timeout: this.timeout
|
|
564
|
+
};
|
|
565
|
+
if (body !== void 0) {
|
|
566
|
+
config.headers = {
|
|
567
|
+
...config.headers,
|
|
568
|
+
"Content-Type": "application/json"
|
|
569
|
+
};
|
|
570
|
+
config.data = body;
|
|
571
|
+
}
|
|
572
|
+
try {
|
|
573
|
+
return (await axios(config)).data;
|
|
574
|
+
} catch (error) {
|
|
575
|
+
if (axios.isAxiosError(error)) {
|
|
576
|
+
const status = error.response?.status;
|
|
577
|
+
const data = error.response?.data;
|
|
578
|
+
throw new MihomoApiError(`mihomo API error (${status ?? "unknown"}): ${data !== void 0 ? JSON.stringify(data) : error.message}`, status, data);
|
|
579
|
+
}
|
|
580
|
+
throw new MihomoApiError(`mihomo API request failed: ${String(error)}`);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
//#endregion
|
|
585
|
+
//#region src/utils/process.ts
|
|
586
|
+
/**
|
|
587
|
+
* 判断给定 PID 的进程是否存活。
|
|
588
|
+
*
|
|
589
|
+
* `process.kill(pid, 0)` 不发送真实信号,只做存在性与权限探测:
|
|
590
|
+
* - 成功 → 进程存在
|
|
591
|
+
* - `ESRCH` → 进程不存在
|
|
592
|
+
* - `EPERM` → 进程**存在**,但当前用户无权向它发信号(如换用户后残留的 daemon)
|
|
593
|
+
*
|
|
594
|
+
* 因此 EPERM 必须视为"存活"。把它当成"已退出"会导致等待退出的逻辑立即返回,
|
|
595
|
+
* 误判进程已结束。
|
|
596
|
+
*/
|
|
597
|
+
function isPidAlive(pid) {
|
|
598
|
+
try {
|
|
599
|
+
process.kill(pid, 0);
|
|
600
|
+
return true;
|
|
601
|
+
} catch (error) {
|
|
602
|
+
return (typeof error === "object" && error !== null ? error.code : void 0) === "EPERM";
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
//#endregion
|
|
606
|
+
//#region src/runtime/daemon-state.ts
|
|
607
|
+
const LYNX_HOME = getLynxHome();
|
|
608
|
+
function getProxyDaemonStatePath() {
|
|
609
|
+
return join(LYNX_HOME, "runtime", "proxy-daemon.json");
|
|
610
|
+
}
|
|
611
|
+
function getProxyDaemonLogPath() {
|
|
612
|
+
return join(LYNX_HOME, "runtime", "proxy-daemon.log");
|
|
613
|
+
}
|
|
614
|
+
function getControlSocketPath() {
|
|
615
|
+
return join(LYNX_HOME, "runtime", "control.sock");
|
|
616
|
+
}
|
|
617
|
+
function loadProxyDaemonState(path = getProxyDaemonStatePath()) {
|
|
618
|
+
if (!existsSync(path)) return;
|
|
619
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
620
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("proxy daemon state must be an object");
|
|
621
|
+
const object = raw;
|
|
622
|
+
if (object["version"] !== 1) throw new Error("proxy daemon state version must be 1");
|
|
623
|
+
const pid = object["pid"];
|
|
624
|
+
const host = object["host"];
|
|
625
|
+
const port = object["port"];
|
|
626
|
+
const startedAt = object["startedAt"];
|
|
627
|
+
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) throw new Error("proxy daemon state pid must be a positive integer");
|
|
628
|
+
if (typeof host !== "string" || host.length === 0) throw new Error("proxy daemon state host must be a non-empty string");
|
|
629
|
+
if (typeof port !== "number" || !Number.isInteger(port) || port <= 0) throw new Error("proxy daemon state port must be a positive integer");
|
|
630
|
+
if (typeof startedAt !== "string" || startedAt.length === 0) throw new Error("proxy daemon state startedAt must be a non-empty string");
|
|
631
|
+
const state = {
|
|
632
|
+
version: 1,
|
|
633
|
+
pid,
|
|
634
|
+
host,
|
|
635
|
+
port,
|
|
636
|
+
startedAt
|
|
637
|
+
};
|
|
638
|
+
if (typeof object["logFile"] === "string") state.logFile = object["logFile"];
|
|
639
|
+
if (typeof object["profile"] === "string") state.profile = object["profile"];
|
|
640
|
+
if (typeof object["profilePath"] === "string") state.profilePath = object["profilePath"];
|
|
641
|
+
const hasExtHost = object["extHost"] !== void 0;
|
|
642
|
+
const hasExtPort = object["extPort"] !== void 0;
|
|
643
|
+
const hasSecret = object["secret"] !== void 0;
|
|
644
|
+
if (hasExtHost || hasExtPort || hasSecret) {
|
|
645
|
+
if (typeof object["extHost"] !== "string" || object["extHost"].length === 0) throw new Error("proxy daemon state extHost must be a non-empty string");
|
|
646
|
+
if (typeof object["extPort"] !== "number" || !Number.isInteger(object["extPort"]) || object["extPort"] <= 0) throw new Error("proxy daemon state extPort must be a positive integer");
|
|
647
|
+
if (typeof object["secret"] !== "string" || object["secret"].length === 0) throw new Error("proxy daemon state secret must be a non-empty string");
|
|
648
|
+
state.extHost = object["extHost"];
|
|
649
|
+
state.extPort = object["extPort"];
|
|
650
|
+
state.secret = object["secret"];
|
|
651
|
+
}
|
|
652
|
+
return state;
|
|
653
|
+
}
|
|
654
|
+
function removeProxyDaemonState(path = getProxyDaemonStatePath()) {
|
|
655
|
+
rmSync(path, { force: true });
|
|
656
|
+
}
|
|
657
|
+
function isProcessRunning(pid) {
|
|
658
|
+
if (!isPidAlive(pid)) return false;
|
|
659
|
+
if (process.platform === "linux") try {
|
|
660
|
+
const cmdline = readFileSync(`/proc/${pid}/cmdline`, "utf8");
|
|
661
|
+
return cmdline.includes("proxy") && cmdline.includes("run-daemon");
|
|
662
|
+
} catch {
|
|
663
|
+
return false;
|
|
664
|
+
}
|
|
665
|
+
return true;
|
|
666
|
+
}
|
|
667
|
+
//#endregion
|
|
668
|
+
//#region src/runtime/control-client.ts
|
|
669
|
+
/**
|
|
670
|
+
* 向 daemon 控制通道发送一条命令并返回响应。
|
|
671
|
+
*
|
|
672
|
+
* 单次请求/单次响应:发送后收到第一行响应即关闭连接。
|
|
673
|
+
* socket 文件不存在或连接被拒(daemon 未运行)时返回 undefined。
|
|
674
|
+
*/
|
|
675
|
+
function sendControlCommand(command, socketPath = getControlSocketPath()) {
|
|
676
|
+
if (!existsSync(socketPath)) return Promise.resolve(void 0);
|
|
677
|
+
return new Promise((resolve, reject) => {
|
|
678
|
+
const socket = createConnection(socketPath);
|
|
679
|
+
let buffer = "";
|
|
680
|
+
socket.setEncoding("utf8");
|
|
681
|
+
socket.on("connect", () => {
|
|
682
|
+
socket.write(`${JSON.stringify(command)}\n`);
|
|
683
|
+
});
|
|
684
|
+
socket.on("data", (chunk) => {
|
|
685
|
+
buffer += chunk;
|
|
686
|
+
const nl = buffer.indexOf("\n");
|
|
687
|
+
if (nl !== -1) {
|
|
688
|
+
socket.end();
|
|
689
|
+
try {
|
|
690
|
+
resolve(JSON.parse(buffer.slice(0, nl)));
|
|
691
|
+
} catch {
|
|
692
|
+
resolve(void 0);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
});
|
|
696
|
+
socket.on("error", (error) => {
|
|
697
|
+
if (error.code === "ECONNREFUSED" || error.code === "ENOENT") {
|
|
698
|
+
resolve(void 0);
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
reject(error);
|
|
702
|
+
});
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
/** 检测控制 socket 是否有 daemon 在监听。Windows 上恒为 false(无 unix socket)。 */
|
|
706
|
+
function isControlSocketReady(socketPath = getControlSocketPath()) {
|
|
707
|
+
if (!existsSync(socketPath)) return Promise.resolve(false);
|
|
708
|
+
return new Promise((resolve) => {
|
|
709
|
+
const probe = createConnection(socketPath);
|
|
710
|
+
const done = (ready) => {
|
|
711
|
+
probe.destroy();
|
|
712
|
+
resolve(ready);
|
|
713
|
+
};
|
|
714
|
+
probe.once("connect", () => done(true));
|
|
715
|
+
probe.once("error", () => done(false));
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
//#endregion
|
|
719
|
+
//#region src/system-proxy/base.ts
|
|
720
|
+
const execFile$1 = promisify(execFile);
|
|
721
|
+
var SystemProxyError = class extends Error {
|
|
722
|
+
controller;
|
|
723
|
+
constructor(message, controller, options) {
|
|
724
|
+
super(message, options);
|
|
725
|
+
this.name = "SystemProxyError";
|
|
726
|
+
this.controller = controller;
|
|
727
|
+
}
|
|
728
|
+
};
|
|
729
|
+
/**
|
|
730
|
+
* 执行一条命令并返回 stdout。非零退出码或命令不存在时抛 SystemProxyError,
|
|
731
|
+
* 由调用方决定是降级(detect)还是上抛(enable/disable)。
|
|
732
|
+
*/
|
|
733
|
+
async function runCommand(controller, file, args) {
|
|
734
|
+
try {
|
|
735
|
+
const { stdout } = await execFile$1(file, [...args]);
|
|
736
|
+
return stdout;
|
|
737
|
+
} catch (error) {
|
|
738
|
+
const execError = error;
|
|
739
|
+
const code = execError?.code ?? "unknown";
|
|
740
|
+
const stderr = typeof execError?.stderr === "string" ? execError.stderr.trim() : "";
|
|
741
|
+
const detail = stderr.length > 0 ? `: ${stderr}` : "";
|
|
742
|
+
throw new SystemProxyError(`${controller}: \`${file} ${args.join(" ")}\` failed (${code})${detail}`, controller, { cause: error });
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
//#endregion
|
|
746
|
+
//#region src/system-proxy/linux.ts
|
|
747
|
+
const GNOME_SCHEMA = "org.gnome.system.proxy";
|
|
748
|
+
const GNOME_HTTP_SCHEMA = "org.gnome.system.proxy.http";
|
|
749
|
+
/** GNOME 桌面:通过 gsettings 写 org.gnome.system.proxy。 */
|
|
750
|
+
const gnomeController = {
|
|
751
|
+
name: "gnome",
|
|
752
|
+
async detect() {
|
|
753
|
+
try {
|
|
754
|
+
await runCommand("gnome", "gsettings", [
|
|
755
|
+
"get",
|
|
756
|
+
GNOME_SCHEMA,
|
|
757
|
+
"mode"
|
|
758
|
+
]);
|
|
759
|
+
return true;
|
|
760
|
+
} catch {
|
|
761
|
+
return false;
|
|
762
|
+
}
|
|
763
|
+
},
|
|
764
|
+
async enable(host, port) {
|
|
765
|
+
await runCommand("gnome", "gsettings", [
|
|
766
|
+
"set",
|
|
767
|
+
GNOME_SCHEMA,
|
|
768
|
+
"mode",
|
|
769
|
+
"manual"
|
|
770
|
+
]);
|
|
771
|
+
await runCommand("gnome", "gsettings", [
|
|
772
|
+
"set",
|
|
773
|
+
GNOME_HTTP_SCHEMA,
|
|
774
|
+
"host",
|
|
775
|
+
host
|
|
776
|
+
]);
|
|
777
|
+
await runCommand("gnome", "gsettings", [
|
|
778
|
+
"set",
|
|
779
|
+
GNOME_HTTP_SCHEMA,
|
|
780
|
+
"port",
|
|
781
|
+
String(port)
|
|
782
|
+
]);
|
|
783
|
+
},
|
|
784
|
+
async disable() {
|
|
785
|
+
await runCommand("gnome", "gsettings", [
|
|
786
|
+
"set",
|
|
787
|
+
GNOME_SCHEMA,
|
|
788
|
+
"mode",
|
|
789
|
+
"none"
|
|
790
|
+
]);
|
|
791
|
+
},
|
|
792
|
+
async current() {
|
|
793
|
+
try {
|
|
794
|
+
if ((await runCommand("gnome", "gsettings", [
|
|
795
|
+
"get",
|
|
796
|
+
GNOME_SCHEMA,
|
|
797
|
+
"mode"
|
|
798
|
+
])).trim() !== "'manual'") return;
|
|
799
|
+
const host = stripGsettingsQuotes(await runCommand("gnome", "gsettings", [
|
|
800
|
+
"get",
|
|
801
|
+
GNOME_HTTP_SCHEMA,
|
|
802
|
+
"host"
|
|
803
|
+
]));
|
|
804
|
+
const port = Number.parseInt((await runCommand("gnome", "gsettings", [
|
|
805
|
+
"get",
|
|
806
|
+
GNOME_HTTP_SCHEMA,
|
|
807
|
+
"port"
|
|
808
|
+
])).trim(), 10);
|
|
809
|
+
if (host.length === 0 || !Number.isInteger(port)) return;
|
|
810
|
+
return {
|
|
811
|
+
host,
|
|
812
|
+
port
|
|
813
|
+
};
|
|
814
|
+
} catch {
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
};
|
|
819
|
+
const KDE_FILE = "kioslaverc";
|
|
820
|
+
const KDE_GROUP = "Proxy Settings";
|
|
821
|
+
/** KDE Plasma 6:通过 kwriteconfig6 写 kioslaverc,并 dbus 通知重载。 */
|
|
822
|
+
const kdeController = {
|
|
823
|
+
name: "kde",
|
|
824
|
+
async detect() {
|
|
825
|
+
try {
|
|
826
|
+
await runCommand("kde", "kwriteconfig6", ["--version"]);
|
|
827
|
+
return true;
|
|
828
|
+
} catch {
|
|
829
|
+
return false;
|
|
830
|
+
}
|
|
831
|
+
},
|
|
832
|
+
async enable(host, port) {
|
|
833
|
+
const endpoint = `http://${host}:${port}`;
|
|
834
|
+
await runCommand("kde", "kwriteconfig6", [
|
|
835
|
+
"--file",
|
|
836
|
+
KDE_FILE,
|
|
837
|
+
"--group",
|
|
838
|
+
KDE_GROUP,
|
|
839
|
+
"--key",
|
|
840
|
+
"ProxyType",
|
|
841
|
+
"1"
|
|
842
|
+
]);
|
|
843
|
+
await runCommand("kde", "kwriteconfig6", [
|
|
844
|
+
"--file",
|
|
845
|
+
KDE_FILE,
|
|
846
|
+
"--group",
|
|
847
|
+
KDE_GROUP,
|
|
848
|
+
"--key",
|
|
849
|
+
"httpProxy",
|
|
850
|
+
endpoint
|
|
851
|
+
]);
|
|
852
|
+
await runCommand("kde", "kwriteconfig6", [
|
|
853
|
+
"--file",
|
|
854
|
+
KDE_FILE,
|
|
855
|
+
"--group",
|
|
856
|
+
KDE_GROUP,
|
|
857
|
+
"--key",
|
|
858
|
+
"httpsProxy",
|
|
859
|
+
endpoint
|
|
860
|
+
]);
|
|
861
|
+
await notifyKde();
|
|
862
|
+
},
|
|
863
|
+
async disable() {
|
|
864
|
+
await runCommand("kde", "kwriteconfig6", [
|
|
865
|
+
"--file",
|
|
866
|
+
KDE_FILE,
|
|
867
|
+
"--group",
|
|
868
|
+
KDE_GROUP,
|
|
869
|
+
"--key",
|
|
870
|
+
"ProxyType",
|
|
871
|
+
"0"
|
|
872
|
+
]);
|
|
873
|
+
await notifyKde();
|
|
874
|
+
},
|
|
875
|
+
async current() {
|
|
876
|
+
try {
|
|
877
|
+
if ((await runCommand("kde", "kreadconfig6", [
|
|
878
|
+
"--file",
|
|
879
|
+
KDE_FILE,
|
|
880
|
+
"--group",
|
|
881
|
+
KDE_GROUP,
|
|
882
|
+
"--key",
|
|
883
|
+
"ProxyType",
|
|
884
|
+
"0"
|
|
885
|
+
])).trim() !== "1") return;
|
|
886
|
+
return parseHttpEndpoint((await runCommand("kde", "kreadconfig6", [
|
|
887
|
+
"--file",
|
|
888
|
+
KDE_FILE,
|
|
889
|
+
"--group",
|
|
890
|
+
KDE_GROUP,
|
|
891
|
+
"--key",
|
|
892
|
+
"httpProxy"
|
|
893
|
+
])).trim());
|
|
894
|
+
} catch {
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
/**
|
|
900
|
+
* 通知 KDE 重载 kioslaverc。对已运行应用的即时性弱于 GNOME gsettings,
|
|
901
|
+
* 部分应用需重启;通知失败不致命(写入已生效)。
|
|
902
|
+
*/
|
|
903
|
+
async function notifyKde() {
|
|
904
|
+
try {
|
|
905
|
+
await runCommand("kde", "dbus-send", [
|
|
906
|
+
"--session",
|
|
907
|
+
"--type=signal",
|
|
908
|
+
"/KIO/KTrader/knotify",
|
|
909
|
+
"org.kde.KDirNotify.FilesChanged"
|
|
910
|
+
]);
|
|
911
|
+
} catch {}
|
|
912
|
+
}
|
|
913
|
+
function stripGsettingsQuotes(raw) {
|
|
914
|
+
const trimmed = raw.trim();
|
|
915
|
+
if (trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1);
|
|
916
|
+
return trimmed;
|
|
917
|
+
}
|
|
918
|
+
function parseHttpEndpoint(raw) {
|
|
919
|
+
const match = /^http:\/\/([^:/]+):(\d+)$/.exec(raw);
|
|
920
|
+
if (match === null) return;
|
|
921
|
+
const host = match[1];
|
|
922
|
+
const port = Number.parseInt(match[2] ?? "", 10);
|
|
923
|
+
if (host === void 0 || !Number.isInteger(port)) return;
|
|
924
|
+
return {
|
|
925
|
+
host,
|
|
926
|
+
port
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
//#endregion
|
|
930
|
+
//#region src/system-proxy/macos.ts
|
|
931
|
+
/** macOS:通过 networksetup 枚举所有网络服务逐个设置 HTTP/HTTPS 代理。 */
|
|
932
|
+
const macosController = {
|
|
933
|
+
name: "macos",
|
|
934
|
+
async detect() {
|
|
935
|
+
try {
|
|
936
|
+
await runCommand("macos", "networksetup", ["-listallnetworkservices"]);
|
|
937
|
+
return true;
|
|
938
|
+
} catch {
|
|
939
|
+
return false;
|
|
940
|
+
}
|
|
941
|
+
},
|
|
942
|
+
async enable(host, port) {
|
|
943
|
+
const services = await listNetworkServices();
|
|
944
|
+
for (const service of services) {
|
|
945
|
+
await runCommand("macos", "networksetup", [
|
|
946
|
+
"-setwebproxy",
|
|
947
|
+
service,
|
|
948
|
+
host,
|
|
949
|
+
String(port)
|
|
950
|
+
]);
|
|
951
|
+
await runCommand("macos", "networksetup", [
|
|
952
|
+
"-setsecurewebproxy",
|
|
953
|
+
service,
|
|
954
|
+
host,
|
|
955
|
+
String(port)
|
|
956
|
+
]);
|
|
957
|
+
}
|
|
958
|
+
},
|
|
959
|
+
async disable() {
|
|
960
|
+
const services = await listNetworkServices();
|
|
961
|
+
for (const service of services) {
|
|
962
|
+
await runCommand("macos", "networksetup", [
|
|
963
|
+
"-setwebproxystate",
|
|
964
|
+
service,
|
|
965
|
+
"off"
|
|
966
|
+
]);
|
|
967
|
+
await runCommand("macos", "networksetup", [
|
|
968
|
+
"-setsecurewebproxystate",
|
|
969
|
+
service,
|
|
970
|
+
"off"
|
|
971
|
+
]);
|
|
972
|
+
}
|
|
973
|
+
},
|
|
974
|
+
async current() {
|
|
975
|
+
const services = await listNetworkServices();
|
|
976
|
+
for (const service of services) try {
|
|
977
|
+
const endpoint = parseNetworksetupProxy(await runCommand("macos", "networksetup", ["-getwebproxy", service]));
|
|
978
|
+
if (endpoint !== void 0) return endpoint;
|
|
979
|
+
} catch {
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
};
|
|
984
|
+
/**
|
|
985
|
+
* 解析 `networksetup -listallnetworkservices` 输出:跳过首行标题与星标禁用项。
|
|
986
|
+
*/
|
|
987
|
+
async function listNetworkServices() {
|
|
988
|
+
return (await runCommand("macos", "networksetup", ["-listallnetworkservices"])).split("\n").slice(1).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("*"));
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* 解析 `networksetup -getwebproxy <service>` 输出,仅在 Enabled: Yes 时返回端点。
|
|
992
|
+
*/
|
|
993
|
+
function parseNetworksetupProxy(output) {
|
|
994
|
+
if (!/Enabled:\s*Yes/i.test(output)) return;
|
|
995
|
+
const host = /^Server:\s*(.+)$/m.exec(output)?.[1]?.trim();
|
|
996
|
+
const portMatch = /^Port:\s*(\d+)$/m.exec(output)?.[1];
|
|
997
|
+
const port = portMatch === void 0 ? NaN : Number.parseInt(portMatch, 10);
|
|
998
|
+
if (host === void 0 || host.length === 0 || !Number.isInteger(port)) return;
|
|
999
|
+
return {
|
|
1000
|
+
host,
|
|
1001
|
+
port
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
//#endregion
|
|
1005
|
+
//#region src/system-proxy/windows.ts
|
|
1006
|
+
/**
|
|
1007
|
+
* Windows 系统代理层(注册表 InternetSettings + WM_SETTINGCHANGE)标记为 P2,
|
|
1008
|
+
* 本次仅占位。`detect()` 返回 false 使 daemon 跳过系统代理同步,由用户用
|
|
1009
|
+
* `lynx env on` 管理 CLI 入口。
|
|
1010
|
+
*
|
|
1011
|
+
* TODO(P2): 实现注册表 ProxyEnable/ProxyServer 写入与 WM_SETTINGCHANGE 广播。
|
|
1012
|
+
*/
|
|
1013
|
+
const windowsController = {
|
|
1014
|
+
name: "windows",
|
|
1015
|
+
async detect() {
|
|
1016
|
+
return false;
|
|
1017
|
+
},
|
|
1018
|
+
async enable() {
|
|
1019
|
+
throw new SystemProxyError("Windows 系统代理层待实现,请用 `lynx env on`", "windows");
|
|
1020
|
+
},
|
|
1021
|
+
async disable() {},
|
|
1022
|
+
async current() {}
|
|
1023
|
+
};
|
|
1024
|
+
//#endregion
|
|
1025
|
+
//#region src/system-proxy/detect.ts
|
|
1026
|
+
/**
|
|
1027
|
+
* 按平台与可用工具选择首个 `detect()` 为 true 的系统代理控制器;都不支持时返回 undefined。
|
|
1028
|
+
*/
|
|
1029
|
+
async function detectSystemProxyController() {
|
|
1030
|
+
for (const candidate of getCandidatesForPlatform()) try {
|
|
1031
|
+
if (await candidate.detect()) return candidate;
|
|
1032
|
+
} catch {
|
|
1033
|
+
continue;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
function getCandidatesForPlatform(platform = process.platform) {
|
|
1037
|
+
switch (platform) {
|
|
1038
|
+
case "linux": return [gnomeController, kdeController];
|
|
1039
|
+
case "darwin": return [macosController];
|
|
1040
|
+
case "win32": return [windowsController];
|
|
1041
|
+
default: return [];
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* 报告系统代理状态:enabled(指向某端点)/ disabled(无 manual 代理)/
|
|
1046
|
+
* not-supported(本机无可用系统代理 API)。
|
|
1047
|
+
*/
|
|
1048
|
+
async function getSystemProxyStatus(controller) {
|
|
1049
|
+
if (controller === void 0) return "not-supported";
|
|
1050
|
+
try {
|
|
1051
|
+
if (await controller.current() !== void 0) return "enabled";
|
|
1052
|
+
return "disabled";
|
|
1053
|
+
} catch {
|
|
1054
|
+
return "disabled";
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
//#endregion
|
|
1058
|
+
//#region src/runtime/daemon-lifecycle.ts
|
|
1059
|
+
const STOP_TIMEOUT_MS = 5e3;
|
|
1060
|
+
const SYSTEM_PROXY_ENV = "LYNX_SYSTEM_PROXY";
|
|
1061
|
+
const ALPHA_ENV = "LYNX_ALPHA";
|
|
1062
|
+
/**
|
|
1063
|
+
* 主 CLI 产物路径(dist/index.mjs)。
|
|
1064
|
+
*
|
|
1065
|
+
* 本模块会被主 CLI 与 TUI 两个 bundle 同时打包,但两者都位于 dist/ 下,
|
|
1066
|
+
* 因此相对本模块目录解析 index.mjs 在两种情况下都指向主 CLI。
|
|
1067
|
+
* 不能用 process.argv[1]——在 TUI 进程里它指向 tui.mjs,会导致递归自启。
|
|
1068
|
+
*/
|
|
1069
|
+
const MAIN_CLI_ENTRY = resolve(dirname(fileURLToPath(import.meta.url)), "index.mjs");
|
|
1070
|
+
/**
|
|
1071
|
+
* 读取并校验 daemon state;state 文件损坏时清理并抛错(与原 CLI 行为一致)。
|
|
1072
|
+
*/
|
|
1073
|
+
function readDaemonState() {
|
|
1074
|
+
try {
|
|
1075
|
+
return loadProxyDaemonState();
|
|
1076
|
+
} catch (error) {
|
|
1077
|
+
removeProxyDaemonState();
|
|
1078
|
+
throw new Error(`Invalid proxy daemon state removed: ${errorMessage(error)}`);
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
/**
|
|
1082
|
+
* 以后台 detached 子进程启动 daemon(执行 `lynx proxy run-daemon`)。
|
|
1083
|
+
* 不打印任何内容;由调用方(CLI/TUI)决定如何呈现结果。
|
|
1084
|
+
*/
|
|
1085
|
+
async function startDaemonDetached(options = {}) {
|
|
1086
|
+
const noSystemProxy = options.noSystemProxy ?? false;
|
|
1087
|
+
const alpha = options.alpha ?? false;
|
|
1088
|
+
const existing = readDaemonState();
|
|
1089
|
+
if (existing !== void 0) {
|
|
1090
|
+
if (isProcessRunning(existing.pid)) return {
|
|
1091
|
+
status: "already-running",
|
|
1092
|
+
pid: existing.pid,
|
|
1093
|
+
logFile: existing.logFile ?? getProxyDaemonLogPath(),
|
|
1094
|
+
listen: `${existing.host}:${existing.port}`,
|
|
1095
|
+
kernel: alpha ? "alpha" : "stable",
|
|
1096
|
+
systemProxySkipped: noSystemProxy
|
|
1097
|
+
};
|
|
1098
|
+
removeProxyDaemonState();
|
|
1099
|
+
}
|
|
1100
|
+
const lynxConfig = loadLynxConfig();
|
|
1101
|
+
const logFile = getProxyDaemonLogPath();
|
|
1102
|
+
mkdirSync(dirname(logFile), { recursive: true });
|
|
1103
|
+
const out = openSync(logFile, "a");
|
|
1104
|
+
const child = spawn(process.execPath, [
|
|
1105
|
+
MAIN_CLI_ENTRY,
|
|
1106
|
+
"proxy",
|
|
1107
|
+
"run-daemon"
|
|
1108
|
+
], {
|
|
1109
|
+
detached: true,
|
|
1110
|
+
stdio: [
|
|
1111
|
+
"ignore",
|
|
1112
|
+
out,
|
|
1113
|
+
out
|
|
1114
|
+
],
|
|
1115
|
+
windowsHide: true,
|
|
1116
|
+
env: {
|
|
1117
|
+
...process.env,
|
|
1118
|
+
[SYSTEM_PROXY_ENV]: noSystemProxy ? "0" : "1",
|
|
1119
|
+
...alpha ? { [ALPHA_ENV]: "1" } : {}
|
|
1120
|
+
}
|
|
1121
|
+
});
|
|
1122
|
+
child.unref();
|
|
1123
|
+
if (child.pid === void 0) throw new Error("Failed to start daemon: child process has no PID");
|
|
1124
|
+
return {
|
|
1125
|
+
status: "started",
|
|
1126
|
+
pid: child.pid,
|
|
1127
|
+
logFile,
|
|
1128
|
+
listen: lynxConfig.listen ?? "127.0.0.1:7890",
|
|
1129
|
+
kernel: alpha ? "alpha" : "stable",
|
|
1130
|
+
systemProxySkipped: noSystemProxy
|
|
1131
|
+
};
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* 停止后台 daemon:SIGTERM 优雅退出,超时 SIGKILL,最后清理 state。
|
|
1135
|
+
* 默认在停止前清系统代理(除非 noSystemProxy)。
|
|
1136
|
+
*/
|
|
1137
|
+
async function stopDaemon(options = {}) {
|
|
1138
|
+
const noSystemProxy = options.noSystemProxy ?? false;
|
|
1139
|
+
const state = readDaemonState();
|
|
1140
|
+
if (state === void 0) return { stopped: false };
|
|
1141
|
+
if (!isProcessRunning(state.pid)) {
|
|
1142
|
+
removeProxyDaemonState();
|
|
1143
|
+
return {
|
|
1144
|
+
stopped: false,
|
|
1145
|
+
staleRemoved: true,
|
|
1146
|
+
pid: state.pid
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
if (!noSystemProxy) await clearSystemProxyEntry();
|
|
1150
|
+
process.kill(state.pid, "SIGTERM");
|
|
1151
|
+
let exited = await waitForExit(state.pid, STOP_TIMEOUT_MS);
|
|
1152
|
+
if (!exited) {
|
|
1153
|
+
try {
|
|
1154
|
+
process.kill(state.pid, "SIGKILL");
|
|
1155
|
+
} catch {}
|
|
1156
|
+
exited = await waitForExit(state.pid, STOP_TIMEOUT_MS);
|
|
1157
|
+
}
|
|
1158
|
+
removeProxyDaemonState();
|
|
1159
|
+
return {
|
|
1160
|
+
stopped: exited,
|
|
1161
|
+
pid: state.pid
|
|
1162
|
+
};
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* 停止时清系统代理(best-effort,失败不抛错)。
|
|
1166
|
+
*/
|
|
1167
|
+
async function clearSystemProxyEntry() {
|
|
1168
|
+
const controller = await detectSystemProxyController();
|
|
1169
|
+
if (controller === void 0) return;
|
|
1170
|
+
try {
|
|
1171
|
+
await controller.disable();
|
|
1172
|
+
} catch {}
|
|
1173
|
+
}
|
|
1174
|
+
function waitForExit(pid, timeoutMs) {
|
|
1175
|
+
return new Promise((resolve) => {
|
|
1176
|
+
const started = Date.now();
|
|
1177
|
+
const timer = setInterval(() => {
|
|
1178
|
+
if (!isProcessRunning(pid)) {
|
|
1179
|
+
clearInterval(timer);
|
|
1180
|
+
resolve(true);
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
if (Date.now() - started >= timeoutMs) {
|
|
1184
|
+
clearInterval(timer);
|
|
1185
|
+
resolve(false);
|
|
1186
|
+
}
|
|
1187
|
+
}, 100);
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* 轮询等待 daemon 就绪:state 已写入 extHost/extPort/secret 三字段,且 mihomo API 可连通。
|
|
1192
|
+
* Windows 不要求 control socket 就绪。
|
|
1193
|
+
*/
|
|
1194
|
+
async function waitForDaemonReady(timeoutMs = 3e4, pollMs = 300) {
|
|
1195
|
+
const deadline = Date.now() + timeoutMs;
|
|
1196
|
+
let lastState;
|
|
1197
|
+
while (Date.now() < deadline) {
|
|
1198
|
+
const state = readDaemonState();
|
|
1199
|
+
if (state !== void 0 && isProcessRunning(state.pid)) {
|
|
1200
|
+
lastState = state;
|
|
1201
|
+
if (state.extHost !== void 0 && state.extPort !== void 0 && state.secret !== void 0) {
|
|
1202
|
+
if (await new MihomoApiClient(state.extHost, state.extPort, state.secret, 4e3).isReady()) if (process.platform !== "win32" && !await isControlSocketReady()) {} else return state;
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
await new Promise((resolve) => {
|
|
1206
|
+
setTimeout(resolve, pollMs);
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
throw new Error(lastState !== void 0 ? `Timed out waiting for daemon (PID ${lastState.pid}) to become ready` : "Timed out waiting for daemon to start (no state file written)");
|
|
1210
|
+
}
|
|
1211
|
+
//#endregion
|
|
1212
|
+
//#region src/utils/format.ts
|
|
1213
|
+
/**
|
|
1214
|
+
* 从字节数生成人类可读的体积字符串。
|
|
1215
|
+
* 覆盖 B / KB / MB / GB 四个量级,使用 1024 进制。
|
|
1216
|
+
*/
|
|
1217
|
+
/**
|
|
1218
|
+
* 解析 "host:port" 格式字符串,返回 host 与 port。
|
|
1219
|
+
*
|
|
1220
|
+
* 注意:不支持 IPv6 字面量(如 `[::1]:7890`),当前调用点均使用
|
|
1221
|
+
* IPv4 地址(127.0.0.1 / 0.0.0.0 / 局域网 IP),暂不处理方括号。
|
|
1222
|
+
*/
|
|
1223
|
+
function parseHostPort(input, defaultHost, defaultPort) {
|
|
1224
|
+
const parts = input?.split(":") ?? [];
|
|
1225
|
+
const rawHost = parts[0];
|
|
1226
|
+
return {
|
|
1227
|
+
host: rawHost !== void 0 && rawHost.length > 0 ? rawHost : defaultHost,
|
|
1228
|
+
port: Number(parts[1]) || defaultPort
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
//#endregion
|
|
1232
|
+
//#region src/tui/runtime/types.ts
|
|
1233
|
+
/** 把 mihomo ConnectionEntry 投影为连接视图(累计字节,速率由 reducer 差分)。 */
|
|
1234
|
+
function toConnectionView(entry) {
|
|
1235
|
+
const metadata = entry.metadata;
|
|
1236
|
+
const hostRaw = metadata.host ?? metadata.destinationIP ?? "(unknown)";
|
|
1237
|
+
const port = metadata.destinationPort;
|
|
1238
|
+
const hostWithPort = port !== void 0 && port !== "" && port !== "443" && port !== "80" ? `${hostRaw}:${port}` : hostRaw;
|
|
1239
|
+
const rule = entry.rulePayload !== void 0 && entry.rulePayload.length > 0 ? `${entry.rule}:${entry.rulePayload}` : entry.rule;
|
|
1240
|
+
return {
|
|
1241
|
+
id: entry.id,
|
|
1242
|
+
host: hostWithPort,
|
|
1243
|
+
hostRaw,
|
|
1244
|
+
network: metadata.network ?? "",
|
|
1245
|
+
type: metadata.type ?? "",
|
|
1246
|
+
rule,
|
|
1247
|
+
chain: entry.chains[0] ?? "",
|
|
1248
|
+
chainsFull: entry.chains.slice(),
|
|
1249
|
+
up: entry.upload,
|
|
1250
|
+
down: entry.download,
|
|
1251
|
+
upRate: 0,
|
|
1252
|
+
downRate: 0,
|
|
1253
|
+
startedAt: Date.parse(entry.start),
|
|
1254
|
+
sourceIP: metadata.sourceIP ?? "",
|
|
1255
|
+
sourcePort: metadata.sourcePort ?? "",
|
|
1256
|
+
destinationIP: metadata.destinationIP ?? "",
|
|
1257
|
+
destinationPort: metadata.destinationPort ?? "",
|
|
1258
|
+
processPath: metadata.processPath ?? "",
|
|
1259
|
+
dnsMode: metadata.dnsMode ?? ""
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
//#endregion
|
|
1263
|
+
//#region src/tui/runtime/state.ts
|
|
1264
|
+
/** 日志环形缓冲上限(暂停时新日志直接丢弃,故正常情况下不会暴涨)。 */
|
|
1265
|
+
const LOG_WINDOW = 1e3;
|
|
1266
|
+
/**
|
|
1267
|
+
* 用新快照更新连接列表,按 id 合并并对累计字节做差分得到速率。
|
|
1268
|
+
* 消失的连接移除;新连接加入(速率从 0 起)。
|
|
1269
|
+
*/
|
|
1270
|
+
function mergeConnections(previous, entries, elapsedMs) {
|
|
1271
|
+
const prevById = /* @__PURE__ */ new Map();
|
|
1272
|
+
for (const row of previous) prevById.set(row.id, row);
|
|
1273
|
+
const seconds = elapsedMs > 0 ? elapsedMs / 1e3 : 0;
|
|
1274
|
+
const next = [];
|
|
1275
|
+
for (const entry of entries) {
|
|
1276
|
+
const view = toConnectionView(entry);
|
|
1277
|
+
const prev = prevById.get(entry.id);
|
|
1278
|
+
if (prev !== void 0 && seconds > 0) {
|
|
1279
|
+
view.upRate = Math.max(0, (view.up - prev.up) / seconds);
|
|
1280
|
+
view.downRate = Math.max(0, (view.down - prev.down) / seconds);
|
|
1281
|
+
}
|
|
1282
|
+
next.push(view);
|
|
1283
|
+
}
|
|
1284
|
+
return next;
|
|
1285
|
+
}
|
|
1286
|
+
//#endregion
|
|
1287
|
+
//#region src/tui/runtime/mihomo-connect.ts
|
|
1288
|
+
function openTrafficWebSocket(host, port, secret, handlers) {
|
|
1289
|
+
const baseDelay = 1e3;
|
|
1290
|
+
const maxDelay = 1e4;
|
|
1291
|
+
let attempt = 0;
|
|
1292
|
+
let stopped = false;
|
|
1293
|
+
let ws;
|
|
1294
|
+
let reconnectTimer;
|
|
1295
|
+
const connect = () => {
|
|
1296
|
+
if (stopped) return;
|
|
1297
|
+
const url = `ws://${host}:${port}/traffic?token=${encodeURIComponent(secret)}`;
|
|
1298
|
+
let socket;
|
|
1299
|
+
try {
|
|
1300
|
+
socket = new WebSocket(url);
|
|
1301
|
+
} catch {
|
|
1302
|
+
scheduleReconnect();
|
|
1303
|
+
return;
|
|
1304
|
+
}
|
|
1305
|
+
ws = socket;
|
|
1306
|
+
socket.onopen = () => {
|
|
1307
|
+
attempt = 0;
|
|
1308
|
+
handlers.onStatusChange?.(true);
|
|
1309
|
+
};
|
|
1310
|
+
socket.onmessage = (event) => {
|
|
1311
|
+
try {
|
|
1312
|
+
const data = JSON.parse(String(event.data));
|
|
1313
|
+
handlers.onTraffic(data.up ?? 0, data.down ?? 0);
|
|
1314
|
+
} catch {}
|
|
1315
|
+
};
|
|
1316
|
+
const onClosed = () => {
|
|
1317
|
+
handlers.onStatusChange?.(false);
|
|
1318
|
+
if (!stopped) scheduleReconnect();
|
|
1319
|
+
};
|
|
1320
|
+
socket.onerror = () => {
|
|
1321
|
+
try {
|
|
1322
|
+
socket.close();
|
|
1323
|
+
} catch {}
|
|
1324
|
+
};
|
|
1325
|
+
socket.onclose = onClosed;
|
|
1326
|
+
};
|
|
1327
|
+
const scheduleReconnect = () => {
|
|
1328
|
+
if (stopped) return;
|
|
1329
|
+
const delay = Math.min(maxDelay, baseDelay * 2 ** attempt) + Math.floor(Math.random() * 300);
|
|
1330
|
+
attempt += 1;
|
|
1331
|
+
reconnectTimer = setTimeout(connect, delay);
|
|
1332
|
+
};
|
|
1333
|
+
connect();
|
|
1334
|
+
return { stop() {
|
|
1335
|
+
stopped = true;
|
|
1336
|
+
if (reconnectTimer !== void 0) clearTimeout(reconnectTimer);
|
|
1337
|
+
if (ws !== void 0) try {
|
|
1338
|
+
ws.close();
|
|
1339
|
+
} catch {}
|
|
1340
|
+
} };
|
|
1341
|
+
}
|
|
1342
|
+
//#endregion
|
|
1343
|
+
//#region src/tui/runtime/mihomo-log-connect.ts
|
|
1344
|
+
const VALID_LEVELS = /* @__PURE__ */ new Set([
|
|
1345
|
+
"debug",
|
|
1346
|
+
"info",
|
|
1347
|
+
"warning",
|
|
1348
|
+
"error"
|
|
1349
|
+
]);
|
|
1350
|
+
/**
|
|
1351
|
+
* 解析一帧 mihomo 日志消息为 LogEntryView。
|
|
1352
|
+
* 纯函数,导出供单测。无法解析或级别非法时返回 undefined。
|
|
1353
|
+
*
|
|
1354
|
+
* @param data WebSocket 帧数据
|
|
1355
|
+
* @param receivedAt 接收时刻毫秒时间戳(由调用方传入,避免测试依赖 Date.now)
|
|
1356
|
+
*/
|
|
1357
|
+
function parseLogFrame(data, receivedAt) {
|
|
1358
|
+
let parsed;
|
|
1359
|
+
try {
|
|
1360
|
+
parsed = JSON.parse(typeof data === "string" ? data : String(data));
|
|
1361
|
+
} catch {
|
|
1362
|
+
return;
|
|
1363
|
+
}
|
|
1364
|
+
if (typeof parsed.type !== "string" || !VALID_LEVELS.has(parsed.type)) return;
|
|
1365
|
+
const payload = typeof parsed.payload === "string" ? parsed.payload : "";
|
|
1366
|
+
return {
|
|
1367
|
+
receivedAt,
|
|
1368
|
+
level: parsed.type,
|
|
1369
|
+
payload
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
function openLogWebSocket(host, port, secret, initialLevel, handlers) {
|
|
1373
|
+
const baseDelay = 1e3;
|
|
1374
|
+
const maxDelay = 1e4;
|
|
1375
|
+
let attempt = 0;
|
|
1376
|
+
let stopped = false;
|
|
1377
|
+
let level = initialLevel;
|
|
1378
|
+
let ws;
|
|
1379
|
+
let reconnectTimer;
|
|
1380
|
+
const teardownSocket = () => {
|
|
1381
|
+
if (ws !== void 0) {
|
|
1382
|
+
const socket = ws;
|
|
1383
|
+
ws = void 0;
|
|
1384
|
+
socket.onopen = null;
|
|
1385
|
+
socket.onmessage = null;
|
|
1386
|
+
socket.onerror = null;
|
|
1387
|
+
socket.onclose = null;
|
|
1388
|
+
try {
|
|
1389
|
+
socket.close();
|
|
1390
|
+
} catch {}
|
|
1391
|
+
}
|
|
1392
|
+
};
|
|
1393
|
+
const connect = () => {
|
|
1394
|
+
if (stopped) return;
|
|
1395
|
+
const url = `ws://${host}:${port}/logs?level=${encodeURIComponent(level)}`;
|
|
1396
|
+
let socket;
|
|
1397
|
+
try {
|
|
1398
|
+
socket = new WebSocket(url, { headers: { Authorization: `Bearer ${secret}` } });
|
|
1399
|
+
} catch {
|
|
1400
|
+
scheduleReconnect();
|
|
1401
|
+
return;
|
|
1402
|
+
}
|
|
1403
|
+
ws = socket;
|
|
1404
|
+
socket.onopen = () => {
|
|
1405
|
+
attempt = 0;
|
|
1406
|
+
handlers.onStatusChange?.(true);
|
|
1407
|
+
};
|
|
1408
|
+
socket.onmessage = (event) => {
|
|
1409
|
+
const entry = parseLogFrame(event.data, Date.now());
|
|
1410
|
+
if (entry !== void 0) handlers.onLog(entry);
|
|
1411
|
+
};
|
|
1412
|
+
socket.onerror = () => {
|
|
1413
|
+
try {
|
|
1414
|
+
socket.close();
|
|
1415
|
+
} catch {}
|
|
1416
|
+
};
|
|
1417
|
+
socket.onclose = () => {
|
|
1418
|
+
if (ws === socket) ws = void 0;
|
|
1419
|
+
handlers.onStatusChange?.(false);
|
|
1420
|
+
if (!stopped) scheduleReconnect();
|
|
1421
|
+
};
|
|
1422
|
+
};
|
|
1423
|
+
const scheduleReconnect = () => {
|
|
1424
|
+
if (stopped) return;
|
|
1425
|
+
if (reconnectTimer !== void 0) clearTimeout(reconnectTimer);
|
|
1426
|
+
const delay = Math.min(maxDelay, baseDelay * 2 ** attempt) + Math.floor(Math.random() * 300);
|
|
1427
|
+
attempt += 1;
|
|
1428
|
+
reconnectTimer = setTimeout(connect, delay);
|
|
1429
|
+
};
|
|
1430
|
+
connect();
|
|
1431
|
+
return {
|
|
1432
|
+
setLevel(next) {
|
|
1433
|
+
if (next === level) return;
|
|
1434
|
+
level = next;
|
|
1435
|
+
if (stopped) return;
|
|
1436
|
+
if (reconnectTimer !== void 0) {
|
|
1437
|
+
clearTimeout(reconnectTimer);
|
|
1438
|
+
reconnectTimer = void 0;
|
|
1439
|
+
}
|
|
1440
|
+
attempt = 0;
|
|
1441
|
+
teardownSocket();
|
|
1442
|
+
connect();
|
|
1443
|
+
},
|
|
1444
|
+
stop() {
|
|
1445
|
+
stopped = true;
|
|
1446
|
+
if (reconnectTimer !== void 0) clearTimeout(reconnectTimer);
|
|
1447
|
+
reconnectTimer = void 0;
|
|
1448
|
+
teardownSocket();
|
|
1449
|
+
}
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
//#endregion
|
|
1453
|
+
//#region src/tui/runtime/polling.ts
|
|
1454
|
+
function startPolling(intervalMs, task, options = {}) {
|
|
1455
|
+
let stopped = false;
|
|
1456
|
+
let inFlight = false;
|
|
1457
|
+
const tick = async () => {
|
|
1458
|
+
if (stopped || inFlight) return;
|
|
1459
|
+
inFlight = true;
|
|
1460
|
+
try {
|
|
1461
|
+
await task();
|
|
1462
|
+
} catch {} finally {
|
|
1463
|
+
inFlight = false;
|
|
1464
|
+
}
|
|
1465
|
+
};
|
|
1466
|
+
if (options.runImmediately) tick();
|
|
1467
|
+
const id = setInterval(() => {
|
|
1468
|
+
tick();
|
|
1469
|
+
}, intervalMs);
|
|
1470
|
+
if (typeof id.unref === "function") id.unref();
|
|
1471
|
+
return { stop() {
|
|
1472
|
+
stopped = true;
|
|
1473
|
+
clearInterval(id);
|
|
1474
|
+
} };
|
|
1475
|
+
}
|
|
1476
|
+
//#endregion
|
|
1477
|
+
//#region src/tui/runtime/offline-proxies.ts
|
|
1478
|
+
/**
|
|
1479
|
+
* 离线代理数据:从 mihomo config.yaml 解析出的代理组 + 节点,
|
|
1480
|
+
* 并用 profiles.yaml 里记录的 selections 填充每组当前选中(now)。
|
|
1481
|
+
*
|
|
1482
|
+
* daemon 未运行时没有 mihomo API,TUI 用它渲染代理页并允许预选节点。
|
|
1483
|
+
* 数据来源是上一次生成的 config.yaml(纯 YAML),不经过配置生成管线
|
|
1484
|
+
* (Merge/Script 在 vm 中执行,按构建边界禁止进入 TUI bundle)。
|
|
1485
|
+
*/
|
|
1486
|
+
const GROUP_TYPE_MAP = {
|
|
1487
|
+
"select": "Selector",
|
|
1488
|
+
"url-test": "URLTest",
|
|
1489
|
+
"fallback": "Fallback",
|
|
1490
|
+
"load-balance": "LoadBalance",
|
|
1491
|
+
"relay": "Relay"
|
|
1492
|
+
};
|
|
1493
|
+
/**
|
|
1494
|
+
* 从已解析的 mihomo config 对象构建离线代理数据(纯函数,便于单测)。
|
|
1495
|
+
*
|
|
1496
|
+
* @param config mihomo config.yaml 的解析结果(mapping)
|
|
1497
|
+
* @param selections 组名→选中节点(来自当前 profile 的 selections)
|
|
1498
|
+
*/
|
|
1499
|
+
function buildOfflineProxies(config, selections) {
|
|
1500
|
+
const groups = [];
|
|
1501
|
+
const proxies = {};
|
|
1502
|
+
const rawGroups = config?.["proxy-groups"];
|
|
1503
|
+
if (!Array.isArray(rawGroups)) return {
|
|
1504
|
+
groups,
|
|
1505
|
+
proxies
|
|
1506
|
+
};
|
|
1507
|
+
const groupNames = /* @__PURE__ */ new Set();
|
|
1508
|
+
for (const g of rawGroups) {
|
|
1509
|
+
if (typeof g !== "object" || g === null || Array.isArray(g)) continue;
|
|
1510
|
+
const raw = g;
|
|
1511
|
+
if (typeof raw.name !== "string" || raw.name.length === 0) continue;
|
|
1512
|
+
groupNames.add(raw.name);
|
|
1513
|
+
}
|
|
1514
|
+
for (const g of rawGroups) {
|
|
1515
|
+
if (typeof g !== "object" || g === null || Array.isArray(g)) continue;
|
|
1516
|
+
const raw = g;
|
|
1517
|
+
if (typeof raw.name !== "string" || raw.name.length === 0) continue;
|
|
1518
|
+
if (!Array.isArray(raw.proxies)) continue;
|
|
1519
|
+
const members = raw.proxies.filter((m) => typeof m === "string");
|
|
1520
|
+
const type = typeof raw.type === "string" ? GROUP_TYPE_MAP[raw.type] ?? "Selector" : "Selector";
|
|
1521
|
+
const selected = selections[raw.name];
|
|
1522
|
+
const now = selected !== void 0 && members.includes(selected) ? selected : type === "Selector" ? members[0] ?? "" : "";
|
|
1523
|
+
groups.push({
|
|
1524
|
+
name: raw.name,
|
|
1525
|
+
type,
|
|
1526
|
+
now,
|
|
1527
|
+
all: members
|
|
1528
|
+
});
|
|
1529
|
+
proxies[raw.name] = {
|
|
1530
|
+
name: raw.name,
|
|
1531
|
+
type,
|
|
1532
|
+
now,
|
|
1533
|
+
all: members,
|
|
1534
|
+
history: []
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
for (const group of groups) for (const member of group.all) if (proxies[member] === void 0) proxies[member] = {
|
|
1538
|
+
name: member,
|
|
1539
|
+
type: "Unknown",
|
|
1540
|
+
now: "",
|
|
1541
|
+
all: [],
|
|
1542
|
+
history: []
|
|
1543
|
+
};
|
|
1544
|
+
return {
|
|
1545
|
+
groups,
|
|
1546
|
+
proxies
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
/**
|
|
1550
|
+
* 读取磁盘上的 config.yaml 并结合 selections 构建离线代理数据。
|
|
1551
|
+
* 文件缺失/解析失败时返回空数据(调用方据此显示"无配置"占位)。
|
|
1552
|
+
*/
|
|
1553
|
+
function loadOfflineProxies(selections) {
|
|
1554
|
+
try {
|
|
1555
|
+
return buildOfflineProxies(load(readFileSync(getMihomoConfigPath(), "utf8")), selections);
|
|
1556
|
+
} catch {
|
|
1557
|
+
return {
|
|
1558
|
+
groups: [],
|
|
1559
|
+
proxies: {}
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
//#endregion
|
|
1564
|
+
//#region src/web/web-runtime.ts
|
|
1565
|
+
/**
|
|
1566
|
+
* Web 管理器运行时:TuiRuntime 的无 pi-tui 镜像。
|
|
1567
|
+
*
|
|
1568
|
+
* 职责与 src/tui/runtime/tui-runtime.ts 一一对应——持有唯一的 mihomo 数据源
|
|
1569
|
+
* (MihomoApiClient + traffic/logs WebSocket + 轮询),在 daemon 在线/离线之间
|
|
1570
|
+
* 切换数据源;区别仅在于:状态变化不触发终端重绘,而是通过 SseHub 广播事件给浏览器。
|
|
1571
|
+
*
|
|
1572
|
+
* 复用 TUI 的纯函数/连接器(均不依赖 pi-tui):mergeConnections、
|
|
1573
|
+
* openTrafficWebSocket、openLogWebSocket、startPolling、loadOfflineProxies。
|
|
1574
|
+
* 动作方法返回结构化 ActionResult,供 HTTP 层映射为状态码(离线 → 503)。
|
|
1575
|
+
*/
|
|
1576
|
+
const GROUP_TYPES = /* @__PURE__ */ new Set([
|
|
1577
|
+
"Selector",
|
|
1578
|
+
"URLTest",
|
|
1579
|
+
"Fallback",
|
|
1580
|
+
"LoadBalance",
|
|
1581
|
+
"Relay"
|
|
1582
|
+
]);
|
|
1583
|
+
const TRAFFIC_WINDOW = 60;
|
|
1584
|
+
const DELAY_TEST_URL = "https://www.gstatic.com/generate_204";
|
|
1585
|
+
const DELAY_TEST_TIMEOUT = 5e3;
|
|
1586
|
+
function ok(message) {
|
|
1587
|
+
return message !== void 0 ? {
|
|
1588
|
+
ok: true,
|
|
1589
|
+
message
|
|
1590
|
+
} : { ok: true };
|
|
1591
|
+
}
|
|
1592
|
+
function fail(error) {
|
|
1593
|
+
return {
|
|
1594
|
+
ok: false,
|
|
1595
|
+
error
|
|
1596
|
+
};
|
|
1597
|
+
}
|
|
1598
|
+
function offlineFail(action) {
|
|
1599
|
+
return {
|
|
1600
|
+
ok: false,
|
|
1601
|
+
offline: true,
|
|
1602
|
+
error: `daemon 未运行,无法${action}。`
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
function pushSample(arr, value) {
|
|
1606
|
+
const next = arr.length >= TRAFFIC_WINDOW ? arr.slice(arr.length - TRAFFIC_WINDOW + 1) : arr.slice();
|
|
1607
|
+
next.push(value);
|
|
1608
|
+
return next;
|
|
1609
|
+
}
|
|
1610
|
+
var WebRuntime = class {
|
|
1611
|
+
apiClient;
|
|
1612
|
+
hub;
|
|
1613
|
+
traffic;
|
|
1614
|
+
logs;
|
|
1615
|
+
pollers = [];
|
|
1616
|
+
systemProxyController;
|
|
1617
|
+
proxiesSerial = 0;
|
|
1618
|
+
lastConnectionsAt = 0;
|
|
1619
|
+
consecutiveFailures = 0;
|
|
1620
|
+
reconnectTimer;
|
|
1621
|
+
daemon = "stopped";
|
|
1622
|
+
secretMissing = false;
|
|
1623
|
+
error;
|
|
1624
|
+
daemonState;
|
|
1625
|
+
trafficRing = {
|
|
1626
|
+
up: [],
|
|
1627
|
+
down: []
|
|
1628
|
+
};
|
|
1629
|
+
upRate = 0;
|
|
1630
|
+
downRate = 0;
|
|
1631
|
+
connRows = [];
|
|
1632
|
+
uploadTotal = 0;
|
|
1633
|
+
downloadTotal = 0;
|
|
1634
|
+
logEntries = [];
|
|
1635
|
+
logLevel = "info";
|
|
1636
|
+
overview = {
|
|
1637
|
+
upRate: 0,
|
|
1638
|
+
downRate: 0,
|
|
1639
|
+
uploadTotal: 0,
|
|
1640
|
+
downloadTotal: 0,
|
|
1641
|
+
systemProxy: "unknown",
|
|
1642
|
+
kernelChannel: "stable"
|
|
1643
|
+
};
|
|
1644
|
+
proxies = {
|
|
1645
|
+
groups: [],
|
|
1646
|
+
proxies: {},
|
|
1647
|
+
delayOverrides: {},
|
|
1648
|
+
testing: false
|
|
1649
|
+
};
|
|
1650
|
+
profilesSnapshot = { items: [] };
|
|
1651
|
+
constructor(hub) {
|
|
1652
|
+
this.hub = hub;
|
|
1653
|
+
}
|
|
1654
|
+
async start() {
|
|
1655
|
+
await this.detectSystemProxy();
|
|
1656
|
+
this.loadStaticMeta();
|
|
1657
|
+
this.refreshProfiles();
|
|
1658
|
+
await this.bootstrap();
|
|
1659
|
+
if (this.apiClient === void 0) this.refreshOfflineProxies();
|
|
1660
|
+
}
|
|
1661
|
+
stop() {
|
|
1662
|
+
this.traffic?.stop();
|
|
1663
|
+
this.logs?.stop();
|
|
1664
|
+
this.logs = void 0;
|
|
1665
|
+
for (const poller of this.pollers) poller.stop();
|
|
1666
|
+
this.pollers = [];
|
|
1667
|
+
if (this.reconnectTimer !== void 0) clearTimeout(this.reconnectTimer);
|
|
1668
|
+
}
|
|
1669
|
+
emit(event, data) {
|
|
1670
|
+
this.hub.broadcast(event, data);
|
|
1671
|
+
}
|
|
1672
|
+
emitStatus() {
|
|
1673
|
+
this.emit("status", {
|
|
1674
|
+
daemon: this.daemon,
|
|
1675
|
+
secretMissing: this.secretMissing,
|
|
1676
|
+
online: this.apiClient !== void 0,
|
|
1677
|
+
...this.error !== void 0 ? { error: this.error } : {}
|
|
1678
|
+
});
|
|
1679
|
+
}
|
|
1680
|
+
emitOverview() {
|
|
1681
|
+
this.emit("overview", {
|
|
1682
|
+
...this.overview,
|
|
1683
|
+
upRate: this.upRate,
|
|
1684
|
+
downRate: this.downRate,
|
|
1685
|
+
uploadTotal: this.uploadTotal,
|
|
1686
|
+
downloadTotal: this.downloadTotal
|
|
1687
|
+
});
|
|
1688
|
+
}
|
|
1689
|
+
emitProxies() {
|
|
1690
|
+
this.emit("proxies", this.proxies);
|
|
1691
|
+
}
|
|
1692
|
+
emitConnections() {
|
|
1693
|
+
const snapshot = {
|
|
1694
|
+
rows: this.connRows,
|
|
1695
|
+
uploadTotal: this.uploadTotal,
|
|
1696
|
+
downloadTotal: this.downloadTotal
|
|
1697
|
+
};
|
|
1698
|
+
this.emit("connections", snapshot);
|
|
1699
|
+
}
|
|
1700
|
+
async bootstrap() {
|
|
1701
|
+
let state;
|
|
1702
|
+
try {
|
|
1703
|
+
state = loadProxyDaemonState();
|
|
1704
|
+
} catch {
|
|
1705
|
+
removeProxyDaemonState();
|
|
1706
|
+
state = void 0;
|
|
1707
|
+
}
|
|
1708
|
+
if (state === void 0 || !isProcessRunning(state.pid)) {
|
|
1709
|
+
if (state !== void 0) removeProxyDaemonState();
|
|
1710
|
+
this.setDaemon("stopped");
|
|
1711
|
+
return;
|
|
1712
|
+
}
|
|
1713
|
+
if (state.extHost === void 0 || state.extPort === void 0 || state.secret === void 0) {
|
|
1714
|
+
this.daemonState = state;
|
|
1715
|
+
this.secretMissing = true;
|
|
1716
|
+
this.daemon = "running";
|
|
1717
|
+
this.error = "旧 daemon 缺少外部控制器凭据,请重启 daemon。";
|
|
1718
|
+
this.emitStatus();
|
|
1719
|
+
return;
|
|
1720
|
+
}
|
|
1721
|
+
await this.connect(state);
|
|
1722
|
+
}
|
|
1723
|
+
async connect(state) {
|
|
1724
|
+
if (state.extHost === void 0 || state.extPort === void 0 || state.secret === void 0) return;
|
|
1725
|
+
this.daemonState = state;
|
|
1726
|
+
this.secretMissing = false;
|
|
1727
|
+
this.error = void 0;
|
|
1728
|
+
this.daemon = "starting";
|
|
1729
|
+
this.emitStatus();
|
|
1730
|
+
const client = new MihomoApiClient(state.extHost, state.extPort, state.secret, 8e3);
|
|
1731
|
+
this.apiClient = client;
|
|
1732
|
+
if (!await client.isReady()) {
|
|
1733
|
+
this.daemon = "reconnecting";
|
|
1734
|
+
this.error = "mihomo API 未就绪,重连中…";
|
|
1735
|
+
this.emitStatus();
|
|
1736
|
+
this.reconnectTimer = setTimeout(() => {
|
|
1737
|
+
this.bootstrap();
|
|
1738
|
+
}, 1500);
|
|
1739
|
+
if (typeof this.reconnectTimer.unref === "function") this.reconnectTimer.unref();
|
|
1740
|
+
return;
|
|
1741
|
+
}
|
|
1742
|
+
this.daemon = "running";
|
|
1743
|
+
this.error = void 0;
|
|
1744
|
+
this.consecutiveFailures = 0;
|
|
1745
|
+
this.emitStatus();
|
|
1746
|
+
this.loadStaticMeta();
|
|
1747
|
+
this.fetchOverview();
|
|
1748
|
+
this.fetchProxies();
|
|
1749
|
+
this.traffic = openTrafficWebSocket(state.extHost, state.extPort, state.secret, {
|
|
1750
|
+
onTraffic: (up, down) => {
|
|
1751
|
+
this.upRate = up;
|
|
1752
|
+
this.downRate = down;
|
|
1753
|
+
this.trafficRing = {
|
|
1754
|
+
up: pushSample(this.trafficRing.up, up),
|
|
1755
|
+
down: pushSample(this.trafficRing.down, down)
|
|
1756
|
+
};
|
|
1757
|
+
this.emit("traffic", {
|
|
1758
|
+
up,
|
|
1759
|
+
down
|
|
1760
|
+
});
|
|
1761
|
+
},
|
|
1762
|
+
onStatusChange: (connected) => {
|
|
1763
|
+
if (!connected && this.daemon === "running") {
|
|
1764
|
+
this.error = "流量通道断开,重连中…";
|
|
1765
|
+
this.emitStatus();
|
|
1766
|
+
} else if (connected && this.error === "流量通道断开,重连中…") {
|
|
1767
|
+
this.error = void 0;
|
|
1768
|
+
this.emitStatus();
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
});
|
|
1772
|
+
this.logs = openLogWebSocket(state.extHost, state.extPort, state.secret, this.logLevel, { onLog: (entry) => {
|
|
1773
|
+
this.appendLog(entry);
|
|
1774
|
+
this.emit("log", entry);
|
|
1775
|
+
} });
|
|
1776
|
+
this.pollers = [
|
|
1777
|
+
startPolling(1e3, () => this.fetchConnections(), { runImmediately: true }),
|
|
1778
|
+
startPolling(3e3, () => this.fetchOverview()),
|
|
1779
|
+
startPolling(4e3, () => this.fetchProxies())
|
|
1780
|
+
];
|
|
1781
|
+
}
|
|
1782
|
+
resetToStopped(message) {
|
|
1783
|
+
this.traffic?.stop();
|
|
1784
|
+
this.traffic = void 0;
|
|
1785
|
+
this.logs?.stop();
|
|
1786
|
+
this.logs = void 0;
|
|
1787
|
+
for (const poller of this.pollers) poller.stop();
|
|
1788
|
+
this.pollers = [];
|
|
1789
|
+
this.apiClient = void 0;
|
|
1790
|
+
this.daemonState = void 0;
|
|
1791
|
+
this.daemon = "stopped";
|
|
1792
|
+
this.error = message;
|
|
1793
|
+
this.upRate = 0;
|
|
1794
|
+
this.downRate = 0;
|
|
1795
|
+
this.trafficRing = {
|
|
1796
|
+
up: [],
|
|
1797
|
+
down: []
|
|
1798
|
+
};
|
|
1799
|
+
this.connRows = [];
|
|
1800
|
+
this.emitStatus();
|
|
1801
|
+
this.emitConnections();
|
|
1802
|
+
this.refreshOfflineProxies();
|
|
1803
|
+
this.loadStaticMeta();
|
|
1804
|
+
}
|
|
1805
|
+
setDaemon(status) {
|
|
1806
|
+
this.daemon = status;
|
|
1807
|
+
if (status === "stopped") {
|
|
1808
|
+
this.apiClient = void 0;
|
|
1809
|
+
this.upRate = 0;
|
|
1810
|
+
this.downRate = 0;
|
|
1811
|
+
this.trafficRing = {
|
|
1812
|
+
up: [],
|
|
1813
|
+
down: []
|
|
1814
|
+
};
|
|
1815
|
+
this.connRows = [];
|
|
1816
|
+
if (this.error === void 0) this.error = void 0;
|
|
1817
|
+
}
|
|
1818
|
+
this.emitStatus();
|
|
1819
|
+
}
|
|
1820
|
+
refreshOfflineProxies() {
|
|
1821
|
+
if (this.apiClient !== void 0) return;
|
|
1822
|
+
try {
|
|
1823
|
+
const { groups, proxies } = loadOfflineProxies(getProfileSelections(getCurrentProfile(loadProfiles())));
|
|
1824
|
+
this.proxies = {
|
|
1825
|
+
groups,
|
|
1826
|
+
proxies,
|
|
1827
|
+
delayOverrides: {},
|
|
1828
|
+
testing: false
|
|
1829
|
+
};
|
|
1830
|
+
this.emitProxies();
|
|
1831
|
+
} catch {}
|
|
1832
|
+
}
|
|
1833
|
+
loadStaticMeta() {
|
|
1834
|
+
try {
|
|
1835
|
+
const lynx = loadLynxConfig();
|
|
1836
|
+
const current = getCurrentProfile(loadProfiles());
|
|
1837
|
+
if (current?.name !== void 0) this.overview.profileName = current.name;
|
|
1838
|
+
else delete this.overview.profileName;
|
|
1839
|
+
this.overview.kernelChannel = lynx.mihomo.kernel ?? "stable";
|
|
1840
|
+
if (lynx.mihomo.mode !== void 0 && this.apiClient === void 0) this.overview.mode = lynx.mihomo.mode;
|
|
1841
|
+
this.emitOverview();
|
|
1842
|
+
} catch {}
|
|
1843
|
+
}
|
|
1844
|
+
refreshProfiles() {
|
|
1845
|
+
try {
|
|
1846
|
+
const profiles = loadProfiles();
|
|
1847
|
+
const items = (profiles.items ?? []).filter((p) => p !== void 0).map((p) => ({
|
|
1848
|
+
uid: p.uid,
|
|
1849
|
+
type: p.type,
|
|
1850
|
+
name: p.name,
|
|
1851
|
+
...p.url !== void 0 ? { url: p.url } : {},
|
|
1852
|
+
...p.updated !== void 0 ? { updated: p.updated } : {}
|
|
1853
|
+
}));
|
|
1854
|
+
this.profilesSnapshot = {
|
|
1855
|
+
...profiles.current !== void 0 ? { current: profiles.current } : {},
|
|
1856
|
+
items
|
|
1857
|
+
};
|
|
1858
|
+
} catch {
|
|
1859
|
+
this.profilesSnapshot = { items: [] };
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
async fetchOverview() {
|
|
1863
|
+
const client = this.apiClient;
|
|
1864
|
+
if (client === void 0) return;
|
|
1865
|
+
try {
|
|
1866
|
+
const configs = await client.getConfigs();
|
|
1867
|
+
this.overview.mode = configs.mode;
|
|
1868
|
+
if (configs["log-level"] !== void 0) this.overview.logLevel = configs["log-level"];
|
|
1869
|
+
} catch {
|
|
1870
|
+
this.handleApiError();
|
|
1871
|
+
}
|
|
1872
|
+
try {
|
|
1873
|
+
this.overview.version = await client.getVersion();
|
|
1874
|
+
} catch {}
|
|
1875
|
+
try {
|
|
1876
|
+
this.overview.memory = await client.getMemory();
|
|
1877
|
+
} catch {}
|
|
1878
|
+
await this.refreshSystemProxyStatus();
|
|
1879
|
+
this.emitOverview();
|
|
1880
|
+
}
|
|
1881
|
+
async fetchProxies() {
|
|
1882
|
+
const client = this.apiClient;
|
|
1883
|
+
if (client === void 0) return;
|
|
1884
|
+
const serial = ++this.proxiesSerial;
|
|
1885
|
+
try {
|
|
1886
|
+
const resp = await client.getProxies();
|
|
1887
|
+
if (serial !== this.proxiesSerial) return;
|
|
1888
|
+
const proxies = {};
|
|
1889
|
+
const groups = [];
|
|
1890
|
+
for (const [name, info] of Object.entries(resp.proxies)) {
|
|
1891
|
+
proxies[name] = info;
|
|
1892
|
+
if (GROUP_TYPES.has(info.type)) groups.push({
|
|
1893
|
+
name,
|
|
1894
|
+
type: info.type,
|
|
1895
|
+
now: info.now,
|
|
1896
|
+
all: info.all
|
|
1897
|
+
});
|
|
1898
|
+
}
|
|
1899
|
+
this.proxies = {
|
|
1900
|
+
groups,
|
|
1901
|
+
proxies,
|
|
1902
|
+
delayOverrides: this.proxies.delayOverrides,
|
|
1903
|
+
testing: false
|
|
1904
|
+
};
|
|
1905
|
+
this.emitProxies();
|
|
1906
|
+
} catch {
|
|
1907
|
+
this.handleApiError();
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
async fetchConnections() {
|
|
1911
|
+
const client = this.apiClient;
|
|
1912
|
+
if (client === void 0) return;
|
|
1913
|
+
const now = Date.now();
|
|
1914
|
+
const elapsed = this.lastConnectionsAt === 0 ? 0 : now - this.lastConnectionsAt;
|
|
1915
|
+
this.lastConnectionsAt = now;
|
|
1916
|
+
try {
|
|
1917
|
+
const resp = await client.getConnections();
|
|
1918
|
+
this.connRows = mergeConnections(this.connRows, resp.connections ?? [], elapsed);
|
|
1919
|
+
this.uploadTotal = resp.uploadTotal;
|
|
1920
|
+
this.downloadTotal = resp.downloadTotal;
|
|
1921
|
+
this.emitConnections();
|
|
1922
|
+
} catch {
|
|
1923
|
+
this.handleApiError();
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
handleApiError() {
|
|
1927
|
+
this.consecutiveFailures += 1;
|
|
1928
|
+
if (this.consecutiveFailures >= 5) {
|
|
1929
|
+
this.consecutiveFailures = 0;
|
|
1930
|
+
const state = this.daemonState;
|
|
1931
|
+
if (state !== void 0 && !isProcessRunning(state.pid)) this.resetToStopped("daemon 已退出。");
|
|
1932
|
+
else {
|
|
1933
|
+
this.error = "mihomo API 不可达,重连中…";
|
|
1934
|
+
this.emitStatus();
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
async detectSystemProxy() {
|
|
1939
|
+
try {
|
|
1940
|
+
this.systemProxyController = await detectSystemProxyController();
|
|
1941
|
+
} catch {
|
|
1942
|
+
this.systemProxyController = void 0;
|
|
1943
|
+
}
|
|
1944
|
+
await this.refreshSystemProxyStatus();
|
|
1945
|
+
}
|
|
1946
|
+
async refreshSystemProxyStatus() {
|
|
1947
|
+
const status = await getSystemProxyStatus(this.systemProxyController);
|
|
1948
|
+
this.overview.systemProxy = status;
|
|
1949
|
+
}
|
|
1950
|
+
appendLog(entry) {
|
|
1951
|
+
const next = this.logEntries.length >= 1e3 ? this.logEntries.slice(this.logEntries.length - LOG_WINDOW + 1) : this.logEntries.slice();
|
|
1952
|
+
next.push(entry);
|
|
1953
|
+
this.logEntries = next;
|
|
1954
|
+
}
|
|
1955
|
+
getSnapshot() {
|
|
1956
|
+
const settingsConfig = this.readLynxConfig();
|
|
1957
|
+
return {
|
|
1958
|
+
daemon: this.daemon,
|
|
1959
|
+
secretMissing: this.secretMissing,
|
|
1960
|
+
online: this.apiClient !== void 0,
|
|
1961
|
+
...this.error !== void 0 ? { error: this.error } : {},
|
|
1962
|
+
overview: {
|
|
1963
|
+
...this.overview,
|
|
1964
|
+
upRate: this.upRate,
|
|
1965
|
+
downRate: this.downRate,
|
|
1966
|
+
uploadTotal: this.uploadTotal,
|
|
1967
|
+
downloadTotal: this.downloadTotal
|
|
1968
|
+
},
|
|
1969
|
+
proxies: this.proxies,
|
|
1970
|
+
connections: {
|
|
1971
|
+
rows: this.connRows,
|
|
1972
|
+
uploadTotal: this.uploadTotal,
|
|
1973
|
+
downloadTotal: this.downloadTotal
|
|
1974
|
+
},
|
|
1975
|
+
traffic: this.trafficRing,
|
|
1976
|
+
logs: this.logEntries.slice(-300),
|
|
1977
|
+
logLevel: this.logLevel,
|
|
1978
|
+
profiles: this.profilesSnapshot,
|
|
1979
|
+
settings: { config: settingsConfig }
|
|
1980
|
+
};
|
|
1981
|
+
}
|
|
1982
|
+
readLynxConfig() {
|
|
1983
|
+
try {
|
|
1984
|
+
return loadLynxConfig();
|
|
1985
|
+
} catch {
|
|
1986
|
+
return {
|
|
1987
|
+
version: 1,
|
|
1988
|
+
listen: "127.0.0.1:7890",
|
|
1989
|
+
mihomo: {
|
|
1990
|
+
"mixed-port": 7891,
|
|
1991
|
+
"external-controller": "127.0.0.1:9090",
|
|
1992
|
+
"auto-update": true
|
|
1993
|
+
},
|
|
1994
|
+
"system-proxy": false,
|
|
1995
|
+
log: {
|
|
1996
|
+
level: "info",
|
|
1997
|
+
access: true
|
|
1998
|
+
}
|
|
1999
|
+
};
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
async startDaemon() {
|
|
2003
|
+
if (this.daemon === "starting") return ok("正在启动…");
|
|
2004
|
+
this.daemon = "starting";
|
|
2005
|
+
this.error = void 0;
|
|
2006
|
+
this.secretMissing = false;
|
|
2007
|
+
this.emitStatus();
|
|
2008
|
+
try {
|
|
2009
|
+
if ((await startDaemonDetached()).status === "already-running") {
|
|
2010
|
+
await this.bootstrap();
|
|
2011
|
+
return ok("daemon 已在运行。");
|
|
2012
|
+
}
|
|
2013
|
+
const state = await waitForDaemonReady(3e4, 300);
|
|
2014
|
+
await this.connect(state);
|
|
2015
|
+
return ok("daemon 已启动。");
|
|
2016
|
+
} catch (error) {
|
|
2017
|
+
this.daemon = "stopped";
|
|
2018
|
+
this.error = `启动失败:${String(error)}`;
|
|
2019
|
+
this.emitStatus();
|
|
2020
|
+
return fail(`启动失败:${String(error)}`);
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
async stopDaemon() {
|
|
2024
|
+
this.daemon = "starting";
|
|
2025
|
+
this.error = void 0;
|
|
2026
|
+
this.emitStatus();
|
|
2027
|
+
try {
|
|
2028
|
+
await stopDaemon();
|
|
2029
|
+
} catch {}
|
|
2030
|
+
this.resetToStopped();
|
|
2031
|
+
return ok("daemon 已停止。");
|
|
2032
|
+
}
|
|
2033
|
+
async restartDaemon() {
|
|
2034
|
+
this.daemon = "starting";
|
|
2035
|
+
this.error = void 0;
|
|
2036
|
+
this.emitStatus();
|
|
2037
|
+
try {
|
|
2038
|
+
try {
|
|
2039
|
+
await stopDaemon();
|
|
2040
|
+
} catch {}
|
|
2041
|
+
if ((await startDaemonDetached()).status !== "already-running") {
|
|
2042
|
+
const state = await waitForDaemonReady(3e4, 300);
|
|
2043
|
+
await this.connect(state);
|
|
2044
|
+
} else await this.bootstrap();
|
|
2045
|
+
return ok("daemon 已重启。");
|
|
2046
|
+
} catch (error) {
|
|
2047
|
+
this.resetToStopped(`重启失败:${String(error)}`);
|
|
2048
|
+
return fail(`重启失败:${String(error)}`);
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
async setMode(mode) {
|
|
2052
|
+
if (this.apiClient === void 0) {
|
|
2053
|
+
if (!this.updateLynxConfig((config) => {
|
|
2054
|
+
config.mihomo.mode = mode;
|
|
2055
|
+
})) return fail("写入 lynx.json 失败。");
|
|
2056
|
+
this.overview.mode = mode;
|
|
2057
|
+
this.emitOverview();
|
|
2058
|
+
return ok(`路由模式已设为 ${mode},下次启动生效。`);
|
|
2059
|
+
}
|
|
2060
|
+
try {
|
|
2061
|
+
await this.apiClient.patchConfigs({ mode });
|
|
2062
|
+
this.overview.mode = mode;
|
|
2063
|
+
this.emitOverview();
|
|
2064
|
+
return ok(`路由模式:${mode}`);
|
|
2065
|
+
} catch (error) {
|
|
2066
|
+
return fail(`切换模式失败:${String(error)}`);
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
async switchKernel(channel) {
|
|
2070
|
+
if (this.overview.kernelChannel === channel) return ok(`已是 ${channel} 内核。`);
|
|
2071
|
+
try {
|
|
2072
|
+
const lynx = loadLynxConfig();
|
|
2073
|
+
lynx.mihomo.kernel = channel;
|
|
2074
|
+
writeLynxConfig(lynx);
|
|
2075
|
+
} catch (error) {
|
|
2076
|
+
return fail(`写入 lynx.json 失败:${String(error)}`);
|
|
2077
|
+
}
|
|
2078
|
+
this.overview.kernelChannel = channel;
|
|
2079
|
+
this.loadStaticMeta();
|
|
2080
|
+
if (this.apiClient === void 0) return ok(`已选择 ${channel} 内核,下次启动生效。`);
|
|
2081
|
+
this.daemon = "starting";
|
|
2082
|
+
this.emitStatus();
|
|
2083
|
+
try {
|
|
2084
|
+
try {
|
|
2085
|
+
await stopDaemon();
|
|
2086
|
+
} catch {}
|
|
2087
|
+
if ((await startDaemonDetached({ alpha: channel === "alpha" })).status === "already-running") {
|
|
2088
|
+
await this.bootstrap();
|
|
2089
|
+
return ok(`已切换到 ${channel} 内核。`);
|
|
2090
|
+
}
|
|
2091
|
+
const state = await waitForDaemonReady(3e4, 300);
|
|
2092
|
+
await this.connect(state);
|
|
2093
|
+
return ok(`已切换到 ${channel} 内核。`);
|
|
2094
|
+
} catch (error) {
|
|
2095
|
+
this.daemon = "stopped";
|
|
2096
|
+
this.error = `切换内核失败:${String(error)}`;
|
|
2097
|
+
this.emitStatus();
|
|
2098
|
+
return fail(`切换内核失败:${String(error)}(若未安装可执行 lynx mihomo install ${channel})`);
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
/** 系统代理要指向的地址:优先 daemon 实际监听,回落到 lynx.json 的 listen。 */
|
|
2102
|
+
resolveProxyTarget() {
|
|
2103
|
+
const state = this.daemonState;
|
|
2104
|
+
if (state !== void 0) return {
|
|
2105
|
+
host: state.host,
|
|
2106
|
+
port: state.port
|
|
2107
|
+
};
|
|
2108
|
+
try {
|
|
2109
|
+
return parseHostPort(loadLynxConfig().listen, "127.0.0.1", 7890);
|
|
2110
|
+
} catch {
|
|
2111
|
+
return;
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
async setSystemProxy(on) {
|
|
2115
|
+
const controller = this.systemProxyController;
|
|
2116
|
+
if (controller === void 0) return fail("当前平台不支持系统代理接管。");
|
|
2117
|
+
try {
|
|
2118
|
+
if (!on) {
|
|
2119
|
+
await controller.disable();
|
|
2120
|
+
await this.refreshSystemProxyStatus();
|
|
2121
|
+
this.emitOverview();
|
|
2122
|
+
return ok("系统代理已关闭。");
|
|
2123
|
+
}
|
|
2124
|
+
const target = this.resolveProxyTarget();
|
|
2125
|
+
if (target === void 0) return fail("无法确定代理监听地址,请先启动一次 daemon。");
|
|
2126
|
+
await controller.enable(target.host, target.port);
|
|
2127
|
+
await this.refreshSystemProxyStatus();
|
|
2128
|
+
this.emitOverview();
|
|
2129
|
+
return ok(this.apiClient === void 0 ? `系统代理已指向 ${target.host}:${target.port}(daemon 未运行,启动后生效)。` : `系统代理已指向 ${target.host}:${target.port}。`);
|
|
2130
|
+
} catch (error) {
|
|
2131
|
+
return fail(`系统代理操作失败:${String(error)}`);
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
async selectProxy(group, proxy) {
|
|
2135
|
+
if (group === void 0 || group === "" || proxy === void 0 || proxy === "") return fail("缺少 group 或 proxy。");
|
|
2136
|
+
if (this.apiClient === void 0) return this.persistOfflineSelection(group, proxy);
|
|
2137
|
+
try {
|
|
2138
|
+
await this.apiClient.selectProxy(group, proxy);
|
|
2139
|
+
this.persistSelectionToProfile(group, proxy);
|
|
2140
|
+
this.optimisticProxy(group, proxy);
|
|
2141
|
+
this.fetchProxies();
|
|
2142
|
+
return ok(`已切换:${group} → ${proxy}`);
|
|
2143
|
+
} catch (error) {
|
|
2144
|
+
return fail(`切换节点失败:${String(error)}`);
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
optimisticProxy(group, now) {
|
|
2148
|
+
this.proxies = {
|
|
2149
|
+
...this.proxies,
|
|
2150
|
+
groups: this.proxies.groups.map((g) => g.name === group ? {
|
|
2151
|
+
...g,
|
|
2152
|
+
now
|
|
2153
|
+
} : g),
|
|
2154
|
+
proxies: this.proxies.proxies[group] !== void 0 ? {
|
|
2155
|
+
...this.proxies.proxies,
|
|
2156
|
+
[group]: {
|
|
2157
|
+
...this.proxies.proxies[group],
|
|
2158
|
+
now
|
|
2159
|
+
}
|
|
2160
|
+
} : this.proxies.proxies
|
|
2161
|
+
};
|
|
2162
|
+
this.emitProxies();
|
|
2163
|
+
}
|
|
2164
|
+
persistSelectionToProfile(group, proxy) {
|
|
2165
|
+
try {
|
|
2166
|
+
const profiles = loadProfiles();
|
|
2167
|
+
const current = getCurrentProfile(profiles);
|
|
2168
|
+
if (current === void 0) return;
|
|
2169
|
+
if (setProfileSelection(profiles, current.uid, group, proxy)) saveProfiles(profiles);
|
|
2170
|
+
} catch {}
|
|
2171
|
+
}
|
|
2172
|
+
persistOfflineSelection(group, proxy) {
|
|
2173
|
+
try {
|
|
2174
|
+
const profiles = loadProfiles();
|
|
2175
|
+
const current = getCurrentProfile(profiles);
|
|
2176
|
+
if (current === void 0) return fail("未选择 Profile,无法预选节点。");
|
|
2177
|
+
if (!setProfileSelection(profiles, current.uid, group, proxy)) return ok("选择未变化。");
|
|
2178
|
+
saveProfiles(profiles);
|
|
2179
|
+
this.optimisticProxy(group, proxy);
|
|
2180
|
+
return ok(`已预选:${group} → ${proxy}(下次启动生效)`);
|
|
2181
|
+
} catch (error) {
|
|
2182
|
+
return fail(`写入预选失败:${String(error)}`);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
/** 测试一个组内所有真实节点的延迟,返回节点名→ms(0=超时)。 */
|
|
2186
|
+
async testGroupDelay(groupName) {
|
|
2187
|
+
if (this.apiClient === void 0) return offlineFail("测速");
|
|
2188
|
+
const group = this.proxies.groups.find((g) => g.name === groupName);
|
|
2189
|
+
if (group === void 0) return fail(`代理组不存在:${groupName}`);
|
|
2190
|
+
this.proxies = {
|
|
2191
|
+
...this.proxies,
|
|
2192
|
+
testing: true
|
|
2193
|
+
};
|
|
2194
|
+
this.emitProxies();
|
|
2195
|
+
const client = this.apiClient;
|
|
2196
|
+
const overrides = { ...this.proxies.delayOverrides };
|
|
2197
|
+
const nodes = group.all.filter((name) => {
|
|
2198
|
+
const info = this.proxies.proxies[name];
|
|
2199
|
+
return info !== void 0 && !GROUP_TYPES.has(info.type);
|
|
2200
|
+
});
|
|
2201
|
+
const concurrency = 8;
|
|
2202
|
+
let index = 0;
|
|
2203
|
+
const runOne = async (name) => {
|
|
2204
|
+
try {
|
|
2205
|
+
const resp = await client.getProxyDelay(name, DELAY_TEST_URL, DELAY_TEST_TIMEOUT);
|
|
2206
|
+
overrides[name] = Object.values(resp).filter((v) => typeof v === "number")[0] ?? 0;
|
|
2207
|
+
} catch {
|
|
2208
|
+
overrides[name] = 0;
|
|
2209
|
+
}
|
|
2210
|
+
};
|
|
2211
|
+
const workers = [];
|
|
2212
|
+
for (let w = 0; w < concurrency; w += 1) workers.push((async () => {
|
|
2213
|
+
while (index < nodes.length) {
|
|
2214
|
+
const current = index;
|
|
2215
|
+
index += 1;
|
|
2216
|
+
const name = nodes[current];
|
|
2217
|
+
if (name !== void 0) await runOne(name);
|
|
2218
|
+
}
|
|
2219
|
+
})());
|
|
2220
|
+
await Promise.all(workers);
|
|
2221
|
+
this.proxies = {
|
|
2222
|
+
...this.proxies,
|
|
2223
|
+
delayOverrides: overrides,
|
|
2224
|
+
testing: false
|
|
2225
|
+
};
|
|
2226
|
+
this.emitProxies();
|
|
2227
|
+
return ok("测速完成。");
|
|
2228
|
+
}
|
|
2229
|
+
async closeConnection(id) {
|
|
2230
|
+
if (this.apiClient === void 0) return offlineFail("断开连接");
|
|
2231
|
+
try {
|
|
2232
|
+
if (id === void 0 || id === "") {
|
|
2233
|
+
await this.apiClient.closeConnections();
|
|
2234
|
+
this.connRows = [];
|
|
2235
|
+
this.emitConnections();
|
|
2236
|
+
return ok("已断开全部连接。");
|
|
2237
|
+
}
|
|
2238
|
+
await this.apiClient.closeConnection(id);
|
|
2239
|
+
this.connRows = this.connRows.filter((r) => r.id !== id);
|
|
2240
|
+
this.emitConnections();
|
|
2241
|
+
return ok("连接已断开。");
|
|
2242
|
+
} catch (error) {
|
|
2243
|
+
return fail(`断开连接失败:${String(error)}`);
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
async switchProfile(uid) {
|
|
2247
|
+
if (uid === void 0 || uid === "") return fail("缺少 uid。");
|
|
2248
|
+
if (this.apiClient !== void 0 && process.platform !== "win32") try {
|
|
2249
|
+
const resp = await sendControlCommand({
|
|
2250
|
+
cmd: "useProfile",
|
|
2251
|
+
uid
|
|
2252
|
+
});
|
|
2253
|
+
if (resp === void 0) return this.writeProfileSelection(uid, "daemon 无响应,已写入配置,重启后生效。");
|
|
2254
|
+
if (resp.ok) {
|
|
2255
|
+
this.loadStaticMeta();
|
|
2256
|
+
this.refreshProfiles();
|
|
2257
|
+
this.fetchProxies();
|
|
2258
|
+
this.fetchOverview();
|
|
2259
|
+
return ok("已切换 Profile。");
|
|
2260
|
+
}
|
|
2261
|
+
return fail(`切换 Profile 失败:${resp.error ?? "未知错误"}`);
|
|
2262
|
+
} catch (error) {
|
|
2263
|
+
return fail(`切换 Profile 失败:${String(error)}`);
|
|
2264
|
+
}
|
|
2265
|
+
return this.writeProfileSelection(uid, process.platform === "win32" ? "已写入配置,重启 daemon 后生效。" : "已切换 Profile,下次启动生效。");
|
|
2266
|
+
}
|
|
2267
|
+
writeProfileSelection(uid, message) {
|
|
2268
|
+
try {
|
|
2269
|
+
const profiles = loadProfiles();
|
|
2270
|
+
if (!setCurrentProfile(profiles, uid)) return fail("切换失败:Profile 不存在。");
|
|
2271
|
+
saveProfiles(profiles);
|
|
2272
|
+
this.refreshProfiles();
|
|
2273
|
+
this.loadStaticMeta();
|
|
2274
|
+
this.refreshOfflineProxies();
|
|
2275
|
+
return ok(message);
|
|
2276
|
+
} catch (error) {
|
|
2277
|
+
return fail(`写入 profiles.yaml 失败:${String(error)}`);
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
async reload() {
|
|
2281
|
+
if (process.platform === "win32") return fail("Windows 不支持 reload,请重启 daemon。");
|
|
2282
|
+
if (this.apiClient === void 0) return offlineFail("刷新订阅");
|
|
2283
|
+
try {
|
|
2284
|
+
const resp = await sendControlCommand({ cmd: "reload" });
|
|
2285
|
+
if (resp === void 0) return fail("daemon 无响应。");
|
|
2286
|
+
if (resp.ok) {
|
|
2287
|
+
this.fetchProxies();
|
|
2288
|
+
return ok("已刷新订阅与配置。");
|
|
2289
|
+
}
|
|
2290
|
+
return fail(`刷新失败:${resp.error ?? "未知错误"}`);
|
|
2291
|
+
} catch (error) {
|
|
2292
|
+
return fail(`刷新失败:${String(error)}`);
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
/**
|
|
2296
|
+
* 修改并保存 lynx.json(离线可写)。mutator 在加载出的配置上原地修改。
|
|
2297
|
+
* 在线时不自动重启(前端提示重启生效)。
|
|
2298
|
+
*/
|
|
2299
|
+
updateLynxConfig(mutator) {
|
|
2300
|
+
let config;
|
|
2301
|
+
try {
|
|
2302
|
+
config = loadLynxConfig();
|
|
2303
|
+
} catch {
|
|
2304
|
+
return false;
|
|
2305
|
+
}
|
|
2306
|
+
mutator(config);
|
|
2307
|
+
try {
|
|
2308
|
+
writeLynxConfig(config);
|
|
2309
|
+
} catch {
|
|
2310
|
+
return false;
|
|
2311
|
+
}
|
|
2312
|
+
this.loadStaticMeta();
|
|
2313
|
+
return true;
|
|
2314
|
+
}
|
|
2315
|
+
async updateSettings(patch) {
|
|
2316
|
+
try {
|
|
2317
|
+
const config = loadLynxConfig();
|
|
2318
|
+
if (typeof patch.listen === "string") config.listen = patch.listen;
|
|
2319
|
+
if (typeof patch["mixed-port"] === "number") config.mihomo["mixed-port"] = patch["mixed-port"];
|
|
2320
|
+
if (typeof patch.kernel === "string" && (patch.kernel === "stable" || patch.kernel === "alpha")) config.mihomo.kernel = patch.kernel;
|
|
2321
|
+
if (typeof patch.mode === "string" && [
|
|
2322
|
+
"rule",
|
|
2323
|
+
"global",
|
|
2324
|
+
"direct",
|
|
2325
|
+
"script"
|
|
2326
|
+
].includes(patch.mode)) config.mihomo.mode = patch.mode;
|
|
2327
|
+
if (patch.ipv6 === true || patch.ipv6 === false || patch.ipv6 === null) if (patch.ipv6 === null) delete config.mihomo.ipv6;
|
|
2328
|
+
else config.mihomo.ipv6 = patch.ipv6;
|
|
2329
|
+
if (typeof patch.logLevel === "string" && [
|
|
2330
|
+
"debug",
|
|
2331
|
+
"info",
|
|
2332
|
+
"warn",
|
|
2333
|
+
"error"
|
|
2334
|
+
].includes(patch.logLevel)) config.log = {
|
|
2335
|
+
...config.log,
|
|
2336
|
+
level: patch.logLevel
|
|
2337
|
+
};
|
|
2338
|
+
if (typeof patch.accessLog === "boolean") config.log = {
|
|
2339
|
+
...config.log,
|
|
2340
|
+
access: patch.accessLog
|
|
2341
|
+
};
|
|
2342
|
+
writeLynxConfig(config);
|
|
2343
|
+
this.loadStaticMeta();
|
|
2344
|
+
return ok(this.apiClient === void 0 ? "设置已保存,下次启动生效。" : "设置已保存,重启 daemon 后生效。");
|
|
2345
|
+
} catch (error) {
|
|
2346
|
+
return fail(`保存设置失败:${String(error)}`);
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
setLogLevel(level) {
|
|
2350
|
+
if (![
|
|
2351
|
+
"debug",
|
|
2352
|
+
"info",
|
|
2353
|
+
"warning",
|
|
2354
|
+
"error"
|
|
2355
|
+
].includes(level)) return fail(`非法日志级别:${level}`);
|
|
2356
|
+
const lvl = level;
|
|
2357
|
+
this.logLevel = lvl;
|
|
2358
|
+
this.logs?.setLevel(lvl);
|
|
2359
|
+
this.emit("logsLevel", { level: lvl });
|
|
2360
|
+
return ok(`日志级别:${lvl}`);
|
|
2361
|
+
}
|
|
2362
|
+
};
|
|
2363
|
+
//#endregion
|
|
2364
|
+
//#region src/web/server.ts
|
|
2365
|
+
/**
|
|
2366
|
+
* Web 管理器 HTTP 服务器(纯 node:http,无第三方框架)。
|
|
2367
|
+
*
|
|
2368
|
+
* 路由:
|
|
2369
|
+
* GET /sse SSE 事件流(状态/概览/代理/连接/流量/日志/flash)
|
|
2370
|
+
* GET /api/state 全量快照(首屏)
|
|
2371
|
+
* GET /api/settings lynx.json
|
|
2372
|
+
* PATCH /api/settings 保存设置(离线可写)
|
|
2373
|
+
* GET /api/profiles Profile 列表
|
|
2374
|
+
* POST /api/daemon/{start|stop|restart}
|
|
2375
|
+
* POST /api/mode {mode}
|
|
2376
|
+
* POST /api/kernel {channel}
|
|
2377
|
+
* POST /api/system-proxy {on}
|
|
2378
|
+
* POST /api/proxy/select {group,node}
|
|
2379
|
+
* POST /api/proxy/test {group}
|
|
2380
|
+
* POST /api/connections/close {id?}
|
|
2381
|
+
* POST /api/profile/use {uid}
|
|
2382
|
+
* POST /api/profile/reload
|
|
2383
|
+
* GET /* 静态资源(dist/web-assets),SPA 回退 index.html
|
|
2384
|
+
*
|
|
2385
|
+
* 仅绑定 loopback;mihomo secret 只存在于后端,不下发浏览器。
|
|
2386
|
+
*/
|
|
2387
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
2388
|
+
/** 生产模式前端静态资源目录(dist/web-assets)。dev 模式由 vite 托管,可能不存在。 */
|
|
2389
|
+
function getAssetsDir() {
|
|
2390
|
+
return join(__dirname, "web-assets");
|
|
2391
|
+
}
|
|
2392
|
+
const MIME = {
|
|
2393
|
+
".html": "text/html; charset=utf-8",
|
|
2394
|
+
".js": "text/javascript; charset=utf-8",
|
|
2395
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
2396
|
+
".css": "text/css; charset=utf-8",
|
|
2397
|
+
".json": "application/json; charset=utf-8",
|
|
2398
|
+
".svg": "image/svg+xml",
|
|
2399
|
+
".png": "image/png",
|
|
2400
|
+
".ico": "image/x-icon",
|
|
2401
|
+
".woff2": "font/woff2",
|
|
2402
|
+
".map": "application/json; charset=utf-8"
|
|
2403
|
+
};
|
|
2404
|
+
async function startWebServer(options) {
|
|
2405
|
+
const hub = new SseHub();
|
|
2406
|
+
const runtime = new WebRuntime(hub);
|
|
2407
|
+
await runtime.start();
|
|
2408
|
+
const server = createServer((req, res) => {
|
|
2409
|
+
handle(req, res, runtime, hub).catch((error) => {
|
|
2410
|
+
sendJson(res, 500, {
|
|
2411
|
+
ok: false,
|
|
2412
|
+
error: `服务器内部错误:${String(error)}`
|
|
2413
|
+
});
|
|
2414
|
+
});
|
|
2415
|
+
});
|
|
2416
|
+
return await new Promise((resolve, reject) => {
|
|
2417
|
+
server.on("error", reject);
|
|
2418
|
+
server.listen(options.port, options.host ?? "127.0.0.1", () => {
|
|
2419
|
+
resolve({
|
|
2420
|
+
server,
|
|
2421
|
+
runtime,
|
|
2422
|
+
hub,
|
|
2423
|
+
close() {
|
|
2424
|
+
runtime.stop();
|
|
2425
|
+
hub.stop();
|
|
2426
|
+
server.close();
|
|
2427
|
+
}
|
|
2428
|
+
});
|
|
2429
|
+
});
|
|
2430
|
+
});
|
|
2431
|
+
}
|
|
2432
|
+
async function handle(req, res, runtime, hub) {
|
|
2433
|
+
const method = req.method ?? "GET";
|
|
2434
|
+
const path = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
2435
|
+
if (path === "/sse" && method === "GET") {
|
|
2436
|
+
hub.add(res);
|
|
2437
|
+
res.write(`event: snapshot\ndata: ${JSON.stringify(runtime.getSnapshot())}\n\n`);
|
|
2438
|
+
return;
|
|
2439
|
+
}
|
|
2440
|
+
if (path.startsWith("/api/")) {
|
|
2441
|
+
await handleApi(method, path, req, res, runtime);
|
|
2442
|
+
return;
|
|
2443
|
+
}
|
|
2444
|
+
serveStatic(path, res);
|
|
2445
|
+
}
|
|
2446
|
+
async function handleApi(method, path, req, res, runtime) {
|
|
2447
|
+
if (path === "/api/state" && method === "GET") {
|
|
2448
|
+
sendJson(res, 200, runtime.getSnapshot());
|
|
2449
|
+
return;
|
|
2450
|
+
}
|
|
2451
|
+
if (path === "/api/settings" && method === "GET") {
|
|
2452
|
+
sendJson(res, 200, { config: runtime.readLynxConfig() });
|
|
2453
|
+
return;
|
|
2454
|
+
}
|
|
2455
|
+
if (path === "/api/profiles" && method === "GET") {
|
|
2456
|
+
sendJson(res, 200, runtime.getSnapshot().profiles);
|
|
2457
|
+
return;
|
|
2458
|
+
}
|
|
2459
|
+
if (path === "/api/settings" && method === "PATCH") {
|
|
2460
|
+
const body = await readJsonBody(req);
|
|
2461
|
+
sendActionResult(res, await runtime.updateSettings(body));
|
|
2462
|
+
return;
|
|
2463
|
+
}
|
|
2464
|
+
if (method !== "POST") {
|
|
2465
|
+
sendJson(res, 405, {
|
|
2466
|
+
ok: false,
|
|
2467
|
+
error: "Method not allowed"
|
|
2468
|
+
});
|
|
2469
|
+
return;
|
|
2470
|
+
}
|
|
2471
|
+
const result = await dispatchPost(path, await readJsonBody(req).catch(() => ({})), runtime);
|
|
2472
|
+
if (result === void 0) {
|
|
2473
|
+
sendJson(res, 404, {
|
|
2474
|
+
ok: false,
|
|
2475
|
+
error: `未知接口:${path}`
|
|
2476
|
+
});
|
|
2477
|
+
return;
|
|
2478
|
+
}
|
|
2479
|
+
sendActionResult(res, result);
|
|
2480
|
+
}
|
|
2481
|
+
async function dispatchPost(path, body, runtime) {
|
|
2482
|
+
switch (path) {
|
|
2483
|
+
case "/api/daemon/start": return runtime.startDaemon();
|
|
2484
|
+
case "/api/daemon/stop": return runtime.stopDaemon();
|
|
2485
|
+
case "/api/daemon/restart": return runtime.restartDaemon();
|
|
2486
|
+
case "/api/mode": return runtime.setMode(String(body.mode ?? ""));
|
|
2487
|
+
case "/api/kernel": return runtime.switchKernel(String(body.channel ?? ""));
|
|
2488
|
+
case "/api/system-proxy": return runtime.setSystemProxy(body.on === true);
|
|
2489
|
+
case "/api/proxy/select": return runtime.selectProxy(String(body.group ?? ""), String(body.node ?? ""));
|
|
2490
|
+
case "/api/proxy/test": return runtime.testGroupDelay(String(body.group ?? ""));
|
|
2491
|
+
case "/api/connections/close": return runtime.closeConnection(body.id === void 0 ? void 0 : String(body.id));
|
|
2492
|
+
case "/api/profile/use": return runtime.switchProfile(String(body.uid ?? ""));
|
|
2493
|
+
case "/api/profile/reload": return runtime.reload();
|
|
2494
|
+
case "/api/log-level": return Promise.resolve(runtime.setLogLevel(String(body.level ?? "info")));
|
|
2495
|
+
default: return;
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
function sendActionResult(res, result) {
|
|
2499
|
+
if (result.ok) sendJson(res, 200, result);
|
|
2500
|
+
else if (result.offline) sendJson(res, 503, result);
|
|
2501
|
+
else sendJson(res, 400, result);
|
|
2502
|
+
}
|
|
2503
|
+
function sendJson(res, status, data) {
|
|
2504
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
2505
|
+
res.end(JSON.stringify(data));
|
|
2506
|
+
}
|
|
2507
|
+
async function readJsonBody(req) {
|
|
2508
|
+
const chunks = [];
|
|
2509
|
+
for await (const chunk of req) chunks.push(chunk);
|
|
2510
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
2511
|
+
if (raw.length === 0) return {};
|
|
2512
|
+
return JSON.parse(raw);
|
|
2513
|
+
}
|
|
2514
|
+
function serveStatic(path, res) {
|
|
2515
|
+
const assetsDir = getAssetsDir();
|
|
2516
|
+
const rel = normalize(path).replace(/^([/\\])+/, "");
|
|
2517
|
+
const filePath = join(assetsDir, rel);
|
|
2518
|
+
const indexFile = join(assetsDir, "index.html");
|
|
2519
|
+
const serveFile = (target) => {
|
|
2520
|
+
if (!resolve(target).startsWith(resolve(assetsDir) + sep)) return false;
|
|
2521
|
+
if (!existsSync(target) || !statSync(target).isFile()) return false;
|
|
2522
|
+
const mime = MIME[extname(target).toLowerCase()] ?? "application/octet-stream";
|
|
2523
|
+
res.writeHead(200, { "Content-Type": mime });
|
|
2524
|
+
res.end(readFileSync(target));
|
|
2525
|
+
return true;
|
|
2526
|
+
};
|
|
2527
|
+
if (rel !== "" && serveFile(filePath)) return;
|
|
2528
|
+
if (existsSync(indexFile)) {
|
|
2529
|
+
res.writeHead(200, { "Content-Type": MIME[".html"] });
|
|
2530
|
+
res.end(readFileSync(indexFile));
|
|
2531
|
+
return;
|
|
2532
|
+
}
|
|
2533
|
+
res.writeHead(503, { "Content-Type": "text/plain; charset=utf-8" });
|
|
2534
|
+
res.end("Web 前端资源未构建。请先运行 `pnpm build`(或使用 `pnpm dev:web` 开发模式)。");
|
|
2535
|
+
}
|
|
2536
|
+
//#endregion
|
|
2537
|
+
//#region src/web/index.ts
|
|
2538
|
+
/**
|
|
2539
|
+
* LynxProxy Web 控制台独立入口。
|
|
2540
|
+
*
|
|
2541
|
+
* 由 `lynx web` 以独立子进程方式启动(见 src/cli/web-cli.ts),
|
|
2542
|
+
* 不被主 CLI/daemon 产物 dist/index.mjs 引用。
|
|
2543
|
+
*
|
|
2544
|
+
* 与主进程的交互只发生在运行时(与 TUI 相同):
|
|
2545
|
+
* - 读取 ~/.lynx-proxy/runtime/proxy-daemon.json 拿 daemon 状态与 mihomo 凭据
|
|
2546
|
+
* - HTTP 连 mihomo external-controller(MihomoApiClient)+ WebSocket 订阅 /traffic、/logs
|
|
2547
|
+
* - 经控制 socket 发 reload / useProfile;经 daemon-lifecycle 启停 daemon
|
|
2548
|
+
* - 离线时读 config.yaml / lynx.json / profiles.yaml 提供只读/可写的离线配置
|
|
2549
|
+
* 不发生任何进程内调用;mihomo secret 只存在于本进程,不下发浏览器。
|
|
2550
|
+
*/
|
|
2551
|
+
function parseArgs(argv) {
|
|
2552
|
+
let port = 9876;
|
|
2553
|
+
let host = "127.0.0.1";
|
|
2554
|
+
let open = true;
|
|
2555
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
2556
|
+
const arg = argv[i];
|
|
2557
|
+
if (arg === "--port" || arg === "-p") {
|
|
2558
|
+
const value = argv[i + 1];
|
|
2559
|
+
const parsed = Number(value);
|
|
2560
|
+
if (Number.isInteger(parsed) && parsed > 0 && parsed < 65536) port = parsed;
|
|
2561
|
+
i += 1;
|
|
2562
|
+
} else if (arg === "--host" || arg === "-h") {
|
|
2563
|
+
const value = argv[i + 1];
|
|
2564
|
+
if (value !== void 0) host = value;
|
|
2565
|
+
i += 1;
|
|
2566
|
+
} else if (arg === "--no-open") open = false;
|
|
2567
|
+
else if (arg === "--open") open = true;
|
|
2568
|
+
else if (arg === "--help") {
|
|
2569
|
+
printHelp();
|
|
2570
|
+
process.exit(0);
|
|
2571
|
+
}
|
|
2572
|
+
}
|
|
2573
|
+
return {
|
|
2574
|
+
port,
|
|
2575
|
+
host,
|
|
2576
|
+
open
|
|
2577
|
+
};
|
|
2578
|
+
}
|
|
2579
|
+
function printHelp() {
|
|
2580
|
+
process.stdout.write(`lynx web — 启动 Web 控制台
|
|
2581
|
+
|
|
2582
|
+
用法: lynx web [选项]
|
|
2583
|
+
|
|
2584
|
+
选项:
|
|
2585
|
+
-p, --port <端口> 监听端口(默认 9876)
|
|
2586
|
+
-h, --host <地址> 监听地址(默认 127.0.0.1,仅本机访问)
|
|
2587
|
+
--no-open 启动后不自动打开浏览器
|
|
2588
|
+
--help 显示此帮助
|
|
2589
|
+
`);
|
|
2590
|
+
}
|
|
2591
|
+
function openBrowser(url) {
|
|
2592
|
+
const platform = process.platform;
|
|
2593
|
+
const command = platform === "win32" ? "cmd" : platform === "darwin" ? "open" : "xdg-open";
|
|
2594
|
+
const args = platform === "win32" ? [
|
|
2595
|
+
"/c",
|
|
2596
|
+
"start",
|
|
2597
|
+
"",
|
|
2598
|
+
url
|
|
2599
|
+
] : [url];
|
|
2600
|
+
try {
|
|
2601
|
+
const child = spawn(command, args, {
|
|
2602
|
+
stdio: "ignore",
|
|
2603
|
+
detached: true
|
|
2604
|
+
});
|
|
2605
|
+
child.on("error", () => {});
|
|
2606
|
+
child.unref();
|
|
2607
|
+
} catch {}
|
|
2608
|
+
}
|
|
2609
|
+
async function main() {
|
|
2610
|
+
const args = parseArgs(process.argv.slice(2));
|
|
2611
|
+
const web = await startWebServer({
|
|
2612
|
+
port: args.port,
|
|
2613
|
+
host: args.host
|
|
2614
|
+
});
|
|
2615
|
+
const url = `http://${args.host === "0.0.0.0" ? "127.0.0.1" : args.host}:${args.port}`;
|
|
2616
|
+
process.stdout.write(`LynxProxy Web 控制台已启动:${url}\n`);
|
|
2617
|
+
process.stdout.write("按 Ctrl+C 退出。\n");
|
|
2618
|
+
if (args.open) openBrowser(url);
|
|
2619
|
+
const shutdown = () => {
|
|
2620
|
+
web.close();
|
|
2621
|
+
process.exit(0);
|
|
2622
|
+
};
|
|
2623
|
+
process.on("SIGINT", shutdown);
|
|
2624
|
+
process.on("SIGTERM", shutdown);
|
|
2625
|
+
}
|
|
2626
|
+
main().catch((error) => {
|
|
2627
|
+
process.stderr.write(`Web 控制台启动失败:${String(error)}\n`);
|
|
2628
|
+
process.exit(1);
|
|
2629
|
+
});
|
|
2630
|
+
//#endregion
|
|
2631
|
+
export {};
|
|
2632
|
+
|
|
2633
|
+
//# sourceMappingURL=web.mjs.map
|