dsh-clash-subscription 0.4.2-probe.5 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/core.js ADDED
@@ -0,0 +1,734 @@
1
+ /**
2
+ * The private mihomo core: config generation, process lifetime, and the local
3
+ * control API this plugin uses to pick a node and read health.
4
+ *
5
+ * Each subscription is handed to the core as its own `proxy-providers` entry rather
6
+ * than parsed here. That keeps every node type (anytls, hysteria2, vless, ss, trojan…)
7
+ * working without a parser, a YAML dependency, or a schema this plugin would have to
8
+ * track — the core already knows how to read its own subscription formats. Several
9
+ * entries feed one `PROXY` group, so a second subscription adds nodes instead of
10
+ * replacing the first, and one unreachable provider never stops the core from booting.
11
+ *
12
+ * @module dsh-clash-proxy/core
13
+ */
14
+ import { spawn } from 'node:child_process'
15
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
16
+ import { createServer } from 'node:net'
17
+ import { join } from 'node:path'
18
+ import { CN_CIDR } from './cn-cidr.js'
19
+ import { findCoreBinary } from './discovery.js'
20
+
21
+ /**
22
+ * GeoIP files a core can use, and the alternatives each satisfies.
23
+ *
24
+ * Listed here rather than in `discovery` because nothing is discovered about them any more:
25
+ * a database arrives in this plugin's data directory only by being fetched, and this table
26
+ * is what says which names matter.
27
+ */
28
+ const GEO_ASSETS = [
29
+ { source: 'Country.mmdb', targets: ['Country.mmdb', 'geoip.metadb'] },
30
+ { source: 'geoip.dat', targets: ['geoip.dat'] },
31
+ { source: 'geosite.dat', targets: ['geosite.dat'] },
32
+ { source: 'ASN.mmdb', targets: ['ASN.mmdb'] },
33
+ ]
34
+
35
+ /**
36
+ * Domestic suffixes used as an extra signal beside the embedded CIDR list.
37
+ *
38
+ * The CIDR list decides by address and covers every Chinese allocation; this list is
39
+ * not a substitute for it. It exists because a domain rule needs no DNS resolution and
40
+ * therefore answers instantly for the handful of destinations the Harness hits most —
41
+ * and because a `.cn` suffix is authoritative in a way an address lookup cannot be when
42
+ * a site sits behind a foreign CDN.
43
+ */
44
+ const CN_DOMAIN_FALLBACK = [
45
+ 'cn',
46
+ 'baidu.com',
47
+ 'bdstatic.com',
48
+ 'qq.com',
49
+ 'gtimg.cn',
50
+ 'weixin.qq.com',
51
+ 'aliyun.com',
52
+ 'alicdn.com',
53
+ 'alipay.com',
54
+ 'taobao.com',
55
+ 'tmall.com',
56
+ 'jd.com',
57
+ '163.com',
58
+ '126.net',
59
+ 'zhihu.com',
60
+ 'zhimg.com',
61
+ 'bilibili.com',
62
+ 'hdslb.com',
63
+ 'csdn.net',
64
+ 'gitee.com',
65
+ 'douyin.com',
66
+ 'bytedance.com',
67
+ 'toutiao.com',
68
+ 'sina.com.cn',
69
+ 'weibo.com',
70
+ 'jianshu.com',
71
+ 'cnblogs.com',
72
+ 'tencent.com',
73
+ 'huawei.com',
74
+ 'xiaomi.com',
75
+ 'mi.com',
76
+ 'iqiyi.com',
77
+ 'youku.com',
78
+ ]
79
+
80
+ /**
81
+ * File name of the generated domestic address rule set.
82
+ *
83
+ * Written next to the core config, not inside a provider cache, because it is part of
84
+ * this plugin's configuration rather than something downloaded.
85
+ */
86
+ const CN_RULESET_FILE = 'cn-cidr.txt'
87
+
88
+ /** Re-exported so callers keep importing discovery through one module. */
89
+ export { findCoreBinary }
90
+
91
+ /**
92
+ * Write the embedded Chinese address list as a mihomo `ipcidr` rule set.
93
+ *
94
+ * This is what removes the GeoIP database from the critical path. A core with no
95
+ * `Country.mmdb` reports `MMDB invalid, remove and download` and then tries to fetch
96
+ * one over the very tunnel that is not up yet; measured on a clean data directory, so
97
+ * the fallback was previously a 30-domain list that sent meituan.com / xiaohongshu.com /
98
+ * ctrip.com through a foreign node. An `ipcidr` rule set is a plain text file, so the
99
+ * domestic decision survives with no database at all.
100
+ *
101
+ * The rule that consumes it must NOT carry `no-resolve`: a CONNECT to a hostname has no
102
+ * address to compare until the core resolves it, and measured behaviour was that
103
+ * `no-resolve` made every domestic site fall through to `MATCH`.
104
+ *
105
+ * @param workDir - the core's data directory.
106
+ * @returns the rule set path and its entry count.
107
+ */
108
+ export function writeCnRuleSet(workDir) {
109
+ mkdirSync(workDir, { recursive: true })
110
+ const path = join(workDir, CN_RULESET_FILE)
111
+ const body = `${CN_CIDR.join('\n')}\n`
112
+ // Rewrite only when the content actually changed: the core watches nothing here, but a
113
+ // needless write on every boot makes the file's mtime meaningless as a diagnostic.
114
+ let same = false
115
+ try {
116
+ same = readFileSync(path, 'utf8') === body
117
+ } catch {
118
+ same = false
119
+ }
120
+ if (!same) writeFileSync(path, body, 'utf8')
121
+ return { path, count: CN_CIDR.length }
122
+ }
123
+
124
+ /**
125
+ * Report which geo databases this plugin's own data directory already holds.
126
+ *
127
+ * It reads only its own directory. An earlier version copied databases out of a local
128
+ * Clash installation, which made behaviour depend on whether another client happened to be
129
+ * installed — and on which one. That is gone: a database arrives here only by being
130
+ * fetched by this plugin, after routing works.
131
+ *
132
+ * @param workDir - the core's data directory.
133
+ * @returns the file names present, and the ones the core would still like to have.
134
+ */
135
+ export function inspectGeoAssets(workDir) {
136
+ mkdirSync(workDir, { recursive: true })
137
+ const found = []
138
+ const missing = []
139
+ for (const asset of GEO_ASSETS) {
140
+ if (asset.targets.some((target) => existsSync(join(workDir, target)))) found.push(asset.source)
141
+ else missing.push(asset.source)
142
+ }
143
+ return { found, missing }
144
+ }
145
+
146
+ /**
147
+ * Ask the OS for a free loopback TCP port.
148
+ *
149
+ * @returns the port number.
150
+ */
151
+ export function freePort() {
152
+ return new Promise((resolve, reject) => {
153
+ const server = createServer()
154
+ server.once('error', reject)
155
+ server.listen(0, '127.0.0.1', () => {
156
+ const address = server.address()
157
+ const port = typeof address === 'object' && address !== null ? address.port : undefined
158
+ server.close(() => (port === undefined ? reject(new Error('no port assigned')) : resolve(port)))
159
+ })
160
+ })
161
+ }
162
+
163
+ /**
164
+ * Build the core configuration for one or more subscriptions.
165
+ *
166
+ * Routing is deliberately narrow: loopback and LAN stay direct so the Harness'
167
+ * own Web UI, plugin routes and local servers never enter a routing loop, Chinese
168
+ * destinations stay direct so domestic sites behave exactly as before, and
169
+ * everything else goes through the selected subscription node.
170
+ *
171
+ * Every subscription contributes one `proxy-providers` entry and every entry is
172
+ * listed in the single `PROXY` group's `use`, which is what makes the node table the
173
+ * union of all of them.
174
+ *
175
+ * @param options - subscriptions, ports and DNS preferences.
176
+ * @returns the configuration object to serialize as JSON.
177
+ */
178
+ export function buildConfig(options) {
179
+ const {
180
+ mixedPort,
181
+ controllerPort,
182
+ secret,
183
+ subscriptions,
184
+ providerPaths,
185
+ mode,
186
+ dnsServers,
187
+ directDomains,
188
+ proxyDomains,
189
+ cnRuleSet,
190
+ cnRuleSetPath,
191
+ singleUrl,
192
+ subscriptionUrl,
193
+ providerPath,
194
+ } = options
195
+
196
+ // Accept both shapes: a list of subscriptions (0.3) and a single URL (0.2 and the
197
+ // tests written against it). Normalizing here keeps every caller honest without
198
+ // two config builders.
199
+ const one = singleUrl ?? subscriptionUrl
200
+ const list = Array.isArray(subscriptions) && subscriptions.length > 0
201
+ ? subscriptions
202
+ : one !== undefined && one !== ''
203
+ ? [{ provider: 'sub', url: one, prefix: '' }]
204
+ : []
205
+
206
+ const rules = [
207
+ 'IP-CIDR,127.0.0.0/8,DIRECT,no-resolve',
208
+ 'IP-CIDR,10.0.0.0/8,DIRECT,no-resolve',
209
+ 'IP-CIDR,172.16.0.0/12,DIRECT,no-resolve',
210
+ 'IP-CIDR,192.168.0.0/16,DIRECT,no-resolve',
211
+ 'IP-CIDR,169.254.0.0/16,DIRECT,no-resolve',
212
+ 'DOMAIN-SUFFIX,local,DIRECT',
213
+ ]
214
+ for (const domain of splitList(directDomains)) rules.push(`DOMAIN-SUFFIX,${domain},DIRECT`)
215
+ for (const domain of splitList(proxyDomains)) rules.push(`DOMAIN-SUFFIX,${domain},PROXY`)
216
+ for (const suffix of CN_DOMAIN_FALLBACK) rules.push(`DOMAIN-SUFFIX,${suffix},DIRECT`)
217
+ // The address rule comes after the domain list (so a `.cn` name answers without a
218
+ // lookup) and before MATCH. No `no-resolve`: measured, a CONNECT to a hostname has no
219
+ // address until the core resolves it, and `no-resolve` made every domestic site fall
220
+ // through to MATCH — i.e. straight into the tunnel.
221
+ if (cnRuleSet !== undefined && cnRuleSet !== '') rules.push(`RULE-SET,${cnRuleSet},DIRECT`)
222
+ rules.push('MATCH,PROXY')
223
+
224
+ const providers = {}
225
+ const names = []
226
+ for (const [at, entry] of list.entries()) {
227
+ const name = String(entry?.provider ?? `sub${at}`)
228
+ names.push(name)
229
+ const path = Array.isArray(providerPaths) ? providerPaths[at] : providerPath
230
+ providers[name] = {
231
+ type: 'http',
232
+ url: String(entry?.url ?? ''),
233
+ interval: 3600,
234
+ path: path ?? `providers/${name}.yaml`,
235
+ 'health-check': {
236
+ enable: true,
237
+ url: 'http://www.gstatic.com/generate_204',
238
+ interval: 300,
239
+ },
240
+ ...(String(entry?.prefix ?? '') === ''
241
+ ? {}
242
+ : { override: { 'additional-prefix': String(entry.prefix) } }),
243
+ }
244
+ }
245
+
246
+ return {
247
+ 'mixed-port': mixedPort,
248
+ 'allow-lan': false,
249
+ mode: mode === 'global' ? 'global' : 'rule',
250
+ 'log-level': 'warning',
251
+ ipv6: false,
252
+ 'external-controller': `127.0.0.1:${controllerPort}`,
253
+ secret,
254
+ 'unified-delay': true,
255
+ 'tcp-concurrent': true,
256
+ profile: { 'store-selected': true, 'store-fake-ip': true },
257
+ dns: {
258
+ enable: true,
259
+ ipv6: false,
260
+ 'enhanced-mode': 'normal',
261
+ 'use-hosts': true,
262
+ 'default-nameserver': ['223.5.5.5', '119.29.29.29'],
263
+ nameserver: dnsServers.length > 0 ? dnsServers : ['223.5.5.5', '119.29.29.29', '114.114.114.114'],
264
+ 'proxy-server-nameserver': ['223.5.5.5', '119.29.29.29'],
265
+ },
266
+ 'proxy-providers': providers,
267
+ ...(cnRuleSet === undefined || cnRuleSet === ''
268
+ ? {}
269
+ : {
270
+ 'rule-providers': {
271
+ [cnRuleSet]: {
272
+ // `file` rather than `http`: the list ships inside the plugin, so there is
273
+ // nothing to download and no interval to schedule.
274
+ type: 'file',
275
+ behavior: 'ipcidr',
276
+ format: 'text',
277
+ path: cnRuleSetPath,
278
+ interval: 86400,
279
+ },
280
+ },
281
+ }),
282
+ 'proxy-groups': [
283
+ {
284
+ name: 'PROXY',
285
+ type: 'select',
286
+ use: names,
287
+ proxies: ['DIRECT'],
288
+ },
289
+ ],
290
+ rules,
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Split a comma/newline separated list into trimmed non-empty entries.
296
+ *
297
+ * @param value - raw list text.
298
+ * @returns the entries.
299
+ */
300
+ export function splitList(value) {
301
+ return String(value ?? '')
302
+ .split(/[,\s]+/)
303
+ .map((entry) => entry.trim())
304
+ .filter((entry) => entry !== '')
305
+ }
306
+
307
+ /**
308
+ * One running core process plus the control calls this plugin needs.
309
+ */
310
+ export class Core {
311
+ constructor({ binary, workDir, logger }) {
312
+ this.binary = binary
313
+ this.workDir = workDir
314
+ this.log = logger ?? (() => {})
315
+ this.child = undefined
316
+ this.configPath = join(workDir, 'config.json')
317
+ this.providerPath = join(workDir, 'providers', 'sub.yaml')
318
+ /** Provider names in configuration order, refreshed on every start. */
319
+ this.providerNames = ['sub']
320
+ this.mixedPort = undefined
321
+ this.controllerPort = undefined
322
+ this.secret = undefined
323
+ this.startedAt = undefined
324
+ this.lastError = undefined
325
+ this.geo = { found: [], missing: [] }
326
+ /** The generated domestic address rule set, refreshed on every start. */
327
+ this.cnRuleSet = undefined
328
+ /** Where that rule set lives, so the config builder can point the core at it. */
329
+ this.cnRuleSetPath = join(workDir, CN_RULESET_FILE)
330
+ /** Budget for the startup node search, in milliseconds. */
331
+ this.selectBudgetMs = 45_000
332
+ }
333
+
334
+ /** Whether the plugin currently owns a live process. */
335
+ get running() {
336
+ return this.child !== undefined && this.child.exitCode === null && !this.child.killed
337
+ }
338
+
339
+ /**
340
+ * Write the configuration and start the core.
341
+ *
342
+ * @param options - subscriptions and routing preferences.
343
+ * @returns the local proxy endpoint.
344
+ */
345
+ async start(options) {
346
+ await this.stop()
347
+ mkdirSync(join(this.workDir, 'providers'), { recursive: true })
348
+ // Only this plugin's own directory is consulted. Nothing is copied in from another
349
+ // Clash installation, so the same data directory produces the same behaviour whether or
350
+ // not the machine has one.
351
+ this.geo = inspectGeoAssets(this.workDir)
352
+ this.cnRuleSet = writeCnRuleSet(this.workDir)
353
+ this.mixedPort = await freePort()
354
+ this.controllerPort = await freePort()
355
+ this.secret = `dsh-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`
356
+
357
+ const subscriptions = Array.isArray(options.subscriptions) ? options.subscriptions : []
358
+ if (subscriptions.length > 0) this.providerNames = subscriptions.map((entry) => String(entry.provider))
359
+ else if (String(options.subscriptionUrl ?? '') !== '') this.providerNames = ['sub']
360
+
361
+ const config = buildConfig({
362
+ ...options,
363
+ mixedPort: this.mixedPort,
364
+ controllerPort: this.controllerPort,
365
+ secret: this.secret,
366
+ providerPaths: this.providerNames.map((name) => join(this.workDir, 'providers', `${name}.yaml`)),
367
+ // The domestic address list is generated from the plugin's own data, so the
368
+ // bypass no longer depends on whether a GeoIP database happens to be present.
369
+ cnRuleSet: 'cn-cidr',
370
+ cnRuleSetPath: this.cnRuleSetPath,
371
+ })
372
+ writeFileSync(this.configPath, `${JSON.stringify(config, null, 2)}\n`, 'utf8')
373
+
374
+ const child = spawn(this.binary, ['-d', this.workDir, '-f', this.configPath], {
375
+ cwd: this.workDir,
376
+ windowsHide: true,
377
+ stdio: ['ignore', 'pipe', 'pipe'],
378
+ env: { ...process.env, NO_PROXY: '*', no_proxy: '*' },
379
+ })
380
+ this.child = child
381
+ this.startedAt = Date.now()
382
+ this.lastError = undefined
383
+
384
+ const collect = (chunk) => {
385
+ const text = String(chunk)
386
+ for (const line of text.split(/\r?\n/)) {
387
+ const trimmed = line.trim()
388
+ if (trimmed === '') continue
389
+ if (/level=(error|fatal)/.test(trimmed)) this.lastError = trimmed
390
+ this.log(trimmed)
391
+ }
392
+ }
393
+ child.stdout?.on('data', collect)
394
+ child.stderr?.on('data', collect)
395
+ child.once('exit', (code) => {
396
+ this.log(`core exited code=${code}`)
397
+ if (this.child === child) {
398
+ this.child = undefined
399
+ this.lastError = this.lastError ?? `core exited with code ${code}`
400
+ }
401
+ })
402
+
403
+ await this.waitForApi(25_000)
404
+ return {
405
+ host: '127.0.0.1',
406
+ port: this.mixedPort,
407
+ geo: this.geo,
408
+ providers: this.providerNames,
409
+ // Flattened to the two facts a caller can act on: the rule-set name the core knows and
410
+ // how many blocks it loaded. Returning the `{path, count}` object made every consumer
411
+ // that printed it show `undefined` for a rule set that was demonstrably working.
412
+ cnRuleSet: this.cnRuleSet?.count === undefined
413
+ ? undefined
414
+ : { name: 'cn-cidr', count: this.cnRuleSet.count, path: this.cnRuleSet.path },
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Poll the control API until it answers, so callers never race the first request.
420
+ *
421
+ * @param timeoutMs - total budget.
422
+ */
423
+ async waitForApi(timeoutMs) {
424
+ const deadline = Date.now() + timeoutMs
425
+ while (Date.now() < deadline) {
426
+ if (this.child === undefined) throw new Error(this.lastError ?? 'core exited before its control API answered')
427
+ try {
428
+ const response = await fetch(`http://127.0.0.1:${this.controllerPort}/version`, {
429
+ headers: { authorization: `Bearer ${this.secret}` },
430
+ signal: AbortSignal.timeout(1500),
431
+ })
432
+ if (response.ok) return
433
+ } catch {
434
+ // not listening yet
435
+ }
436
+ await new Promise((resolve) => setTimeout(resolve, 250))
437
+ }
438
+ throw new Error('core did not answer its control API in time')
439
+ }
440
+
441
+ /**
442
+ * Call the control API.
443
+ *
444
+ * @param path - API path beginning with a slash.
445
+ * @param init - extra request options.
446
+ * @returns the decoded JSON body, or undefined for an empty response.
447
+ */
448
+ async api(path, init = {}) {
449
+ if (this.controllerPort === undefined) throw new Error('core is not running')
450
+ const response = await fetch(`http://127.0.0.1:${this.controllerPort}${path}`, {
451
+ ...init,
452
+ headers: {
453
+ authorization: `Bearer ${this.secret}`,
454
+ ...(init.body === undefined ? {} : { 'content-type': 'application/json' }),
455
+ ...(init.headers ?? {}),
456
+ },
457
+ signal: init.signal ?? AbortSignal.timeout(10_000),
458
+ })
459
+ const text = await response.text()
460
+ if (!response.ok) throw new Error(`control API ${path} failed: ${response.status} ${text.slice(0, 200)}`)
461
+ return text === '' ? undefined : JSON.parse(text)
462
+ }
463
+
464
+ /** The `PROXY` group's node table and current selection. */
465
+ async group() {
466
+ const data = await this.api('/proxies/PROXY')
467
+ return { name: data?.name, now: data?.now, all: Array.isArray(data?.all) ? data.all : [] }
468
+ }
469
+
470
+ /**
471
+ * Select a node in the `PROXY` group.
472
+ *
473
+ * @param name - exact node name from the group's `all` list.
474
+ */
475
+ async select(name) {
476
+ await this.api('/proxies/PROXY', { method: 'PUT', body: JSON.stringify({ name }) })
477
+ return await this.group()
478
+ }
479
+
480
+ /** Live connections the core is carrying, for the status report. */
481
+ async connections() {
482
+ const data = await this.api('/connections')
483
+ const list = Array.isArray(data?.connections) ? data.connections : []
484
+ return { count: list.length, download: data?.downloadTotal ?? 0, upload: data?.uploadTotal ?? 0 }
485
+ }
486
+
487
+ /**
488
+ * Which provider currently holds a node.
489
+ *
490
+ * Nodes that arrive from a `proxy-provider` do not live in the core's own proxy
491
+ * table: `/proxies/<name>/delay` answers `Resource not found` for them, and the
492
+ * provider namespace is the only route that answers. With several providers the
493
+ * namespace is not known up front, so this reads the provider table once and finds
494
+ * the owner. A node name that appears in two providers resolves to the first, which
495
+ * is why {@link buildConfig} gives each provider a distinct prefix whenever more
496
+ * than one subscription is configured.
497
+ *
498
+ * @param name - node name.
499
+ * @returns the provider name, or undefined when no provider lists it.
500
+ */
501
+ async providerOf(name) {
502
+ try {
503
+ const data = await this.api('/providers/proxies')
504
+ const map = data?.providers !== null && typeof data?.providers === 'object' ? data.providers : {}
505
+ for (const [provider, detail] of Object.entries(map)) {
506
+ const nodes = detail?.proxies
507
+ if (nodes !== null && typeof nodes === 'object' && Object.hasOwn(nodes, name)) return provider
508
+ }
509
+ } catch {
510
+ // fall through to the name list
511
+ }
512
+ for (const provider of this.providerNames) {
513
+ try {
514
+ const detail = await this.api(`/providers/proxies/${encodeURIComponent(provider)}`)
515
+ const nodes = detail?.proxies
516
+ if (nodes !== null && typeof nodes === 'object' && Object.hasOwn(nodes, name)) return provider
517
+ } catch {
518
+ // try the next one
519
+ }
520
+ }
521
+ return undefined
522
+ }
523
+
524
+ /**
525
+ * Measure one node's latency through the core.
526
+ *
527
+ * Nodes that arrive from a `proxy-provider` do not live in the core's own proxy
528
+ * table: `/proxies/<name>/delay` answers `Resource not found` for them. They are
529
+ * reachable only through the provider namespace, under `healthcheck`. Both paths
530
+ * are tried so a group proxy and a provider proxy behave the same to callers.
531
+ *
532
+ * @param name - node name.
533
+ * @param timeoutMs - per-request budget.
534
+ * @returns the delay in milliseconds, or null when it failed.
535
+ */
536
+ async delay(name, timeoutMs = 5000) {
537
+ const query = new URLSearchParams({ timeout: String(timeoutMs), url: 'http://www.gstatic.com/generate_204' })
538
+ const encoded = encodeURIComponent(name)
539
+ const owner = await this.providerOf(name)
540
+ const paths = [
541
+ ...(owner === undefined ? [] : [`/providers/proxies/${encodeURIComponent(owner)}/${encoded}/healthcheck`]),
542
+ ...this.providerNames.map((provider) => `/providers/proxies/${encodeURIComponent(provider)}/${encoded}/healthcheck`),
543
+ `/proxies/${encoded}/delay`,
544
+ ]
545
+ for (const path of paths) {
546
+ try {
547
+ const data = await this.api(`${path}?${query}`)
548
+ if (typeof data?.delay === 'number' && data.delay > 0) return data.delay
549
+ } catch {
550
+ // try the next namespace
551
+ }
552
+ }
553
+ return null
554
+ }
555
+
556
+ /**
557
+ * Choose a working exit node, in this order: the caller's preference, then the
558
+ * lowest measured latency across a sample, then a single-node verification of the
559
+ * rest. Nodes whose latency cannot be measured are dead and are never chosen.
560
+ *
561
+ * `DIRECT` is a legal group member but never a useful selection for this plugin —
562
+ * leaving it selected would silently route foreign traffic straight out.
563
+ *
564
+ * @param preferred - a node name to honour when it exists and answers.
565
+ * @returns the selected node name, or undefined when nothing answered.
566
+ */
567
+ async autoSelect(preferred) {
568
+ const group = await this.group()
569
+ const candidates = group.all.filter((entry) => entry !== 'DIRECT')
570
+ if (candidates.length === 0) return undefined
571
+
572
+ const wanted = String(preferred ?? '').trim()
573
+ if (wanted !== '' && candidates.includes(wanted)) {
574
+ const delay = await this.delay(wanted, 5000)
575
+ if (delay !== null) {
576
+ await this.select(wanted)
577
+ return wanted
578
+ }
579
+ this.log(`preferred node "${wanted}" did not answer a latency test; choosing another`)
580
+ }
581
+
582
+ // Probe in bounded concurrent batches: one measurement per node is the only
583
+ // reliable "is this node usable" answer, and sequential probing over a 50-node
584
+ // subscription takes longer than the whole startup. A node that misreports itself
585
+ // as alive still fails here, which is why latency rather than health status gates
586
+ // the choice.
587
+ const deadline = Date.now() + (this.selectBudgetMs ?? 45_000)
588
+ const batchSize = 10
589
+ let best
590
+ for (let at = 0; at < candidates.length && Date.now() < deadline; at += batchSize) {
591
+ const batch = candidates.slice(at, at + batchSize)
592
+ const results = await Promise.all(
593
+ batch.map(async (name) => ({ name, delay: await this.delay(name, 4000) })),
594
+ )
595
+ for (const result of results) {
596
+ if (result.delay === null) continue
597
+ if (best === undefined || result.delay < best.delay) best = result
598
+ }
599
+ // A clearly good node ends the search early: the first working exit is enough to
600
+ // bring routing up, and the panel can re-test later.
601
+ if (best !== undefined && best.delay <= 1200) break
602
+ }
603
+ if (best === undefined) {
604
+ this.log('no node answered a latency test; leaving the group on its current selection')
605
+ return undefined
606
+ }
607
+ await this.select(best.name)
608
+ return best.name
609
+ }
610
+
611
+ /**
612
+ * Every provider's fetch state: whether its subscription downloaded and when.
613
+ *
614
+ * The panel shows one row per subscription, so a provider that alone failed is
615
+ * visible as such instead of being averaged into a single healthy flag.
616
+ *
617
+ * @returns one entry per configured provider.
618
+ */
619
+ async providerStatus() {
620
+ const rows = []
621
+ for (const provider of this.providerNames) {
622
+ try {
623
+ const data = await this.api(`/providers/proxies/${encodeURIComponent(provider)}`)
624
+ const nodes = data?.proxies !== null && typeof data?.proxies === 'object' ? Object.keys(data.proxies) : []
625
+ const updatedAt = data?.updatedAt ?? null
626
+ // mihomo reports a never-fetched provider as the zero time, not null.
627
+ const fetched = updatedAt !== null && !String(updatedAt).startsWith('0001-01-01')
628
+ rows.push({
629
+ provider,
630
+ updatedAt: fetched ? updatedAt : null,
631
+ vehicleType: data?.vehicleType ?? null,
632
+ nodeCount: nodes.length,
633
+ ok: fetched && nodes.length > 0,
634
+ })
635
+ } catch {
636
+ rows.push({ provider, updatedAt: null, vehicleType: null, nodeCount: 0, ok: false })
637
+ }
638
+ }
639
+ const healthy = rows.filter((row) => row.ok)
640
+ return {
641
+ /** Kept for the 0.2 panel/API shape: the first provider's timestamp. */
642
+ updatedAt: rows[0]?.updatedAt ?? null,
643
+ vehicleType: rows[0]?.vehicleType ?? null,
644
+ providers: rows,
645
+ ok: rows.length > 0 && healthy.length > 0,
646
+ healthy: healthy.length,
647
+ total: rows.length,
648
+ }
649
+ }
650
+
651
+ /**
652
+ * Re-download every subscription now.
653
+ *
654
+ * @returns the provider status after the refresh.
655
+ */
656
+ async updateProvider() {
657
+ const failed = []
658
+ for (const provider of this.providerNames) {
659
+ try {
660
+ await this.api(`/providers/proxies/${encodeURIComponent(provider)}`, { method: 'PUT' })
661
+ } catch (error) {
662
+ failed.push({ provider, reason: String(error?.message ?? error) })
663
+ }
664
+ }
665
+ const status = await this.providerStatus()
666
+ return { ...status, failed }
667
+ }
668
+
669
+ /** Stop the owned process. Never touches another Clash installation. */
670
+ async stop() {
671
+ const child = this.child
672
+ this.child = undefined
673
+ if (child === undefined) return
674
+ try {
675
+ child.kill()
676
+ } catch {
677
+ // already gone
678
+ }
679
+ let deadline = Date.now() + 4000
680
+ while (child.exitCode === null && Date.now() < deadline) {
681
+ await new Promise((resolve) => setTimeout(resolve, 100))
682
+ }
683
+ // `child.kill()` alone is not enough on Windows: a core that is mid-connection (or one
684
+ // that simply ignores the default signal) survives it, and then a restart leaves two
685
+ // cores holding the same config file — observed as two `mihomo.exe` processes with the
686
+ // same `-d` directory, the older one orphaned and unreachable through the control API.
687
+ // Escalate to a forced termination of this pid only; never by image name, because a
688
+ // user's own Clash process would match that.
689
+ if (child.exitCode === null && process.platform === 'win32') {
690
+ try {
691
+ await new Promise((resolve) => {
692
+ const killer = spawn('taskkill', ['/F', '/PID', String(child.pid)], { windowsHide: true, stdio: 'ignore' })
693
+ killer.once('exit', resolve)
694
+ killer.once('error', resolve)
695
+ })
696
+ } catch {
697
+ // Reported by the wait below rather than thrown from a stop path.
698
+ }
699
+ deadline = Date.now() + 3000
700
+ while (child.exitCode === null && Date.now() < deadline) {
701
+ await new Promise((resolve) => setTimeout(resolve, 100))
702
+ }
703
+ if (child.exitCode === null) this.log(`core pid ${child.pid} did not exit after a forced kill`)
704
+ }
705
+ }
706
+
707
+ /**
708
+ * Whether a process with this pid is still alive.
709
+ *
710
+ * Used by the watchdog to notice a core it lost track of, so an orphan cannot keep the
711
+ * port while a new core is started beside it.
712
+ *
713
+ * @param pid - process id to test.
714
+ * @returns true when the process still exists.
715
+ */
716
+ static pidAlive(pid) {
717
+ if (typeof pid !== 'number' || pid <= 0) return false
718
+ try {
719
+ process.kill(pid, 0)
720
+ return true
721
+ } catch (error) {
722
+ return error?.code === 'EPERM'
723
+ }
724
+ }
725
+
726
+ /** Read back the config actually written, for diagnostics. */
727
+ readConfig() {
728
+ try {
729
+ return JSON.parse(readFileSync(this.configPath, 'utf8'))
730
+ } catch {
731
+ return undefined
732
+ }
733
+ }
734
+ }