dsh-clash-subscription 0.2.2 → 0.4.2-probe.5
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 +2 -127
- package/index.js +1 -678
- package/package.json +6 -62
- package/LICENSE +0 -21
- package/client.js +0 -786
- package/cordis.patch.yml +0 -5
- package/icon.svg +0 -14
- package/lib/core.js +0 -496
- package/lib/discovery.js +0 -94
- package/lib/install.js +0 -83
- package/lib/routes.js +0 -262
- package/lib/routing.js +0 -173
- package/lib/subscription.js +0 -138
- package/locale/en.json +0 -6
- package/locale/zh.json +0 -6
package/cordis.patch.yml
DELETED
package/icon.svg
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48" height="48">
|
|
2
|
-
<defs>
|
|
3
|
-
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
|
|
4
|
-
<stop offset="0%" stop-color="#2b6cb0"/>
|
|
5
|
-
<stop offset="100%" stop-color="#1a202c"/>
|
|
6
|
-
</linearGradient>
|
|
7
|
-
</defs>
|
|
8
|
-
<rect x="2" y="2" width="44" height="44" rx="10" fill="url(#g)"/>
|
|
9
|
-
<circle cx="24" cy="24" r="12.5" fill="none" stroke="#e2e8f0" stroke-width="2.2"/>
|
|
10
|
-
<path d="M11.8 24h24.4" stroke="#e2e8f0" stroke-width="2.2" stroke-linecap="round"/>
|
|
11
|
-
<path d="M24 11.5c3.9 3.6 6.1 8 6.1 12.5s-2.2 8.9-6.1 12.5c-3.9-3.6-6.1-8-6.1-12.5s2.2-8.9 6.1-12.5z" fill="none" stroke="#e2e8f0" stroke-width="2.2"/>
|
|
12
|
-
<path d="M31 31.5l5.5 5.5" stroke="#68d391" stroke-width="2.6" stroke-linecap="round"/>
|
|
13
|
-
<circle cx="35.8" cy="36.3" r="2.4" fill="#68d391"/>
|
|
14
|
-
</svg>
|
package/lib/core.js
DELETED
|
@@ -1,496 +0,0 @@
|
|
|
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
|
-
* The subscription is handed to the core as a `proxy-providers` entry rather than
|
|
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
|
-
* to track — the core already knows how to read its own subscription formats.
|
|
9
|
-
*
|
|
10
|
-
* @module dsh-clash-proxy/core
|
|
11
|
-
*/
|
|
12
|
-
import { spawn } from 'node:child_process'
|
|
13
|
-
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
14
|
-
import { createServer } from 'node:net'
|
|
15
|
-
import { join } from 'node:path'
|
|
16
|
-
import { GEO_ASSETS, findCoreBinary, geoDirs } from './discovery.js'
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Domestic suffixes used when no GeoIP database is available.
|
|
20
|
-
*
|
|
21
|
-
* Only a fallback: a real database classifies every Chinese address, while this
|
|
22
|
-
* list covers the destinations the Harness actually reaches. It is deliberately
|
|
23
|
-
* short — a wrong entry here would send a domestic site through a foreign node.
|
|
24
|
-
*/
|
|
25
|
-
const CN_DOMAIN_FALLBACK = [
|
|
26
|
-
'cn',
|
|
27
|
-
'baidu.com',
|
|
28
|
-
'bdstatic.com',
|
|
29
|
-
'qq.com',
|
|
30
|
-
'gtimg.cn',
|
|
31
|
-
'weixin.qq.com',
|
|
32
|
-
'aliyun.com',
|
|
33
|
-
'alicdn.com',
|
|
34
|
-
'alipay.com',
|
|
35
|
-
'taobao.com',
|
|
36
|
-
'tmall.com',
|
|
37
|
-
'jd.com',
|
|
38
|
-
'163.com',
|
|
39
|
-
'126.net',
|
|
40
|
-
'zhihu.com',
|
|
41
|
-
'zhimg.com',
|
|
42
|
-
'bilibili.com',
|
|
43
|
-
'hdslb.com',
|
|
44
|
-
'csdn.net',
|
|
45
|
-
'gitee.com',
|
|
46
|
-
'douyin.com',
|
|
47
|
-
'bytedance.com',
|
|
48
|
-
'toutiao.com',
|
|
49
|
-
'sina.com.cn',
|
|
50
|
-
'weibo.com',
|
|
51
|
-
'jianshu.com',
|
|
52
|
-
'cnblogs.com',
|
|
53
|
-
'tencent.com',
|
|
54
|
-
'huawei.com',
|
|
55
|
-
'xiaomi.com',
|
|
56
|
-
'mi.com',
|
|
57
|
-
'iqiyi.com',
|
|
58
|
-
'youku.com',
|
|
59
|
-
]
|
|
60
|
-
|
|
61
|
-
/** Re-exported so callers keep importing discovery through one module. */
|
|
62
|
-
export { findCoreBinary }
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Copy the geo databases a core needs into its data directory.
|
|
66
|
-
*
|
|
67
|
-
* A cold start with no database makes the core fetch one from GitHub, which cannot
|
|
68
|
-
* succeed on the very connection this plugin exists to provide. Reusing a local
|
|
69
|
-
* Clash Verge copy removes that dependency entirely.
|
|
70
|
-
*
|
|
71
|
-
* @param workDir - the core's data directory.
|
|
72
|
-
* @param extraDirs - additional directories to search, e.g. a configured one.
|
|
73
|
-
* @returns what was found, and which assets are still missing.
|
|
74
|
-
*/
|
|
75
|
-
export function seedGeoAssets(workDir, extraDirs = []) {
|
|
76
|
-
mkdirSync(workDir, { recursive: true })
|
|
77
|
-
const found = []
|
|
78
|
-
const missing = []
|
|
79
|
-
for (const asset of GEO_ASSETS) {
|
|
80
|
-
if (asset.targets.some((target) => existsSync(join(workDir, target)))) {
|
|
81
|
-
found.push(asset.source)
|
|
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)
|
|
107
|
-
}
|
|
108
|
-
return { found, missing }
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Ask the OS for a free loopback TCP port.
|
|
113
|
-
*
|
|
114
|
-
* @returns the port number.
|
|
115
|
-
*/
|
|
116
|
-
export function freePort() {
|
|
117
|
-
return new Promise((resolve, reject) => {
|
|
118
|
-
const server = createServer()
|
|
119
|
-
server.once('error', reject)
|
|
120
|
-
server.listen(0, '127.0.0.1', () => {
|
|
121
|
-
const address = server.address()
|
|
122
|
-
const port = typeof address === 'object' && address !== null ? address.port : undefined
|
|
123
|
-
server.close(() => (port === undefined ? reject(new Error('no port assigned')) : resolve(port)))
|
|
124
|
-
})
|
|
125
|
-
})
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* Build the core configuration for one subscription.
|
|
130
|
-
*
|
|
131
|
-
* Routing is deliberately narrow: loopback and LAN stay direct so the Harness'
|
|
132
|
-
* own Web UI, plugin routes and local servers never enter a routing loop, Chinese
|
|
133
|
-
* destinations stay direct so domestic sites behave exactly as before, and
|
|
134
|
-
* everything else goes through the selected subscription node.
|
|
135
|
-
*
|
|
136
|
-
* @param options - subscription, ports and DNS preferences.
|
|
137
|
-
* @returns the configuration object to serialize as JSON.
|
|
138
|
-
*/
|
|
139
|
-
export function buildConfig(options) {
|
|
140
|
-
const { mixedPort, controllerPort, secret, subscriptionUrl, providerPath, mode, dnsServers, directDomains, proxyDomains, useGeoIp } = options
|
|
141
|
-
const rules = [
|
|
142
|
-
'IP-CIDR,127.0.0.0/8,DIRECT,no-resolve',
|
|
143
|
-
'IP-CIDR,10.0.0.0/8,DIRECT,no-resolve',
|
|
144
|
-
'IP-CIDR,172.16.0.0/12,DIRECT,no-resolve',
|
|
145
|
-
'IP-CIDR,192.168.0.0/16,DIRECT,no-resolve',
|
|
146
|
-
'IP-CIDR,169.254.0.0/16,DIRECT,no-resolve',
|
|
147
|
-
'DOMAIN-SUFFIX,local,DIRECT',
|
|
148
|
-
]
|
|
149
|
-
for (const domain of splitList(directDomains)) rules.push(`DOMAIN-SUFFIX,${domain},DIRECT`)
|
|
150
|
-
for (const domain of splitList(proxyDomains)) rules.push(`DOMAIN-SUFFIX,${domain},PROXY`)
|
|
151
|
-
if (useGeoIp !== false) rules.push('GEOIP,CN,DIRECT')
|
|
152
|
-
else for (const suffix of CN_DOMAIN_FALLBACK) rules.push(`DOMAIN-SUFFIX,${suffix},DIRECT`)
|
|
153
|
-
rules.push('MATCH,PROXY')
|
|
154
|
-
|
|
155
|
-
return {
|
|
156
|
-
'mixed-port': mixedPort,
|
|
157
|
-
'allow-lan': false,
|
|
158
|
-
mode: mode === 'global' ? 'global' : 'rule',
|
|
159
|
-
'log-level': 'warning',
|
|
160
|
-
ipv6: false,
|
|
161
|
-
'external-controller': `127.0.0.1:${controllerPort}`,
|
|
162
|
-
secret,
|
|
163
|
-
'unified-delay': true,
|
|
164
|
-
'tcp-concurrent': true,
|
|
165
|
-
profile: { 'store-selected': true, 'store-fake-ip': true },
|
|
166
|
-
dns: {
|
|
167
|
-
enable: true,
|
|
168
|
-
ipv6: false,
|
|
169
|
-
'enhanced-mode': 'normal',
|
|
170
|
-
'use-hosts': true,
|
|
171
|
-
'default-nameserver': ['223.5.5.5', '119.29.29.29'],
|
|
172
|
-
nameserver: dnsServers.length > 0 ? dnsServers : ['223.5.5.5', '119.29.29.29', '114.114.114.114'],
|
|
173
|
-
'proxy-server-nameserver': ['223.5.5.5', '119.29.29.29'],
|
|
174
|
-
},
|
|
175
|
-
'proxy-providers': {
|
|
176
|
-
sub: {
|
|
177
|
-
type: 'http',
|
|
178
|
-
url: subscriptionUrl,
|
|
179
|
-
interval: 3600,
|
|
180
|
-
path: providerPath,
|
|
181
|
-
'health-check': {
|
|
182
|
-
enable: true,
|
|
183
|
-
url: 'http://www.gstatic.com/generate_204',
|
|
184
|
-
interval: 300,
|
|
185
|
-
},
|
|
186
|
-
},
|
|
187
|
-
},
|
|
188
|
-
'proxy-groups': [
|
|
189
|
-
{
|
|
190
|
-
name: 'PROXY',
|
|
191
|
-
type: 'select',
|
|
192
|
-
use: ['sub'],
|
|
193
|
-
proxies: ['DIRECT'],
|
|
194
|
-
},
|
|
195
|
-
],
|
|
196
|
-
rules,
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* Split a comma/newline separated list into trimmed non-empty entries.
|
|
202
|
-
*
|
|
203
|
-
* @param value - raw list text.
|
|
204
|
-
* @returns the entries.
|
|
205
|
-
*/
|
|
206
|
-
export function splitList(value) {
|
|
207
|
-
return String(value ?? '')
|
|
208
|
-
.split(/[,\s]+/)
|
|
209
|
-
.map((entry) => entry.trim())
|
|
210
|
-
.filter((entry) => entry !== '')
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* One running core process plus the control calls this plugin needs.
|
|
215
|
-
*/
|
|
216
|
-
export class Core {
|
|
217
|
-
constructor({ binary, workDir, logger }) {
|
|
218
|
-
this.binary = binary
|
|
219
|
-
this.workDir = workDir
|
|
220
|
-
this.log = logger ?? (() => {})
|
|
221
|
-
this.child = undefined
|
|
222
|
-
this.configPath = join(workDir, 'config.json')
|
|
223
|
-
this.providerPath = join(workDir, 'providers', 'sub.yaml')
|
|
224
|
-
/** Name of the `proxy-providers` entry, which also names its proxy namespace. */
|
|
225
|
-
this.providerName = 'sub'
|
|
226
|
-
this.mixedPort = undefined
|
|
227
|
-
this.controllerPort = undefined
|
|
228
|
-
this.secret = undefined
|
|
229
|
-
this.startedAt = undefined
|
|
230
|
-
this.lastError = undefined
|
|
231
|
-
this.geo = { found: [], missing: [] }
|
|
232
|
-
/** Budget for the startup node search, in milliseconds. */
|
|
233
|
-
this.selectBudgetMs = 45_000
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
/** Whether the plugin currently owns a live process. */
|
|
237
|
-
get running() {
|
|
238
|
-
return this.child !== undefined && this.child.exitCode === null && !this.child.killed
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/**
|
|
242
|
-
* Write the configuration and start the core.
|
|
243
|
-
*
|
|
244
|
-
* @param options - subscription and routing preferences.
|
|
245
|
-
* @returns the local proxy endpoint.
|
|
246
|
-
*/
|
|
247
|
-
async start(options) {
|
|
248
|
-
await this.stop()
|
|
249
|
-
mkdirSync(join(this.workDir, 'providers'), { recursive: true })
|
|
250
|
-
this.geo = seedGeoAssets(this.workDir, options.geoDirs ?? [])
|
|
251
|
-
if (this.geo.missing.length > 0) this.log(`geo assets missing: ${this.geo.missing.join(', ')}`)
|
|
252
|
-
this.mixedPort = await freePort()
|
|
253
|
-
this.controllerPort = await freePort()
|
|
254
|
-
this.secret = `dsh-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`
|
|
255
|
-
|
|
256
|
-
const config = buildConfig({
|
|
257
|
-
...options,
|
|
258
|
-
mixedPort: this.mixedPort,
|
|
259
|
-
controllerPort: this.controllerPort,
|
|
260
|
-
secret: this.secret,
|
|
261
|
-
providerPath: this.providerPath,
|
|
262
|
-
// A missing database turns the geo rule into a startup download that cannot
|
|
263
|
-
// succeed before the tunnel exists; the core refuses to boot instead. Falling
|
|
264
|
-
// back to a domain list keeps the domestic bypass working.
|
|
265
|
-
useGeoIp: !this.geo.missing.includes('Country.mmdb'),
|
|
266
|
-
})
|
|
267
|
-
writeFileSync(this.configPath, `${JSON.stringify(config, null, 2)}\n`, 'utf8')
|
|
268
|
-
|
|
269
|
-
const child = spawn(this.binary, ['-d', this.workDir, '-f', this.configPath], {
|
|
270
|
-
cwd: this.workDir,
|
|
271
|
-
windowsHide: true,
|
|
272
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
273
|
-
env: { ...process.env, NO_PROXY: '*', no_proxy: '*' },
|
|
274
|
-
})
|
|
275
|
-
this.child = child
|
|
276
|
-
this.startedAt = Date.now()
|
|
277
|
-
this.lastError = undefined
|
|
278
|
-
|
|
279
|
-
const collect = (chunk) => {
|
|
280
|
-
const text = String(chunk)
|
|
281
|
-
for (const line of text.split(/\r?\n/)) {
|
|
282
|
-
const trimmed = line.trim()
|
|
283
|
-
if (trimmed === '') continue
|
|
284
|
-
if (/level=(error|fatal)/.test(trimmed)) this.lastError = trimmed
|
|
285
|
-
this.log(trimmed)
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
child.stdout?.on('data', collect)
|
|
289
|
-
child.stderr?.on('data', collect)
|
|
290
|
-
child.once('exit', (code) => {
|
|
291
|
-
this.log(`core exited code=${code}`)
|
|
292
|
-
if (this.child === child) {
|
|
293
|
-
this.child = undefined
|
|
294
|
-
this.lastError = this.lastError ?? `core exited with code ${code}`
|
|
295
|
-
}
|
|
296
|
-
})
|
|
297
|
-
|
|
298
|
-
await this.waitForApi(25_000)
|
|
299
|
-
return { host: '127.0.0.1', port: this.mixedPort, geo: this.geo }
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
/**
|
|
303
|
-
* Poll the control API until it answers, so callers never race the first request.
|
|
304
|
-
*
|
|
305
|
-
* @param timeoutMs - total budget.
|
|
306
|
-
*/
|
|
307
|
-
async waitForApi(timeoutMs) {
|
|
308
|
-
const deadline = Date.now() + timeoutMs
|
|
309
|
-
while (Date.now() < deadline) {
|
|
310
|
-
if (this.child === undefined) throw new Error(this.lastError ?? 'core exited before its control API answered')
|
|
311
|
-
try {
|
|
312
|
-
const response = await fetch(`http://127.0.0.1:${this.controllerPort}/version`, {
|
|
313
|
-
headers: { authorization: `Bearer ${this.secret}` },
|
|
314
|
-
signal: AbortSignal.timeout(1500),
|
|
315
|
-
})
|
|
316
|
-
if (response.ok) return
|
|
317
|
-
} catch {
|
|
318
|
-
// not listening yet
|
|
319
|
-
}
|
|
320
|
-
await new Promise((resolve) => setTimeout(resolve, 250))
|
|
321
|
-
}
|
|
322
|
-
throw new Error('core did not answer its control API in time')
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
/**
|
|
326
|
-
* Call the control API.
|
|
327
|
-
*
|
|
328
|
-
* @param path - API path beginning with a slash.
|
|
329
|
-
* @param init - extra request options.
|
|
330
|
-
* @returns the decoded JSON body, or undefined for an empty response.
|
|
331
|
-
*/
|
|
332
|
-
async api(path, init = {}) {
|
|
333
|
-
if (this.controllerPort === undefined) throw new Error('core is not running')
|
|
334
|
-
const response = await fetch(`http://127.0.0.1:${this.controllerPort}${path}`, {
|
|
335
|
-
...init,
|
|
336
|
-
headers: {
|
|
337
|
-
authorization: `Bearer ${this.secret}`,
|
|
338
|
-
...(init.body === undefined ? {} : { 'content-type': 'application/json' }),
|
|
339
|
-
...(init.headers ?? {}),
|
|
340
|
-
},
|
|
341
|
-
signal: init.signal ?? AbortSignal.timeout(10_000),
|
|
342
|
-
})
|
|
343
|
-
const text = await response.text()
|
|
344
|
-
if (!response.ok) throw new Error(`control API ${path} failed: ${response.status} ${text.slice(0, 200)}`)
|
|
345
|
-
return text === '' ? undefined : JSON.parse(text)
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
/** The `PROXY` group's node table and current selection. */
|
|
349
|
-
async group() {
|
|
350
|
-
const data = await this.api('/proxies/PROXY')
|
|
351
|
-
return { name: data?.name, now: data?.now, all: Array.isArray(data?.all) ? data.all : [] }
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* Select a node in the `PROXY` group.
|
|
356
|
-
*
|
|
357
|
-
* @param name - exact node name from the group's `all` list.
|
|
358
|
-
*/
|
|
359
|
-
async select(name) {
|
|
360
|
-
await this.api('/proxies/PROXY', { method: 'PUT', body: JSON.stringify({ name }) })
|
|
361
|
-
return await this.group()
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
/** Live connections the core is carrying, for the status report. */
|
|
365
|
-
async connections() {
|
|
366
|
-
const data = await this.api('/connections')
|
|
367
|
-
const list = Array.isArray(data?.connections) ? data.connections : []
|
|
368
|
-
return { count: list.length, download: data?.downloadTotal ?? 0, upload: data?.uploadTotal ?? 0 }
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
/**
|
|
372
|
-
* Measure one node's latency through the core.
|
|
373
|
-
*
|
|
374
|
-
* Nodes that arrive from a `proxy-provider` do not live in the core's own proxy
|
|
375
|
-
* table: `/proxies/<name>/delay` answers `Resource not found` for them. They are
|
|
376
|
-
* reachable only through the provider namespace, under `healthcheck`. Both paths
|
|
377
|
-
* are tried so a group proxy and a provider proxy behave the same to callers.
|
|
378
|
-
*
|
|
379
|
-
* @param name - node name.
|
|
380
|
-
* @param timeoutMs - per-request budget.
|
|
381
|
-
* @returns the delay in milliseconds, or null when it failed.
|
|
382
|
-
*/
|
|
383
|
-
async delay(name, timeoutMs = 5000) {
|
|
384
|
-
const query = new URLSearchParams({ timeout: String(timeoutMs), url: 'http://www.gstatic.com/generate_204' })
|
|
385
|
-
const encoded = encodeURIComponent(name)
|
|
386
|
-
for (const path of [`/providers/proxies/${this.providerName}/${encoded}/healthcheck`, `/proxies/${encoded}/delay`]) {
|
|
387
|
-
try {
|
|
388
|
-
const data = await this.api(`${path}?${query}`)
|
|
389
|
-
if (typeof data?.delay === 'number' && data.delay > 0) return data.delay
|
|
390
|
-
} catch {
|
|
391
|
-
// try the next namespace
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
return null
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
/**
|
|
398
|
-
* Choose a working exit node, in this order: the caller's preference, then the
|
|
399
|
-
* lowest measured latency across a sample, then a single-node verification of the
|
|
400
|
-
* rest. Nodes whose latency cannot be measured are dead and are never chosen.
|
|
401
|
-
*
|
|
402
|
-
* `DIRECT` is a legal group member but never a useful selection for this plugin —
|
|
403
|
-
* leaving it selected would silently route foreign traffic straight out.
|
|
404
|
-
*
|
|
405
|
-
* @param preferred - a node name to honour when it exists and answers.
|
|
406
|
-
* @returns the selected node name, or undefined when nothing answered.
|
|
407
|
-
*/
|
|
408
|
-
async autoSelect(preferred) {
|
|
409
|
-
const group = await this.group()
|
|
410
|
-
const candidates = group.all.filter((entry) => entry !== 'DIRECT')
|
|
411
|
-
if (candidates.length === 0) return undefined
|
|
412
|
-
|
|
413
|
-
const wanted = String(preferred ?? '').trim()
|
|
414
|
-
if (wanted !== '' && candidates.includes(wanted)) {
|
|
415
|
-
const delay = await this.delay(wanted, 5000)
|
|
416
|
-
if (delay !== null) {
|
|
417
|
-
await this.select(wanted)
|
|
418
|
-
return wanted
|
|
419
|
-
}
|
|
420
|
-
this.log(`preferred node "${wanted}" did not answer a latency test; choosing another`)
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
// Probe in bounded concurrent batches: one measurement per node is the only
|
|
424
|
-
// reliable "is this node usable" answer, and sequential probing over a 50-node
|
|
425
|
-
// subscription takes longer than the whole startup. A node that misreports itself
|
|
426
|
-
// as alive still fails here, which is why latency rather than health status gates
|
|
427
|
-
// the choice.
|
|
428
|
-
const deadline = Date.now() + (this.selectBudgetMs ?? 45_000)
|
|
429
|
-
const batchSize = 10
|
|
430
|
-
let best
|
|
431
|
-
for (let at = 0; at < candidates.length && Date.now() < deadline; at += batchSize) {
|
|
432
|
-
const batch = candidates.slice(at, at + batchSize)
|
|
433
|
-
const results = await Promise.all(
|
|
434
|
-
batch.map(async (name) => ({ name, delay: await this.delay(name, 4000) })),
|
|
435
|
-
)
|
|
436
|
-
for (const result of results) {
|
|
437
|
-
if (result.delay === null) continue
|
|
438
|
-
if (best === undefined || result.delay < best.delay) best = result
|
|
439
|
-
}
|
|
440
|
-
// A clearly good node ends the search early: the first working exit is enough to
|
|
441
|
-
// bring routing up, and the panel can re-test later.
|
|
442
|
-
if (best !== undefined && best.delay <= 1200) break
|
|
443
|
-
}
|
|
444
|
-
if (best === undefined) {
|
|
445
|
-
this.log('no node answered a latency test; leaving the group on its current selection')
|
|
446
|
-
return undefined
|
|
447
|
-
}
|
|
448
|
-
await this.select(best.name)
|
|
449
|
-
return best.name
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
/** The provider's fetch state: whether the subscription downloaded and when. */
|
|
453
|
-
async providerStatus() {
|
|
454
|
-
try {
|
|
455
|
-
const data = await this.api('/providers/proxies/sub')
|
|
456
|
-
return { updatedAt: data?.updatedAt ?? null, vehicleType: data?.vehicleType ?? null }
|
|
457
|
-
} catch {
|
|
458
|
-
return { updatedAt: null, vehicleType: null }
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
/**
|
|
463
|
-
* Re-download the subscription now.
|
|
464
|
-
*
|
|
465
|
-
* @returns the provider status after the refresh.
|
|
466
|
-
*/
|
|
467
|
-
async updateProvider() {
|
|
468
|
-
await this.api('/providers/proxies/sub', { method: 'PUT' })
|
|
469
|
-
return await this.providerStatus()
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
/** Stop the owned process. Never touches another Clash installation. */
|
|
473
|
-
async stop() {
|
|
474
|
-
const child = this.child
|
|
475
|
-
this.child = undefined
|
|
476
|
-
if (child === undefined) return
|
|
477
|
-
try {
|
|
478
|
-
child.kill()
|
|
479
|
-
} catch {
|
|
480
|
-
// already gone
|
|
481
|
-
}
|
|
482
|
-
const deadline = Date.now() + 4000
|
|
483
|
-
while (child.exitCode === null && Date.now() < deadline) {
|
|
484
|
-
await new Promise((resolve) => setTimeout(resolve, 100))
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
/** Read back the config actually written, for diagnostics. */
|
|
489
|
-
readConfig() {
|
|
490
|
-
try {
|
|
491
|
-
return JSON.parse(readFileSync(this.configPath, 'utf8'))
|
|
492
|
-
} catch {
|
|
493
|
-
return undefined
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
}
|
package/lib/discovery.js
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Optional local Clash/mihomo installation discovery.
|
|
3
|
-
*
|
|
4
|
-
* This module deliberately knows nothing about a user's subscriptions, node choices,
|
|
5
|
-
* or profile files: a published plugin must not read whatever proxy configuration
|
|
6
|
-
* happens to sit on the installation machine. What it does provide is the two pieces
|
|
7
|
-
* of machine-level information that are genuinely reusable and contain no personal
|
|
8
|
-
* data:
|
|
9
|
-
*
|
|
10
|
-
* - where a mihomo-compatible executable lives, so the user does not have to type a
|
|
11
|
-
* path to a core the machine already has; and
|
|
12
|
-
* - where downloaded GeoIP/GeoSite databases live, because the core needs them before
|
|
13
|
-
* it can classify a single connection, and the alternative is a download over the
|
|
14
|
-
* very tunnel those databases are needed to establish.
|
|
15
|
-
*
|
|
16
|
-
* Everything else — subscription URL, node choice, routing rules — comes from the
|
|
17
|
-
* plugin's own configuration.
|
|
18
|
-
*
|
|
19
|
-
* @module dsh-clash-proxy/discovery
|
|
20
|
-
*/
|
|
21
|
-
import { existsSync } from 'node:fs'
|
|
22
|
-
import { join } from 'node:path'
|
|
23
|
-
|
|
24
|
-
/** Core executable names a Clash/mihomo installation ships, most specific first. */
|
|
25
|
-
const CORE_BINARIES = ['verge-mihomo.exe', 'verge-mihomo-alpha.exe', 'mihomo.exe', 'clash-meta.exe', 'clash.exe']
|
|
26
|
-
|
|
27
|
-
/** Directories a desktop Clash client installs its core into. */
|
|
28
|
-
const CORE_DIRS = [
|
|
29
|
-
'C:/Program Files/Clash Verge',
|
|
30
|
-
'C:/Program Files/Clash Verge Rev',
|
|
31
|
-
'C:/Program Files/mihomo',
|
|
32
|
-
'C:/Program Files/Clash Meta',
|
|
33
|
-
]
|
|
34
|
-
|
|
35
|
-
/** Directory names a desktop Clash client uses for its data under the roaming profile. */
|
|
36
|
-
const DATA_DIR_NAMES = ['io.github.clash-verge-rev.clash-verge-rev', 'clash-verge', 'mihomo', 'Clash Verge']
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Find a mihomo-compatible core.
|
|
40
|
-
*
|
|
41
|
-
* @param configured - an explicit path from plugin config; when it names a file it wins.
|
|
42
|
-
* @returns the absolute binary path, or undefined when none was found.
|
|
43
|
-
*/
|
|
44
|
-
export function findCoreBinary(configured) {
|
|
45
|
-
if (typeof configured === 'string' && configured.trim() !== '') {
|
|
46
|
-
const path = configured.trim()
|
|
47
|
-
if (existsSync(path)) return path
|
|
48
|
-
}
|
|
49
|
-
for (const dir of CORE_DIRS) {
|
|
50
|
-
for (const name of CORE_BINARIES) {
|
|
51
|
-
const candidate = join(dir, name)
|
|
52
|
-
if (existsSync(candidate)) return candidate
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
for (const root of [process.env.LOCALAPPDATA, process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)']]) {
|
|
56
|
-
if (typeof root !== 'string' || root === '') continue
|
|
57
|
-
for (const name of CORE_BINARIES) {
|
|
58
|
-
for (const sub of ['Clash Verge', 'mihomo', 'Clash Meta', '']) {
|
|
59
|
-
const candidate = join(root, sub, name)
|
|
60
|
-
if (existsSync(candidate)) return candidate
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
return undefined
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Directories that may hold downloaded geo databases.
|
|
69
|
-
*
|
|
70
|
-
* Only the directory itself is used; no file in it is read except the four database
|
|
71
|
-
* files named by {@link GEO_ASSETS}, and nothing is written back.
|
|
72
|
-
*
|
|
73
|
-
* @returns existing candidate directories, most likely first.
|
|
74
|
-
*/
|
|
75
|
-
export function geoDirs() {
|
|
76
|
-
const found = []
|
|
77
|
-
const roots = [process.env.APPDATA, process.env.LOCALAPPDATA]
|
|
78
|
-
for (const root of roots) {
|
|
79
|
-
if (typeof root !== 'string' || root === '') continue
|
|
80
|
-
for (const name of DATA_DIR_NAMES) {
|
|
81
|
-
const dir = join(root, name)
|
|
82
|
-
if (existsSync(dir) && !found.includes(dir)) found.push(dir)
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
return found
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/** Geo assets a core needs before it can evaluate GEOIP/GEOSITE rules. */
|
|
89
|
-
export const GEO_ASSETS = [
|
|
90
|
-
{ source: 'Country.mmdb', targets: ['Country.mmdb', 'geoip.metadb'] },
|
|
91
|
-
{ source: 'geoip.dat', targets: ['geoip.dat'] },
|
|
92
|
-
{ source: 'geosite.dat', targets: ['geosite.dat'] },
|
|
93
|
-
{ source: 'ASN.mmdb', targets: ['ASN.mmdb'] },
|
|
94
|
-
]
|
package/lib/install.js
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Locating the Harness installation root.
|
|
3
|
-
*
|
|
4
|
-
* A profile-installed plugin resolves modules from `$DSH_PROFILE_DIR/node_modules`,
|
|
5
|
-
* which holds only profile packages. The Harness' own building blocks — and the one
|
|
6
|
-
* `undici` instance the host process already routes through — live in the dsh
|
|
7
|
-
* installation instead. Resolving from the installation's own manifest yields the
|
|
8
|
-
* same module instance the host loaded, which is what makes a proxy policy installed
|
|
9
|
-
* here visible to `ctx.web`, the LLM transports, and every spawned child.
|
|
10
|
-
*
|
|
11
|
-
* @module dsh-clash-proxy/install
|
|
12
|
-
*/
|
|
13
|
-
import { createRequire } from 'node:module'
|
|
14
|
-
import { existsSync, readFileSync } from 'node:fs'
|
|
15
|
-
import { join, normalize } from 'node:path'
|
|
16
|
-
import { pathToFileURL } from 'node:url'
|
|
17
|
-
|
|
18
|
-
/** Candidate installation-root tails inside one `argv` entry. */
|
|
19
|
-
const INSTALL_TAILS = ['resources/app/dsh', 'app/dsh']
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Find the dsh installation root from the process argument list.
|
|
23
|
-
*
|
|
24
|
-
* The host passes its own entry script in `argv`, which lives inside the
|
|
25
|
-
* installation, so a path containing a known tail identifies the root. A packaged
|
|
26
|
-
* Desktop build nests it under `resources/app/dsh`; a source checkout puts the
|
|
27
|
-
* checkout at the matched prefix, whose manifest is named `deepseek-harness`.
|
|
28
|
-
*
|
|
29
|
-
* @param argv - process argument list to inspect.
|
|
30
|
-
* @returns the absolute installation root, or undefined when nothing matches.
|
|
31
|
-
*/
|
|
32
|
-
export function locateInstallRoot(argv) {
|
|
33
|
-
for (const entry of argv) {
|
|
34
|
-
if (typeof entry !== 'string' || entry === '') continue
|
|
35
|
-
const path = normalize(entry).replaceAll('\\', '/')
|
|
36
|
-
for (const tail of INSTALL_TAILS) {
|
|
37
|
-
const at = path.indexOf(`/${tail}/`)
|
|
38
|
-
if (at < 0) continue
|
|
39
|
-
const root = path.slice(0, at + tail.length + 1)
|
|
40
|
-
if (existsSync(join(root, 'package.json'))) return root
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return undefined
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Read the package name of an installation root, for a diagnostic.
|
|
48
|
-
*
|
|
49
|
-
* @param root - installation root.
|
|
50
|
-
* @returns the declared name, or undefined.
|
|
51
|
-
*/
|
|
52
|
-
export function installName(root) {
|
|
53
|
-
try {
|
|
54
|
-
return JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))?.name
|
|
55
|
-
} catch {
|
|
56
|
-
return undefined
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Resolve one module from the installation, so the plugin shares the host's copy.
|
|
62
|
-
*
|
|
63
|
-
* @param root - dsh installation root.
|
|
64
|
-
* @param id - module specifier to resolve.
|
|
65
|
-
* @returns the resolved absolute file path.
|
|
66
|
-
*/
|
|
67
|
-
export function resolveFromInstall(root, id) {
|
|
68
|
-
return createRequire(join(root, 'package.json')).resolve(id)
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Load the installation's own proxy-policy module.
|
|
73
|
-
*
|
|
74
|
-
* Importing through a file URL keeps one module instance: the host boots its policy
|
|
75
|
-
* from this same file, so installing here replaces the dispatcher the host already
|
|
76
|
-
* set instead of creating a second, invisible one.
|
|
77
|
-
*
|
|
78
|
-
* @param root - dsh installation root.
|
|
79
|
-
* @returns the loaded policy module.
|
|
80
|
-
*/
|
|
81
|
-
export async function loadHttpProxyModule(root) {
|
|
82
|
-
return import(pathToFileURL(resolveFromInstall(root, '@deepseek-ai/dsh-http-proxy')).href)
|
|
83
|
-
}
|