lynx-proxy 0.0.1
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/CLI.md +259 -0
- package/LICENSE +21 -0
- package/README.md +97 -0
- package/dist/index.d.mts +11 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2902 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +60 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2902 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { appendFileSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { dump, load } from "js-yaml";
|
|
5
|
+
import { basename, dirname, extname, isAbsolute, join } from "node:path";
|
|
6
|
+
import { parse, stringify } from "smol-toml";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { createConnection, createServer, isIP } from "node:net";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import { connect } from "node:tls";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { TextEncoder } from "node:util";
|
|
13
|
+
//#region src/config/models.ts
|
|
14
|
+
var ConfigError = class extends Error {
|
|
15
|
+
constructor(message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "ConfigError";
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/router/rules.ts
|
|
22
|
+
const MATCH_TYPES = new Set([
|
|
23
|
+
"domain",
|
|
24
|
+
"domain_suffix",
|
|
25
|
+
"domain_keyword",
|
|
26
|
+
"ip",
|
|
27
|
+
"ip_cidr",
|
|
28
|
+
"ip_cidr6",
|
|
29
|
+
"port",
|
|
30
|
+
"scheme",
|
|
31
|
+
"geoip"
|
|
32
|
+
]);
|
|
33
|
+
const CLASH_RULE_TYPES = new Map([
|
|
34
|
+
["DOMAIN", "domain"],
|
|
35
|
+
["DOMAIN-SUFFIX", "domain_suffix"],
|
|
36
|
+
["DOMAIN-KEYWORD", "domain_keyword"],
|
|
37
|
+
["IP-CIDR", "ip_cidr"],
|
|
38
|
+
["IP-CIDR6", "ip_cidr6"],
|
|
39
|
+
["GEOIP", "geoip"]
|
|
40
|
+
]);
|
|
41
|
+
function isRuleMatchType(value) {
|
|
42
|
+
return MATCH_TYPES.has(value);
|
|
43
|
+
}
|
|
44
|
+
function parseClashRuleItem(item, index, resolveTarget) {
|
|
45
|
+
const parts = item.split(",").map((part) => part.trim());
|
|
46
|
+
const type = parts[0]?.toUpperCase();
|
|
47
|
+
if (type === "MATCH") {
|
|
48
|
+
if (parts.length !== 2) throw new ConfigError(`MATCH rule must have 2 fields: ${item}`);
|
|
49
|
+
const target = parts[1];
|
|
50
|
+
ensureNonEmpty(target, "target", item);
|
|
51
|
+
return {
|
|
52
|
+
kind: "match",
|
|
53
|
+
target: resolveTarget(target)
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
if (type === void 0) throw new ConfigError(`Unsupported Clash rule type "${String(parts[0])}" in: ${item}`);
|
|
57
|
+
const match = CLASH_RULE_TYPES.get(type);
|
|
58
|
+
if (match === void 0) throw new ConfigError(`Unsupported Clash rule type "${String(parts[0])}" in: ${item}`);
|
|
59
|
+
if (parts.length < 3) throw new ConfigError(`Clash rule must have at least 3 fields: ${item}`);
|
|
60
|
+
const value = parts[1];
|
|
61
|
+
const target = parts[2];
|
|
62
|
+
ensureNonEmpty(value, "value", item);
|
|
63
|
+
ensureNonEmpty(target, "target", item);
|
|
64
|
+
const resolved = resolveTarget(target);
|
|
65
|
+
const name = `${type}:${value || index}`;
|
|
66
|
+
if (resolved.action === "DIRECT") return {
|
|
67
|
+
action: "DIRECT",
|
|
68
|
+
match,
|
|
69
|
+
value,
|
|
70
|
+
name
|
|
71
|
+
};
|
|
72
|
+
return {
|
|
73
|
+
action: "PROXY",
|
|
74
|
+
match,
|
|
75
|
+
value,
|
|
76
|
+
proxy: resolved.targetName,
|
|
77
|
+
name
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function ensureNonEmpty(value, field, item) {
|
|
81
|
+
if (value === void 0 || value.length === 0) throw new ConfigError(`Rule field ${field} is empty in: ${item}`);
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region src/config/validator.ts
|
|
85
|
+
const ROUTE_ACTIONS = new Set(["DIRECT", "PROXY"]);
|
|
86
|
+
const PROXY_TYPES = new Set([
|
|
87
|
+
"direct",
|
|
88
|
+
"socks5",
|
|
89
|
+
"trojan"
|
|
90
|
+
]);
|
|
91
|
+
const LOG_LEVELS = new Set([
|
|
92
|
+
"debug",
|
|
93
|
+
"info",
|
|
94
|
+
"warn",
|
|
95
|
+
"error"
|
|
96
|
+
]);
|
|
97
|
+
function validateConfig(config) {
|
|
98
|
+
validateServer(config.server);
|
|
99
|
+
validateRoute(config.route);
|
|
100
|
+
validateLog(config.log);
|
|
101
|
+
validateUser(config.user);
|
|
102
|
+
validateProxies(config.proxies);
|
|
103
|
+
validateRules(config);
|
|
104
|
+
}
|
|
105
|
+
function assertRouteAction(value, field) {
|
|
106
|
+
if (!ROUTE_ACTIONS.has(value)) throw new ConfigError(`${field} must be DIRECT or PROXY`);
|
|
107
|
+
}
|
|
108
|
+
function assertProxyType(value, field) {
|
|
109
|
+
if (!PROXY_TYPES.has(value)) throw new ConfigError(`${field} has unsupported proxy type: ${value}`);
|
|
110
|
+
}
|
|
111
|
+
function assertLogLevel(value, field) {
|
|
112
|
+
if (!LOG_LEVELS.has(value)) throw new ConfigError(`${field} has unsupported log level: ${value}`);
|
|
113
|
+
}
|
|
114
|
+
function validatePort(port, field) {
|
|
115
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new ConfigError(`${field} must be an integer from 1 to 65535`);
|
|
116
|
+
}
|
|
117
|
+
function validateServer(server) {
|
|
118
|
+
validateNonEmptyString(server.host, "server.host");
|
|
119
|
+
validatePort(server.port, "server.port");
|
|
120
|
+
validatePositiveInteger(server.connectTimeoutMs, "server.connect_timeout_ms");
|
|
121
|
+
validatePositiveInteger(server.idleTimeoutMs, "server.idle_timeout_ms");
|
|
122
|
+
}
|
|
123
|
+
function validateRoute(route) {
|
|
124
|
+
assertRouteAction(route.default, "route.default");
|
|
125
|
+
if (route.default === "PROXY") validateNonEmptyString(route.defaultProxy, "route.default_proxy");
|
|
126
|
+
}
|
|
127
|
+
function validateLog(log) {
|
|
128
|
+
assertLogLevel(log.level, "log.level");
|
|
129
|
+
if (log.file !== void 0) validateNonEmptyString(log.file, "log.file");
|
|
130
|
+
}
|
|
131
|
+
function validateUser(user) {
|
|
132
|
+
for (const [groupName, proxyName] of Object.entries(user.proxyGroupSelections)) {
|
|
133
|
+
validateNonEmptyString(groupName, "user.proxyGroupSelections group name");
|
|
134
|
+
validateNonEmptyString(proxyName, `user.proxyGroupSelections.${groupName}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function validateProxies(proxies) {
|
|
138
|
+
const names = /* @__PURE__ */ new Set();
|
|
139
|
+
for (const proxy of proxies) {
|
|
140
|
+
validateNonEmptyString(proxy.name, "proxy.name");
|
|
141
|
+
assertProxyType(proxy.type, `proxy ${proxy.name}.type`);
|
|
142
|
+
if (names.has(proxy.name)) throw new ConfigError(`Duplicate proxy name: ${proxy.name}`);
|
|
143
|
+
names.add(proxy.name);
|
|
144
|
+
if (proxy.type === "socks5") {
|
|
145
|
+
validateNonEmptyString(proxy.host, `proxy ${proxy.name}.host`);
|
|
146
|
+
validatePort(proxy.port, `proxy ${proxy.name}.port`);
|
|
147
|
+
validateOptionalPair(proxy.username, proxy.password, proxy.name);
|
|
148
|
+
} else if (proxy.type === "trojan") validateTrojanProxy(proxy);
|
|
149
|
+
else validateDirectProxy(proxy);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function validateDirectProxy(proxy) {
|
|
153
|
+
if (proxy.type !== "direct") throw new ConfigError(`Invalid direct proxy type: ${proxy.name}`);
|
|
154
|
+
}
|
|
155
|
+
function validateTrojanProxy(proxy) {
|
|
156
|
+
validateNonEmptyString(proxy.host, `proxy ${proxy.name}.host`);
|
|
157
|
+
validatePort(proxy.port, `proxy ${proxy.name}.port`);
|
|
158
|
+
validateNonEmptyString(proxy.password, `proxy ${proxy.name}.password`);
|
|
159
|
+
validateNonEmptyString(proxy.serverName, `proxy ${proxy.name}.server_name`);
|
|
160
|
+
}
|
|
161
|
+
function validateRules(config) {
|
|
162
|
+
const proxyNames = new Set(config.proxies.map((proxy) => proxy.name));
|
|
163
|
+
const proxyGroupNames = new Set(config.proxyGroups.map((group) => group.name));
|
|
164
|
+
if (config.route.defaultProxy !== void 0 && !proxyNames.has(config.route.defaultProxy) && !proxyGroupNames.has(config.route.defaultProxy)) throw new ConfigError(`route.default_proxy references unknown proxy or proxy-group: ${config.route.defaultProxy}`);
|
|
165
|
+
for (const rule of config.rules) {
|
|
166
|
+
validateNonEmptyString(rule.name, "rule.name");
|
|
167
|
+
if (!isRuleMatchType(rule.match)) throw new ConfigError(`Rule ${rule.name} has unsupported match type: ${rule.match}`);
|
|
168
|
+
if (rule.action === "DIRECT") {
|
|
169
|
+
if (rule.proxy !== void 0) throw new ConfigError(`DIRECT rule ${rule.name} must not specify proxy`);
|
|
170
|
+
} else {
|
|
171
|
+
const proxyName = rule.proxy ?? config.route.defaultProxy;
|
|
172
|
+
if (proxyName === void 0 || proxyName.length === 0) throw new ConfigError(`PROXY rule ${rule.name} requires a proxy or route.default_proxy`);
|
|
173
|
+
if (!proxyNames.has(proxyName) && !proxyGroupNames.has(proxyName)) throw new ConfigError(`Rule ${rule.name} references unknown proxy or proxy-group: ${proxyName}`);
|
|
174
|
+
}
|
|
175
|
+
if (rule.match === "port") validatePort(Number(rule.value), `rule ${rule.name}.value`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
function validateNonEmptyString(value, field) {
|
|
179
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new ConfigError(`${field} must be a non-empty string`);
|
|
180
|
+
}
|
|
181
|
+
function validatePositiveInteger(value, field) {
|
|
182
|
+
if (!Number.isInteger(value) || value <= 0) throw new ConfigError(`${field} must be a positive integer`);
|
|
183
|
+
}
|
|
184
|
+
function validateOptionalPair(username, password, proxyName) {
|
|
185
|
+
if (username === void 0 !== (password === void 0)) throw new ConfigError(`SOCKS5 proxy ${proxyName} requires both username and password when using authentication`);
|
|
186
|
+
}
|
|
187
|
+
//#endregion
|
|
188
|
+
//#region src/config/loader.ts
|
|
189
|
+
const DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
|
|
190
|
+
const DEFAULT_IDLE_TIMEOUT_MS = 6e4;
|
|
191
|
+
function parseConfigFile(file, content) {
|
|
192
|
+
const ext = extname(file);
|
|
193
|
+
switch (ext) {
|
|
194
|
+
case ".json": return JSON.parse(content);
|
|
195
|
+
case ".toml": return parse(content);
|
|
196
|
+
case ".yml":
|
|
197
|
+
case ".yaml": return load(content);
|
|
198
|
+
default: throw new ConfigError(`Unsupported config file extension: ${ext}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function loadConfig(configPath) {
|
|
202
|
+
return loadConfigFromRaw(parseConfigFile(configPath, readFileSync(configPath, "utf8")));
|
|
203
|
+
}
|
|
204
|
+
function loadConfigFromRaw(raw) {
|
|
205
|
+
const config = parseAppConfig(raw);
|
|
206
|
+
validateConfig(config);
|
|
207
|
+
return config;
|
|
208
|
+
}
|
|
209
|
+
function applyProfileState(raw, state) {
|
|
210
|
+
if (state === void 0) return cloneRecord(raw);
|
|
211
|
+
const effective = cloneRecord(raw);
|
|
212
|
+
if (state["proxy-groups"] !== void 0) {
|
|
213
|
+
const user = { ...asOptionalRecord$1(effective["user"], "user") };
|
|
214
|
+
user["proxy-groups"] = {
|
|
215
|
+
...asOptionalRecord$1(user["proxy-groups"], "user.proxy-groups"),
|
|
216
|
+
...state["proxy-groups"]
|
|
217
|
+
};
|
|
218
|
+
effective["user"] = user;
|
|
219
|
+
}
|
|
220
|
+
return effective;
|
|
221
|
+
}
|
|
222
|
+
function parseAppConfig(raw) {
|
|
223
|
+
const object = asRecord$2(raw, "config");
|
|
224
|
+
rejectLegacyAppConfig(object);
|
|
225
|
+
return parseClashStyleAppConfig(object);
|
|
226
|
+
}
|
|
227
|
+
function rejectLegacyAppConfig(object) {
|
|
228
|
+
if (object["server"] !== void 0 || object["route"] !== void 0) throw new ConfigError("Legacy internal config shape is no longer supported. Profile configs must use Clash-style fields such as top-level port, proxies[].server, proxy-groups, and rules[].");
|
|
229
|
+
const rules = object["rules"];
|
|
230
|
+
if (typeof rules === "object" && rules !== null && !Array.isArray(rules) && "items" in rules) throw new ConfigError("Legacy rules.items config shape is no longer supported. Use Clash-style top-level rules as a string array.");
|
|
231
|
+
const proxies = object["proxies"];
|
|
232
|
+
if (!Array.isArray(proxies)) return;
|
|
233
|
+
proxies.forEach((proxy, index) => {
|
|
234
|
+
if (typeof proxy !== "object" || proxy === null || Array.isArray(proxy)) return;
|
|
235
|
+
if ("host" in proxy || "server_name" in proxy || "allow_invalid_cert" in proxy) throw new ConfigError(`Legacy proxy fields are no longer supported at proxies[${index}]. Use Clash-style server, sni, and skip-cert-verify fields.`);
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
function parseClashStyleAppConfig(object) {
|
|
239
|
+
const proxies = parseClashProxies(object["proxies"]);
|
|
240
|
+
const proxyNames = new Set(proxies.map((proxy) => proxy.name));
|
|
241
|
+
const proxyGroups = parseProxyGroups(object["proxy-groups"]);
|
|
242
|
+
const user = parseUserConfig(object["user"]);
|
|
243
|
+
resolveProxyGroups(proxyGroups, proxyNames);
|
|
244
|
+
const resolveTarget = (target) => {
|
|
245
|
+
if (target === "DIRECT") return {
|
|
246
|
+
action: "DIRECT",
|
|
247
|
+
targetName: "DIRECT"
|
|
248
|
+
};
|
|
249
|
+
if (proxyNames.has(target)) return {
|
|
250
|
+
action: "PROXY",
|
|
251
|
+
targetName: target
|
|
252
|
+
};
|
|
253
|
+
if (proxyGroups.some((g) => g.name === target)) return {
|
|
254
|
+
action: "PROXY",
|
|
255
|
+
targetName: target
|
|
256
|
+
};
|
|
257
|
+
throw new ConfigError(`Unknown Clash rule target: ${target}`);
|
|
258
|
+
};
|
|
259
|
+
const parsedRules = parseClashRules(object["rules"], resolveTarget);
|
|
260
|
+
const userConfig = toUserConfig(user);
|
|
261
|
+
return {
|
|
262
|
+
server: parseClashServerConfig(object),
|
|
263
|
+
route: parsedRules.route,
|
|
264
|
+
user: userConfig,
|
|
265
|
+
log: parseClashLogConfig(object),
|
|
266
|
+
proxies,
|
|
267
|
+
proxyGroups,
|
|
268
|
+
rules: parsedRules.rules
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
function parseClashServerConfig(object) {
|
|
272
|
+
const allowLan = getOptionalBoolean(object, "allow-lan", false);
|
|
273
|
+
return {
|
|
274
|
+
host: getOptionalString(object, "bind-address") ?? (allowLan ? "0.0.0.0" : "127.0.0.1"),
|
|
275
|
+
port: getRequiredNumber(object, "port", "port"),
|
|
276
|
+
connectTimeoutMs: getOptionalNumber(object, "connect-timeout-ms", DEFAULT_CONNECT_TIMEOUT_MS),
|
|
277
|
+
idleTimeoutMs: getOptionalNumber(object, "idle-timeout-ms", DEFAULT_IDLE_TIMEOUT_MS)
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
function parseClashLogConfig(object) {
|
|
281
|
+
if (process.env["NODE_ENV"] == "development") return withOptionalLogFile({
|
|
282
|
+
level: "debug",
|
|
283
|
+
access: true
|
|
284
|
+
}, getOptionalString(object, "log-file"));
|
|
285
|
+
const rawLevel = getOptionalString(object, "log-level") ?? "debug";
|
|
286
|
+
const access = getOptionalBoolean(object, "access-log", true);
|
|
287
|
+
if (rawLevel === "silent") return withOptionalLogFile({
|
|
288
|
+
level: "error",
|
|
289
|
+
access
|
|
290
|
+
}, getOptionalString(object, "log-file"));
|
|
291
|
+
if (rawLevel === "warning") return withOptionalLogFile({
|
|
292
|
+
level: "warn",
|
|
293
|
+
access
|
|
294
|
+
}, getOptionalString(object, "log-file"));
|
|
295
|
+
if (rawLevel !== "debug" && rawLevel !== "info" && rawLevel !== "warn" && rawLevel !== "error") throw new ConfigError("log-level must be silent, debug, info, warning, warn or error");
|
|
296
|
+
return withOptionalLogFile({
|
|
297
|
+
level: rawLevel,
|
|
298
|
+
access
|
|
299
|
+
}, getOptionalString(object, "log-file"));
|
|
300
|
+
}
|
|
301
|
+
function withOptionalLogFile(config, file) {
|
|
302
|
+
if (file === void 0) return config;
|
|
303
|
+
return {
|
|
304
|
+
...config,
|
|
305
|
+
file
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
function parseClashProxies(raw) {
|
|
309
|
+
if (raw === void 0) return [];
|
|
310
|
+
if (!Array.isArray(raw)) throw new ConfigError("proxies must be an array");
|
|
311
|
+
return raw.map((item, index) => parseClashProxy(item, index));
|
|
312
|
+
}
|
|
313
|
+
function parseClashProxy(raw, index) {
|
|
314
|
+
const object = asRecord$2(raw, `proxies[${index}]`);
|
|
315
|
+
const name = getRequiredString(object, "name", `proxies[${index}].name`);
|
|
316
|
+
const rawType = getRequiredString(object, "type", `proxy ${name}.type`);
|
|
317
|
+
const type = rawType === "socks" ? "socks5" : rawType;
|
|
318
|
+
if (type === "direct") return {
|
|
319
|
+
name,
|
|
320
|
+
type
|
|
321
|
+
};
|
|
322
|
+
if (type === "socks5") {
|
|
323
|
+
const username = getOptionalString(object, "username");
|
|
324
|
+
const password = getOptionalString(object, "password");
|
|
325
|
+
const proxy = {
|
|
326
|
+
name,
|
|
327
|
+
type,
|
|
328
|
+
host: getRequiredString(object, "server", `proxy ${name}.server`),
|
|
329
|
+
port: getRequiredNumber(object, "port", `proxy ${name}.port`)
|
|
330
|
+
};
|
|
331
|
+
if (username !== void 0) proxy.username = username;
|
|
332
|
+
if (password !== void 0) proxy.password = password;
|
|
333
|
+
return proxy;
|
|
334
|
+
}
|
|
335
|
+
if (type === "trojan") {
|
|
336
|
+
const host = getRequiredString(object, "server", `proxy ${name}.server`);
|
|
337
|
+
const serverName = getOptionalString(object, "sni") ?? host;
|
|
338
|
+
return {
|
|
339
|
+
name,
|
|
340
|
+
type,
|
|
341
|
+
host,
|
|
342
|
+
port: getRequiredNumber(object, "port", `proxy ${name}.port`),
|
|
343
|
+
password: getRequiredString(object, "password", `proxy ${name}.password`),
|
|
344
|
+
serverName,
|
|
345
|
+
allowInvalidCert: getOptionalBoolean(object, "skip-cert-verify", false)
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
throw new ConfigError(`Unsupported proxy type "${rawType}" for proxy ${name}`);
|
|
349
|
+
}
|
|
350
|
+
function parseUserConfig(raw) {
|
|
351
|
+
if (raw === void 0) return { "proxy-groups": {} };
|
|
352
|
+
return { "proxy-groups": parseStringRecord(asRecord$2(raw, "user")["proxy-groups"], "user.proxy-groups") };
|
|
353
|
+
}
|
|
354
|
+
function toUserConfig(user) {
|
|
355
|
+
return { proxyGroupSelections: user["proxy-groups"] ?? {} };
|
|
356
|
+
}
|
|
357
|
+
function parseProxyGroups(raw) {
|
|
358
|
+
if (raw === void 0) return [];
|
|
359
|
+
if (!Array.isArray(raw)) throw new ConfigError("proxy-groups must be an array");
|
|
360
|
+
return raw.map((item, index) => {
|
|
361
|
+
const object = asRecord$2(item, `proxy-groups[${index}]`);
|
|
362
|
+
const name = getRequiredString(object, "name", `proxy-groups[${index}].name`);
|
|
363
|
+
const type = getRequiredString(object, "type", `proxy-group ${name}.type`);
|
|
364
|
+
if (type !== "select") throw new ConfigError(`Unsupported proxy-group type "${type}" for ${name}`);
|
|
365
|
+
return {
|
|
366
|
+
name,
|
|
367
|
+
type,
|
|
368
|
+
proxies: getRequiredStringArray(object, "proxies", `proxy-group ${name}.proxies`)
|
|
369
|
+
};
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
function resolveProxyGroups(groups, proxyNames) {
|
|
373
|
+
const groupsByName = new Map(groups.map((group) => [group.name, group]));
|
|
374
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
375
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
376
|
+
const resolveGroup = (name) => {
|
|
377
|
+
const cached = resolved.get(name);
|
|
378
|
+
if (cached !== void 0) return cached;
|
|
379
|
+
if (visiting.has(name)) throw new ConfigError(`proxy-groups contains a cycle at ${name}`);
|
|
380
|
+
const group = groupsByName.get(name);
|
|
381
|
+
if (group === void 0) throw new ConfigError(`Unknown proxy-group: ${name}`);
|
|
382
|
+
visiting.add(name);
|
|
383
|
+
const resolvedProxies = [];
|
|
384
|
+
for (const candidate of group.proxies) if (candidate === "DIRECT") resolvedProxies.push("DIRECT");
|
|
385
|
+
else if (proxyNames.has(candidate)) resolvedProxies.push(candidate);
|
|
386
|
+
else if (groupsByName.has(candidate)) {
|
|
387
|
+
const nested = resolveGroup(candidate);
|
|
388
|
+
resolvedProxies.push(...nested);
|
|
389
|
+
}
|
|
390
|
+
visiting.delete(name);
|
|
391
|
+
if (resolvedProxies.length === 0) throw new ConfigError(`proxy-group ${name} has no resolvable proxy`);
|
|
392
|
+
resolved.set(name, resolvedProxies);
|
|
393
|
+
return resolvedProxies;
|
|
394
|
+
};
|
|
395
|
+
for (const group of groups) resolveGroup(group.name);
|
|
396
|
+
return resolved;
|
|
397
|
+
}
|
|
398
|
+
function parseClashRules(raw, resolveTarget) {
|
|
399
|
+
if (raw === void 0) return {
|
|
400
|
+
route: { default: "DIRECT" },
|
|
401
|
+
rules: []
|
|
402
|
+
};
|
|
403
|
+
if (!Array.isArray(raw)) throw new ConfigError("rules must be an array");
|
|
404
|
+
let route = { default: "DIRECT" };
|
|
405
|
+
const rules = [];
|
|
406
|
+
raw.forEach((item, index) => {
|
|
407
|
+
if (typeof item !== "string") throw new ConfigError(`rules[${index}] must be a string`);
|
|
408
|
+
const rule = parseClashRuleItem(item, index, resolveTarget);
|
|
409
|
+
if ("kind" in rule) {
|
|
410
|
+
route = routeFromTarget(rule.target);
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
rules.push(rule);
|
|
414
|
+
});
|
|
415
|
+
return {
|
|
416
|
+
route,
|
|
417
|
+
rules
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function routeFromTarget(target) {
|
|
421
|
+
if (target.action === "DIRECT") return { default: "DIRECT" };
|
|
422
|
+
return {
|
|
423
|
+
default: "PROXY",
|
|
424
|
+
defaultProxy: target.targetName
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
function parseStringRecord(raw, field) {
|
|
428
|
+
if (raw === void 0) return {};
|
|
429
|
+
const object = asRecord$2(raw, field);
|
|
430
|
+
const result = {};
|
|
431
|
+
for (const [key, value] of Object.entries(object)) {
|
|
432
|
+
if (key.trim().length === 0) throw new ConfigError(`${field} keys must be non-empty strings`);
|
|
433
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new ConfigError(`${field}.${key} must be a non-empty string`);
|
|
434
|
+
result[key] = value;
|
|
435
|
+
}
|
|
436
|
+
return result;
|
|
437
|
+
}
|
|
438
|
+
function asRecord$2(value, field) {
|
|
439
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ConfigError(`${field} must be a table`);
|
|
440
|
+
return value;
|
|
441
|
+
}
|
|
442
|
+
function asOptionalRecord$1(value, field) {
|
|
443
|
+
if (value === void 0) return {};
|
|
444
|
+
return asRecord$2(value, field);
|
|
445
|
+
}
|
|
446
|
+
function cloneRecord(raw) {
|
|
447
|
+
return structuredClone(raw);
|
|
448
|
+
}
|
|
449
|
+
function getRequiredString(object, key, field) {
|
|
450
|
+
const value = object[key];
|
|
451
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new ConfigError(`${field} must be a non-empty string`);
|
|
452
|
+
return value;
|
|
453
|
+
}
|
|
454
|
+
function getOptionalString(object, key) {
|
|
455
|
+
const value = object[key];
|
|
456
|
+
if (value === void 0) return;
|
|
457
|
+
if (typeof value !== "string") throw new ConfigError(`${key} must be a string`);
|
|
458
|
+
return value;
|
|
459
|
+
}
|
|
460
|
+
function getRequiredNumber(object, key, field) {
|
|
461
|
+
const value = object[key];
|
|
462
|
+
if (typeof value !== "number") throw new ConfigError(`${field} must be a number`);
|
|
463
|
+
return value;
|
|
464
|
+
}
|
|
465
|
+
function getOptionalNumber(object, key, defaultValue) {
|
|
466
|
+
const value = object[key];
|
|
467
|
+
if (value === void 0) return defaultValue;
|
|
468
|
+
if (typeof value !== "number") throw new ConfigError(`${key} must be a number`);
|
|
469
|
+
return value;
|
|
470
|
+
}
|
|
471
|
+
function getOptionalBoolean(object, key, defaultValue) {
|
|
472
|
+
const value = object[key];
|
|
473
|
+
if (value === void 0) return defaultValue;
|
|
474
|
+
if (typeof value !== "boolean") throw new ConfigError(`${key} must be a boolean`);
|
|
475
|
+
return value;
|
|
476
|
+
}
|
|
477
|
+
function getRequiredStringArray(object, key, field) {
|
|
478
|
+
const value = object[key];
|
|
479
|
+
if (!Array.isArray(value) || value.length === 0) throw new ConfigError(`${field} must be a non-empty array`);
|
|
480
|
+
return value.map((item, index) => {
|
|
481
|
+
if (typeof item !== "string" || item.trim().length === 0) throw new ConfigError(`${field}[${index}] must be a non-empty string`);
|
|
482
|
+
return item;
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
//#endregion
|
|
486
|
+
//#region src/config/subscription.ts
|
|
487
|
+
const DEFAULT_USER_AGENT = "clash-verge/v1.6.0";
|
|
488
|
+
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
489
|
+
async function fetchSubscription(url, options = {}) {
|
|
490
|
+
const userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
|
|
491
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
492
|
+
let response;
|
|
493
|
+
try {
|
|
494
|
+
response = await fetch(url, {
|
|
495
|
+
headers: { "User-Agent": userAgent },
|
|
496
|
+
redirect: "follow",
|
|
497
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
498
|
+
});
|
|
499
|
+
} catch (error) {
|
|
500
|
+
throw new ConfigError(`Failed to fetch subscription ${url}: ${error instanceof Error ? error.message : String(error)}`);
|
|
501
|
+
}
|
|
502
|
+
if (!response.ok) throw new ConfigError(`Subscription request failed: ${response.status} ${response.statusText} (${url})`);
|
|
503
|
+
return {
|
|
504
|
+
content: await response.text(),
|
|
505
|
+
subInfo: parseSubscriptionUserinfo(response.headers.get("subscription-userinfo")),
|
|
506
|
+
fileName: parseContentDispositionFilename(response.headers.get("content-disposition"))
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
function parseSubscriptionUserinfo(header) {
|
|
510
|
+
if (header === null || header === void 0 || header.trim().length === 0) return;
|
|
511
|
+
const fields = {};
|
|
512
|
+
for (const part of header.split(";")) {
|
|
513
|
+
const [rawKey, rawValue] = part.split("=");
|
|
514
|
+
if (rawKey === void 0 || rawValue === void 0) continue;
|
|
515
|
+
const key = rawKey.trim().toLowerCase();
|
|
516
|
+
const value = Number(rawValue.trim());
|
|
517
|
+
if (key.length > 0 && Number.isFinite(value)) fields[key] = value;
|
|
518
|
+
}
|
|
519
|
+
return {
|
|
520
|
+
upload: fields["upload"] ?? 0,
|
|
521
|
+
download: fields["download"] ?? 0,
|
|
522
|
+
total: fields["total"] ?? 0,
|
|
523
|
+
expire: fields["expire"] ?? 0
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
function parseContentDispositionFilename(header) {
|
|
527
|
+
if (header === null || header === void 0) return;
|
|
528
|
+
const extended = /filename\*\s*=\s*(?:UTF-8'')?([^;]+)/i.exec(header);
|
|
529
|
+
if (extended?.[1] !== void 0) {
|
|
530
|
+
const value = extended[1].trim().replace(/^["']|["']$/g, "");
|
|
531
|
+
try {
|
|
532
|
+
return decodeURIComponent(value) || void 0;
|
|
533
|
+
} catch {
|
|
534
|
+
return value || void 0;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const plain = /filename\s*=\s*("?)([^";]+)\1/i.exec(header);
|
|
538
|
+
if (plain?.[2] !== void 0) return plain[2].trim() || void 0;
|
|
539
|
+
}
|
|
540
|
+
//#endregion
|
|
541
|
+
//#region src/config/user-config.ts
|
|
542
|
+
const APP_CONFIG_DIR = "lynx-proxy";
|
|
543
|
+
const USER_CONFIG_FILE = "user.json";
|
|
544
|
+
const STATE_CONFIG_FILE = "state.json";
|
|
545
|
+
const PROFILE_DIR = "profile";
|
|
546
|
+
const LEGACY_CONFIG_PATH = "config.toml";
|
|
547
|
+
const DEFAULT_USER_CONFIG = { profile: "default" };
|
|
548
|
+
const PROFILE_EXTENSIONS$1 = [
|
|
549
|
+
".toml",
|
|
550
|
+
".yaml",
|
|
551
|
+
".yml",
|
|
552
|
+
".json"
|
|
553
|
+
];
|
|
554
|
+
function getLynxConfigHome() {
|
|
555
|
+
const xdgConfigHome = process.env["XDG_CONFIG_HOME"];
|
|
556
|
+
if (xdgConfigHome !== void 0 && xdgConfigHome.length > 0) return join(xdgConfigHome, APP_CONFIG_DIR);
|
|
557
|
+
return join(homedir(), ".config", APP_CONFIG_DIR);
|
|
558
|
+
}
|
|
559
|
+
function getDefaultUserConfigPath() {
|
|
560
|
+
return join(getLynxConfigHome(), USER_CONFIG_FILE);
|
|
561
|
+
}
|
|
562
|
+
function getDefaultStateConfigPath() {
|
|
563
|
+
return join(getLynxConfigHome(), STATE_CONFIG_FILE);
|
|
564
|
+
}
|
|
565
|
+
function getDefaultProfileDir() {
|
|
566
|
+
return join(getLynxConfigHome(), PROFILE_DIR);
|
|
567
|
+
}
|
|
568
|
+
function loadLynxUserConfig(userConfigPath = getDefaultUserConfigPath()) {
|
|
569
|
+
ensureDefaultUserConfig(userConfigPath);
|
|
570
|
+
const profile = asRecord$1(parseConfigFile(userConfigPath, readFileSync(userConfigPath, "utf8")), "user config")["profile"];
|
|
571
|
+
if (typeof profile !== "string" || profile.trim().length === 0) throw new ConfigError("user config profile must be a non-empty string");
|
|
572
|
+
return { profile: profile.trim() };
|
|
573
|
+
}
|
|
574
|
+
function ensureDefaultUserConfig(userConfigPath = getDefaultUserConfigPath()) {
|
|
575
|
+
mkdirSync(dirname(userConfigPath), { recursive: true });
|
|
576
|
+
mkdirSync(getDefaultProfileDir(), { recursive: true });
|
|
577
|
+
if (existsSync(userConfigPath)) return;
|
|
578
|
+
writeLynxUserConfig(DEFAULT_USER_CONFIG, userConfigPath);
|
|
579
|
+
}
|
|
580
|
+
function writeLynxUserConfig(config, userConfigPath = getDefaultUserConfigPath()) {
|
|
581
|
+
mkdirSync(dirname(userConfigPath), { recursive: true });
|
|
582
|
+
writeFileSync(userConfigPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
583
|
+
}
|
|
584
|
+
function loadLynxStateConfig(stateConfigPath = getDefaultStateConfigPath()) {
|
|
585
|
+
if (!existsSync(stateConfigPath)) return {
|
|
586
|
+
version: 1,
|
|
587
|
+
files: []
|
|
588
|
+
};
|
|
589
|
+
const object = asRecord$1(parseConfigFile(stateConfigPath, readFileSync(stateConfigPath, "utf8")), "state config");
|
|
590
|
+
const version = object["version"];
|
|
591
|
+
if (version !== void 0 && version !== 1) throw new ConfigError("state config version must be 1");
|
|
592
|
+
if (object["profiles"] !== void 0) return {
|
|
593
|
+
version: 1,
|
|
594
|
+
files: Object.entries(object.profiles).map(([name, legacyProfile]) => {
|
|
595
|
+
const profile = asRecord$1(legacyProfile, `state config profiles.${name}`);
|
|
596
|
+
const selected = [];
|
|
597
|
+
const user = asOptionalRecord(profile["user"], "user");
|
|
598
|
+
if (user !== void 0) {
|
|
599
|
+
const activeGroup = user["proxy-group"];
|
|
600
|
+
if (typeof activeGroup === "string") selected.push({
|
|
601
|
+
name: "GLOBAL",
|
|
602
|
+
now: activeGroup
|
|
603
|
+
});
|
|
604
|
+
const selections = asOptionalRecord(user["proxy-groups"], "user.proxy-groups");
|
|
605
|
+
if (selections !== void 0) {
|
|
606
|
+
for (const [groupName, proxyName] of Object.entries(selections)) if (typeof proxyName === "string") selected.push({
|
|
607
|
+
name: groupName,
|
|
608
|
+
now: proxyName
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
return {
|
|
613
|
+
name,
|
|
614
|
+
selected
|
|
615
|
+
};
|
|
616
|
+
})
|
|
617
|
+
};
|
|
618
|
+
const filesRaw = object["files"];
|
|
619
|
+
if (!Array.isArray(filesRaw)) return {
|
|
620
|
+
version: 1,
|
|
621
|
+
files: []
|
|
622
|
+
};
|
|
623
|
+
return {
|
|
624
|
+
version: 1,
|
|
625
|
+
files: filesRaw.map((item, index) => {
|
|
626
|
+
const entry = asRecord$1(item, `state config files[${index}]`);
|
|
627
|
+
const name = entry["name"];
|
|
628
|
+
if (typeof name !== "string" || name.trim().length === 0) throw new ConfigError(`state config files[${index}].name must be a non-empty string`);
|
|
629
|
+
const selectedRaw = entry["selected"];
|
|
630
|
+
const selected = Array.isArray(selectedRaw) ? selectedRaw.map((sel, selIndex) => {
|
|
631
|
+
const selObj = asRecord$1(sel, `state config files[${index}].selected[${selIndex}]`);
|
|
632
|
+
const selName = selObj["name"];
|
|
633
|
+
const now = selObj["now"];
|
|
634
|
+
if (typeof selName === "string" && typeof now === "string") return {
|
|
635
|
+
name: selName,
|
|
636
|
+
now
|
|
637
|
+
};
|
|
638
|
+
return null;
|
|
639
|
+
}).filter((sel) => sel !== null) : [];
|
|
640
|
+
const time = typeof entry["time"] === "string" ? entry["time"] : void 0;
|
|
641
|
+
const url = typeof entry["url"] === "string" ? entry["url"] : void 0;
|
|
642
|
+
const interval = typeof entry["interval"] === "number" ? entry["interval"] : void 0;
|
|
643
|
+
const mode = typeof entry["mode"] === "string" && [
|
|
644
|
+
"global",
|
|
645
|
+
"rule",
|
|
646
|
+
"direct",
|
|
647
|
+
"script"
|
|
648
|
+
].includes(entry["mode"]) ? entry["mode"] : void 0;
|
|
649
|
+
const cron = typeof entry["cron"] === "string" ? entry["cron"] : void 0;
|
|
650
|
+
const headers = typeof entry["headers"] === "string" ? entry["headers"] : void 0;
|
|
651
|
+
const homeWeb = typeof entry["homeWeb"] === "string" ? entry["homeWeb"] : void 0;
|
|
652
|
+
const subInfo = entry["subInfo"];
|
|
653
|
+
return {
|
|
654
|
+
name,
|
|
655
|
+
time,
|
|
656
|
+
url,
|
|
657
|
+
selected,
|
|
658
|
+
interval,
|
|
659
|
+
subInfo: subInfo !== void 0 && typeof subInfo === "object" && subInfo !== null ? {
|
|
660
|
+
upload: subInfo["upload"],
|
|
661
|
+
download: subInfo["download"],
|
|
662
|
+
total: subInfo["total"],
|
|
663
|
+
expire: subInfo["expire"]
|
|
664
|
+
} : void 0,
|
|
665
|
+
homeWeb,
|
|
666
|
+
mode,
|
|
667
|
+
cron,
|
|
668
|
+
headers
|
|
669
|
+
};
|
|
670
|
+
})
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
function writeLynxStateConfig(config, stateConfigPath = getDefaultStateConfigPath()) {
|
|
674
|
+
mkdirSync(dirname(stateConfigPath), { recursive: true });
|
|
675
|
+
writeFileSync(stateConfigPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
676
|
+
}
|
|
677
|
+
function findProfileStateEntry(state, profileName) {
|
|
678
|
+
return state.files.find((entry) => entry.name === profileName);
|
|
679
|
+
}
|
|
680
|
+
function selectedToProxySelection(selected) {
|
|
681
|
+
const user = {};
|
|
682
|
+
const proxyGroups = {};
|
|
683
|
+
for (const item of selected) proxyGroups[item.name] = item.now;
|
|
684
|
+
if (Object.keys(proxyGroups).length > 0) user["proxy-groups"] = proxyGroups;
|
|
685
|
+
return user;
|
|
686
|
+
}
|
|
687
|
+
function getProfileStateKey(profilePath) {
|
|
688
|
+
return basename(profilePath);
|
|
689
|
+
}
|
|
690
|
+
function updateProfileState(profilePath, updater) {
|
|
691
|
+
const stateConfig = loadLynxStateConfig();
|
|
692
|
+
const profileName = getProfileStateKey(profilePath);
|
|
693
|
+
const existingIndex = stateConfig.files.findIndex((entry) => entry.name === profileName);
|
|
694
|
+
const nextState = updater(existingIndex >= 0 ? stateConfig.files[existingIndex] : {
|
|
695
|
+
name: profileName,
|
|
696
|
+
selected: []
|
|
697
|
+
});
|
|
698
|
+
if (existingIndex >= 0) stateConfig.files[existingIndex] = nextState;
|
|
699
|
+
else stateConfig.files.push(nextState);
|
|
700
|
+
writeLynxStateConfig(stateConfig);
|
|
701
|
+
return nextState;
|
|
702
|
+
}
|
|
703
|
+
function loadEffectiveProfileConfig(profilePath) {
|
|
704
|
+
const object = asRecord$1(parseConfigFile(profilePath, readFileSync(profilePath, "utf8")), "profile config");
|
|
705
|
+
const profileName = getProfileStateKey(profilePath);
|
|
706
|
+
const stateEntry = findProfileStateEntry(loadLynxStateConfig(), profileName);
|
|
707
|
+
return loadConfigFromRaw(applyProfileState(object, stateEntry?.selected !== void 0 && stateEntry.selected.length > 0 ? selectedToProxySelection(stateEntry.selected) : void 0));
|
|
708
|
+
}
|
|
709
|
+
function resolveProfilePath(profile, profileDir = getDefaultProfileDir()) {
|
|
710
|
+
validateProfileName(profile);
|
|
711
|
+
const ext = extname(profile);
|
|
712
|
+
if (ext.length > 0) {
|
|
713
|
+
if (!isSupportedProfileExtension(ext)) throw new ConfigError(`Unsupported profile file extension: ${ext}`);
|
|
714
|
+
const profilePath = join(profileDir, profile);
|
|
715
|
+
if (!existsSync(profilePath)) throw new ConfigError(`Profile "${profile}" was not found: ${profilePath}`);
|
|
716
|
+
return profilePath;
|
|
717
|
+
}
|
|
718
|
+
const candidates = PROFILE_EXTENSIONS$1.map((extension) => join(profileDir, `${profile}${extension}`));
|
|
719
|
+
const existing = candidates.filter((candidate) => existsSync(candidate));
|
|
720
|
+
if (existing.length === 1) {
|
|
721
|
+
const [profilePath] = existing;
|
|
722
|
+
if (profilePath === void 0) throw new ConfigError(`Profile "${profile}" was not found`);
|
|
723
|
+
return profilePath;
|
|
724
|
+
}
|
|
725
|
+
if (existing.length > 1) throw new ConfigError(`Profile "${profile}" is ambiguous. Multiple files exist: ${existing.join(", ")}. Specify the extension in user.json.`);
|
|
726
|
+
throw new ConfigError(`Profile "${profile}" was not found in ${profileDir}. Searched: ${candidates.join(", ")}`);
|
|
727
|
+
}
|
|
728
|
+
function loadConfigFromUserProfile(userConfigPath = getDefaultUserConfigPath()) {
|
|
729
|
+
const profilePath = resolveProfilePath(loadLynxUserConfig(userConfigPath).profile, getDefaultProfileDir());
|
|
730
|
+
return {
|
|
731
|
+
config: loadEffectiveProfileConfig(profilePath),
|
|
732
|
+
profilePath
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
function loadDefaultConfigWithPath() {
|
|
736
|
+
const userConfigPath = getDefaultUserConfigPath();
|
|
737
|
+
if (existsSync(userConfigPath)) return loadConfigFromUserProfile(userConfigPath);
|
|
738
|
+
if (existsSync(LEGACY_CONFIG_PATH)) return { config: loadConfig(LEGACY_CONFIG_PATH) };
|
|
739
|
+
ensureDefaultUserConfig(userConfigPath);
|
|
740
|
+
throw new ConfigError(`Created default user config: ${userConfigPath}. Add a Clash-style profile with 'lynx config add <name> --file <path>' (or --url / --template), then select it with 'lynx config use <profile>'. Expected profile file: ${getDefaultProfileDir()}/${DEFAULT_USER_CONFIG.profile}.toml (or .yaml/.json).`);
|
|
741
|
+
}
|
|
742
|
+
function asOptionalRecord(raw, field) {
|
|
743
|
+
if (raw === void 0) return;
|
|
744
|
+
return asRecord$1(raw, field);
|
|
745
|
+
}
|
|
746
|
+
function asRecord$1(value, field) {
|
|
747
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ConfigError(`${field} must be a table`);
|
|
748
|
+
return value;
|
|
749
|
+
}
|
|
750
|
+
function validateProfileName(profile) {
|
|
751
|
+
if (profile.length === 0) throw new ConfigError("profile must be a non-empty string");
|
|
752
|
+
if (isAbsolute(profile) || profile.includes("/") || profile.includes("\\") || profile.includes("\0") || profile === "." || profile === ".." || basename(profile) !== profile) throw new ConfigError(`profile must be a file name under ${getDefaultProfileDir()}, not a path: ${profile}`);
|
|
753
|
+
}
|
|
754
|
+
function isSupportedProfileExtension(ext) {
|
|
755
|
+
return PROFILE_EXTENSIONS$1.includes(ext);
|
|
756
|
+
}
|
|
757
|
+
//#endregion
|
|
758
|
+
//#region src/cli/config-cli.ts
|
|
759
|
+
const PROFILE_EXTENSIONS = new Set([
|
|
760
|
+
".toml",
|
|
761
|
+
".yaml",
|
|
762
|
+
".yml",
|
|
763
|
+
".json"
|
|
764
|
+
]);
|
|
765
|
+
const DEFAULT_TEMPLATE = {
|
|
766
|
+
port: 8080,
|
|
767
|
+
"allow-lan": false,
|
|
768
|
+
mode: "rule",
|
|
769
|
+
"log-level": "debug",
|
|
770
|
+
"access-log": true,
|
|
771
|
+
proxies: [],
|
|
772
|
+
"proxy-groups": [{
|
|
773
|
+
name: "default",
|
|
774
|
+
type: "select",
|
|
775
|
+
proxies: ["DIRECT"]
|
|
776
|
+
}],
|
|
777
|
+
rules: ["MATCH,DIRECT"]
|
|
778
|
+
};
|
|
779
|
+
async function runConfigCommand(args) {
|
|
780
|
+
const [command, ...rest] = args;
|
|
781
|
+
if (command === void 0 || command === "--help" || command === "-h") {
|
|
782
|
+
console.log(createConfigHelpText());
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
if (command === "list") {
|
|
786
|
+
listProfiles();
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
if (command === "current") {
|
|
790
|
+
showCurrentConfig();
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
if (command === "use") {
|
|
794
|
+
useProfile(requireArg$1(rest[0], "profile"));
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
if (command === "add") {
|
|
798
|
+
await addProfile(rest);
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
if (command === "update") {
|
|
802
|
+
await updateProfile(rest);
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
if (command === "info") {
|
|
806
|
+
showSubscriptionInfo(rest);
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
if (command === "show") {
|
|
810
|
+
showProfile(rest);
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
if (command === "remove") {
|
|
814
|
+
removeProfile(requireArg$1(rest[0], "profile"));
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
if (command === "path") {
|
|
818
|
+
showConfigPaths();
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
throw new Error(`Unknown config command: ${command}`);
|
|
822
|
+
}
|
|
823
|
+
function listProfiles() {
|
|
824
|
+
ensureDefaultUserConfig();
|
|
825
|
+
const profileDir = getDefaultProfileDir();
|
|
826
|
+
const current = loadLynxUserConfig().profile;
|
|
827
|
+
const entries = readdirSync(profileDir, { withFileTypes: true }).filter((entry) => entry.isFile()).map((entry) => entry.name).filter((name) => PROFILE_EXTENSIONS.has(extname(name))).sort();
|
|
828
|
+
if (entries.length === 0) {
|
|
829
|
+
console.log(`No profiles found in ${profileDir}`);
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
for (const entry of entries) {
|
|
833
|
+
const stem = stripSupportedExtension(entry);
|
|
834
|
+
console.log(`${current === entry || current === stem ? "*" : " "} ${entry}`);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
function showCurrentConfig() {
|
|
838
|
+
ensureDefaultUserConfig();
|
|
839
|
+
const userConfig = loadLynxUserConfig();
|
|
840
|
+
console.log(`user config: ${getDefaultUserConfigPath()}`);
|
|
841
|
+
console.log(`state config: ${getDefaultStateConfigPath()}`);
|
|
842
|
+
console.log(`profile: ${userConfig.profile}`);
|
|
843
|
+
console.log(`profile dir: ${getDefaultProfileDir()}`);
|
|
844
|
+
try {
|
|
845
|
+
const profilePath = resolveProfilePath(userConfig.profile);
|
|
846
|
+
const config = loadEffectiveProfileConfig(profilePath);
|
|
847
|
+
console.log(`profile path: ${profilePath}`);
|
|
848
|
+
console.log(`state key: ${getProfileStateKey(profilePath)}`);
|
|
849
|
+
console.log(`effective listen: ${config.server.host}:${config.server.port}`);
|
|
850
|
+
const globalSelection = config.user.proxyGroupSelections["GLOBAL"];
|
|
851
|
+
console.log(`global proxy: ${globalSelection ?? "(not set)"}`);
|
|
852
|
+
const entries = Object.entries(config.user.proxyGroupSelections).filter(([group]) => group !== "GLOBAL");
|
|
853
|
+
if (entries.length === 0) console.log("selections: (none)");
|
|
854
|
+
else {
|
|
855
|
+
console.log("selections:");
|
|
856
|
+
for (const [group, proxy] of entries) console.log(` ${group}: ${proxy}`);
|
|
857
|
+
}
|
|
858
|
+
} catch (error) {
|
|
859
|
+
console.log(`profile path: ${error instanceof Error ? error.message : String(error)}`);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
function useProfile(profile) {
|
|
863
|
+
loadConfig(resolveProfilePath(profile));
|
|
864
|
+
writeLynxUserConfig({ profile });
|
|
865
|
+
console.log(`Using profile: ${profile}`);
|
|
866
|
+
}
|
|
867
|
+
async function addProfile(args) {
|
|
868
|
+
const name = requireArg$1(args[0], "name");
|
|
869
|
+
const fileIndex = args.indexOf("--file");
|
|
870
|
+
const urlIndex = args.indexOf("--url");
|
|
871
|
+
const useTemplate = args.includes("--template");
|
|
872
|
+
const userAgentIndex = args.indexOf("--user-agent");
|
|
873
|
+
const userAgent = userAgentIndex === -1 ? void 0 : requireArg$1(args[userAgentIndex + 1], "user-agent");
|
|
874
|
+
const sourceCount = (fileIndex === -1 ? 0 : 1) + (urlIndex === -1 ? 0 : 1) + (useTemplate ? 1 : 0);
|
|
875
|
+
if (sourceCount === 0) throw new Error("config add requires --file <path>, --url <url>, or --template");
|
|
876
|
+
if (sourceCount > 1) throw new Error("config add accepts only one of --file, --url, or --template");
|
|
877
|
+
if (urlIndex !== -1) {
|
|
878
|
+
await addProfileFromUrl(name, requireArg$1(args[urlIndex + 1], "url"), userAgent);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
const source = fileIndex === -1 ? void 0 : requireArg$1(args[fileIndex + 1], "file");
|
|
882
|
+
const ext = extname(name) || (source === void 0 ? ".toml" : extname(source));
|
|
883
|
+
if (!PROFILE_EXTENSIONS.has(ext)) throw new ConfigError(`Unsupported profile file extension: ${ext}`);
|
|
884
|
+
const fileName = extname(name) ? name : `${name}${ext}`;
|
|
885
|
+
ensureProfileFileName(fileName);
|
|
886
|
+
mkdirSync(getDefaultProfileDir(), { recursive: true });
|
|
887
|
+
const targetPath = join(getDefaultProfileDir(), fileName);
|
|
888
|
+
if (existsSync(targetPath)) throw new ConfigError(`Profile already exists: ${targetPath}`);
|
|
889
|
+
if (source === void 0) writeFileSync(targetPath, serializeTemplate(targetPath), "utf8");
|
|
890
|
+
else {
|
|
891
|
+
loadConfig(source);
|
|
892
|
+
copyFileSync(source, targetPath);
|
|
893
|
+
}
|
|
894
|
+
loadConfig(targetPath);
|
|
895
|
+
console.log(`Added profile: ${targetPath}`);
|
|
896
|
+
}
|
|
897
|
+
async function addProfileFromUrl(name, url, userAgent) {
|
|
898
|
+
const ext = extname(name) || ".yaml";
|
|
899
|
+
if (!PROFILE_EXTENSIONS.has(ext)) throw new ConfigError(`Unsupported profile file extension: ${ext}`);
|
|
900
|
+
const fileName = extname(name) ? name : `${name}${ext}`;
|
|
901
|
+
ensureProfileFileName(fileName);
|
|
902
|
+
mkdirSync(getDefaultProfileDir(), { recursive: true });
|
|
903
|
+
const targetPath = join(getDefaultProfileDir(), fileName);
|
|
904
|
+
if (existsSync(targetPath)) throw new ConfigError(`Profile already exists: ${targetPath}`);
|
|
905
|
+
const result = await fetchSubscription(url, { userAgent });
|
|
906
|
+
validateSubscriptionContent(result.content, ext);
|
|
907
|
+
writeFileSync(targetPath, result.content, "utf8");
|
|
908
|
+
updateProfileState(targetPath, (state) => ({
|
|
909
|
+
...state,
|
|
910
|
+
url,
|
|
911
|
+
time: nowIsoString(),
|
|
912
|
+
subInfo: result.subInfo ?? state.subInfo
|
|
913
|
+
}));
|
|
914
|
+
console.log(`Added subscription profile: ${targetPath}`);
|
|
915
|
+
console.log(` url: ${url}`);
|
|
916
|
+
}
|
|
917
|
+
async function updateProfile(args) {
|
|
918
|
+
const userAgentIndex = args.indexOf("--user-agent");
|
|
919
|
+
const cliUserAgent = userAgentIndex === -1 ? void 0 : requireArg$1(args[userAgentIndex + 1], "user-agent");
|
|
920
|
+
const name = args.filter((arg, index) => arg !== "--user-agent" && index !== userAgentIndex + 1)[0] ?? loadLynxUserConfig().profile;
|
|
921
|
+
const profilePath = resolveProfilePath(name);
|
|
922
|
+
const stateKey = getProfileStateKey(profilePath);
|
|
923
|
+
const entry = findProfileStateEntry(loadLynxStateConfig(), stateKey);
|
|
924
|
+
const url = entry?.url;
|
|
925
|
+
if (url === void 0 || url.length === 0) throw new ConfigError(`Profile "${name}" is not a subscription (no url recorded in state.json). Use "config add ${name} --url <url>" first.`);
|
|
926
|
+
const ext = extname(profilePath);
|
|
927
|
+
const result = await fetchSubscription(url, { userAgent: cliUserAgent ?? entry?.headers });
|
|
928
|
+
validateSubscriptionContent(result.content, ext);
|
|
929
|
+
writeFileSync(profilePath, result.content, "utf8");
|
|
930
|
+
updateProfileState(profilePath, (state) => ({
|
|
931
|
+
...state,
|
|
932
|
+
time: nowIsoString(),
|
|
933
|
+
subInfo: result.subInfo ?? state.subInfo
|
|
934
|
+
}));
|
|
935
|
+
console.log(`Updated subscription profile: ${profilePath}`);
|
|
936
|
+
console.log("Run 'lynx proxy restart' to apply the new config.");
|
|
937
|
+
}
|
|
938
|
+
function showSubscriptionInfo(args) {
|
|
939
|
+
if (args.length > 1) throw new Error(`Unknown config info argument: ${args[1]}`);
|
|
940
|
+
const name = args[0] ?? loadLynxUserConfig().profile;
|
|
941
|
+
const stateKey = getProfileStateKey(resolveProfilePath(name));
|
|
942
|
+
const entry = findProfileStateEntry(loadLynxStateConfig(), stateKey);
|
|
943
|
+
if (entry?.url === void 0 || entry.url.length === 0) {
|
|
944
|
+
console.log(`Profile "${name}" is not a subscription (no url recorded).`);
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
console.log(`profile: ${stateKey}`);
|
|
948
|
+
console.log(`url: ${entry.url}`);
|
|
949
|
+
console.log(`updated: ${entry.time ?? "(never)"}`);
|
|
950
|
+
const subInfo = entry.subInfo;
|
|
951
|
+
if (subInfo === void 0) {
|
|
952
|
+
console.log("traffic: (unknown)");
|
|
953
|
+
console.log("expire: (unknown)");
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
const used = subInfo.upload + subInfo.download;
|
|
957
|
+
console.log(`traffic: ${formatBytes(used)} / ${formatBytes(subInfo.total)}`);
|
|
958
|
+
console.log(`expire: ${formatExpire(subInfo.expire)}`);
|
|
959
|
+
}
|
|
960
|
+
function showProfile(args) {
|
|
961
|
+
const effective = args.includes("--effective");
|
|
962
|
+
const rest = args.filter((arg) => arg !== "--effective");
|
|
963
|
+
if (rest.length > 1) throw new Error(`Unknown config show argument: ${rest[1]}`);
|
|
964
|
+
const profilePath = resolveProfilePath(rest[0] ?? loadLynxUserConfig().profile);
|
|
965
|
+
if (!effective) {
|
|
966
|
+
console.log(readFileSync(profilePath, "utf8"));
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
console.log(`${JSON.stringify(loadEffectiveProfileConfig(profilePath), null, 2)}\n`);
|
|
970
|
+
}
|
|
971
|
+
function removeProfile(profile) {
|
|
972
|
+
const userConfig = loadLynxUserConfig();
|
|
973
|
+
const profilePath = resolveProfilePath(profile);
|
|
974
|
+
const fileName = basename(profilePath);
|
|
975
|
+
if (userConfig.profile === profile || userConfig.profile === fileName) throw new ConfigError("Cannot remove the active profile. Switch profiles first.");
|
|
976
|
+
rmSync(profilePath);
|
|
977
|
+
console.log(`Removed profile: ${profilePath}`);
|
|
978
|
+
}
|
|
979
|
+
function showConfigPaths() {
|
|
980
|
+
ensureDefaultUserConfig();
|
|
981
|
+
console.log(`config home: ${getLynxConfigHome()}`);
|
|
982
|
+
console.log(`user config: ${getDefaultUserConfigPath()}`);
|
|
983
|
+
console.log(`state config: ${getDefaultStateConfigPath()}`);
|
|
984
|
+
console.log(`profile dir: ${getDefaultProfileDir()}`);
|
|
985
|
+
}
|
|
986
|
+
function serializeTemplate(path) {
|
|
987
|
+
const ext = extname(path);
|
|
988
|
+
if (ext === ".json") return `${JSON.stringify(DEFAULT_TEMPLATE, null, 2)}\n`;
|
|
989
|
+
if (ext === ".toml") return stringify(DEFAULT_TEMPLATE);
|
|
990
|
+
if (ext === ".yaml" || ext === ".yml") return dump(DEFAULT_TEMPLATE);
|
|
991
|
+
throw new ConfigError(`Unsupported profile file extension: ${ext}`);
|
|
992
|
+
}
|
|
993
|
+
function validateSubscriptionContent(content, ext) {
|
|
994
|
+
loadConfigFromRaw(parseConfigFile(`subscription${ext}`, content));
|
|
995
|
+
}
|
|
996
|
+
function nowIsoString() {
|
|
997
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
998
|
+
}
|
|
999
|
+
function formatBytes(bytes) {
|
|
1000
|
+
if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
|
|
1001
|
+
const units = [
|
|
1002
|
+
"B",
|
|
1003
|
+
"KB",
|
|
1004
|
+
"MB",
|
|
1005
|
+
"GB",
|
|
1006
|
+
"TB",
|
|
1007
|
+
"PB"
|
|
1008
|
+
];
|
|
1009
|
+
let value = bytes;
|
|
1010
|
+
let unit = 0;
|
|
1011
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
1012
|
+
value /= 1024;
|
|
1013
|
+
unit += 1;
|
|
1014
|
+
}
|
|
1015
|
+
return `${unit === 0 ? value : Math.round(value * 100) / 100} ${units[unit]}`;
|
|
1016
|
+
}
|
|
1017
|
+
function formatExpire(expire) {
|
|
1018
|
+
if (!Number.isFinite(expire) || expire <= 0) return "(no expiry)";
|
|
1019
|
+
return (/* @__PURE__ */ new Date(expire * 1e3)).toISOString().slice(0, 10);
|
|
1020
|
+
}
|
|
1021
|
+
function stripSupportedExtension(fileName) {
|
|
1022
|
+
const ext = extname(fileName);
|
|
1023
|
+
return PROFILE_EXTENSIONS.has(ext) ? fileName.slice(0, -ext.length) : fileName;
|
|
1024
|
+
}
|
|
1025
|
+
function ensureProfileFileName(fileName) {
|
|
1026
|
+
if (fileName.length === 0 || fileName.includes("/") || fileName.includes("\\") || fileName.includes("\0") || basename(fileName) !== fileName) throw new ConfigError(`profile must be a file name, not a path: ${fileName}`);
|
|
1027
|
+
}
|
|
1028
|
+
function requireArg$1(value, name) {
|
|
1029
|
+
if (value === void 0 || value.length === 0) throw new Error(`Missing ${name}`);
|
|
1030
|
+
return value;
|
|
1031
|
+
}
|
|
1032
|
+
function createConfigHelpText() {
|
|
1033
|
+
return `Usage: lynx config <command> [options]
|
|
1034
|
+
|
|
1035
|
+
Commands:
|
|
1036
|
+
list List profile config files
|
|
1037
|
+
current Show active user config and resolved profile
|
|
1038
|
+
use <profile> Select active profile in user.json
|
|
1039
|
+
add <name> --file <path> Copy a profile config into the profile dir
|
|
1040
|
+
add <name> --template Create a Clash-style profile from the default template; extension controls TOML/YAML/JSON format
|
|
1041
|
+
add <name> --url <url> Fetch a subscription and save it as a profile (default .yaml); optional --user-agent <ua>
|
|
1042
|
+
update [profile] Re-fetch a subscription profile by its recorded url and overwrite it (defaults to active profile)
|
|
1043
|
+
info [profile] Show subscription url, last update time, traffic, and expiry
|
|
1044
|
+
show [profile] Print raw profile config
|
|
1045
|
+
show [profile] --effective Print resolved profile + state.json as JSON
|
|
1046
|
+
remove <profile> Remove an inactive profile
|
|
1047
|
+
path Show config paths`;
|
|
1048
|
+
}
|
|
1049
|
+
//#endregion
|
|
1050
|
+
//#region src/runtime/daemon-state.ts
|
|
1051
|
+
function getProxyDaemonStatePath() {
|
|
1052
|
+
return join(getLynxConfigHome(), "runtime", "proxy-daemon.json");
|
|
1053
|
+
}
|
|
1054
|
+
function getProxyDaemonLogPath() {
|
|
1055
|
+
return join(getLynxConfigHome(), "runtime", "proxy-daemon.log");
|
|
1056
|
+
}
|
|
1057
|
+
function getControlSocketPath() {
|
|
1058
|
+
return join(getLynxConfigHome(), "runtime", "control.sock");
|
|
1059
|
+
}
|
|
1060
|
+
function loadProxyDaemonState(path = getProxyDaemonStatePath()) {
|
|
1061
|
+
if (!existsSync(path)) return;
|
|
1062
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
1063
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("proxy daemon state must be an object");
|
|
1064
|
+
const object = raw;
|
|
1065
|
+
if (object["version"] !== 1) throw new Error("proxy daemon state version must be 1");
|
|
1066
|
+
const pid = object["pid"];
|
|
1067
|
+
const host = object["host"];
|
|
1068
|
+
const port = object["port"];
|
|
1069
|
+
const startedAt = object["startedAt"];
|
|
1070
|
+
const logFile = object["logFile"];
|
|
1071
|
+
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) throw new Error("proxy daemon state pid must be a positive integer");
|
|
1072
|
+
if (typeof host !== "string" || host.length === 0) throw new Error("proxy daemon state host must be a non-empty string");
|
|
1073
|
+
if (typeof port !== "number" || !Number.isInteger(port) || port <= 0) throw new Error("proxy daemon state port must be a positive integer");
|
|
1074
|
+
if (typeof startedAt !== "string" || startedAt.length === 0) throw new Error("proxy daemon state startedAt must be a non-empty string");
|
|
1075
|
+
if (typeof logFile !== "string" || logFile.length === 0) throw new Error("proxy daemon state logFile must be a non-empty string");
|
|
1076
|
+
const state = {
|
|
1077
|
+
version: 1,
|
|
1078
|
+
pid,
|
|
1079
|
+
host,
|
|
1080
|
+
port,
|
|
1081
|
+
startedAt,
|
|
1082
|
+
logFile
|
|
1083
|
+
};
|
|
1084
|
+
if (typeof object["profile"] === "string") state.profile = object["profile"];
|
|
1085
|
+
if (typeof object["profilePath"] === "string") state.profilePath = object["profilePath"];
|
|
1086
|
+
return state;
|
|
1087
|
+
}
|
|
1088
|
+
function writeProxyDaemonState(state, path = getProxyDaemonStatePath()) {
|
|
1089
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
1090
|
+
writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, "utf8");
|
|
1091
|
+
}
|
|
1092
|
+
function removeProxyDaemonState(path = getProxyDaemonStatePath()) {
|
|
1093
|
+
rmSync(path, { force: true });
|
|
1094
|
+
}
|
|
1095
|
+
function isProcessRunning(pid) {
|
|
1096
|
+
try {
|
|
1097
|
+
process.kill(pid, 0);
|
|
1098
|
+
return true;
|
|
1099
|
+
} catch (error) {
|
|
1100
|
+
return (typeof error === "object" && error !== null ? error.code : void 0) === "EPERM";
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
//#endregion
|
|
1104
|
+
//#region src/runtime/control.ts
|
|
1105
|
+
const SUPPORTED_MODES = [
|
|
1106
|
+
"rule",
|
|
1107
|
+
"global",
|
|
1108
|
+
"direct",
|
|
1109
|
+
"script"
|
|
1110
|
+
];
|
|
1111
|
+
/**
|
|
1112
|
+
* 在 Unix domain socket 上监听控制命令,按逐行 JSON 解析并应用到运行中的 ProxyServer。
|
|
1113
|
+
* 非 Unix 平台(不支持 Unix domain socket)下返回 undefined,由调用方降级。
|
|
1114
|
+
*/
|
|
1115
|
+
async function startControlServer(proxy, config, socketPath = getControlSocketPath()) {
|
|
1116
|
+
if (process.platform === "win32") return;
|
|
1117
|
+
await prepareSocketPath(socketPath);
|
|
1118
|
+
const server = createServer((socket) => {
|
|
1119
|
+
handleConnection(socket, proxy, config);
|
|
1120
|
+
});
|
|
1121
|
+
return new Promise((resolve, reject) => {
|
|
1122
|
+
const onError = (error) => {
|
|
1123
|
+
server.removeListener("listening", onListening);
|
|
1124
|
+
reject(error);
|
|
1125
|
+
};
|
|
1126
|
+
const onListening = () => {
|
|
1127
|
+
server.removeListener("error", onError);
|
|
1128
|
+
resolve(new NodeControlServer(server, socketPath));
|
|
1129
|
+
};
|
|
1130
|
+
server.once("error", onError);
|
|
1131
|
+
server.once("listening", onListening);
|
|
1132
|
+
mkdirSync(dirname(socketPath), { recursive: true });
|
|
1133
|
+
server.listen(socketPath);
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
var NodeControlServer = class {
|
|
1137
|
+
server;
|
|
1138
|
+
socketPath;
|
|
1139
|
+
constructor(server, socketPath) {
|
|
1140
|
+
this.server = server;
|
|
1141
|
+
this.socketPath = socketPath;
|
|
1142
|
+
}
|
|
1143
|
+
close() {
|
|
1144
|
+
return new Promise((resolve) => {
|
|
1145
|
+
this.server.close(() => {
|
|
1146
|
+
rmSync(this.socketPath, { force: true });
|
|
1147
|
+
resolve();
|
|
1148
|
+
});
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
};
|
|
1152
|
+
/**
|
|
1153
|
+
* 启动监听前处理残留 socket 文件:先尝试连接,连得上说明已有 daemon 在跑(抛错),
|
|
1154
|
+
* 连不上则删除残留文件后允许重新监听。
|
|
1155
|
+
*/
|
|
1156
|
+
async function prepareSocketPath(socketPath) {
|
|
1157
|
+
if (!existsSync(socketPath)) return;
|
|
1158
|
+
if (await isSocketAlive(socketPath)) throw new Error(`Control socket already in use by a running daemon: ${socketPath}`);
|
|
1159
|
+
rmSync(socketPath, { force: true });
|
|
1160
|
+
}
|
|
1161
|
+
function isSocketAlive(socketPath) {
|
|
1162
|
+
return new Promise((resolve) => {
|
|
1163
|
+
const probe = createConnection(socketPath);
|
|
1164
|
+
const done = (alive) => {
|
|
1165
|
+
probe.destroy();
|
|
1166
|
+
resolve(alive);
|
|
1167
|
+
};
|
|
1168
|
+
probe.once("connect", () => done(true));
|
|
1169
|
+
probe.once("error", () => done(false));
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
function handleConnection(socket, proxy, config) {
|
|
1173
|
+
let buffer = "";
|
|
1174
|
+
socket.setEncoding("utf8");
|
|
1175
|
+
socket.on("data", (chunk) => {
|
|
1176
|
+
buffer += chunk;
|
|
1177
|
+
let newlineIndex = buffer.indexOf("\n");
|
|
1178
|
+
while (newlineIndex !== -1) {
|
|
1179
|
+
const line = buffer.slice(0, newlineIndex);
|
|
1180
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
1181
|
+
const response = processLine(line, proxy, config);
|
|
1182
|
+
socket.write(`${JSON.stringify(response)}\n`);
|
|
1183
|
+
newlineIndex = buffer.indexOf("\n");
|
|
1184
|
+
}
|
|
1185
|
+
});
|
|
1186
|
+
socket.on("error", () => {
|
|
1187
|
+
socket.destroy();
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
function processLine(line, proxy, config) {
|
|
1191
|
+
const trimmed = line.trim();
|
|
1192
|
+
if (trimmed.length === 0) return {
|
|
1193
|
+
ok: false,
|
|
1194
|
+
error: "empty command"
|
|
1195
|
+
};
|
|
1196
|
+
let command;
|
|
1197
|
+
try {
|
|
1198
|
+
command = JSON.parse(trimmed);
|
|
1199
|
+
} catch {
|
|
1200
|
+
return {
|
|
1201
|
+
ok: false,
|
|
1202
|
+
error: "invalid JSON command"
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
return applyCommand(command, proxy, config);
|
|
1206
|
+
}
|
|
1207
|
+
function applyCommand(command, proxy, config) {
|
|
1208
|
+
switch (command.cmd) {
|
|
1209
|
+
case "query": return {
|
|
1210
|
+
ok: true,
|
|
1211
|
+
state: proxy.getSnapshot()
|
|
1212
|
+
};
|
|
1213
|
+
case "setMode": return applySetMode(command.mode, proxy);
|
|
1214
|
+
case "useGroup": return applyUseGroup(command.group, proxy, config);
|
|
1215
|
+
case "selectGroup": return applySelectGroup(command.group, command.proxy, proxy, config);
|
|
1216
|
+
case "unsetGroup": return applyUnsetGroup(command.group, proxy, config);
|
|
1217
|
+
default: return {
|
|
1218
|
+
ok: false,
|
|
1219
|
+
error: `unknown command: ${String(command.cmd)}`
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
function applySetMode(mode, proxy) {
|
|
1224
|
+
if (mode === void 0 || !SUPPORTED_MODES.includes(mode)) return {
|
|
1225
|
+
ok: false,
|
|
1226
|
+
error: `unsupported mode: ${String(mode)}`
|
|
1227
|
+
};
|
|
1228
|
+
proxy.setMode(mode);
|
|
1229
|
+
return {
|
|
1230
|
+
ok: true,
|
|
1231
|
+
state: proxy.getSnapshot()
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
function applyUseGroup(group, proxy, config) {
|
|
1235
|
+
if (group === void 0) return {
|
|
1236
|
+
ok: false,
|
|
1237
|
+
error: "missing group"
|
|
1238
|
+
};
|
|
1239
|
+
if (!groupExists(config, group)) return {
|
|
1240
|
+
ok: false,
|
|
1241
|
+
error: `unknown proxy-group: ${group}`
|
|
1242
|
+
};
|
|
1243
|
+
proxy.setGlobalProxy(group);
|
|
1244
|
+
return {
|
|
1245
|
+
ok: true,
|
|
1246
|
+
state: proxy.getSnapshot()
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
function applySelectGroup(group, selected, proxy, config) {
|
|
1250
|
+
if (group === void 0 || selected === void 0) return {
|
|
1251
|
+
ok: false,
|
|
1252
|
+
error: "missing group or proxy"
|
|
1253
|
+
};
|
|
1254
|
+
const members = groupMembers(config, group);
|
|
1255
|
+
if (members === void 0) return {
|
|
1256
|
+
ok: false,
|
|
1257
|
+
error: `unknown proxy-group: ${group}`
|
|
1258
|
+
};
|
|
1259
|
+
if (!members.includes(selected)) return {
|
|
1260
|
+
ok: false,
|
|
1261
|
+
error: `proxy-group ${group} does not contain selectable proxy: ${selected}`
|
|
1262
|
+
};
|
|
1263
|
+
proxy.selectGroup(group, selected);
|
|
1264
|
+
return {
|
|
1265
|
+
ok: true,
|
|
1266
|
+
state: proxy.getSnapshot()
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
function applyUnsetGroup(group, proxy, config) {
|
|
1270
|
+
if (group === void 0) return {
|
|
1271
|
+
ok: false,
|
|
1272
|
+
error: "missing group"
|
|
1273
|
+
};
|
|
1274
|
+
if (!groupExists(config, group)) return {
|
|
1275
|
+
ok: false,
|
|
1276
|
+
error: `unknown proxy-group: ${group}`
|
|
1277
|
+
};
|
|
1278
|
+
proxy.unsetGroup(group);
|
|
1279
|
+
return {
|
|
1280
|
+
ok: true,
|
|
1281
|
+
state: proxy.getSnapshot()
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
function groupExists(config, group) {
|
|
1285
|
+
return config.proxyGroups.some((g) => g.name === group);
|
|
1286
|
+
}
|
|
1287
|
+
function groupMembers(config, group) {
|
|
1288
|
+
return config.proxyGroups.find((g) => g.name === group)?.proxies;
|
|
1289
|
+
}
|
|
1290
|
+
/**
|
|
1291
|
+
* CLI 端:连接控制 socket 发送一条命令并返回响应。
|
|
1292
|
+
* daemon 未运行(socket 不存在或拒绝连接)时返回 undefined,由调用方降级为"仅写盘"。
|
|
1293
|
+
*/
|
|
1294
|
+
function sendControlCommand(command, socketPath = getControlSocketPath()) {
|
|
1295
|
+
if (!existsSync(socketPath)) return Promise.resolve(void 0);
|
|
1296
|
+
return new Promise((resolve, reject) => {
|
|
1297
|
+
const socket = createConnection(socketPath);
|
|
1298
|
+
let buffer = "";
|
|
1299
|
+
socket.setEncoding("utf8");
|
|
1300
|
+
socket.on("connect", () => {
|
|
1301
|
+
socket.write(`${JSON.stringify(command)}\n`);
|
|
1302
|
+
});
|
|
1303
|
+
socket.on("data", (chunk) => {
|
|
1304
|
+
buffer += chunk;
|
|
1305
|
+
const newlineIndex = buffer.indexOf("\n");
|
|
1306
|
+
if (newlineIndex !== -1) {
|
|
1307
|
+
const line = buffer.slice(0, newlineIndex);
|
|
1308
|
+
socket.end();
|
|
1309
|
+
try {
|
|
1310
|
+
resolve(JSON.parse(line));
|
|
1311
|
+
} catch {
|
|
1312
|
+
resolve(void 0);
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
});
|
|
1316
|
+
socket.on("error", (error) => {
|
|
1317
|
+
if (error.code === "ECONNREFUSED" || error.code === "ENOENT") {
|
|
1318
|
+
resolve(void 0);
|
|
1319
|
+
return;
|
|
1320
|
+
}
|
|
1321
|
+
reject(error);
|
|
1322
|
+
});
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* 检测控制 socket 是否有 daemon 在监听(供 proxy status 报告)。
|
|
1327
|
+
*/
|
|
1328
|
+
function isControlSocketReady(socketPath = getControlSocketPath()) {
|
|
1329
|
+
if (!existsSync(socketPath)) return Promise.resolve(false);
|
|
1330
|
+
return new Promise((resolve) => {
|
|
1331
|
+
const probe = createConnection(socketPath);
|
|
1332
|
+
const done = (ready) => {
|
|
1333
|
+
probe.destroy();
|
|
1334
|
+
resolve(ready);
|
|
1335
|
+
};
|
|
1336
|
+
probe.once("connect", () => done(true));
|
|
1337
|
+
probe.once("error", () => done(false));
|
|
1338
|
+
});
|
|
1339
|
+
}
|
|
1340
|
+
//#endregion
|
|
1341
|
+
//#region src/cli/groups-cli.ts
|
|
1342
|
+
async function runGroupsCommand(args) {
|
|
1343
|
+
const [command, ...rest] = args;
|
|
1344
|
+
if (command === void 0 || command === "--help" || command === "-h") {
|
|
1345
|
+
console.log(createGroupsHelpText());
|
|
1346
|
+
return;
|
|
1347
|
+
}
|
|
1348
|
+
if (command === "list") {
|
|
1349
|
+
listGroups(parseOptions(rest).profile);
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
if (command === "current") {
|
|
1353
|
+
await showCurrentGroups(parseOptions(rest).profile);
|
|
1354
|
+
return;
|
|
1355
|
+
}
|
|
1356
|
+
if (command === "use") {
|
|
1357
|
+
const options = parseOptions(rest);
|
|
1358
|
+
await useGroup(requireArg(options.rest[0], "group"), options.profile);
|
|
1359
|
+
return;
|
|
1360
|
+
}
|
|
1361
|
+
if (command === "select") {
|
|
1362
|
+
const options = parseOptions(rest);
|
|
1363
|
+
await selectGroupProxy(requireArg(options.rest[0], "group"), requireArg(options.rest[1], "proxy"), options.profile);
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
if (command === "mode") {
|
|
1367
|
+
const options = parseOptions(rest);
|
|
1368
|
+
await setRuntimeMode(requireArg(options.rest[0], "mode"), options.profile);
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1371
|
+
if (command === "unset") {
|
|
1372
|
+
const options = parseOptions(rest);
|
|
1373
|
+
await unsetGroupSelection(requireArg(options.rest[0], "group"), options.profile);
|
|
1374
|
+
return;
|
|
1375
|
+
}
|
|
1376
|
+
if (command === "rule") {
|
|
1377
|
+
runRuleCommand(rest);
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
throw new Error(`Unknown groups command: ${command}`);
|
|
1381
|
+
}
|
|
1382
|
+
function listGroups(profile) {
|
|
1383
|
+
const context = loadProfileContext(profile);
|
|
1384
|
+
const groups = getProxyGroups(context.raw);
|
|
1385
|
+
if (groups.length === 0) {
|
|
1386
|
+
console.log(`No proxy groups found in ${context.path}`);
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
const selections = context.config.user.proxyGroupSelections;
|
|
1390
|
+
for (const group of groups) {
|
|
1391
|
+
const selected = selections[group.name] ?? group.proxies[0] ?? "";
|
|
1392
|
+
console.log(` ${group.name}`);
|
|
1393
|
+
console.log(` selected: ${selected || "(none)"}`);
|
|
1394
|
+
console.log(` proxies: ${group.proxies.join(", ")}`);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
async function showCurrentGroups(profile) {
|
|
1398
|
+
const context = loadProfileContext(profile);
|
|
1399
|
+
console.log(`profile path: ${context.path}`);
|
|
1400
|
+
console.log(`state config: ${context.statePath}`);
|
|
1401
|
+
console.log(`state key: ${context.stateKey}`);
|
|
1402
|
+
const activeProfile = loadLynxUserConfig().profile;
|
|
1403
|
+
const live = profile === void 0 || profile === activeProfile ? await sendControlCommand({ cmd: "query" }) : void 0;
|
|
1404
|
+
if (live?.ok && live.state !== void 0) {
|
|
1405
|
+
console.log("source: running daemon (live)");
|
|
1406
|
+
console.log(`mode: ${live.state.mode ?? "(default)"}`);
|
|
1407
|
+
console.log(`global proxy: ${live.state.globalProxy ?? "(not set)"}`);
|
|
1408
|
+
const entries = Object.entries(live.state.groupSelections);
|
|
1409
|
+
if (entries.length === 0) {
|
|
1410
|
+
console.log("group selections: (none)");
|
|
1411
|
+
return;
|
|
1412
|
+
}
|
|
1413
|
+
console.log("group selections:");
|
|
1414
|
+
for (const [group, proxy] of entries) console.log(` ${group}: ${proxy}`);
|
|
1415
|
+
return;
|
|
1416
|
+
}
|
|
1417
|
+
console.log("source: state.json");
|
|
1418
|
+
const globalSelection = context.config.user.proxyGroupSelections["GLOBAL"];
|
|
1419
|
+
console.log(`global proxy: ${globalSelection ?? "(not set)"}`);
|
|
1420
|
+
const entries = Object.entries(context.config.user.proxyGroupSelections).filter(([group]) => group !== "GLOBAL");
|
|
1421
|
+
if (entries.length === 0) {
|
|
1422
|
+
console.log("group selections: (none)");
|
|
1423
|
+
return;
|
|
1424
|
+
}
|
|
1425
|
+
console.log("group selections:");
|
|
1426
|
+
for (const [group, proxy] of entries) console.log(` ${group}: ${proxy}`);
|
|
1427
|
+
}
|
|
1428
|
+
function useGroup(groupName, profile) {
|
|
1429
|
+
const context = loadProfileContext(profile);
|
|
1430
|
+
ensureGroupExists(context.raw, groupName);
|
|
1431
|
+
updateProfileState(context.path, (state) => {
|
|
1432
|
+
const selected = [...state.selected ?? []];
|
|
1433
|
+
const existingIndex = selected.findIndex((s) => s.name === "GLOBAL");
|
|
1434
|
+
if (existingIndex >= 0) selected[existingIndex] = {
|
|
1435
|
+
name: "GLOBAL",
|
|
1436
|
+
now: groupName
|
|
1437
|
+
};
|
|
1438
|
+
else selected.push({
|
|
1439
|
+
name: "GLOBAL",
|
|
1440
|
+
now: groupName
|
|
1441
|
+
});
|
|
1442
|
+
return {
|
|
1443
|
+
...state,
|
|
1444
|
+
selected
|
|
1445
|
+
};
|
|
1446
|
+
});
|
|
1447
|
+
loadEffectiveProfileConfig(context.path);
|
|
1448
|
+
console.log(`Active proxy group: ${groupName}`);
|
|
1449
|
+
return dispatchLive(profile, {
|
|
1450
|
+
cmd: "useGroup",
|
|
1451
|
+
group: groupName
|
|
1452
|
+
});
|
|
1453
|
+
}
|
|
1454
|
+
function selectGroupProxy(groupName, proxyName, profile) {
|
|
1455
|
+
const context = loadProfileContext(profile);
|
|
1456
|
+
if (!ensureGroupExists(context.raw, groupName).proxies.includes(proxyName)) throw new ConfigError(`proxy-group ${groupName} does not contain selectable proxy: ${proxyName}`);
|
|
1457
|
+
updateProfileState(context.path, (state) => {
|
|
1458
|
+
const selected = [...state.selected ?? []];
|
|
1459
|
+
const existingIndex = selected.findIndex((s) => s.name === groupName);
|
|
1460
|
+
if (existingIndex >= 0) selected[existingIndex] = {
|
|
1461
|
+
name: groupName,
|
|
1462
|
+
now: proxyName
|
|
1463
|
+
};
|
|
1464
|
+
else selected.push({
|
|
1465
|
+
name: groupName,
|
|
1466
|
+
now: proxyName
|
|
1467
|
+
});
|
|
1468
|
+
return {
|
|
1469
|
+
...state,
|
|
1470
|
+
selected
|
|
1471
|
+
};
|
|
1472
|
+
});
|
|
1473
|
+
loadEffectiveProfileConfig(context.path);
|
|
1474
|
+
console.log(`Selected ${proxyName} for group ${groupName}`);
|
|
1475
|
+
return dispatchLive(profile, {
|
|
1476
|
+
cmd: "selectGroup",
|
|
1477
|
+
group: groupName,
|
|
1478
|
+
proxy: proxyName
|
|
1479
|
+
});
|
|
1480
|
+
}
|
|
1481
|
+
function setRuntimeMode(mode, profile) {
|
|
1482
|
+
if (![
|
|
1483
|
+
"rule",
|
|
1484
|
+
"global",
|
|
1485
|
+
"direct",
|
|
1486
|
+
"script"
|
|
1487
|
+
].includes(mode)) throw new ConfigError(`Unsupported mode: ${mode}`);
|
|
1488
|
+
const context = loadProfileContext(profile);
|
|
1489
|
+
updateProfileState(context.path, (state) => ({
|
|
1490
|
+
...state,
|
|
1491
|
+
mode
|
|
1492
|
+
}));
|
|
1493
|
+
loadEffectiveProfileConfig(context.path);
|
|
1494
|
+
console.log(`Mode set to ${mode}`);
|
|
1495
|
+
return dispatchLive(profile, {
|
|
1496
|
+
cmd: "setMode",
|
|
1497
|
+
mode
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
function unsetGroupSelection(groupName, profile) {
|
|
1501
|
+
const context = loadProfileContext(profile);
|
|
1502
|
+
ensureGroupExists(context.raw, groupName);
|
|
1503
|
+
updateProfileState(context.path, (state) => {
|
|
1504
|
+
const selected = (state.selected ?? []).filter((s) => s.name !== groupName);
|
|
1505
|
+
return {
|
|
1506
|
+
...state,
|
|
1507
|
+
selected
|
|
1508
|
+
};
|
|
1509
|
+
});
|
|
1510
|
+
loadEffectiveProfileConfig(context.path);
|
|
1511
|
+
console.log(`Removed explicit selection for group ${groupName}`);
|
|
1512
|
+
return dispatchLive(profile, {
|
|
1513
|
+
cmd: "unsetGroup",
|
|
1514
|
+
group: groupName
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* 写盘后把变更下发给运行中的 daemon。仅当操作的是当前活动 profile 时下发;
|
|
1519
|
+
* daemon 未运行时静默跳过,提示下次启动生效。
|
|
1520
|
+
*/
|
|
1521
|
+
async function dispatchLive(profile, command) {
|
|
1522
|
+
const activeProfile = loadLynxUserConfig().profile;
|
|
1523
|
+
if (profile !== void 0 && profile !== activeProfile) return;
|
|
1524
|
+
const response = await sendControlCommand(command);
|
|
1525
|
+
if (response === void 0) {
|
|
1526
|
+
console.log("Daemon not running; change will apply on next start.");
|
|
1527
|
+
return;
|
|
1528
|
+
}
|
|
1529
|
+
if (response.ok) console.log("Applied to running daemon.");
|
|
1530
|
+
else console.log(`Daemon rejected live update: ${response.error ?? "unknown error"}`);
|
|
1531
|
+
}
|
|
1532
|
+
function runRuleCommand(args) {
|
|
1533
|
+
const [command, ...rest] = args;
|
|
1534
|
+
if (command === "list") {
|
|
1535
|
+
listRules(parseOptions(rest).profile);
|
|
1536
|
+
return;
|
|
1537
|
+
}
|
|
1538
|
+
if (command === "set") {
|
|
1539
|
+
const options = parseOptions(rest);
|
|
1540
|
+
setRuleTarget(requireArg(options.rest[0], "rule"), requireArg(options.rest[1], "target"), options.profile);
|
|
1541
|
+
return;
|
|
1542
|
+
}
|
|
1543
|
+
throw new Error(`Unknown groups rule command: ${String(command)}`);
|
|
1544
|
+
}
|
|
1545
|
+
function listRules(profile) {
|
|
1546
|
+
const context = loadProfileContext(profile);
|
|
1547
|
+
const rules = getRules(context.raw);
|
|
1548
|
+
if (rules.length === 0) {
|
|
1549
|
+
console.log(`No rules found in ${context.path}`);
|
|
1550
|
+
return;
|
|
1551
|
+
}
|
|
1552
|
+
rules.forEach((rule, index) => {
|
|
1553
|
+
const parts = splitRule(rule);
|
|
1554
|
+
const target = (parts[0] ?? "").toUpperCase() === "MATCH" ? parts[1] : parts[2];
|
|
1555
|
+
console.log(`${index}: ${rule}`);
|
|
1556
|
+
if (target !== void 0) console.log(` target: ${target}`);
|
|
1557
|
+
});
|
|
1558
|
+
console.log(`default: ${formatRoute(context.config)}`);
|
|
1559
|
+
}
|
|
1560
|
+
function setRuleTarget(ruleRef, target, profile) {
|
|
1561
|
+
const context = loadProfileContext(profile);
|
|
1562
|
+
ensureTargetExists(context.raw, target);
|
|
1563
|
+
const rules = getRules(context.raw);
|
|
1564
|
+
const index = resolveRuleIndex(rules, ruleRef);
|
|
1565
|
+
const rule = rules[index];
|
|
1566
|
+
if (rule === void 0) throw new ConfigError(`Rule not found: ${ruleRef}`);
|
|
1567
|
+
const parts = splitRule(rule);
|
|
1568
|
+
if (parts[0]?.toUpperCase() === "MATCH") rules[index] = `MATCH,${target}`;
|
|
1569
|
+
else if (parts.length >= 3) {
|
|
1570
|
+
parts[2] = target;
|
|
1571
|
+
rules[index] = parts.join(",");
|
|
1572
|
+
} else throw new ConfigError(`Cannot update malformed rule: ${rule}`);
|
|
1573
|
+
writeProfileContext(context);
|
|
1574
|
+
console.log(`Updated rule ${index} target to ${target}`);
|
|
1575
|
+
}
|
|
1576
|
+
function loadProfileContext(profile) {
|
|
1577
|
+
const path = resolveProfilePath(profile ?? loadLynxUserConfig().profile);
|
|
1578
|
+
const object = asRecord(parseConfigFile(path, readFileSync(path, "utf8")), "profile config");
|
|
1579
|
+
const stateKey = getProfileStateKey(path);
|
|
1580
|
+
const state = findProfileStateEntry(loadLynxStateConfig(), stateKey) ?? {
|
|
1581
|
+
name: stateKey,
|
|
1582
|
+
selected: []
|
|
1583
|
+
};
|
|
1584
|
+
return {
|
|
1585
|
+
path,
|
|
1586
|
+
stateKey,
|
|
1587
|
+
statePath: getDefaultStateConfigPath(),
|
|
1588
|
+
raw: object,
|
|
1589
|
+
config: loadEffectiveProfileConfig(path),
|
|
1590
|
+
state
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
function writeProfileContext(context) {
|
|
1594
|
+
writeFileSync(context.path, serializeConfig(context.path, context.raw), "utf8");
|
|
1595
|
+
loadConfigFromRaw(asRecord(parseConfigFile(context.path, readFileSync(context.path, "utf8")), "profile config"));
|
|
1596
|
+
loadEffectiveProfileConfig(context.path);
|
|
1597
|
+
}
|
|
1598
|
+
function serializeConfig(path, raw) {
|
|
1599
|
+
const ext = extname(path);
|
|
1600
|
+
if (ext === ".json") return `${JSON.stringify(raw, null, 2)}\n`;
|
|
1601
|
+
if (ext === ".toml") return stringify(raw);
|
|
1602
|
+
if (ext === ".yaml" || ext === ".yml") return dump(raw);
|
|
1603
|
+
throw new ConfigError(`Unsupported profile file extension: ${ext}`);
|
|
1604
|
+
}
|
|
1605
|
+
function getProxyGroups(raw) {
|
|
1606
|
+
const value = raw["proxy-groups"];
|
|
1607
|
+
if (value === void 0) return [];
|
|
1608
|
+
if (!Array.isArray(value)) throw new ConfigError("proxy-groups must be an array");
|
|
1609
|
+
return value.map((item, index) => {
|
|
1610
|
+
const object = asRecord(item, `proxy-groups[${index}]`);
|
|
1611
|
+
return {
|
|
1612
|
+
name: requireString(object["name"], `proxy-groups[${index}].name`),
|
|
1613
|
+
proxies: requireStringArray(object["proxies"], `proxy-groups[${index}].proxies`)
|
|
1614
|
+
};
|
|
1615
|
+
});
|
|
1616
|
+
}
|
|
1617
|
+
function ensureGroupExists(raw, groupName) {
|
|
1618
|
+
const group = getProxyGroups(raw).find((candidate) => candidate.name === groupName);
|
|
1619
|
+
if (group === void 0) throw new ConfigError(`Unknown proxy-group: ${groupName}`);
|
|
1620
|
+
return group;
|
|
1621
|
+
}
|
|
1622
|
+
function ensureTargetExists(raw, target) {
|
|
1623
|
+
if (target === "DIRECT") return;
|
|
1624
|
+
const proxyNames = new Set(getNamedItems(raw["proxies"], "proxies").map((proxy) => proxy.name));
|
|
1625
|
+
const groupNames = new Set(getProxyGroups(raw).map((group) => group.name));
|
|
1626
|
+
if (!proxyNames.has(target) && !groupNames.has(target)) throw new ConfigError(`Unknown rule target: ${target}`);
|
|
1627
|
+
}
|
|
1628
|
+
function getNamedItems(value, field) {
|
|
1629
|
+
if (value === void 0) return [];
|
|
1630
|
+
if (!Array.isArray(value)) throw new ConfigError(`${field} must be an array`);
|
|
1631
|
+
return value.map((item, index) => {
|
|
1632
|
+
return { name: requireString(asRecord(item, `${field}[${index}]`)["name"], `${field}[${index}].name`) };
|
|
1633
|
+
});
|
|
1634
|
+
}
|
|
1635
|
+
function getRules(raw) {
|
|
1636
|
+
const value = raw["rules"];
|
|
1637
|
+
if (value === void 0) {
|
|
1638
|
+
const rules = [];
|
|
1639
|
+
raw["rules"] = rules;
|
|
1640
|
+
return rules;
|
|
1641
|
+
}
|
|
1642
|
+
if (!Array.isArray(value)) throw new ConfigError("rules must be an array");
|
|
1643
|
+
value.forEach((item, index) => {
|
|
1644
|
+
requireString(item, `rules[${index}]`);
|
|
1645
|
+
});
|
|
1646
|
+
return value;
|
|
1647
|
+
}
|
|
1648
|
+
function resolveRuleIndex(rules, ruleRef) {
|
|
1649
|
+
if (/^\d+$/.test(ruleRef)) {
|
|
1650
|
+
const index = Number(ruleRef);
|
|
1651
|
+
if (index < rules.length) return index;
|
|
1652
|
+
}
|
|
1653
|
+
if (ruleRef.toUpperCase() === "MATCH") {
|
|
1654
|
+
const index = rules.findIndex((rule) => splitRule(rule)[0]?.toUpperCase() === "MATCH");
|
|
1655
|
+
if (index !== -1) return index;
|
|
1656
|
+
}
|
|
1657
|
+
const index = rules.findIndex((rule) => rule === ruleRef);
|
|
1658
|
+
if (index !== -1) return index;
|
|
1659
|
+
throw new ConfigError(`Rule not found: ${ruleRef}`);
|
|
1660
|
+
}
|
|
1661
|
+
function parseOptions(args) {
|
|
1662
|
+
const rest = [];
|
|
1663
|
+
let profile;
|
|
1664
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
1665
|
+
const arg = args[index];
|
|
1666
|
+
if (arg === "--profile") {
|
|
1667
|
+
profile = requireArg(args[index + 1], "profile");
|
|
1668
|
+
index += 1;
|
|
1669
|
+
} else if (arg !== void 0) rest.push(arg);
|
|
1670
|
+
}
|
|
1671
|
+
if (profile === void 0) return { rest };
|
|
1672
|
+
return {
|
|
1673
|
+
profile,
|
|
1674
|
+
rest
|
|
1675
|
+
};
|
|
1676
|
+
}
|
|
1677
|
+
function splitRule(rule) {
|
|
1678
|
+
return rule.split(",").map((part) => part.trim());
|
|
1679
|
+
}
|
|
1680
|
+
function formatRoute(config) {
|
|
1681
|
+
if (config.route.default === "DIRECT") return "DIRECT";
|
|
1682
|
+
return `PROXY ${config.route.defaultProxy ?? "(missing proxy)"}`;
|
|
1683
|
+
}
|
|
1684
|
+
function requireString(value, field) {
|
|
1685
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new ConfigError(`${field} must be a non-empty string`);
|
|
1686
|
+
return value;
|
|
1687
|
+
}
|
|
1688
|
+
function requireStringArray(value, field) {
|
|
1689
|
+
if (!Array.isArray(value)) throw new ConfigError(`${field} must be an array`);
|
|
1690
|
+
return value.map((item, index) => requireString(item, `${field}[${index}]`));
|
|
1691
|
+
}
|
|
1692
|
+
function asRecord(value, field) {
|
|
1693
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ConfigError(`${field} must be a table`);
|
|
1694
|
+
return value;
|
|
1695
|
+
}
|
|
1696
|
+
function requireArg(value, name) {
|
|
1697
|
+
if (value === void 0 || value.length === 0) throw new Error(`Missing ${name}`);
|
|
1698
|
+
return value;
|
|
1699
|
+
}
|
|
1700
|
+
function createGroupsHelpText() {
|
|
1701
|
+
return `Usage: lynx groups <command> [options]
|
|
1702
|
+
|
|
1703
|
+
Commands:
|
|
1704
|
+
list [--profile <profile>] List proxy groups and selections
|
|
1705
|
+
current [--profile <profile>] Show active group and all selections
|
|
1706
|
+
use <group> [--profile <profile>] Set active proxy group in state.json
|
|
1707
|
+
select <group> <proxy> [--profile <profile>] Select a proxy for a group in state.json
|
|
1708
|
+
mode <rule|global|direct|script> [--profile p] Set runtime mode in state.json
|
|
1709
|
+
unset <group> [--profile <profile>] Remove explicit state selection
|
|
1710
|
+
rule list [--profile <profile>] List rules and targets
|
|
1711
|
+
rule set <rule|index|MATCH> <target> [--profile p] Update a rule target
|
|
1712
|
+
|
|
1713
|
+
Selection, group and mode changes are written to state.json and, when the daemon
|
|
1714
|
+
is running the active profile, applied live over the control socket.`;
|
|
1715
|
+
}
|
|
1716
|
+
//#endregion
|
|
1717
|
+
//#region src/logging/logger.ts
|
|
1718
|
+
const LEVEL_PRIORITY = {
|
|
1719
|
+
debug: 10,
|
|
1720
|
+
info: 20,
|
|
1721
|
+
warn: 30,
|
|
1722
|
+
error: 40
|
|
1723
|
+
};
|
|
1724
|
+
function createLogger(config) {
|
|
1725
|
+
return new ConsoleLogger(config);
|
|
1726
|
+
}
|
|
1727
|
+
function createDefaultLogger() {
|
|
1728
|
+
return createLogger({
|
|
1729
|
+
level: "debug",
|
|
1730
|
+
access: true
|
|
1731
|
+
});
|
|
1732
|
+
}
|
|
1733
|
+
var ConsoleLogger = class {
|
|
1734
|
+
config;
|
|
1735
|
+
constructor(config) {
|
|
1736
|
+
this.config = config;
|
|
1737
|
+
}
|
|
1738
|
+
debug(message) {
|
|
1739
|
+
this.write("debug", message);
|
|
1740
|
+
}
|
|
1741
|
+
info(message) {
|
|
1742
|
+
this.write("info", message);
|
|
1743
|
+
}
|
|
1744
|
+
warn(message) {
|
|
1745
|
+
this.write("warn", message);
|
|
1746
|
+
}
|
|
1747
|
+
error(message) {
|
|
1748
|
+
this.write("error", message);
|
|
1749
|
+
}
|
|
1750
|
+
access(message) {
|
|
1751
|
+
if (!this.config.access) return;
|
|
1752
|
+
this.writeLine(`${message}\n`, "stdout");
|
|
1753
|
+
}
|
|
1754
|
+
isAccessEnabled() {
|
|
1755
|
+
return this.config.access;
|
|
1756
|
+
}
|
|
1757
|
+
write(level, message) {
|
|
1758
|
+
if (!this.shouldWrite(level)) return;
|
|
1759
|
+
const line = `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase()} ${message}\n`;
|
|
1760
|
+
this.writeLine(line, level === "error" ? "stderr" : "stdout");
|
|
1761
|
+
}
|
|
1762
|
+
writeLine(line, stream) {
|
|
1763
|
+
if (stream === "stderr") process.stderr.write(line);
|
|
1764
|
+
else process.stdout.write(line);
|
|
1765
|
+
if (this.config.file !== void 0) appendFileSync(this.config.file, line, "utf8");
|
|
1766
|
+
}
|
|
1767
|
+
shouldWrite(level) {
|
|
1768
|
+
return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[this.config.level];
|
|
1769
|
+
}
|
|
1770
|
+
};
|
|
1771
|
+
//#endregion
|
|
1772
|
+
//#region src/transport/tcp.ts
|
|
1773
|
+
function connectTcp(options) {
|
|
1774
|
+
return new Promise((resolve, reject) => {
|
|
1775
|
+
const socket = createConnection({
|
|
1776
|
+
host: options.host,
|
|
1777
|
+
port: options.port
|
|
1778
|
+
});
|
|
1779
|
+
const cleanup = () => {
|
|
1780
|
+
socket.removeListener("connect", onConnect);
|
|
1781
|
+
socket.removeListener("error", onError);
|
|
1782
|
+
socket.removeListener("timeout", onTimeout);
|
|
1783
|
+
};
|
|
1784
|
+
const onConnect = () => {
|
|
1785
|
+
cleanup();
|
|
1786
|
+
socket.setTimeout(0);
|
|
1787
|
+
resolve(socket);
|
|
1788
|
+
};
|
|
1789
|
+
const onError = (error) => {
|
|
1790
|
+
cleanup();
|
|
1791
|
+
reject(error);
|
|
1792
|
+
};
|
|
1793
|
+
const onTimeout = () => {
|
|
1794
|
+
cleanup();
|
|
1795
|
+
socket.destroy();
|
|
1796
|
+
reject(/* @__PURE__ */ new Error(`TCP connect timeout: ${options.host}:${options.port}`));
|
|
1797
|
+
};
|
|
1798
|
+
socket.setTimeout(options.timeoutMs);
|
|
1799
|
+
socket.once("connect", onConnect);
|
|
1800
|
+
socket.once("error", onError);
|
|
1801
|
+
socket.once("timeout", onTimeout);
|
|
1802
|
+
});
|
|
1803
|
+
}
|
|
1804
|
+
//#endregion
|
|
1805
|
+
//#region src/protocol/direct.ts
|
|
1806
|
+
var DirectProxy = class {
|
|
1807
|
+
connectTimeoutMs;
|
|
1808
|
+
constructor(connectTimeoutMs) {
|
|
1809
|
+
this.connectTimeoutMs = connectTimeoutMs;
|
|
1810
|
+
}
|
|
1811
|
+
connect(targetHost, targetPort) {
|
|
1812
|
+
return connectTcp({
|
|
1813
|
+
host: targetHost,
|
|
1814
|
+
port: targetPort,
|
|
1815
|
+
timeoutMs: this.connectTimeoutMs
|
|
1816
|
+
});
|
|
1817
|
+
}
|
|
1818
|
+
};
|
|
1819
|
+
//#endregion
|
|
1820
|
+
//#region src/protocol/socks5.ts
|
|
1821
|
+
const SOCKS_VERSION = 5;
|
|
1822
|
+
const USERPASS_VERSION = 1;
|
|
1823
|
+
var Socks5Proxy = class {
|
|
1824
|
+
config;
|
|
1825
|
+
connectTimeoutMs;
|
|
1826
|
+
constructor(config, connectTimeoutMs) {
|
|
1827
|
+
this.config = config;
|
|
1828
|
+
this.connectTimeoutMs = connectTimeoutMs;
|
|
1829
|
+
}
|
|
1830
|
+
async connect(targetHost, targetPort) {
|
|
1831
|
+
const socket = await connectTcp({
|
|
1832
|
+
host: this.config.host,
|
|
1833
|
+
port: this.config.port,
|
|
1834
|
+
timeoutMs: this.connectTimeoutMs
|
|
1835
|
+
});
|
|
1836
|
+
try {
|
|
1837
|
+
await this.negotiate(socket);
|
|
1838
|
+
await this.sendConnect(socket, targetHost, targetPort);
|
|
1839
|
+
return socket;
|
|
1840
|
+
} catch (error) {
|
|
1841
|
+
socket.destroy();
|
|
1842
|
+
throw error;
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
async negotiate(socket) {
|
|
1846
|
+
const methods = this.config.username === void 0 ? Buffer.from([
|
|
1847
|
+
SOCKS_VERSION,
|
|
1848
|
+
1,
|
|
1849
|
+
0
|
|
1850
|
+
]) : Buffer.from([
|
|
1851
|
+
SOCKS_VERSION,
|
|
1852
|
+
2,
|
|
1853
|
+
0,
|
|
1854
|
+
2
|
|
1855
|
+
]);
|
|
1856
|
+
socket.write(methods);
|
|
1857
|
+
const response = await readExact(socket, 2);
|
|
1858
|
+
if (response[0] !== SOCKS_VERSION) throw new Error("Invalid SOCKS5 negotiation response");
|
|
1859
|
+
const method = response[1];
|
|
1860
|
+
if (method === 0) return;
|
|
1861
|
+
if (method === 2) {
|
|
1862
|
+
await this.authenticate(socket);
|
|
1863
|
+
return;
|
|
1864
|
+
}
|
|
1865
|
+
throw new Error("SOCKS5 server does not accept supported authentication methods");
|
|
1866
|
+
}
|
|
1867
|
+
async authenticate(socket) {
|
|
1868
|
+
const username = this.config.username;
|
|
1869
|
+
const password = this.config.password;
|
|
1870
|
+
if (username === void 0 || password === void 0) throw new Error("SOCKS5 username/password authentication requested but credentials are missing");
|
|
1871
|
+
const usernameBytes = Buffer.from(username, "utf8");
|
|
1872
|
+
const passwordBytes = Buffer.from(password, "utf8");
|
|
1873
|
+
if (usernameBytes.length > 255 || passwordBytes.length > 255) throw new Error("SOCKS5 username and password must be at most 255 bytes");
|
|
1874
|
+
socket.write(Buffer.concat([
|
|
1875
|
+
Buffer.from([USERPASS_VERSION, usernameBytes.length]),
|
|
1876
|
+
usernameBytes,
|
|
1877
|
+
Buffer.from([passwordBytes.length]),
|
|
1878
|
+
passwordBytes
|
|
1879
|
+
]));
|
|
1880
|
+
const response = await readExact(socket, 2);
|
|
1881
|
+
if (response[0] !== USERPASS_VERSION || response[1] !== 0) throw new Error("SOCKS5 username/password authentication failed");
|
|
1882
|
+
}
|
|
1883
|
+
async sendConnect(socket, targetHost, targetPort) {
|
|
1884
|
+
socket.write(buildSocksConnectRequest(targetHost, targetPort));
|
|
1885
|
+
const header = await readExact(socket, 4);
|
|
1886
|
+
if (header[0] !== SOCKS_VERSION) throw new Error("Invalid SOCKS5 CONNECT response");
|
|
1887
|
+
if (header[1] !== 0) throw new Error(`SOCKS5 CONNECT failed with code ${header[1]}`);
|
|
1888
|
+
const atyp = header[3];
|
|
1889
|
+
if (atyp === 1) await readExact(socket, 6);
|
|
1890
|
+
else if (atyp === 3) {
|
|
1891
|
+
const length = await readExact(socket, 1);
|
|
1892
|
+
await readExact(socket, Number(length[0]) + 2);
|
|
1893
|
+
} else if (atyp === 4) await readExact(socket, 18);
|
|
1894
|
+
else throw new Error("SOCKS5 CONNECT response has unsupported address type");
|
|
1895
|
+
}
|
|
1896
|
+
};
|
|
1897
|
+
function buildSocksConnectRequest(targetHost, targetPort) {
|
|
1898
|
+
const port = Buffer.allocUnsafe(2);
|
|
1899
|
+
port.writeUInt16BE(targetPort, 0);
|
|
1900
|
+
const ipType = isIP(targetHost);
|
|
1901
|
+
if (ipType === 4) {
|
|
1902
|
+
const octets = targetHost.split(".").map((part) => Number(part));
|
|
1903
|
+
return Buffer.concat([Buffer.from([
|
|
1904
|
+
SOCKS_VERSION,
|
|
1905
|
+
1,
|
|
1906
|
+
0,
|
|
1907
|
+
1,
|
|
1908
|
+
...octets
|
|
1909
|
+
]), port]);
|
|
1910
|
+
}
|
|
1911
|
+
if (ipType === 6) {
|
|
1912
|
+
const address = ipv6ToBuffer$1(targetHost);
|
|
1913
|
+
return Buffer.concat([
|
|
1914
|
+
Buffer.from([
|
|
1915
|
+
SOCKS_VERSION,
|
|
1916
|
+
1,
|
|
1917
|
+
0,
|
|
1918
|
+
4
|
|
1919
|
+
]),
|
|
1920
|
+
address,
|
|
1921
|
+
port
|
|
1922
|
+
]);
|
|
1923
|
+
}
|
|
1924
|
+
const domain = Buffer.from(targetHost, "utf8");
|
|
1925
|
+
if (domain.length > 255) throw new Error("SOCKS5 target domain is too long");
|
|
1926
|
+
return Buffer.concat([
|
|
1927
|
+
Buffer.from([
|
|
1928
|
+
SOCKS_VERSION,
|
|
1929
|
+
1,
|
|
1930
|
+
0,
|
|
1931
|
+
3,
|
|
1932
|
+
domain.length
|
|
1933
|
+
]),
|
|
1934
|
+
domain,
|
|
1935
|
+
port
|
|
1936
|
+
]);
|
|
1937
|
+
}
|
|
1938
|
+
function readExact(socket, length) {
|
|
1939
|
+
return new Promise((resolve, reject) => {
|
|
1940
|
+
let buffered = Buffer.alloc(0);
|
|
1941
|
+
const cleanup = () => {
|
|
1942
|
+
socket.removeListener("data", onData);
|
|
1943
|
+
socket.removeListener("error", onError);
|
|
1944
|
+
socket.removeListener("close", onClose);
|
|
1945
|
+
};
|
|
1946
|
+
const onData = (chunk) => {
|
|
1947
|
+
buffered = Buffer.concat([buffered, chunk]);
|
|
1948
|
+
if (buffered.length >= length) {
|
|
1949
|
+
cleanup();
|
|
1950
|
+
const needed = buffered.subarray(0, length);
|
|
1951
|
+
const rest = buffered.subarray(length);
|
|
1952
|
+
if (rest.length > 0) socket.unshift(rest);
|
|
1953
|
+
resolve(needed);
|
|
1954
|
+
}
|
|
1955
|
+
};
|
|
1956
|
+
const onError = (error) => {
|
|
1957
|
+
cleanup();
|
|
1958
|
+
reject(error);
|
|
1959
|
+
};
|
|
1960
|
+
const onClose = () => {
|
|
1961
|
+
cleanup();
|
|
1962
|
+
reject(/* @__PURE__ */ new Error("Socket closed while reading SOCKS5 response"));
|
|
1963
|
+
};
|
|
1964
|
+
socket.on("data", onData);
|
|
1965
|
+
socket.once("error", onError);
|
|
1966
|
+
socket.once("close", onClose);
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
function ipv6ToBuffer$1(address) {
|
|
1970
|
+
const normalized = expandIpv6(address);
|
|
1971
|
+
const buffer = Buffer.allocUnsafe(16);
|
|
1972
|
+
normalized.forEach((part, index) => {
|
|
1973
|
+
buffer.writeUInt16BE(part, index * 2);
|
|
1974
|
+
});
|
|
1975
|
+
return buffer;
|
|
1976
|
+
}
|
|
1977
|
+
function expandIpv6(address) {
|
|
1978
|
+
const halves = address.split("::");
|
|
1979
|
+
const left = halves[0] === void 0 || halves[0].length === 0 ? [] : halves[0].split(":");
|
|
1980
|
+
const right = halves[1] === void 0 || halves[1].length === 0 ? [] : halves[1].split(":");
|
|
1981
|
+
const missing = 8 - left.length - right.length;
|
|
1982
|
+
return [
|
|
1983
|
+
...left,
|
|
1984
|
+
...Array.from({ length: missing }, () => "0"),
|
|
1985
|
+
...right
|
|
1986
|
+
].map((part) => Number.parseInt(part, 16));
|
|
1987
|
+
}
|
|
1988
|
+
//#endregion
|
|
1989
|
+
//#region src/utils/Crypto.ts
|
|
1990
|
+
function hashPassword(str) {
|
|
1991
|
+
const hash = createHash("sha224");
|
|
1992
|
+
let encoder = new TextEncoder();
|
|
1993
|
+
let hashStr = hash.update(encoder.encode(str)).digest("hex");
|
|
1994
|
+
return encoder.encode(hashStr);
|
|
1995
|
+
}
|
|
1996
|
+
//#endregion
|
|
1997
|
+
//#region src/protocol/trojan.ts
|
|
1998
|
+
const TROJAN_CMD_CONNECT = 1;
|
|
1999
|
+
var TrojanProxy = class {
|
|
2000
|
+
config;
|
|
2001
|
+
connectTimeoutMs;
|
|
2002
|
+
constructor(config, connectTimeoutMs) {
|
|
2003
|
+
this.config = config;
|
|
2004
|
+
this.connectTimeoutMs = connectTimeoutMs;
|
|
2005
|
+
}
|
|
2006
|
+
async connect(targetHost, targetPort) {
|
|
2007
|
+
const socket = await this.connectTls();
|
|
2008
|
+
try {
|
|
2009
|
+
socket.write(buildTrojanRequest(this.config.password, targetHost, targetPort));
|
|
2010
|
+
return socket;
|
|
2011
|
+
} catch (error) {
|
|
2012
|
+
socket.destroy();
|
|
2013
|
+
throw error;
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
connectTls() {
|
|
2017
|
+
return new Promise((resolve, reject) => {
|
|
2018
|
+
const socket = connect({
|
|
2019
|
+
host: this.config.host,
|
|
2020
|
+
port: this.config.port,
|
|
2021
|
+
servername: this.config.serverName,
|
|
2022
|
+
rejectUnauthorized: !this.config.allowInvalidCert
|
|
2023
|
+
});
|
|
2024
|
+
const cleanup = () => {
|
|
2025
|
+
socket.removeListener("secureConnect", onSecureConnect);
|
|
2026
|
+
socket.removeListener("error", onError);
|
|
2027
|
+
socket.removeListener("timeout", onTimeout);
|
|
2028
|
+
};
|
|
2029
|
+
const onSecureConnect = () => {
|
|
2030
|
+
cleanup();
|
|
2031
|
+
socket.setTimeout(0);
|
|
2032
|
+
resolve(socket);
|
|
2033
|
+
};
|
|
2034
|
+
const onError = (error) => {
|
|
2035
|
+
cleanup();
|
|
2036
|
+
reject(error);
|
|
2037
|
+
};
|
|
2038
|
+
const onTimeout = () => {
|
|
2039
|
+
cleanup();
|
|
2040
|
+
socket.destroy();
|
|
2041
|
+
reject(/* @__PURE__ */ new Error(`Trojan TLS connect timeout: ${this.config.host}:${this.config.port}`));
|
|
2042
|
+
};
|
|
2043
|
+
socket.setTimeout(this.connectTimeoutMs);
|
|
2044
|
+
socket.once("secureConnect", onSecureConnect);
|
|
2045
|
+
socket.once("error", onError);
|
|
2046
|
+
socket.once("timeout", onTimeout);
|
|
2047
|
+
});
|
|
2048
|
+
}
|
|
2049
|
+
};
|
|
2050
|
+
function buildTrojanRequest(password, targetHost, targetPort) {
|
|
2051
|
+
const hash = Buffer.from(hashPassword(password));
|
|
2052
|
+
const crlf = Buffer.from("\r\n", "ascii");
|
|
2053
|
+
const command = Buffer.from([TROJAN_CMD_CONNECT]);
|
|
2054
|
+
const address = encodeAddress(targetHost);
|
|
2055
|
+
const port = Buffer.allocUnsafe(2);
|
|
2056
|
+
port.writeUInt16BE(targetPort, 0);
|
|
2057
|
+
return Buffer.concat([
|
|
2058
|
+
hash,
|
|
2059
|
+
crlf,
|
|
2060
|
+
command,
|
|
2061
|
+
address,
|
|
2062
|
+
port,
|
|
2063
|
+
crlf
|
|
2064
|
+
]);
|
|
2065
|
+
}
|
|
2066
|
+
function encodeAddress(host) {
|
|
2067
|
+
const ipType = isIP(host);
|
|
2068
|
+
if (ipType === 4) return Buffer.from([1, ...host.split(".").map((part) => Number(part))]);
|
|
2069
|
+
if (ipType === 6) return Buffer.concat([Buffer.from([4]), ipv6ToBuffer(host)]);
|
|
2070
|
+
const domain = Buffer.from(host, "utf8");
|
|
2071
|
+
if (domain.length > 255) throw new Error("Trojan target domain is too long");
|
|
2072
|
+
return Buffer.concat([Buffer.from([3, domain.length]), domain]);
|
|
2073
|
+
}
|
|
2074
|
+
function ipv6ToBuffer(address) {
|
|
2075
|
+
const halves = address.split("::");
|
|
2076
|
+
const left = halves[0] === void 0 || halves[0].length === 0 ? [] : halves[0].split(":");
|
|
2077
|
+
const right = halves[1] === void 0 || halves[1].length === 0 ? [] : halves[1].split(":");
|
|
2078
|
+
const missing = 8 - left.length - right.length;
|
|
2079
|
+
const parts = [
|
|
2080
|
+
...left,
|
|
2081
|
+
...Array.from({ length: missing }, () => "0"),
|
|
2082
|
+
...right
|
|
2083
|
+
];
|
|
2084
|
+
const buffer = Buffer.allocUnsafe(16);
|
|
2085
|
+
parts.forEach((part, index) => {
|
|
2086
|
+
buffer.writeUInt16BE(Number.parseInt(part, 16), index * 2);
|
|
2087
|
+
});
|
|
2088
|
+
return buffer;
|
|
2089
|
+
}
|
|
2090
|
+
//#endregion
|
|
2091
|
+
//#region src/protocol/base.ts
|
|
2092
|
+
function createUpstreamProxy(config, connectTimeoutMs) {
|
|
2093
|
+
if (config.type === "direct") return new DirectProxy(connectTimeoutMs);
|
|
2094
|
+
if (config.type === "socks5") return new Socks5Proxy(config, connectTimeoutMs);
|
|
2095
|
+
return new TrojanProxy(config, connectTimeoutMs);
|
|
2096
|
+
}
|
|
2097
|
+
//#endregion
|
|
2098
|
+
//#region src/http/parser.ts
|
|
2099
|
+
const HEADER_END = "\r\n\r\n";
|
|
2100
|
+
var HttpParseError = class extends Error {
|
|
2101
|
+
constructor(message) {
|
|
2102
|
+
super(message);
|
|
2103
|
+
this.name = "HttpParseError";
|
|
2104
|
+
}
|
|
2105
|
+
};
|
|
2106
|
+
function findHeaderEnd(buffer) {
|
|
2107
|
+
return buffer.indexOf(HEADER_END);
|
|
2108
|
+
}
|
|
2109
|
+
function parseHttpRequest(buffer) {
|
|
2110
|
+
const headerEnd = findHeaderEnd(buffer);
|
|
2111
|
+
if (headerEnd < 0) throw new HttpParseError("HTTP header is incomplete");
|
|
2112
|
+
const lines = buffer.subarray(0, headerEnd).toString("latin1").split("\r\n");
|
|
2113
|
+
const requestLine = lines[0];
|
|
2114
|
+
if (requestLine === void 0) throw new HttpParseError("Missing request line");
|
|
2115
|
+
const requestParts = requestLine.split(" ").filter((part) => part.length > 0);
|
|
2116
|
+
if (requestParts.length !== 3) throw new HttpParseError("Invalid request line");
|
|
2117
|
+
const method = requestParts[0];
|
|
2118
|
+
const requestTarget = requestParts[1];
|
|
2119
|
+
const version = requestParts[2];
|
|
2120
|
+
if (method === void 0 || requestTarget === void 0 || version === void 0 || !version.startsWith("HTTP/")) throw new HttpParseError("Invalid request line");
|
|
2121
|
+
const headers = {};
|
|
2122
|
+
for (const line of lines.slice(1)) {
|
|
2123
|
+
if (line.length === 0) continue;
|
|
2124
|
+
const colonIndex = line.indexOf(":");
|
|
2125
|
+
if (colonIndex <= 0) throw new HttpParseError(`Invalid header line: ${line}`);
|
|
2126
|
+
const name = line.slice(0, colonIndex).trim().toLowerCase();
|
|
2127
|
+
headers[name] = line.slice(colonIndex + 1).trim();
|
|
2128
|
+
}
|
|
2129
|
+
return {
|
|
2130
|
+
method,
|
|
2131
|
+
requestTarget,
|
|
2132
|
+
version,
|
|
2133
|
+
headers,
|
|
2134
|
+
headerLength: headerEnd + 4
|
|
2135
|
+
};
|
|
2136
|
+
}
|
|
2137
|
+
function parseTarget(request) {
|
|
2138
|
+
if (request.method.toUpperCase() === "CONNECT") {
|
|
2139
|
+
const { host, port } = parseHostPort(request.requestTarget, 443, { requirePort: true });
|
|
2140
|
+
return {
|
|
2141
|
+
host,
|
|
2142
|
+
port,
|
|
2143
|
+
scheme: "https",
|
|
2144
|
+
path: "",
|
|
2145
|
+
isConnect: true
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
if (request.requestTarget.startsWith("http://") || request.requestTarget.startsWith("https://")) {
|
|
2149
|
+
let url;
|
|
2150
|
+
try {
|
|
2151
|
+
url = new URL(request.requestTarget);
|
|
2152
|
+
} catch {
|
|
2153
|
+
throw new HttpParseError("Invalid request target URL");
|
|
2154
|
+
}
|
|
2155
|
+
const scheme = url.protocol.slice(0, -1);
|
|
2156
|
+
const port = url.port.length > 0 ? parsePort(url.port) : defaultPortForScheme(scheme);
|
|
2157
|
+
if (url.hostname.length === 0) throw new HttpParseError("Missing target host");
|
|
2158
|
+
return {
|
|
2159
|
+
host: url.hostname,
|
|
2160
|
+
port,
|
|
2161
|
+
scheme,
|
|
2162
|
+
path: `${url.pathname}${url.search}`,
|
|
2163
|
+
isConnect: false
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
const hostHeader = request.headers["host"];
|
|
2167
|
+
if (hostHeader === void 0 || hostHeader.trim().length === 0) throw new HttpParseError("Missing Host header");
|
|
2168
|
+
const { host, port } = parseHostPort(hostHeader, 80);
|
|
2169
|
+
return {
|
|
2170
|
+
host,
|
|
2171
|
+
port,
|
|
2172
|
+
scheme: "http",
|
|
2173
|
+
path: request.requestTarget,
|
|
2174
|
+
isConnect: false
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
function rewriteAbsoluteFormToOriginForm(request, originalBuffer) {
|
|
2178
|
+
if (request.method.toUpperCase() === "CONNECT") return originalBuffer;
|
|
2179
|
+
const target = parseTarget(request);
|
|
2180
|
+
const headerEnd = findHeaderEnd(originalBuffer);
|
|
2181
|
+
if (headerEnd < 0) throw new HttpParseError("HTTP header is incomplete");
|
|
2182
|
+
const lines = originalBuffer.subarray(0, headerEnd).toString("latin1").split("\r\n");
|
|
2183
|
+
const rewrittenLines = [`${request.method} ${target.path.length > 0 ? target.path : "/"} ${request.version}`];
|
|
2184
|
+
for (const line of lines.slice(1)) {
|
|
2185
|
+
const colonIndex = line.indexOf(":");
|
|
2186
|
+
if (colonIndex <= 0) continue;
|
|
2187
|
+
if (line.slice(0, colonIndex).trim().toLowerCase() === "proxy-connection") continue;
|
|
2188
|
+
rewrittenLines.push(line);
|
|
2189
|
+
}
|
|
2190
|
+
const rewrittenHeader = `${rewrittenLines.join("\r\n")}\r\n\r\n`;
|
|
2191
|
+
const body = originalBuffer.subarray(headerEnd + 4);
|
|
2192
|
+
return Buffer.concat([Buffer.from(rewrittenHeader, "latin1"), body]);
|
|
2193
|
+
}
|
|
2194
|
+
function createHttpErrorResponse(statusCode, reason) {
|
|
2195
|
+
const body = `${statusCode} ${reason}\n`;
|
|
2196
|
+
return Buffer.from(`HTTP/1.1 ${statusCode} ${reason}\r\nConnection: close\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`, "utf8");
|
|
2197
|
+
}
|
|
2198
|
+
function parseHostPort(value, defaultPort, options = {}) {
|
|
2199
|
+
const trimmed = value.trim();
|
|
2200
|
+
if (trimmed.length === 0) throw new HttpParseError("Missing host");
|
|
2201
|
+
if (trimmed.startsWith("[")) {
|
|
2202
|
+
const closing = trimmed.indexOf("]");
|
|
2203
|
+
if (closing < 0) throw new HttpParseError(`Invalid host:port value: ${value}`);
|
|
2204
|
+
const host = trimmed.slice(1, closing);
|
|
2205
|
+
if (host.length === 0) throw new HttpParseError("Missing host");
|
|
2206
|
+
const rest = trimmed.slice(closing + 1);
|
|
2207
|
+
if (rest.length === 0) {
|
|
2208
|
+
if (options.requirePort === true) throw new HttpParseError(`Missing port in host:port value: ${value}`);
|
|
2209
|
+
return {
|
|
2210
|
+
host,
|
|
2211
|
+
port: defaultPort
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
if (!rest.startsWith(":")) throw new HttpParseError(`Invalid host:port value: ${value}`);
|
|
2215
|
+
return {
|
|
2216
|
+
host,
|
|
2217
|
+
port: parsePort(rest.slice(1))
|
|
2218
|
+
};
|
|
2219
|
+
}
|
|
2220
|
+
if (trimmed.includes("[") || trimmed.includes("]")) throw new HttpParseError(`Invalid host:port value: ${value}`);
|
|
2221
|
+
const firstColon = trimmed.indexOf(":");
|
|
2222
|
+
const lastColon = trimmed.lastIndexOf(":");
|
|
2223
|
+
if (firstColon !== lastColon) throw new HttpParseError(`Invalid host:port value: ${value}`);
|
|
2224
|
+
if (lastColon >= 0) {
|
|
2225
|
+
const host = trimmed.slice(0, lastColon);
|
|
2226
|
+
if (host.length === 0) throw new HttpParseError("Missing host");
|
|
2227
|
+
return {
|
|
2228
|
+
host,
|
|
2229
|
+
port: parsePort(trimmed.slice(lastColon + 1))
|
|
2230
|
+
};
|
|
2231
|
+
}
|
|
2232
|
+
if (options.requirePort === true) throw new HttpParseError(`Missing port in host:port value: ${value}`);
|
|
2233
|
+
return {
|
|
2234
|
+
host: trimmed,
|
|
2235
|
+
port: defaultPort
|
|
2236
|
+
};
|
|
2237
|
+
}
|
|
2238
|
+
function parsePort(value) {
|
|
2239
|
+
if (!/^\d+$/.test(value)) throw new HttpParseError(`Invalid port: ${value}`);
|
|
2240
|
+
const port = Number(value);
|
|
2241
|
+
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) throw new HttpParseError(`Invalid port: ${value}`);
|
|
2242
|
+
return port;
|
|
2243
|
+
}
|
|
2244
|
+
function defaultPortForScheme(scheme) {
|
|
2245
|
+
if (scheme === "https") return 443;
|
|
2246
|
+
return 80;
|
|
2247
|
+
}
|
|
2248
|
+
//#endregion
|
|
2249
|
+
//#region src/router/matcher.ts
|
|
2250
|
+
function matchRoute(config, target, mode, globalProxySelection, groupSelections) {
|
|
2251
|
+
if (mode === "direct" || mode === "script") return {
|
|
2252
|
+
action: "DIRECT",
|
|
2253
|
+
ruleName: "direct-mode"
|
|
2254
|
+
};
|
|
2255
|
+
if (mode === "global") {
|
|
2256
|
+
if (globalProxySelection === void 0 || globalProxySelection === "DIRECT") return {
|
|
2257
|
+
action: "DIRECT",
|
|
2258
|
+
ruleName: "global-mode"
|
|
2259
|
+
};
|
|
2260
|
+
return {
|
|
2261
|
+
action: "PROXY",
|
|
2262
|
+
proxyName: globalProxySelection,
|
|
2263
|
+
ruleName: "global-mode"
|
|
2264
|
+
};
|
|
2265
|
+
}
|
|
2266
|
+
const proxyNames = new Set(config.proxies.map((p) => p.name));
|
|
2267
|
+
const proxyGroups = new Map(config.proxyGroups.map((g) => [g.name, g]));
|
|
2268
|
+
const selections = groupSelections !== void 0 ? Object.fromEntries(groupSelections) : config.user.proxyGroupSelections;
|
|
2269
|
+
for (const rule of config.rules) if (matchesRule(rule, target)) {
|
|
2270
|
+
if (rule.action === "DIRECT") return {
|
|
2271
|
+
action: "DIRECT",
|
|
2272
|
+
ruleName: rule.name
|
|
2273
|
+
};
|
|
2274
|
+
const proxyName = resolveProxyTarget(rule.proxy, config.route.defaultProxy, selections, proxyNames, proxyGroups);
|
|
2275
|
+
if (proxyName === "DIRECT") return {
|
|
2276
|
+
action: "DIRECT",
|
|
2277
|
+
ruleName: rule.name
|
|
2278
|
+
};
|
|
2279
|
+
return {
|
|
2280
|
+
action: "PROXY",
|
|
2281
|
+
proxyName,
|
|
2282
|
+
ruleName: rule.name
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
if (config.route.default === "DIRECT") return {
|
|
2286
|
+
action: "DIRECT",
|
|
2287
|
+
ruleName: "default"
|
|
2288
|
+
};
|
|
2289
|
+
const defaultProxy = resolveProxyTarget(config.route.defaultProxy, void 0, selections, proxyNames, proxyGroups);
|
|
2290
|
+
if (defaultProxy === "DIRECT") return {
|
|
2291
|
+
action: "DIRECT",
|
|
2292
|
+
ruleName: "default"
|
|
2293
|
+
};
|
|
2294
|
+
return {
|
|
2295
|
+
action: "PROXY",
|
|
2296
|
+
proxyName: defaultProxy,
|
|
2297
|
+
ruleName: "default"
|
|
2298
|
+
};
|
|
2299
|
+
}
|
|
2300
|
+
function resolveProxyTarget(target, fallback, selections, proxyNames, proxyGroups, visiting = /* @__PURE__ */ new Set()) {
|
|
2301
|
+
const targetName = target ?? fallback;
|
|
2302
|
+
if (targetName === void 0) throw new Error("No proxy target specified");
|
|
2303
|
+
if (targetName === "DIRECT") return "DIRECT";
|
|
2304
|
+
if (proxyNames.has(targetName)) return targetName;
|
|
2305
|
+
const group = proxyGroups.get(targetName);
|
|
2306
|
+
if (group !== void 0) {
|
|
2307
|
+
if (visiting.has(targetName)) throw new Error(`Cannot resolve cyclic proxy group: ${targetName}`);
|
|
2308
|
+
const nextVisiting = new Set(visiting);
|
|
2309
|
+
nextVisiting.add(targetName);
|
|
2310
|
+
const selected = selections[targetName];
|
|
2311
|
+
if (selected !== void 0) try {
|
|
2312
|
+
return resolveProxyTarget(selected, void 0, selections, proxyNames, proxyGroups, nextVisiting);
|
|
2313
|
+
} catch {}
|
|
2314
|
+
for (const candidate of group.proxies) try {
|
|
2315
|
+
return resolveProxyTarget(candidate, void 0, selections, proxyNames, proxyGroups, nextVisiting);
|
|
2316
|
+
} catch {}
|
|
2317
|
+
}
|
|
2318
|
+
throw new Error(`Cannot resolve proxy target: ${targetName}`);
|
|
2319
|
+
}
|
|
2320
|
+
function matchesRule(rule, target) {
|
|
2321
|
+
const host = target.host.toLowerCase();
|
|
2322
|
+
const value = rule.value.toLowerCase();
|
|
2323
|
+
switch (rule.match) {
|
|
2324
|
+
case "domain": return host === value;
|
|
2325
|
+
case "domain_suffix": return matchesDomainSuffix(host, value);
|
|
2326
|
+
case "domain_keyword": return host.includes(value);
|
|
2327
|
+
case "ip": return host === value;
|
|
2328
|
+
case "ip_cidr": return matchesIpv4Cidr(host, value);
|
|
2329
|
+
case "ip_cidr6": return matchesIpv6Cidr(host, value);
|
|
2330
|
+
case "port": return target.port === Number(rule.value);
|
|
2331
|
+
case "scheme": return target.scheme?.toLowerCase() === value;
|
|
2332
|
+
case "geoip": return false;
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
function matchesDomainSuffix(host, suffix) {
|
|
2336
|
+
const normalized = suffix.startsWith(".") ? suffix.slice(1) : suffix;
|
|
2337
|
+
return host === normalized || host.endsWith(`.${normalized}`);
|
|
2338
|
+
}
|
|
2339
|
+
function matchesIpv4Cidr(host, cidr) {
|
|
2340
|
+
const [network, prefixText] = cidr.split("/");
|
|
2341
|
+
if (network === void 0 || prefixText === void 0) return false;
|
|
2342
|
+
const ipValue = ipv4ToNumber(host);
|
|
2343
|
+
const networkValue = ipv4ToNumber(network);
|
|
2344
|
+
const prefix = Number(prefixText);
|
|
2345
|
+
if (ipValue === null || networkValue === null || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false;
|
|
2346
|
+
const mask = prefix === 0 ? 0 : 4294967295 << 32 - prefix >>> 0;
|
|
2347
|
+
return (ipValue & mask) === (networkValue & mask);
|
|
2348
|
+
}
|
|
2349
|
+
function ipv4ToNumber(value) {
|
|
2350
|
+
const parts = value.split(".");
|
|
2351
|
+
if (parts.length !== 4) return null;
|
|
2352
|
+
let result = 0;
|
|
2353
|
+
for (const part of parts) {
|
|
2354
|
+
if (!/^\d+$/.test(part)) return null;
|
|
2355
|
+
const byte = Number(part);
|
|
2356
|
+
if (!Number.isInteger(byte) || byte < 0 || byte > 255) return null;
|
|
2357
|
+
result = (result << 8 | byte) >>> 0;
|
|
2358
|
+
}
|
|
2359
|
+
return result;
|
|
2360
|
+
}
|
|
2361
|
+
function matchesIpv6Cidr(host, cidr) {
|
|
2362
|
+
const [network, prefixText] = cidr.split("/");
|
|
2363
|
+
if (network === void 0 || prefixText === void 0) return false;
|
|
2364
|
+
const ipValue = ipv6ToBigInt(host);
|
|
2365
|
+
const networkValue = ipv6ToBigInt(network);
|
|
2366
|
+
const prefix = Number(prefixText);
|
|
2367
|
+
if (ipValue === null || networkValue === null || !Number.isInteger(prefix) || prefix < 0 || prefix > 128) return false;
|
|
2368
|
+
const hostBits = 128n - BigInt(prefix);
|
|
2369
|
+
const mask = prefix === 0 ? 0n : (1n << BigInt(prefix)) - 1n << hostBits;
|
|
2370
|
+
return (ipValue & mask) === (networkValue & mask);
|
|
2371
|
+
}
|
|
2372
|
+
function ipv6ToBigInt(value) {
|
|
2373
|
+
if (value.includes(".")) return null;
|
|
2374
|
+
const separatorIndex = value.indexOf("::");
|
|
2375
|
+
const hasCompression = separatorIndex !== -1;
|
|
2376
|
+
if (hasCompression && value.indexOf("::", separatorIndex + 2) !== -1) return null;
|
|
2377
|
+
const left = hasCompression ? value.slice(0, separatorIndex) : value;
|
|
2378
|
+
const right = hasCompression ? value.slice(separatorIndex + 2) : "";
|
|
2379
|
+
const leftParts = splitIpv6Part(left);
|
|
2380
|
+
const rightParts = splitIpv6Part(right);
|
|
2381
|
+
if (leftParts === null || rightParts === null) return null;
|
|
2382
|
+
const missing = 8 - leftParts.length - rightParts.length;
|
|
2383
|
+
if (hasCompression ? missing < 1 : missing !== 0) return null;
|
|
2384
|
+
const parts = [
|
|
2385
|
+
...leftParts,
|
|
2386
|
+
...Array(missing).fill(0),
|
|
2387
|
+
...rightParts
|
|
2388
|
+
];
|
|
2389
|
+
if (parts.length !== 8) return null;
|
|
2390
|
+
let result = 0n;
|
|
2391
|
+
for (const part of parts) result = result << 16n | BigInt(part);
|
|
2392
|
+
return result;
|
|
2393
|
+
}
|
|
2394
|
+
function splitIpv6Part(value) {
|
|
2395
|
+
if (value.length === 0) return [];
|
|
2396
|
+
const fields = value.split(":");
|
|
2397
|
+
const parts = [];
|
|
2398
|
+
for (const field of fields) {
|
|
2399
|
+
if (field.length === 0 || !/^[0-9a-fA-F]{1,4}$/.test(field)) return null;
|
|
2400
|
+
parts.push(Number.parseInt(field, 16));
|
|
2401
|
+
}
|
|
2402
|
+
return parts;
|
|
2403
|
+
}
|
|
2404
|
+
//#endregion
|
|
2405
|
+
//#region src/transport/relay.ts
|
|
2406
|
+
function relaySockets(client, remote) {
|
|
2407
|
+
const closeBoth = () => {
|
|
2408
|
+
if (!client.destroyed) client.destroy();
|
|
2409
|
+
if (!remote.destroyed) remote.destroy();
|
|
2410
|
+
};
|
|
2411
|
+
client.on("error", closeBoth);
|
|
2412
|
+
remote.on("error", closeBoth);
|
|
2413
|
+
client.on("close", closeBoth);
|
|
2414
|
+
remote.on("close", closeBoth);
|
|
2415
|
+
client.pipe(remote);
|
|
2416
|
+
remote.pipe(client);
|
|
2417
|
+
}
|
|
2418
|
+
//#endregion
|
|
2419
|
+
//#region src/server/handler.ts
|
|
2420
|
+
const MAX_HEADER_SIZE = 64 * 1024;
|
|
2421
|
+
function handleClientConnection(client, context) {
|
|
2422
|
+
let buffer = Buffer.alloc(0);
|
|
2423
|
+
const startedAt = Date.now();
|
|
2424
|
+
const onData = (chunk) => {
|
|
2425
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
2426
|
+
if (buffer.length > MAX_HEADER_SIZE) {
|
|
2427
|
+
client.removeListener("data", onData);
|
|
2428
|
+
writeErrorAndClose(client, 400, "Bad Request");
|
|
2429
|
+
return;
|
|
2430
|
+
}
|
|
2431
|
+
if (findHeaderEnd(buffer) < 0) return;
|
|
2432
|
+
client.removeListener("data", onData);
|
|
2433
|
+
client.pause();
|
|
2434
|
+
processClientRequest(client, buffer, context, startedAt);
|
|
2435
|
+
};
|
|
2436
|
+
client.on("data", onData);
|
|
2437
|
+
client.on("error", () => {
|
|
2438
|
+
client.destroy();
|
|
2439
|
+
});
|
|
2440
|
+
}
|
|
2441
|
+
async function processClientRequest(client, buffer, context, startedAt) {
|
|
2442
|
+
let request;
|
|
2443
|
+
let target;
|
|
2444
|
+
let route;
|
|
2445
|
+
try {
|
|
2446
|
+
request = parseHttpRequest(buffer);
|
|
2447
|
+
target = parseTarget(request);
|
|
2448
|
+
route = matchRoute(context.config, toRouteTarget(request, target), context.runtimeState.mode, context.runtimeState.globalProxy, context.runtimeState.groupSelections);
|
|
2449
|
+
const remote = await selectUpstream(context, route).connect(target.host, target.port);
|
|
2450
|
+
if (target.isConnect) {
|
|
2451
|
+
client.write(Buffer.from("HTTP/1.1 200 Connection Established\r\n\r\n", "ascii"));
|
|
2452
|
+
const rest = buffer.subarray(request.headerLength);
|
|
2453
|
+
if (rest.length > 0) remote.write(rest);
|
|
2454
|
+
logAccess(context, request, target, route, startedAt);
|
|
2455
|
+
relaySockets(client, remote);
|
|
2456
|
+
client.resume();
|
|
2457
|
+
return;
|
|
2458
|
+
}
|
|
2459
|
+
remote.write(rewriteAbsoluteFormToOriginForm(request, buffer));
|
|
2460
|
+
logAccess(context, request, target, route, startedAt);
|
|
2461
|
+
relaySockets(client, remote);
|
|
2462
|
+
client.resume();
|
|
2463
|
+
} catch (error) {
|
|
2464
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2465
|
+
const statusCode = message.includes("Bad Request") || message.includes("Invalid") || message.includes("Missing") ? 400 : 502;
|
|
2466
|
+
logAccess(context, request, target, route, startedAt, message);
|
|
2467
|
+
writeErrorAndClose(client, statusCode, statusCode === 400 ? "Bad Request" : "Bad Gateway");
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
function toRouteTarget(request, target) {
|
|
2471
|
+
return {
|
|
2472
|
+
host: target.host,
|
|
2473
|
+
port: target.port,
|
|
2474
|
+
scheme: target.scheme,
|
|
2475
|
+
method: request.method
|
|
2476
|
+
};
|
|
2477
|
+
}
|
|
2478
|
+
function selectUpstream(context, route) {
|
|
2479
|
+
if (route.action === "DIRECT") return context.directProxy;
|
|
2480
|
+
const proxyName = route.proxyName;
|
|
2481
|
+
if (proxyName === void 0) throw new Error("PROXY route has no proxy name");
|
|
2482
|
+
const upstream = context.upstreams.get(proxyName);
|
|
2483
|
+
if (upstream === void 0) throw new Error(`Unknown upstream proxy: ${proxyName}`);
|
|
2484
|
+
return upstream;
|
|
2485
|
+
}
|
|
2486
|
+
function writeErrorAndClose(client, statusCode, reason) {
|
|
2487
|
+
if (client.destroyed) return;
|
|
2488
|
+
client.end(createHttpErrorResponse(statusCode, reason));
|
|
2489
|
+
}
|
|
2490
|
+
function logAccess(context, request, target, route, startedAt, error) {
|
|
2491
|
+
if (!context.logger.isAccessEnabled()) return;
|
|
2492
|
+
const durationMs = Date.now() - startedAt;
|
|
2493
|
+
const method = request?.method ?? "-";
|
|
2494
|
+
const host = target?.host ?? "-";
|
|
2495
|
+
const port = target?.port ?? "-";
|
|
2496
|
+
const action = route?.action ?? "-";
|
|
2497
|
+
const proxy = route?.proxyName ?? "-";
|
|
2498
|
+
const rule = route?.ruleName ?? "-";
|
|
2499
|
+
const suffix = error === void 0 ? "" : ` error=${JSON.stringify(error)}`;
|
|
2500
|
+
context.logger.access(`access method=${method} target=${host}:${port} action=${action} proxy=${proxy} rule=${JSON.stringify(rule)} duration_ms=${durationMs}${suffix}`);
|
|
2501
|
+
}
|
|
2502
|
+
//#endregion
|
|
2503
|
+
//#region src/server/http-server.ts
|
|
2504
|
+
function startHttpProxyServer(config, logger = createLogger(config.log)) {
|
|
2505
|
+
const directProxy = new DirectProxy(config.server.connectTimeoutMs);
|
|
2506
|
+
const runtimeState = {
|
|
2507
|
+
mode: config.mode,
|
|
2508
|
+
globalProxy: void 0,
|
|
2509
|
+
groupSelections: /* @__PURE__ */ new Map()
|
|
2510
|
+
};
|
|
2511
|
+
const context = {
|
|
2512
|
+
config,
|
|
2513
|
+
upstreams: createUpstreamMap(config),
|
|
2514
|
+
directProxy,
|
|
2515
|
+
logger,
|
|
2516
|
+
runtimeState
|
|
2517
|
+
};
|
|
2518
|
+
const server = createServer((socket) => {
|
|
2519
|
+
handleClientConnection(socket, context);
|
|
2520
|
+
});
|
|
2521
|
+
return new Promise((resolve, reject) => {
|
|
2522
|
+
const onError = (error) => {
|
|
2523
|
+
server.removeListener("listening", onListening);
|
|
2524
|
+
reject(error);
|
|
2525
|
+
};
|
|
2526
|
+
const onListening = () => {
|
|
2527
|
+
server.removeListener("error", onError);
|
|
2528
|
+
resolve(new NodeProxyServer(server, runtimeState));
|
|
2529
|
+
};
|
|
2530
|
+
server.once("error", onError);
|
|
2531
|
+
server.once("listening", onListening);
|
|
2532
|
+
server.listen(config.server.port, config.server.host);
|
|
2533
|
+
});
|
|
2534
|
+
}
|
|
2535
|
+
var NodeProxyServer = class {
|
|
2536
|
+
server;
|
|
2537
|
+
runtimeState;
|
|
2538
|
+
constructor(server, runtimeState) {
|
|
2539
|
+
this.server = server;
|
|
2540
|
+
this.runtimeState = runtimeState;
|
|
2541
|
+
}
|
|
2542
|
+
close() {
|
|
2543
|
+
return new Promise((resolve, reject) => {
|
|
2544
|
+
this.server.close((error) => {
|
|
2545
|
+
if (error !== void 0) {
|
|
2546
|
+
reject(error);
|
|
2547
|
+
return;
|
|
2548
|
+
}
|
|
2549
|
+
resolve();
|
|
2550
|
+
});
|
|
2551
|
+
});
|
|
2552
|
+
}
|
|
2553
|
+
setMode(mode) {
|
|
2554
|
+
this.runtimeState.mode = mode;
|
|
2555
|
+
}
|
|
2556
|
+
setGlobalProxy(proxy) {
|
|
2557
|
+
this.runtimeState.globalProxy = proxy;
|
|
2558
|
+
}
|
|
2559
|
+
selectGroup(group, proxy) {
|
|
2560
|
+
this.runtimeState.groupSelections.set(group, proxy);
|
|
2561
|
+
}
|
|
2562
|
+
unsetGroup(group) {
|
|
2563
|
+
this.runtimeState.groupSelections.delete(group);
|
|
2564
|
+
}
|
|
2565
|
+
getSnapshot() {
|
|
2566
|
+
return {
|
|
2567
|
+
mode: this.runtimeState.mode,
|
|
2568
|
+
globalProxy: this.runtimeState.globalProxy,
|
|
2569
|
+
groupSelections: Object.fromEntries(this.runtimeState.groupSelections)
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
};
|
|
2573
|
+
function createUpstreamMap(config) {
|
|
2574
|
+
const upstreams = /* @__PURE__ */ new Map();
|
|
2575
|
+
for (const proxy of config.proxies) upstreams.set(proxy.name, createProxy(proxy, config.server.connectTimeoutMs));
|
|
2576
|
+
return upstreams;
|
|
2577
|
+
}
|
|
2578
|
+
function createProxy(proxy, connectTimeoutMs) {
|
|
2579
|
+
return createUpstreamProxy(proxy, connectTimeoutMs);
|
|
2580
|
+
}
|
|
2581
|
+
//#endregion
|
|
2582
|
+
//#region src/runtime/proxy-runner.ts
|
|
2583
|
+
async function startForegroundProxy(config, profilePath, options = {}) {
|
|
2584
|
+
const logger = createLogger(config.log);
|
|
2585
|
+
const server = await startHttpProxyServer(config, logger);
|
|
2586
|
+
if (profilePath !== void 0) {
|
|
2587
|
+
const profileName = getProfileStateKey(profilePath);
|
|
2588
|
+
const stateEntry = findProfileStateEntry(loadLynxStateConfig(), profileName);
|
|
2589
|
+
if (stateEntry?.mode !== void 0) server.setMode(stateEntry.mode);
|
|
2590
|
+
for (const selection of stateEntry?.selected ?? []) if (selection.name === "GLOBAL") server.setGlobalProxy(selection.now);
|
|
2591
|
+
else server.selectGroup(selection.name, selection.now);
|
|
2592
|
+
}
|
|
2593
|
+
logger.info(`LynxProxy listening on http://${config.server.host}:${config.server.port}`);
|
|
2594
|
+
let controlServer;
|
|
2595
|
+
try {
|
|
2596
|
+
controlServer = await startControlServer(server, config);
|
|
2597
|
+
if (controlServer === void 0) logger.warn("Control socket unavailable on this platform; live switching disabled.");
|
|
2598
|
+
} catch (error) {
|
|
2599
|
+
logger.warn(`Failed to start control socket: ${error instanceof Error ? error.message : String(error)}`);
|
|
2600
|
+
}
|
|
2601
|
+
if (options.daemonState !== void 0) writeProxyDaemonState(options.daemonState);
|
|
2602
|
+
installShutdownHandler(server, controlServer, logger);
|
|
2603
|
+
}
|
|
2604
|
+
function installShutdownHandler(server, controlServer, logger) {
|
|
2605
|
+
let closing = false;
|
|
2606
|
+
const close = (signal) => {
|
|
2607
|
+
if (closing) return;
|
|
2608
|
+
closing = true;
|
|
2609
|
+
logger.info(`received ${signal}, shutting down`);
|
|
2610
|
+
Promise.all([server.close(), controlServer?.close() ?? Promise.resolve()]).then(() => {
|
|
2611
|
+
process.exitCode = 0;
|
|
2612
|
+
}, (error) => {
|
|
2613
|
+
logger.error(error instanceof Error ? error.message : String(error));
|
|
2614
|
+
process.exitCode = 1;
|
|
2615
|
+
});
|
|
2616
|
+
};
|
|
2617
|
+
process.once("SIGINT", close);
|
|
2618
|
+
process.once("SIGTERM", close);
|
|
2619
|
+
}
|
|
2620
|
+
//#endregion
|
|
2621
|
+
//#region src/cli/proxy-cli.ts
|
|
2622
|
+
const STOP_TIMEOUT_MS = 5e3;
|
|
2623
|
+
async function runProxyCommand(args) {
|
|
2624
|
+
const [command, ...rest] = args;
|
|
2625
|
+
if (command === void 0 || command === "--help" || command === "-h") {
|
|
2626
|
+
console.log(createProxyHelpText());
|
|
2627
|
+
return;
|
|
2628
|
+
}
|
|
2629
|
+
if (command === "status") {
|
|
2630
|
+
ensureNoArgs(command, rest);
|
|
2631
|
+
await showStatus();
|
|
2632
|
+
return;
|
|
2633
|
+
}
|
|
2634
|
+
if (command === "start") {
|
|
2635
|
+
ensureNoArgs(command, rest);
|
|
2636
|
+
startDaemon();
|
|
2637
|
+
return;
|
|
2638
|
+
}
|
|
2639
|
+
if (command === "run-daemon") {
|
|
2640
|
+
ensureNoArgs(command, rest);
|
|
2641
|
+
await runDaemonForeground();
|
|
2642
|
+
return;
|
|
2643
|
+
}
|
|
2644
|
+
if (command === "stop") {
|
|
2645
|
+
ensureNoArgs(command, rest);
|
|
2646
|
+
await stopDaemon();
|
|
2647
|
+
return;
|
|
2648
|
+
}
|
|
2649
|
+
if (command === "restart") {
|
|
2650
|
+
ensureNoArgs(command, rest);
|
|
2651
|
+
await restartDaemon();
|
|
2652
|
+
return;
|
|
2653
|
+
}
|
|
2654
|
+
if (command === "reload") {
|
|
2655
|
+
ensureNoArgs(command, rest);
|
|
2656
|
+
console.log("lynx proxy reload is not implemented yet. Use `lynx proxy restart` to apply configuration changes.");
|
|
2657
|
+
return;
|
|
2658
|
+
}
|
|
2659
|
+
if (command === "logs") {
|
|
2660
|
+
ensureNoArgs(command, rest);
|
|
2661
|
+
showLogs();
|
|
2662
|
+
return;
|
|
2663
|
+
}
|
|
2664
|
+
throw new Error(`Unknown proxy command: ${command}`);
|
|
2665
|
+
}
|
|
2666
|
+
async function showStatus() {
|
|
2667
|
+
const state = readStateForStatus();
|
|
2668
|
+
if (state === void 0) {
|
|
2669
|
+
console.log("LynxProxy daemon is not running.");
|
|
2670
|
+
return;
|
|
2671
|
+
}
|
|
2672
|
+
if (!isProcessRunning(state.pid)) {
|
|
2673
|
+
removeProxyDaemonState();
|
|
2674
|
+
console.log("LynxProxy daemon is not running. Removed stale daemon state.");
|
|
2675
|
+
return;
|
|
2676
|
+
}
|
|
2677
|
+
console.log("LynxProxy daemon is running.");
|
|
2678
|
+
console.log(`pid: ${state.pid}`);
|
|
2679
|
+
console.log(`listen: ${state.host}:${state.port}`);
|
|
2680
|
+
console.log(`profile: ${state.profile ?? "(unknown)"}`);
|
|
2681
|
+
if (state.profilePath !== void 0) console.log(`profile path: ${state.profilePath}`);
|
|
2682
|
+
console.log(`started at: ${state.startedAt}`);
|
|
2683
|
+
console.log(`log file: ${state.logFile}`);
|
|
2684
|
+
const controlReady = await isControlSocketReady();
|
|
2685
|
+
console.log(`control socket: ${controlReady ? "ready (live switching available)" : "unavailable"}`);
|
|
2686
|
+
}
|
|
2687
|
+
function startDaemon() {
|
|
2688
|
+
const existing = readStateForStatus();
|
|
2689
|
+
if (existing !== void 0) {
|
|
2690
|
+
if (isProcessRunning(existing.pid)) {
|
|
2691
|
+
console.log(`LynxProxy daemon is already running with PID ${existing.pid}.`);
|
|
2692
|
+
return;
|
|
2693
|
+
}
|
|
2694
|
+
removeProxyDaemonState();
|
|
2695
|
+
}
|
|
2696
|
+
const { config, profilePath } = loadDefaultConfigWithPath();
|
|
2697
|
+
const profile = loadLynxUserConfig().profile;
|
|
2698
|
+
const logFile = getProxyDaemonLogPath();
|
|
2699
|
+
mkdirSync(dirname(logFile), { recursive: true });
|
|
2700
|
+
const out = openSync(logFile, "a");
|
|
2701
|
+
const child = spawn(process.execPath, [
|
|
2702
|
+
process.argv[1],
|
|
2703
|
+
"proxy",
|
|
2704
|
+
"run-daemon"
|
|
2705
|
+
], {
|
|
2706
|
+
detached: true,
|
|
2707
|
+
stdio: [
|
|
2708
|
+
"ignore",
|
|
2709
|
+
out,
|
|
2710
|
+
out
|
|
2711
|
+
],
|
|
2712
|
+
env: process.env
|
|
2713
|
+
});
|
|
2714
|
+
child.unref();
|
|
2715
|
+
console.log(`LynxProxy daemon starting with PID ${child.pid}.`);
|
|
2716
|
+
console.log(`listen: ${config.server.host}:${config.server.port}`);
|
|
2717
|
+
console.log(`profile: ${profile}`);
|
|
2718
|
+
if (profilePath !== void 0) console.log(`profile path: ${profilePath}`);
|
|
2719
|
+
console.log(`log file: ${logFile}`);
|
|
2720
|
+
}
|
|
2721
|
+
async function runDaemonForeground() {
|
|
2722
|
+
const { config, profilePath } = loadDefaultConfigWithPath();
|
|
2723
|
+
const profile = loadLynxUserConfig().profile;
|
|
2724
|
+
const daemonState = {
|
|
2725
|
+
version: 1,
|
|
2726
|
+
pid: process.pid,
|
|
2727
|
+
profile,
|
|
2728
|
+
host: config.server.host,
|
|
2729
|
+
port: config.server.port,
|
|
2730
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2731
|
+
logFile: getProxyDaemonLogPath()
|
|
2732
|
+
};
|
|
2733
|
+
if (profilePath !== void 0) daemonState.profilePath = profilePath;
|
|
2734
|
+
await startForegroundProxy(config, profilePath, { daemonState });
|
|
2735
|
+
}
|
|
2736
|
+
async function stopDaemon() {
|
|
2737
|
+
const state = readStateForStatus();
|
|
2738
|
+
if (state === void 0) {
|
|
2739
|
+
console.log("LynxProxy daemon is not running.");
|
|
2740
|
+
return;
|
|
2741
|
+
}
|
|
2742
|
+
if (!isProcessRunning(state.pid)) {
|
|
2743
|
+
removeProxyDaemonState();
|
|
2744
|
+
console.log("LynxProxy daemon is not running. Removed stale daemon state.");
|
|
2745
|
+
return;
|
|
2746
|
+
}
|
|
2747
|
+
process.kill(state.pid, "SIGTERM");
|
|
2748
|
+
if (!await waitForExit(state.pid, STOP_TIMEOUT_MS)) throw new Error(`Timed out waiting for LynxProxy daemon PID ${state.pid} to stop`);
|
|
2749
|
+
removeProxyDaemonState();
|
|
2750
|
+
console.log(`Stopped LynxProxy daemon PID ${state.pid}.`);
|
|
2751
|
+
}
|
|
2752
|
+
async function restartDaemon() {
|
|
2753
|
+
const state = readStateForStatus();
|
|
2754
|
+
if (state !== void 0 && isProcessRunning(state.pid)) await stopDaemon();
|
|
2755
|
+
else if (state !== void 0) removeProxyDaemonState();
|
|
2756
|
+
startDaemon();
|
|
2757
|
+
}
|
|
2758
|
+
function showLogs() {
|
|
2759
|
+
const logFile = readStateForStatus()?.logFile ?? getProxyDaemonLogPath();
|
|
2760
|
+
if (!existsSync(logFile)) {
|
|
2761
|
+
console.log(`No proxy daemon log file found: ${logFile}`);
|
|
2762
|
+
return;
|
|
2763
|
+
}
|
|
2764
|
+
console.log(readFileSync(logFile, "utf8"));
|
|
2765
|
+
}
|
|
2766
|
+
function readStateForStatus() {
|
|
2767
|
+
try {
|
|
2768
|
+
return loadProxyDaemonState();
|
|
2769
|
+
} catch (error) {
|
|
2770
|
+
removeProxyDaemonState();
|
|
2771
|
+
throw new Error(`Invalid proxy daemon state removed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2772
|
+
}
|
|
2773
|
+
}
|
|
2774
|
+
function waitForExit(pid, timeoutMs) {
|
|
2775
|
+
return new Promise((resolve) => {
|
|
2776
|
+
const started = Date.now();
|
|
2777
|
+
const timer = setInterval(() => {
|
|
2778
|
+
if (!isProcessRunning(pid)) {
|
|
2779
|
+
clearInterval(timer);
|
|
2780
|
+
resolve(true);
|
|
2781
|
+
return;
|
|
2782
|
+
}
|
|
2783
|
+
if (Date.now() - started >= timeoutMs) {
|
|
2784
|
+
clearInterval(timer);
|
|
2785
|
+
resolve(false);
|
|
2786
|
+
}
|
|
2787
|
+
}, 100);
|
|
2788
|
+
});
|
|
2789
|
+
}
|
|
2790
|
+
function ensureNoArgs(command, args) {
|
|
2791
|
+
if (args.length > 0) throw new Error(`Unknown proxy ${command} argument: ${String(args[0])}`);
|
|
2792
|
+
}
|
|
2793
|
+
function createProxyHelpText() {
|
|
2794
|
+
return `Usage: lynx proxy <command> [options]
|
|
2795
|
+
|
|
2796
|
+
Commands:
|
|
2797
|
+
start Start proxy service in background using the active profile
|
|
2798
|
+
stop Stop background proxy service
|
|
2799
|
+
restart Restart background proxy service
|
|
2800
|
+
status Show background proxy status
|
|
2801
|
+
reload Ask user to restart; hot reload is not implemented yet
|
|
2802
|
+
logs Show proxy daemon logs`;
|
|
2803
|
+
}
|
|
2804
|
+
//#endregion
|
|
2805
|
+
//#region src/cli/index.ts
|
|
2806
|
+
const CLI_COMMANDS = new Set([
|
|
2807
|
+
"config",
|
|
2808
|
+
"proxy",
|
|
2809
|
+
"groups"
|
|
2810
|
+
]);
|
|
2811
|
+
function isCliCommand(command) {
|
|
2812
|
+
return command !== void 0 && CLI_COMMANDS.has(command);
|
|
2813
|
+
}
|
|
2814
|
+
async function runCliCommand(args) {
|
|
2815
|
+
const [command, ...rest] = args;
|
|
2816
|
+
if (command === "config") {
|
|
2817
|
+
await runConfigCommand(rest);
|
|
2818
|
+
return;
|
|
2819
|
+
}
|
|
2820
|
+
if (command === "proxy") {
|
|
2821
|
+
await runProxyCommand(rest);
|
|
2822
|
+
return;
|
|
2823
|
+
}
|
|
2824
|
+
if (command === "groups") {
|
|
2825
|
+
await runGroupsCommand(rest);
|
|
2826
|
+
return;
|
|
2827
|
+
}
|
|
2828
|
+
throw new Error(`Unknown command: ${String(command)}`);
|
|
2829
|
+
}
|
|
2830
|
+
function createCliHelpText() {
|
|
2831
|
+
return `Commands:
|
|
2832
|
+
config Manage user config and profile files
|
|
2833
|
+
proxy Control proxy service state
|
|
2834
|
+
groups Manage proxy-group selections
|
|
2835
|
+
|
|
2836
|
+
Run lynx <command> --help for command-specific help.`;
|
|
2837
|
+
}
|
|
2838
|
+
//#endregion
|
|
2839
|
+
//#region src/index.ts
|
|
2840
|
+
const VERSION = "1.0.0";
|
|
2841
|
+
function parseCliArgs(argv) {
|
|
2842
|
+
const options = {
|
|
2843
|
+
help: false,
|
|
2844
|
+
version: false
|
|
2845
|
+
};
|
|
2846
|
+
const args = argv.slice(2);
|
|
2847
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
2848
|
+
const arg = args[index];
|
|
2849
|
+
if (arg === void 0) continue;
|
|
2850
|
+
if (index === 0 && isCliCommand(arg)) {
|
|
2851
|
+
options.commandArgs = args.slice(index);
|
|
2852
|
+
break;
|
|
2853
|
+
}
|
|
2854
|
+
if (arg === "--help" || arg === "-h") options.help = true;
|
|
2855
|
+
else if (arg === "--version" || arg === "-v") options.version = true;
|
|
2856
|
+
else throw new Error(`Unknown argument: ${arg}`);
|
|
2857
|
+
}
|
|
2858
|
+
return options;
|
|
2859
|
+
}
|
|
2860
|
+
async function main(argv = process.argv) {
|
|
2861
|
+
const options = parseCliArgs(argv);
|
|
2862
|
+
if (options.commandArgs !== void 0) {
|
|
2863
|
+
await runCliCommand(options.commandArgs);
|
|
2864
|
+
return;
|
|
2865
|
+
}
|
|
2866
|
+
if (options.help) {
|
|
2867
|
+
console.log(createHelpText());
|
|
2868
|
+
return;
|
|
2869
|
+
}
|
|
2870
|
+
if (options.version) {
|
|
2871
|
+
console.log(VERSION);
|
|
2872
|
+
return;
|
|
2873
|
+
}
|
|
2874
|
+
const { config, profilePath } = loadDefaultConfigWithPath();
|
|
2875
|
+
await startForegroundProxy(config, profilePath);
|
|
2876
|
+
}
|
|
2877
|
+
function createHelpText() {
|
|
2878
|
+
return `Usage: lynx [options]
|
|
2879
|
+
lynx <command> [options]
|
|
2880
|
+
|
|
2881
|
+
Options:
|
|
2882
|
+
-h, --help Show help
|
|
2883
|
+
-v, --version Show version
|
|
2884
|
+
|
|
2885
|
+
${createCliHelpText()}
|
|
2886
|
+
|
|
2887
|
+
LynxProxy reads ~/.config/lynx-proxy/user.json and loads the selected profile
|
|
2888
|
+
from ~/.config/lynx-proxy/profile/. Add a profile with 'lynx config add <name>
|
|
2889
|
+
--file <path>' (or --url / --template), then select it with 'lynx config use
|
|
2890
|
+
<profile>'. If user.json does not exist and ./config.toml is not present,
|
|
2891
|
+
LynxProxy creates a default user.json with profile "default".`;
|
|
2892
|
+
}
|
|
2893
|
+
if (process.argv[1] !== void 0 && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) main(process.argv).catch((error) => {
|
|
2894
|
+
const logger = createDefaultLogger();
|
|
2895
|
+
if (error instanceof ConfigError) logger.error(`Config error: ${error.message}`);
|
|
2896
|
+
else logger.error(error instanceof Error ? error.message : String(error));
|
|
2897
|
+
process.exitCode = 1;
|
|
2898
|
+
});
|
|
2899
|
+
//#endregion
|
|
2900
|
+
export { main, parseCliArgs };
|
|
2901
|
+
|
|
2902
|
+
//# sourceMappingURL=index.mjs.map
|