dsh-clash-subscription 0.2.3 → 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/README.md +132 -167
- package/client.js +223 -29
- package/index.js +687 -83
- package/lib/cn-cidr.js +5526 -0
- package/lib/core.js +323 -85
- package/lib/corefetch.js +618 -0
- package/lib/discovery.js +31 -73
- package/lib/geo.js +130 -0
- package/lib/routes.js +47 -3
- package/lib/subscription.js +196 -0
- package/lib/vendored.js +167 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +8 -3
- package/vendor/SHA256SUMS.json +7 -0
- package/vendor/mihomo.exe.gz +0 -0
package/lib/core.js
CHANGED
|
@@ -2,25 +2,44 @@
|
|
|
2
2
|
* The private mihomo core: config generation, process lifetime, and the local
|
|
3
3
|
* control API this plugin uses to pick a node and read health.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
* 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
|
|
8
|
-
*
|
|
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.
|
|
9
11
|
*
|
|
10
12
|
* @module dsh-clash-proxy/core
|
|
11
13
|
*/
|
|
12
14
|
import { spawn } from 'node:child_process'
|
|
13
|
-
import {
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
14
16
|
import { createServer } from 'node:net'
|
|
15
17
|
import { join } from 'node:path'
|
|
16
|
-
import {
|
|
18
|
+
import { CN_CIDR } from './cn-cidr.js'
|
|
19
|
+
import { findCoreBinary } from './discovery.js'
|
|
17
20
|
|
|
18
21
|
/**
|
|
19
|
-
*
|
|
22
|
+
* GeoIP files a core can use, and the alternatives each satisfies.
|
|
20
23
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
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.
|
|
24
43
|
*/
|
|
25
44
|
const CN_DOMAIN_FALLBACK = [
|
|
26
45
|
'cn',
|
|
@@ -58,52 +77,68 @@ const CN_DOMAIN_FALLBACK = [
|
|
|
58
77
|
'youku.com',
|
|
59
78
|
]
|
|
60
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
|
+
|
|
61
88
|
/** Re-exported so callers keep importing discovery through one module. */
|
|
62
89
|
export { findCoreBinary }
|
|
63
90
|
|
|
64
91
|
/**
|
|
65
|
-
*
|
|
92
|
+
* Write the embedded Chinese address list as a mihomo `ipcidr` rule set.
|
|
66
93
|
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
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`.
|
|
70
104
|
*
|
|
71
105
|
* @param workDir - the core's data directory.
|
|
72
|
-
* @
|
|
73
|
-
* @returns what was found, and which assets are still missing.
|
|
106
|
+
* @returns the rule set path and its entry count.
|
|
74
107
|
*/
|
|
75
|
-
export function
|
|
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) {
|
|
76
136
|
mkdirSync(workDir, { recursive: true })
|
|
77
137
|
const found = []
|
|
78
138
|
const missing = []
|
|
79
139
|
for (const asset of GEO_ASSETS) {
|
|
80
|
-
if (asset.targets.some((target) => existsSync(join(workDir, target))))
|
|
81
|
-
|
|
82
|
-
continue
|
|
83
|
-
}
|
|
84
|
-
let source
|
|
85
|
-
for (const dir of [...extraDirs, ...geoDirs()]) {
|
|
86
|
-
if (dir === '') continue
|
|
87
|
-
const candidate = join(dir, asset.source)
|
|
88
|
-
if (existsSync(candidate)) {
|
|
89
|
-
source = candidate
|
|
90
|
-
break
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
if (source === undefined) {
|
|
94
|
-
missing.push(asset.source)
|
|
95
|
-
continue
|
|
96
|
-
}
|
|
97
|
-
for (const target of asset.targets) {
|
|
98
|
-
const destination = join(workDir, target)
|
|
99
|
-
if (existsSync(destination)) continue
|
|
100
|
-
try {
|
|
101
|
-
copyFileSync(source, destination)
|
|
102
|
-
} catch {
|
|
103
|
-
// A locked or unreadable source only costs this one alias.
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
found.push(asset.source)
|
|
140
|
+
if (asset.targets.some((target) => existsSync(join(workDir, target)))) found.push(asset.source)
|
|
141
|
+
else missing.push(asset.source)
|
|
107
142
|
}
|
|
108
143
|
return { found, missing }
|
|
109
144
|
}
|
|
@@ -126,18 +161,48 @@ export function freePort() {
|
|
|
126
161
|
}
|
|
127
162
|
|
|
128
163
|
/**
|
|
129
|
-
* Build the core configuration for one
|
|
164
|
+
* Build the core configuration for one or more subscriptions.
|
|
130
165
|
*
|
|
131
166
|
* Routing is deliberately narrow: loopback and LAN stay direct so the Harness'
|
|
132
167
|
* own Web UI, plugin routes and local servers never enter a routing loop, Chinese
|
|
133
168
|
* destinations stay direct so domestic sites behave exactly as before, and
|
|
134
169
|
* everything else goes through the selected subscription node.
|
|
135
170
|
*
|
|
136
|
-
*
|
|
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.
|
|
137
176
|
* @returns the configuration object to serialize as JSON.
|
|
138
177
|
*/
|
|
139
178
|
export function buildConfig(options) {
|
|
140
|
-
const {
|
|
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
|
+
|
|
141
206
|
const rules = [
|
|
142
207
|
'IP-CIDR,127.0.0.0/8,DIRECT,no-resolve',
|
|
143
208
|
'IP-CIDR,10.0.0.0/8,DIRECT,no-resolve',
|
|
@@ -148,10 +213,36 @@ export function buildConfig(options) {
|
|
|
148
213
|
]
|
|
149
214
|
for (const domain of splitList(directDomains)) rules.push(`DOMAIN-SUFFIX,${domain},DIRECT`)
|
|
150
215
|
for (const domain of splitList(proxyDomains)) rules.push(`DOMAIN-SUFFIX,${domain},PROXY`)
|
|
151
|
-
|
|
152
|
-
|
|
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`)
|
|
153
222
|
rules.push('MATCH,PROXY')
|
|
154
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
|
+
|
|
155
246
|
return {
|
|
156
247
|
'mixed-port': mixedPort,
|
|
157
248
|
'allow-lan': false,
|
|
@@ -172,24 +263,27 @@ export function buildConfig(options) {
|
|
|
172
263
|
nameserver: dnsServers.length > 0 ? dnsServers : ['223.5.5.5', '119.29.29.29', '114.114.114.114'],
|
|
173
264
|
'proxy-server-nameserver': ['223.5.5.5', '119.29.29.29'],
|
|
174
265
|
},
|
|
175
|
-
'proxy-providers':
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
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
|
+
}),
|
|
188
282
|
'proxy-groups': [
|
|
189
283
|
{
|
|
190
284
|
name: 'PROXY',
|
|
191
285
|
type: 'select',
|
|
192
|
-
use:
|
|
286
|
+
use: names,
|
|
193
287
|
proxies: ['DIRECT'],
|
|
194
288
|
},
|
|
195
289
|
],
|
|
@@ -221,14 +315,18 @@ export class Core {
|
|
|
221
315
|
this.child = undefined
|
|
222
316
|
this.configPath = join(workDir, 'config.json')
|
|
223
317
|
this.providerPath = join(workDir, 'providers', 'sub.yaml')
|
|
224
|
-
/**
|
|
225
|
-
this.
|
|
318
|
+
/** Provider names in configuration order, refreshed on every start. */
|
|
319
|
+
this.providerNames = ['sub']
|
|
226
320
|
this.mixedPort = undefined
|
|
227
321
|
this.controllerPort = undefined
|
|
228
322
|
this.secret = undefined
|
|
229
323
|
this.startedAt = undefined
|
|
230
324
|
this.lastError = undefined
|
|
231
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)
|
|
232
330
|
/** Budget for the startup node search, in milliseconds. */
|
|
233
331
|
this.selectBudgetMs = 45_000
|
|
234
332
|
}
|
|
@@ -241,28 +339,35 @@ export class Core {
|
|
|
241
339
|
/**
|
|
242
340
|
* Write the configuration and start the core.
|
|
243
341
|
*
|
|
244
|
-
* @param options -
|
|
342
|
+
* @param options - subscriptions and routing preferences.
|
|
245
343
|
* @returns the local proxy endpoint.
|
|
246
344
|
*/
|
|
247
345
|
async start(options) {
|
|
248
346
|
await this.stop()
|
|
249
347
|
mkdirSync(join(this.workDir, 'providers'), { recursive: true })
|
|
250
|
-
|
|
251
|
-
|
|
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)
|
|
252
353
|
this.mixedPort = await freePort()
|
|
253
354
|
this.controllerPort = await freePort()
|
|
254
355
|
this.secret = `dsh-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`
|
|
255
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
|
+
|
|
256
361
|
const config = buildConfig({
|
|
257
362
|
...options,
|
|
258
363
|
mixedPort: this.mixedPort,
|
|
259
364
|
controllerPort: this.controllerPort,
|
|
260
365
|
secret: this.secret,
|
|
261
|
-
|
|
262
|
-
//
|
|
263
|
-
//
|
|
264
|
-
|
|
265
|
-
|
|
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,
|
|
266
371
|
})
|
|
267
372
|
writeFileSync(this.configPath, `${JSON.stringify(config, null, 2)}\n`, 'utf8')
|
|
268
373
|
|
|
@@ -296,7 +401,18 @@ export class Core {
|
|
|
296
401
|
})
|
|
297
402
|
|
|
298
403
|
await this.waitForApi(25_000)
|
|
299
|
-
return {
|
|
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
|
+
}
|
|
300
416
|
}
|
|
301
417
|
|
|
302
418
|
/**
|
|
@@ -368,6 +484,43 @@ export class Core {
|
|
|
368
484
|
return { count: list.length, download: data?.downloadTotal ?? 0, upload: data?.uploadTotal ?? 0 }
|
|
369
485
|
}
|
|
370
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
|
+
|
|
371
524
|
/**
|
|
372
525
|
* Measure one node's latency through the core.
|
|
373
526
|
*
|
|
@@ -383,7 +536,13 @@ export class Core {
|
|
|
383
536
|
async delay(name, timeoutMs = 5000) {
|
|
384
537
|
const query = new URLSearchParams({ timeout: String(timeoutMs), url: 'http://www.gstatic.com/generate_204' })
|
|
385
538
|
const encoded = encodeURIComponent(name)
|
|
386
|
-
|
|
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) {
|
|
387
546
|
try {
|
|
388
547
|
const data = await this.api(`${path}?${query}`)
|
|
389
548
|
if (typeof data?.delay === 'number' && data.delay > 0) return data.delay
|
|
@@ -449,24 +608,62 @@ export class Core {
|
|
|
449
608
|
return best.name
|
|
450
609
|
}
|
|
451
610
|
|
|
452
|
-
/**
|
|
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
|
+
*/
|
|
453
619
|
async providerStatus() {
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
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,
|
|
459
648
|
}
|
|
460
649
|
}
|
|
461
650
|
|
|
462
651
|
/**
|
|
463
|
-
* Re-download
|
|
652
|
+
* Re-download every subscription now.
|
|
464
653
|
*
|
|
465
654
|
* @returns the provider status after the refresh.
|
|
466
655
|
*/
|
|
467
656
|
async updateProvider() {
|
|
468
|
-
|
|
469
|
-
|
|
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 }
|
|
470
667
|
}
|
|
471
668
|
|
|
472
669
|
/** Stop the owned process. Never touches another Clash installation. */
|
|
@@ -479,10 +676,51 @@ export class Core {
|
|
|
479
676
|
} catch {
|
|
480
677
|
// already gone
|
|
481
678
|
}
|
|
482
|
-
|
|
679
|
+
let deadline = Date.now() + 4000
|
|
483
680
|
while (child.exitCode === null && Date.now() < deadline) {
|
|
484
681
|
await new Promise((resolve) => setTimeout(resolve, 100))
|
|
485
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
|
+
}
|
|
486
724
|
}
|
|
487
725
|
|
|
488
726
|
/** Read back the config actually written, for diagnostics. */
|