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.
@@ -0,0 +1,618 @@
1
+ /**
2
+ * Obtaining a core without asking the user to install anything.
3
+ *
4
+ * The plugin needs a mihomo-compatible executable. Discovery finds one left by a
5
+ * desktop Clash client; that fails on a machine that never had one, which is exactly
6
+ * the "install this on a fresh Harness" case. So the plugin can also fetch a core
7
+ * itself:
8
+ *
9
+ * 1. ask GitHub for the current release of `MetaCubeX/mihomo`;
10
+ * 2. pick the asset for this platform and CPU;
11
+ * 3. download it, hashing as it arrives;
12
+ * 4. compare the digest with the one the release API published — a truncated or
13
+ * tampered download is rejected before anything is unpacked;
14
+ * 5. unpack with the platform's own tool and keep only the executable.
15
+ *
16
+ * Two properties matter more than speed here. The download is verified, because the
17
+ * whole point of a proxy is that it carries credential-bearing traffic. And nothing is
18
+ * placed in the data directory until it is verified, so a failed attempt leaves the
19
+ * previous state untouched.
20
+ *
21
+ * @module dsh-clash-proxy/corefetch
22
+ */
23
+ import { createHash } from 'node:crypto'
24
+ import { spawn } from 'node:child_process'
25
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
26
+ import { join } from 'node:path'
27
+
28
+ /**
29
+ * Mirror prefixes tried before the direct GitHub URL.
30
+ *
31
+ * Reachability is not the problem a mirror solves — GitHub answered in ~2 s from this
32
+ * machine. Throughput is: measured on the same archive, direct download ran at ~55 KB/s
33
+ * (about six minutes for 22 MB), `gh-proxy.com` at ~120 KB/s and `ghfast.top` at ~90 KB/s.
34
+ * The direct URL is still tried last, so a network where mirrors are blocked pays nothing
35
+ * but one wasted connect.
36
+ *
37
+ * Each mirror serves the same bytes, so the expected digest is unchanged and a mirror
38
+ * that rewrites the payload fails the checksum instead of installing itself.
39
+ */
40
+ const MIRROR_PREFIXES = ['https://gh-proxy.com/', 'https://ghfast.top/', 'https://ghproxy.net/']
41
+
42
+ /**
43
+ * Add mirror-prefixed candidates in front of the direct URL.
44
+ *
45
+ * @param url - the canonical GitHub download URL.
46
+ * @returns candidate URLs, mirrors first, direct last, deduplicated.
47
+ */
48
+ export function downloadCandidates(url) {
49
+ const direct = String(url ?? '')
50
+ if (direct === '') return []
51
+ const mirrored = MIRROR_PREFIXES.map((prefix) => `${prefix}${direct}`)
52
+ return [...mirrored, direct]
53
+ }
54
+ const RELEASE_API = 'https://api.github.com/repos/MetaCubeX/mihomo/releases/latest'
55
+
56
+ /**
57
+ * Release page whose redirect names the current tag without the REST API.
58
+ *
59
+ * The REST API answers 403 `API rate limit exceeded` for an unauthenticated caller
60
+ * behind a shared address — measured on this machine, with and without a user agent.
61
+ * A plugin that can only resolve a version through that endpoint therefore fails for
62
+ * reasons that have nothing to do with the user. GitHub's own `releases/latest` redirect
63
+ * is not rate limited, so the version is read from there and the asset URL is built.
64
+ */
65
+ const RELEASE_PAGE = 'https://github.com/MetaCubeX/mihomo/releases/latest'
66
+
67
+ /**
68
+ * Archive digests this plugin has verified itself, for when the API cannot be asked.
69
+ *
70
+ * Each entry was downloaded, hashed, and cross-checked against the release API's
71
+ * published `digest` field at the time of the plugin release. Verification is never
72
+ * skipped: without either an API digest or an entry here, the download is refused.
73
+ * A stale entry fails the checksum instead of installing an unverified binary, which
74
+ * is the failure mode to prefer — and `coreVersion` in the config pins the version the
75
+ * entry belongs to.
76
+ *
77
+ * @type {Record<string, {url: string, digest: string, size: number, archive: string}>}
78
+ */
79
+ export const KNOWN_ARCHIVES = {
80
+ '1.19.34': {
81
+ 'win32-x64': {
82
+ url: 'https://github.com/MetaCubeX/mihomo/releases/download/v1.19.34/mihomo-windows-amd64-compatible-v1.19.34.zip',
83
+ digest: 'cd6738d4648cc1a5f48049a1343b697ab510889d648f045c5c780fc1ab443a79',
84
+ size: 22417383,
85
+ archive: 'zip',
86
+ },
87
+ },
88
+ }
89
+
90
+ /**
91
+ * Assets this plugin knows how to unpack, by platform and architecture.
92
+ *
93
+ * `windows-amd64-compatible` is preferred over the plain build: it is compiled for the
94
+ * oldest supported CPU baseline, so it runs on machines whose virtualisation or CPU
95
+ * flags would quietly break a `v3` build. The archive format differs per platform,
96
+ * which is why each entry names its own unpacker.
97
+ */
98
+ const ASSET_PATTERNS = {
99
+ 'win32-x64': [
100
+ { match: /^mihomo-windows-amd64-compatible-v[\d.]+\.zip$/, archive: 'zip' },
101
+ { match: /^mihomo-windows-amd64-v[\d.]+\.zip$/, archive: 'zip' },
102
+ { match: /^mihomo-windows-386-v[\d.]+\.zip$/, archive: 'zip' },
103
+ ],
104
+ 'win32-arm64': [{ match: /^mihomo-windows-arm64-v[\d.]+\.zip$/, archive: 'zip' }],
105
+ 'darwin-x64': [{ match: /^mihomo-darwin-amd64-compatible-v[\d.]+\.gz$/, archive: 'gz' }],
106
+ 'darwin-arm64': [{ match: /^mihomo-darwin-arm64-v[\d.]+\.gz$/, archive: 'gz' }],
107
+ 'linux-x64': [
108
+ { match: /^mihomo-linux-amd64-compatible-v[\d.]+\.gz$/, archive: 'gz' },
109
+ { match: /^mihomo-linux-amd64-v[\d.]+\.gz$/, archive: 'gz' },
110
+ ],
111
+ 'linux-arm64': [{ match: /^mihomo-linux-arm64-v[\d.]+\.gz$/, archive: 'gz' }],
112
+ }
113
+
114
+ /** File name the core is stored under, per platform. */
115
+ const CORE_NAME = process.platform === 'win32' ? 'mihomo.exe' : 'mihomo'
116
+
117
+ /**
118
+ * The platform key this module and the release assets agree on.
119
+ *
120
+ * @param platform - `process.platform`.
121
+ * @param arch - `process.arch`.
122
+ * @returns the key, or undefined when this plugin has no asset for the pair.
123
+ */
124
+ export function platformKey(platform = process.platform, arch = process.arch) {
125
+ const key = `${platform}-${arch}`
126
+ return Object.hasOwn(ASSET_PATTERNS, key) ? key : undefined
127
+ }
128
+
129
+ /**
130
+ * Pick the release asset for this machine.
131
+ *
132
+ * @param assets - the release's asset list, `{ name, browser_download_url, digest, size }`.
133
+ * @param platform - `process.platform`.
134
+ * @param arch - `process.arch`.
135
+ * @returns the chosen asset plus its archive kind, or undefined when none fits.
136
+ */
137
+ export function pickAsset(assets, platform = process.platform, arch = process.arch) {
138
+ const key = platformKey(platform, arch)
139
+ if (key === undefined) return undefined
140
+ const list = Array.isArray(assets) ? assets : []
141
+ for (const pattern of ASSET_PATTERNS[key]) {
142
+ const found = list.find((asset) => typeof asset?.name === 'string' && pattern.match.test(asset.name))
143
+ if (found !== undefined) return { ...found, archive: pattern.archive }
144
+ }
145
+ return undefined
146
+ }
147
+
148
+ /**
149
+ * Turn a release digest field into a bare lowercase hex string.
150
+ *
151
+ * GitHub publishes `sha256:<hex>`; older releases carry no digest at all, and a
152
+ * missing digest is a reason to refuse rather than to skip verification.
153
+ *
154
+ * @param digest - the `digest` field of an asset.
155
+ * @returns the hex digest, or undefined when absent or not SHA-256.
156
+ */
157
+ export function digestOf(digest) {
158
+ if (typeof digest !== 'string') return undefined
159
+ const match = /^sha256:([0-9a-f]{64})$/i.exec(digest.trim())
160
+ return match === null ? undefined : match[1].toLowerCase()
161
+ }
162
+
163
+ /**
164
+ * Ask GitHub for the current release tag, without the rate-limited REST API.
165
+ *
166
+ * @param fetchImpl - fetch implementation, injectable for a test.
167
+ * @param timeoutMs - request budget.
168
+ * @returns the tag, e.g. `v1.19.34`, or undefined when it cannot be determined.
169
+ */
170
+ export async function resolveTag(fetchImpl = fetch, timeoutMs = 15_000) {
171
+ try {
172
+ const response = await fetchImpl(RELEASE_PAGE, {
173
+ redirect: 'follow',
174
+ headers: { 'user-agent': 'dsh-clash-subscription' },
175
+ signal: AbortSignal.timeout(timeoutMs),
176
+ })
177
+ // With `redirect: 'follow'` the final URL carries the tag; a fetch implementation
178
+ // that does not expose it leaves `response.url` empty, which is handled below.
179
+ const finalUrl = String(response?.url ?? '')
180
+ const match = /\/tag\/(v?[\d.]+)$/.exec(finalUrl)
181
+ if (match !== null) return match[1]
182
+ } catch {
183
+ // Fall through: the caller decides what a missing tag means.
184
+ }
185
+ return undefined
186
+ }
187
+
188
+ /**
189
+ * Read the current release metadata, falling back to the built-in manifest.
190
+ *
191
+ * Two independent sources, tried in order:
192
+ *
193
+ * 1. the REST API, whose `digest` field is the publisher's own SHA-256; and
194
+ * 2. the release page redirect for the tag, plus {@link KNOWN_ARCHIVES} for the digest.
195
+ *
196
+ * Whichever answers, a digest is required. The fallback exists because the API rate
197
+ * limit is per address and shared, so it fails for reasons the user cannot act on.
198
+ *
199
+ * @param fetchImpl - fetch implementation, injectable for a test.
200
+ * @param timeoutMs - request budget.
201
+ * @param pinned - a version to prefer, from `coreVersion`; empty means current.
202
+ * @returns the file name, download URL, expected digest and archive kind.
203
+ */
204
+ export async function resolveRelease(fetchImpl = fetch, timeoutMs = 20_000, pinned = '') {
205
+ const want = String(pinned ?? '').trim().replace(/^v/, '')
206
+ if (want !== '') {
207
+ const entry = KNOWN_ARCHIVES[want]?.[platformKey() ?? '']
208
+ if (entry === undefined) {
209
+ throw new Error(`coreVersion ${pinned} has no verified archive for ${platformKey() ?? `${process.platform}-${process.arch}`}`)
210
+ }
211
+ return { tag: `v${want}`, name: entry.url.split('/').pop(), url: entry.url, size: entry.size, digest: entry.digest, archive: entry.archive, source: 'pinned' }
212
+ }
213
+
214
+ // 1. The publisher's own digest.
215
+ try {
216
+ const response = await fetchImpl(RELEASE_API, {
217
+ headers: { accept: 'application/vnd.github+json', 'user-agent': 'dsh-clash-subscription' },
218
+ signal: AbortSignal.timeout(timeoutMs),
219
+ })
220
+ if (response.ok) {
221
+ const release = await response.json()
222
+ const asset = pickAsset(release?.assets)
223
+ const digest = digestOf(asset?.digest)
224
+ if (asset !== undefined && digest !== undefined) {
225
+ return { tag: release?.tag_name ?? '', name: asset.name, url: asset.browser_download_url, size: asset.size ?? 0, digest, archive: asset.archive, source: 'api' }
226
+ }
227
+ }
228
+ } catch {
229
+ // Reported through the fallback path's error if that fails too.
230
+ }
231
+
232
+ // 2. The release page for the tag, plus a digest this plugin verified earlier.
233
+ const tag = await resolveTag(fetchImpl, Math.min(timeoutMs, 15_000))
234
+ if (tag === undefined) {
235
+ throw new Error('could not determine a mihomo version: the release API and the release page both failed; set corePath to an existing executable')
236
+ }
237
+ const version = tag.replace(/^v/, '')
238
+ const entry = KNOWN_ARCHIVES[version]?.[platformKey() ?? '']
239
+ if (entry === undefined) {
240
+ throw new Error(
241
+ `release ${tag} has no verified digest for ${platformKey() ?? `${process.platform}-${process.arch}`} in this build of the plugin; set corePath, or set coreVersion to a version this build knows (${Object.keys(KNOWN_ARCHIVES).join(', ')})`,
242
+ )
243
+ }
244
+ return { tag, name: entry.url.split('/').pop(), url: entry.url, size: entry.size, digest: entry.digest, archive: entry.archive, source: 'manifest' }
245
+ }
246
+
247
+ /**
248
+ * Download one file, hashing while it streams, and refuse it if the digest differs.
249
+ *
250
+ * Hashing during the transfer means a 22 MB archive is read once, and the file never
251
+ * reaches its final path until it matches: a partial download cannot be mistaken for
252
+ * a usable core.
253
+ *
254
+ * @param url - download URL.
255
+ * @param destination - where to write the verified bytes.
256
+ * @param expected - expected lowercase hex SHA-256.
257
+ * @param fetchImpl - fetch implementation, injectable for a test.
258
+ * @param onProgress - called with `{ received, total }` while bytes arrive.
259
+ * @returns the byte count and the digest actually observed.
260
+ */
261
+ /**
262
+ * Install a core from an archive the user already downloaded.
263
+ *
264
+ * The network this plugin runs on may be unable to fetch 22 MB from GitHub at all — on
265
+ * this machine every mirror stalled below 40 KB/s. Refusing to work there would defeat the
266
+ * purpose, so an archive placed by hand is accepted, and it is held to the same digest
267
+ * check as a downloaded one: convenience must not become a way to install an unverified
268
+ * binary.
269
+ *
270
+ * @param archivePath - the archive the user supplied.
271
+ * @param digest - expected lowercase hex SHA-256, or empty to accept and report the observed one.
272
+ * @param options - data directory and an optional progress callback.
273
+ * @returns the installed path, size and digest.
274
+ */
275
+ export async function installCoreFromFile(archivePath, digest, options = {}) {
276
+ const dataDir = String(options.dataDir ?? '')
277
+ if (dataDir === '') throw new Error('installCoreFromFile needs a data directory')
278
+ if (!existsSync(archivePath)) throw new Error(`no such file: ${archivePath}`)
279
+ const report = options.onProgress ?? (() => {})
280
+ const bytes = readFileSync(archivePath)
281
+ const actual = createHash('sha256').update(bytes).digest('hex')
282
+ const expected = String(digest ?? '').trim().toLowerCase()
283
+ if (expected !== '' && expected !== actual) {
284
+ throw new Error(`checksum mismatch: expected ${expected}, file is ${actual}`)
285
+ }
286
+ const kind = /\.zip$/i.test(archivePath) ? 'zip' : /\.(gz|tgz)$/i.test(archivePath) ? 'gz' : undefined
287
+ if (kind === undefined) throw new Error(`unsupported archive: ${archivePath} (expected .zip or .gz)`)
288
+ report({ phase: 'verified', digest: actual, bytes: bytes.length })
289
+
290
+ const stageDir = join(dataDir, 'bin-stage')
291
+ mkdirSync(stageDir, { recursive: true })
292
+ try {
293
+ const installed = await unpackCore(archivePath, kind, join(stageDir, 'x'), join(dataDir, 'bin', CORE_NAME))
294
+ report({ phase: 'installed', path: installed.path, bytes: installed.bytes })
295
+ return { ...installed, digest: actual, tag: 'local-file' }
296
+ } finally {
297
+ try {
298
+ rmSync(stageDir, { recursive: true, force: true })
299
+ } catch {
300
+ // A locked file only costs disk space.
301
+ }
302
+ }
303
+ }
304
+
305
+ export async function downloadVerified(url, destination, expected, fetchImpl = fetch, onProgress = () => {}, options = {}) {
306
+ const candidates = Array.isArray(url) ? url : downloadCandidates(url)
307
+ const size = Number(options.size ?? 0)
308
+ const concurrency = Number(options.concurrency ?? 6)
309
+ // A ranged, concurrent fetch is the default when the size is known. One long-lived
310
+ // request for 22 MB was measured to stall at ~1 MB against every mirror in turn; eight
311
+ // independent ranges completed and assembled to the exact digest. Splitting also makes
312
+ // partial progress survivable: one range that dies is retried on another mirror instead
313
+ // of discarding the whole archive.
314
+ if (size > 0 && concurrency > 1) {
315
+ // Two ranged passes. Falling back to a single stream was measured to be worse than
316
+ // useless here: the stream restarts from zero and is abandoned on the same speed gate,
317
+ // so a failed range is retried as a range instead.
318
+ for (let pass = 0; pass < 2; pass += 1) {
319
+ try {
320
+ return await downloadRanged(candidates, destination, expected, fetchImpl, onProgress, { size, concurrency })
321
+ } catch (error) {
322
+ onProgress({ received: 0, total: size, note: `ranged pass ${pass + 1} failed: ${String(error?.message ?? error).slice(0, 90)}` })
323
+ }
324
+ }
325
+ }
326
+ const failures = []
327
+ for (const candidate of candidates) {
328
+ try {
329
+ return await downloadOne(candidate, destination, expected, fetchImpl, onProgress)
330
+ } catch (error) {
331
+ // A mirror that is down, refuses, or serves different bytes only costs one attempt:
332
+ // the digest is checked per candidate, so a rewritten payload cannot slip through.
333
+ failures.push(`${new URL(candidate).host}: ${String(error?.message ?? error).slice(0, 90)}`)
334
+ onProgress({ received: 0, total: 0, failedHost: new URL(candidate).host })
335
+ }
336
+ }
337
+ throw new Error(`every download source failed — ${failures.join(' | ')}`)
338
+ }
339
+
340
+ /**
341
+ * Fetch an archive in independent byte ranges and assemble it.
342
+ *
343
+ * Each range walks the candidate list on its own, so a mirror that stalls costs that one
344
+ * range a retry rather than the whole download. Bytes are only written once the assembled
345
+ * buffer matches the expected digest.
346
+ *
347
+ * @param candidates - URLs serving the same bytes, mirrors first.
348
+ * @param destination - where to write the verified archive.
349
+ * @param expected - expected lowercase hex SHA-256 of the whole archive.
350
+ * @param fetchImpl - fetch implementation.
351
+ * @param onProgress - progress callback; receives the running byte total.
352
+ * @param options - archive size and how many ranges to run at once.
353
+ * @returns the byte count and observed digest.
354
+ */
355
+ async function downloadRanged(candidates, destination, expected, fetchImpl, onProgress, options) {
356
+ const size = Number(options.size)
357
+ const concurrency = Math.min(Math.max(2, Number(options.concurrency) || 6), 12)
358
+ // At least 1 MiB per range, at most ~4 MiB: fewer, larger ranges lose less work when one
359
+ // fails, and small ranges only add request overhead.
360
+ const ranges = Math.max(concurrency, Math.min(16, Math.ceil(size / (2 * 1024 * 1024))))
361
+ const span = Math.ceil(size / ranges)
362
+ const buffers = new Array(ranges)
363
+ let received = 0
364
+
365
+ const fetchRange = async (index) => {
366
+ const start = index * span
367
+ const end = Math.min(size - 1, start + span - 1)
368
+ const problems = []
369
+ for (const candidate of candidates) {
370
+ const host = new URL(candidate).host
371
+ // Two attempts per mirror: a dropped range is often just a reset connection.
372
+ for (let attempt = 0; attempt < 2; attempt += 1) {
373
+ try {
374
+ const response = await fetchImpl(candidate, {
375
+ headers: { range: `bytes=${start}-${end}`, 'user-agent': 'dsh-clash-subscription' },
376
+ redirect: 'follow',
377
+ signal: AbortSignal.timeout(120_000),
378
+ })
379
+ if (response.status !== 206) throw new Error(`range answered ${response.status}`)
380
+ const buffer = Buffer.from(await response.arrayBuffer())
381
+ if (buffer.length !== end - start + 1) {
382
+ throw new Error(`range short: ${buffer.length} of ${end - start + 1}`)
383
+ }
384
+ buffers[index] = buffer
385
+ received += buffer.length
386
+ onProgress({ received, total: size })
387
+ return
388
+ } catch (error) {
389
+ problems.push(`${host}#${index}: ${String(error?.message ?? error).slice(0, 60)}`)
390
+ }
391
+ }
392
+ }
393
+ throw new Error(`range ${index} failed on every source — ${problems.slice(-3).join(' | ')}`)
394
+ }
395
+
396
+ // A small worker pool, so `ranges` requests do not all open at once on a narrow link.
397
+ let next = 0
398
+ const workers = Array.from({ length: Math.min(concurrency, ranges) }, async () => {
399
+ while (next < ranges) {
400
+ const index = next
401
+ next += 1
402
+ await fetchRange(index)
403
+ }
404
+ })
405
+ await Promise.all(workers)
406
+
407
+ const assembled = Buffer.concat(buffers)
408
+ if (assembled.length !== size) throw new Error(`assembled ${assembled.length} bytes, expected ${size}`)
409
+ const actual = createHash('sha256').update(assembled).digest('hex')
410
+ if (actual !== expected) {
411
+ throw new Error(`checksum mismatch: expected ${expected}, assembled ${actual}`)
412
+ }
413
+ writeFileSync(destination, assembled)
414
+ return { bytes: assembled.length, digest: actual, ranged: ranges }
415
+ }
416
+
417
+ /**
418
+ * Download from one URL, hashing while it streams.
419
+ *
420
+ * Guarded by an **idle** timeout, not only an overall one. Measured: a mirror accepted the
421
+ * connection, delivered about 1 MB, then stopped sending while holding the socket open —
422
+ * `curl` to the same host was fast, so the stall is in the long-lived Node request rather
423
+ * than the mirror. A single overall budget would have sat there for its full duration; an
424
+ * idle budget hands control to the next candidate within seconds, which is what makes the
425
+ * mirror list actually useful.
426
+ *
427
+ * @param url - the URL to fetch.
428
+ * @param destination - where to write verified bytes.
429
+ * @param expected - expected lowercase hex SHA-256.
430
+ * @param fetchImpl - fetch implementation.
431
+ * @param onProgress - progress callback.
432
+ * @param idleMs - how long a silent stream may stay open before the attempt is abandoned.
433
+ * @returns the byte count and observed digest.
434
+ */
435
+ async function downloadOne(url, destination, expected, fetchImpl, onProgress, idleMs = 30_000) {
436
+ const controller = new AbortController()
437
+ let lastByteAt = Date.now()
438
+ let settled = false
439
+ const startedAt = Date.now()
440
+ const idle = setInterval(() => {
441
+ if (settled) return
442
+ const silentFor = Date.now() - lastByteAt
443
+ if (silentFor > idleMs) {
444
+ settled = true
445
+ controller.abort(new Error(`no data for ${Math.round(silentFor / 1000)}s`))
446
+ }
447
+ }, 2000)
448
+ const overall = setTimeout(() => {
449
+ if (!settled) controller.abort(new Error('download timed out'))
450
+ }, 900_000)
451
+
452
+ try {
453
+ const response = await fetchImpl(url, {
454
+ redirect: 'follow',
455
+ headers: { 'user-agent': 'dsh-clash-subscription' },
456
+ signal: controller.signal,
457
+ })
458
+ if (!response.ok) throw new Error(`the download answered ${response.status}`)
459
+ const total = Number(response.headers.get('content-length') ?? 0)
460
+ const hash = createHash('sha256')
461
+ const chunks = []
462
+ let received = 0
463
+ // Report at most ten times a second: a progress callback per chunk made the panel poll
464
+ // harder than the download itself could advance.
465
+ let lastReport = 0
466
+ for await (const chunk of response.body) {
467
+ lastByteAt = Date.now()
468
+ hash.update(chunk)
469
+ chunks.push(chunk)
470
+ received += chunk.length
471
+ const now = Date.now()
472
+ if (now - lastReport > 100 || received === total) {
473
+ lastReport = now
474
+ onProgress({ received, total })
475
+ }
476
+ // A trickle is worse than a failure: this mirror delivered ~30 KB per 15 s, which
477
+ // never trips an idle timeout but would take over an hour. Below 40 KB/s it is
478
+ // abandoned in favour of the next candidate, after a grace period so a slow start
479
+ // is not punished.
480
+ const elapsed = (now - startedAt) / 1000
481
+ if (elapsed > 20 && received / elapsed < 40 * 1024) {
482
+ throw new Error(`too slow: ${Math.round(received / elapsed / 1024)} KB/s after ${Math.round(elapsed)}s`)
483
+ }
484
+ }
485
+ const actual = hash.digest('hex')
486
+ if (actual !== expected) {
487
+ throw new Error(`checksum mismatch: expected ${expected}, downloaded ${actual} (${received} bytes)`)
488
+ }
489
+ if (total > 0 && received !== total) {
490
+ throw new Error(`truncated download: expected ${total} bytes, received ${received}`)
491
+ }
492
+ // Write only after the digest matched, so the target path never holds unverified bytes.
493
+ writeFileSync(destination, Buffer.concat(chunks))
494
+ return { bytes: received, digest: actual }
495
+ } finally {
496
+ settled = true
497
+ clearInterval(idle)
498
+ clearTimeout(overall)
499
+ }
500
+ }
501
+
502
+ /**
503
+ * Run an unpacking tool and reject on failure.
504
+ *
505
+ * @param command - executable name.
506
+ * @param args - its arguments.
507
+ * @returns nothing; throws when the tool reports failure.
508
+ */
509
+ function runTool(command, args) {
510
+ return new Promise((resolve, reject) => {
511
+ const child = spawn(command, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
512
+ let stderr = ''
513
+ child.stderr?.on('data', (chunk) => {
514
+ stderr += String(chunk)
515
+ })
516
+ child.once('error', reject)
517
+ child.once('exit', (code) => {
518
+ if (code === 0) resolve(undefined)
519
+ else reject(new Error(`${command} exited ${code}: ${stderr.trim().slice(0, 200)}`))
520
+ })
521
+ })
522
+ }
523
+
524
+ /**
525
+ * Unpack the archive and move the executable into place.
526
+ *
527
+ * `tar` is used for `.gz` on every platform (it is present on Windows 10+, macOS and
528
+ * Linux, and reads gzip natively). `.zip` also goes through `tar` on Windows, whose
529
+ * bundled `bsdtar` reads zip; that avoids shipping an unzip library for one platform.
530
+ *
531
+ * The archive's own file name is not trusted to equal the final name: whichever file
532
+ * looks like the core is renamed, so a release that changes its internal name keeps
533
+ * working.
534
+ *
535
+ * @param archivePath - downloaded archive.
536
+ * @param kind - `zip` or `gz`.
537
+ * @param workDir - directory to unpack into; created if absent.
538
+ * @param finalPath - where the executable must end up.
539
+ * @returns the final path and its size.
540
+ */
541
+ export async function unpackCore(archivePath, kind, workDir, finalPath) {
542
+ mkdirSync(workDir, { recursive: true })
543
+ if (kind === 'gz') {
544
+ // -z: gzip, -x: extract, -f: file, -O: to stdout would lose the name; extract then find.
545
+ await runTool('tar', ['-xzf', archivePath, '-C', workDir])
546
+ } else if (kind === 'zip') {
547
+ await runTool('tar', ['-xf', archivePath, '-C', workDir])
548
+ } else {
549
+ throw new Error(`unsupported archive kind "${kind}"`)
550
+ }
551
+
552
+ const entries = readdirSync(workDir)
553
+ // The archive names its payload after the build, not after the fixed name this plugin
554
+ // stores it under: the Windows zip holds `mihomo-windows-amd64-compatible.exe`. Match the
555
+ // build suffix rather than only the bare `mihomo.exe`, or a correct download is reported
556
+ // as holding no core at all — which is exactly what happened on the first run.
557
+ const isCore = (name) =>
558
+ /^(verge-)?mihomo([-.][\w.-]+)?(\.exe)?$/i.test(name) ||
559
+ /^(verge-)?mihomo(-[\w.-]+)?\.exe$/i.test(name) ||
560
+ /^clash(-meta)?([-.][\w.-]+)?(\.exe)?$/i.test(name)
561
+ const wanted = entries.filter(isCore)
562
+ // Prefer an exact `mihomo` / `mihomo.exe` when the archive ships several matches.
563
+ wanted.sort((a, b) => Number(!/^(verge-)?mihomo(\.exe)?$/i.test(a)) - Number(!/^(verge-)?mihomo(\.exe)?$/i.test(b)))
564
+ const source = wanted.length > 0 ? join(workDir, wanted[0]) : undefined
565
+ if (source === undefined) {
566
+ throw new Error(`the archive held no core executable (found: ${entries.slice(0, 5).join(', ') || 'nothing'})`)
567
+ }
568
+ mkdirSync(join(finalPath, '..'), { recursive: true })
569
+ if (existsSync(finalPath)) rmSync(finalPath, { force: true })
570
+ renameSync(source, finalPath)
571
+ if (process.platform !== 'win32') chmodSync(finalPath, 0o755)
572
+ return { path: finalPath, bytes: statSync(finalPath).size }
573
+ }
574
+
575
+ /**
576
+ * Fetch, verify and install a core into `dataDir/bin`.
577
+ *
578
+ * @param options - data directory plus injectable fetch/tools and a progress callback.
579
+ * @returns the installed executable's path, size and the release it came from.
580
+ */
581
+ export async function installCore(options = {}) {
582
+ const dataDir = String(options.dataDir ?? '')
583
+ if (dataDir === '') throw new Error('installCore needs a data directory')
584
+ const fetchImpl = options.fetch ?? fetch
585
+ const report = options.onProgress ?? (() => {})
586
+ const release = await resolveRelease(fetchImpl, options.timeoutMs ?? 20_000, options.version ?? '')
587
+ report({ phase: 'resolved', tag: release.tag, name: release.name, bytes: release.size })
588
+
589
+ const binDir = join(dataDir, 'bin')
590
+ const stageDir = join(dataDir, 'bin-stage')
591
+ mkdirSync(stageDir, { recursive: true })
592
+ const archivePath = join(stageDir, release.name)
593
+ const finalPath = join(dataDir, 'bin', CORE_NAME)
594
+
595
+ try {
596
+ const downloaded = await downloadVerified(
597
+ release.url,
598
+ archivePath,
599
+ release.digest,
600
+ fetchImpl,
601
+ (progress) => report({ phase: 'downloading', ...progress }),
602
+ // The size comes from the release metadata, which is what lets the ranged path run.
603
+ { size: release.size },
604
+ )
605
+ report({ phase: 'verified', digest: downloaded.digest, bytes: downloaded.bytes })
606
+ const installed = await unpackCore(archivePath, release.archive, join(stageDir, 'x'), finalPath)
607
+ report({ phase: 'installed', path: installed.path, bytes: installed.bytes })
608
+ return { ...installed, tag: release.tag, digest: downloaded.digest }
609
+ } finally {
610
+ // The stage directory only ever holds an archive that has already been consumed or
611
+ // rejected, so removing it is always correct and keeps a retry clean.
612
+ try {
613
+ rmSync(stageDir, { recursive: true, force: true })
614
+ } catch {
615
+ // A locked file only costs disk space.
616
+ }
617
+ }
618
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Where the core comes from.
3
+ *
4
+ * This plugin owns its core. It does not look for a Clash installation, does not read
5
+ * another client's directories, and does not use one it happens to find: a machine with a
6
+ * desktop Clash client and a machine without one must behave identically, or the plugin's
7
+ * behaviour depends on something the user never asked it to depend on.
8
+ *
9
+ * Two sources exist, in this order:
10
+ *
11
+ * 1. `corePath` from the plugin's own configuration, when the user deliberately points at
12
+ * an executable; and
13
+ * 2. the copy this plugin unpacked from `vendor/` into its own data directory.
14
+ *
15
+ * Nothing else. A search of `Program Files` for a mihomo binary was removed on purpose:
16
+ * borrowing another client's executable is the kind of hidden dependency that makes a
17
+ * failure unexplainable later.
18
+ *
19
+ * @module dsh-clash-proxy/discovery
20
+ */
21
+ import { existsSync } from 'node:fs'
22
+ import { join } from 'node:path'
23
+
24
+ /** Executable name this plugin stores its verified core under. */
25
+ export const CORE_NAME = process.platform === 'win32' ? 'mihomo.exe' : 'mihomo'
26
+
27
+ /**
28
+ * The executable this plugin unpacked into its own data directory.
29
+ *
30
+ * @param dataDir - the plugin's data directory.
31
+ * @returns the path when present, else undefined.
32
+ */
33
+ export function ownCorePath(dataDir) {
34
+ if (typeof dataDir !== 'string' || dataDir.trim() === '') return undefined
35
+ const candidate = join(dataDir.trim(), 'bin', CORE_NAME)
36
+ return existsSync(candidate) ? candidate : undefined
37
+ }
38
+
39
+ /**
40
+ * Resolve the executable to run.
41
+ *
42
+ * @param configured - `corePath` from this plugin's configuration; empty means "use ours".
43
+ * @param dataDir - the plugin's data directory.
44
+ * @returns the absolute binary path, or undefined when neither source has one.
45
+ */
46
+ export function findCoreBinary(configured, dataDir) {
47
+ if (typeof configured === 'string' && configured.trim() !== '') {
48
+ const path = configured.trim()
49
+ if (existsSync(path)) return path
50
+ }
51
+ return ownCorePath(dataDir)
52
+ }