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/index.js CHANGED
@@ -1 +1,1314 @@
1
- export const probe = true
1
+ /**
2
+ * Host half of the Clash subscription proxy bundle.
3
+ *
4
+ * The plugin owns a private mihomo core fed by one or more subscriptions the user
5
+ * imports, and points the Harness' existing process-wide outbound policy at that core.
6
+ * Nothing else changes: loopback and LAN stay direct, Chinese destinations stay direct,
7
+ * and only traffic that would otherwise be blocked goes through a subscription node —
8
+ * with no Clash Verge desktop app, system proxy, or per-command environment variable.
9
+ *
10
+ * Several subscriptions may be configured at once. Each becomes its own core provider
11
+ * and contributes its nodes to the same exit group, so adding a second subscription
12
+ * extends the node table instead of replacing the first.
13
+ *
14
+ * @module dsh-clash-proxy
15
+ */
16
+ import { mkdirSync } from 'node:fs'
17
+ import { homedir } from 'node:os'
18
+ import { join } from 'node:path'
19
+ import { Core, findCoreBinary, splitList } from './lib/core.js'
20
+ import { installCore, installCoreFromFile, platformKey } from './lib/corefetch.js'
21
+ import { installVendoredCore, vendoredFor } from './lib/vendored.js'
22
+ import { fetchGeoDatabases, hasGeoDatabase } from './lib/geo.js'
23
+ import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
24
+ import { Routing } from './lib/routing.js'
25
+ import {
26
+ displayName,
27
+ effectiveSubscriptionText,
28
+ nodePrefix,
29
+ parseSubscriptions,
30
+ probeSubscriptions,
31
+ providerName,
32
+ } from './lib/subscription.js'
33
+ import { maskToken, mountRoutes } from './lib/routes.js'
34
+
35
+ export const name = 'clash-proxy'
36
+
37
+ export const inject = ['tools']
38
+
39
+ /**
40
+ * Defaults for every field, so a plugin row may omit all of them.
41
+ *
42
+ * The loader validates a row's config against the exported `Config` only when that
43
+ * export is a native schemastery schema, and the Settings page is discovered from
44
+ * that same schema. A profile-installed plugin cannot import `@deepseek-ai/schemastery`
45
+ * by bare specifier (the profile's `node_modules` holds no copy), so the schema is
46
+ * built from the installation's own module — the same instance the host validates
47
+ * with. {@link resolveConfig} stays as the dependency-free normalization used by
48
+ * code paths that must not await a module load.
49
+ */
50
+ export const CONFIG_DEFAULTS = {
51
+ /** One subscription per line, optionally prefixed with a display name. */
52
+ subscriptionUrls: '',
53
+ /** Single-URL field from 0.2; read for migration, never written back. */
54
+ subscriptionUrl: '',
55
+ node: '',
56
+ corePath: '',
57
+ mode: 'rule',
58
+ autoStart: true,
59
+ dnsServers: '',
60
+ directDomains: '',
61
+ proxyDomains: '',
62
+ dataDir: '',
63
+ /** How often the plugin re-measures its nodes, in minutes; 0 disables the cycle. */
64
+ speedTestMinutes: 30,
65
+ /** How many nodes one cycle measures, lowest-index first in the group's order. */
66
+ speedTestCount: 8,
67
+ /** How often the core is checked for liveness, in minutes; 0 disables the watchdog. */
68
+ healthCheckMinutes: 1,
69
+ /** Download a private core automatically when the machine has none. */
70
+ autoFetchCore: false,
71
+ /** Pin the core version to a build whose digest this plugin ships; empty means current. */
72
+ coreVersion: '',
73
+ /** Fetch GeoIP databases after routing works; they are an upgrade, not a requirement. */
74
+ autoFetchGeo: true,
75
+ }
76
+
77
+ /**
78
+ * Build the native config schema from the installation's schema library.
79
+ *
80
+ * @returns the schema, or undefined when the installation cannot be located.
81
+ */
82
+ async function buildConfigSchema() {
83
+ try {
84
+ const root = locateInstallRoot(process.argv)
85
+ if (root === undefined) return undefined
86
+ const { pathToFileURL } = await import('node:url')
87
+ const loaded = await import(pathToFileURL(resolveFromInstall(root, '@deepseek-ai/schemastery')).href)
88
+ const z = loaded.default ?? loaded
89
+ if (typeof z?.object !== 'function') return undefined
90
+ return z.object({
91
+ subscriptionUrls: z.string().default(''),
92
+ subscriptionUrl: z.string().default(''),
93
+ node: z.string().default(''),
94
+ corePath: z.string().default(''),
95
+ mode: z.string().default('rule'),
96
+ autoStart: z.boolean().default(true),
97
+ dnsServers: z.string().default(''),
98
+ directDomains: z.string().default(''),
99
+ proxyDomains: z.string().default(''),
100
+ dataDir: z.string().default(''),
101
+ speedTestMinutes: z.number().default(30),
102
+ speedTestCount: z.number().default(8),
103
+ healthCheckMinutes: z.number().default(1),
104
+ autoFetchCore: z.boolean().default(false),
105
+ coreVersion: z.string().default(''),
106
+ autoFetchGeo: z.boolean().default(true),
107
+ })
108
+ } catch {
109
+ return undefined
110
+ }
111
+ }
112
+
113
+ /** The native schema, or undefined on a host whose installation cannot be found. */
114
+ export const Config = await buildConfigSchema()
115
+
116
+ /**
117
+ * Coerce and validate one raw configuration.
118
+ *
119
+ * @param raw - the Loader row's `config`, possibly partial or absent.
120
+ * @returns a complete, validated configuration.
121
+ */
122
+ export function resolveConfig(raw) {
123
+ const input = raw !== null && typeof raw === 'object' ? raw : {}
124
+ const config = { ...CONFIG_DEFAULTS, ...input }
125
+ const mode = String(config.mode ?? 'rule').trim().toLowerCase()
126
+ config.mode = mode === 'global' ? 'global' : 'rule'
127
+ config.autoStart = config.autoStart !== false && config.autoStart !== 'false'
128
+ config.autoFetchCore = config.autoFetchCore === true || config.autoFetchCore === 'true'
129
+ config.autoFetchGeo = config.autoFetchGeo !== false && config.autoFetchGeo !== 'false'
130
+ for (const field of ['subscriptionUrls', 'subscriptionUrl', 'node', 'corePath', 'coreVersion', 'dnsServers', 'directDomains', 'proxyDomains', 'dataDir']) {
131
+ config[field] = String(config[field] ?? '').trim()
132
+ }
133
+ // A profile written by 0.2 carries only `subscriptionUrl`. Normalizing it into the
134
+ // list here means every downstream reader sees one shape, and the panel shows the
135
+ // user's existing subscription in the list editor on first open.
136
+ if (config.subscriptionUrls === '' && config.subscriptionUrl !== '') config.subscriptionUrls = config.subscriptionUrl
137
+ const clamp = (value, min, max, fallback) => {
138
+ const numeric = Number(value)
139
+ if (!Number.isFinite(numeric)) return fallback
140
+ return Math.min(max, Math.max(min, Math.round(numeric)))
141
+ }
142
+ config.speedTestMinutes = clamp(config.speedTestMinutes, 0, 1440, 30)
143
+ config.speedTestCount = clamp(config.speedTestCount, 1, 40, 8)
144
+ config.healthCheckMinutes = clamp(config.healthCheckMinutes, 0, 60, 1)
145
+ return config
146
+ }
147
+
148
+ /**
149
+ * Resolve the plugin's data directory.
150
+ *
151
+ * @param configured - configured directory, possibly empty.
152
+ * @returns the absolute directory, created on demand by callers that write.
153
+ */
154
+ function resolveDataDir(configured) {
155
+ if (typeof configured === 'string' && configured.trim() !== '') return configured.trim()
156
+ const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
157
+ return join(home, 'data', 'dsh-clash-proxy')
158
+ }
159
+
160
+ /**
161
+ * Everything one activation owns: the core, the routing policy, and the last outcome.
162
+ *
163
+ * Exported so the measurement policy can be asserted against a stub core, without a
164
+ * real process or network.
165
+ */
166
+ export class Runtime {
167
+ constructor(config, logger) {
168
+ this.config = config
169
+ this.log = logger
170
+ this.dataDir = resolveDataDir(config.dataDir)
171
+ /** Resolved once: the answer cannot change mid-process, and a stable value keeps
172
+ * `blocker` and `ensurePolicyModule` from disagreeing. */
173
+ this.installRoot = locateInstallRoot(process.argv)
174
+ this.binary = findCoreBinary(config.corePath, this.dataDir)
175
+ this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger })
176
+ this.routing = undefined
177
+ this.lastError = undefined
178
+ this.lastProbe = undefined
179
+ /** Result of the last core download, for the panel and the tool. */
180
+ this.bootstrap = undefined
181
+ /** True while a download is in flight, so two clicks cannot race one archive. */
182
+ this.bootstrapping = false
183
+ /** Progress/result of the optional GeoIP upgrade. */
184
+ this.geo = undefined
185
+ /** True while that upgrade is running. */
186
+ this.geoUpgrading = false
187
+ /** True while `start()` is running, so the watchdog never races a deliberate restart. */
188
+ this.starting = false
189
+ /**
190
+ * Whether this activation is supposed to own a running core.
191
+ *
192
+ * The watchdog gates on this rather than on `autoStart`: `autoStart` only says who
193
+ * started the core (the Harness, or the user pressing Start), and a core started by
194
+ * hand deserves the same recovery as one started at boot.
195
+ */
196
+ this.engaged = false
197
+ /** Set when the watchdog gave up and left the process direct. */
198
+ this.degraded = undefined
199
+ this.measured = new Map()
200
+ this.measuredAt = 0
201
+ this.timer = undefined
202
+ this.watchdog = undefined
203
+ /** Persistence hook, set by `apply` from the config editor; undefined when the profile has none. */
204
+ this.editor = undefined
205
+ /** Timer factory and context-bound re-arm, installed by `apply`. */
206
+ this.schedule = undefined
207
+ this.rearm = undefined
208
+ }
209
+
210
+ /**
211
+ * The parsed subscription list.
212
+ *
213
+ * Recomputed on read so a config edit takes effect without a restart of the plugin.
214
+ *
215
+ * @returns `{ entries, errors }`.
216
+ */
217
+ get subscriptions() {
218
+ return parseSubscriptions(effectiveSubscriptionText(this.config))
219
+ }
220
+
221
+ /**
222
+ * Measure node latency, merging into the results already known.
223
+ *
224
+ * Three modes matter here and the first version conflated them, which made the panel
225
+ * report two thirds of a subscription as unreachable:
226
+ *
227
+ * - the cycle measures `speedTestCount` nodes so a long subscription stays affordable;
228
+ * - `only` measures one named node, which is what the panel's per-row test does;
229
+ * - `all` measures every node and is only used when the user explicitly asks.
230
+ *
231
+ * Results accumulate instead of replacing: a node measured in an earlier pass keeps
232
+ * its latency, so the panel distinguishes "not measured yet" from "measured and dead"
233
+ * instead of painting both as unreachable.
234
+ *
235
+ * @param options - `force` ignores the cache window; `only` restricts to one node;
236
+ * `all` measures every node.
237
+ * @returns node name to delay in milliseconds, or null when it did not answer. A node
238
+ * absent from the map has not been measured.
239
+ */
240
+ async nodeDelays(options = {}) {
241
+ if (this.core === undefined || !this.core.running) return {}
242
+ const forced = options.force === true || options.only !== undefined || options.all === true
243
+ const fresh = Date.now() - this.measuredAt < this.config.speedTestMinutes * 60_000
244
+ if (!forced && fresh && this.measured.size > 0) return Object.fromEntries(this.measured)
245
+
246
+ const group = await this.core.group()
247
+ const available = group.all.filter((entry) => entry !== 'DIRECT')
248
+ let candidates
249
+ if (options.only !== undefined) {
250
+ const only = String(options.only).trim()
251
+ candidates = available.includes(only) ? [only] : []
252
+ } else if (options.all === true) {
253
+ candidates = available
254
+ } else {
255
+ // Prefer nodes with no measurement yet, so repeated cycles eventually cover the
256
+ // whole subscription instead of re-testing the same first N forever.
257
+ const unmeasured = available.filter((name) => !this.measured.has(name))
258
+ const pool = unmeasured.length > 0 ? unmeasured : available
259
+ candidates = pool.slice(0, this.config.speedTestCount)
260
+ }
261
+
262
+ const measured = new Map(this.measured)
263
+ const batchSize = 5
264
+ for (let at = 0; at < candidates.length; at += batchSize) {
265
+ const batch = candidates.slice(at, at + batchSize)
266
+ const answers = await Promise.all(
267
+ batch.map(async (name) => ({ name, delay: await this.core.delay(name, 5000) })),
268
+ )
269
+ for (const answer of answers) measured.set(answer.name, answer.delay)
270
+ }
271
+ this.measured = measured
272
+ this.measuredAt = Date.now()
273
+ return Object.fromEntries(measured)
274
+ }
275
+
276
+ /** Record a node the user picked, so a restart keeps it without a config edit. */
277
+ rememberNode(name) {
278
+ this.config.node = name
279
+ }
280
+
281
+ /** The configuration a page may read, with the subscription tokens masked. */
282
+ publicConfig() {
283
+ const parsed = this.subscriptions
284
+ return {
285
+ subscriptionUrls: effectiveSubscriptionText(this.config),
286
+ /** Masked one-per-line echo, for a read-only display. */
287
+ effectiveSubscriptionUrls: this.maskList(parsed.entries),
288
+ /** Kept for a 0.2 client: the first subscription, masked. */
289
+ subscriptionUrl: parsed.entries[0]?.url ?? '',
290
+ effectiveSubscriptionUrl: maskToken(parsed.entries[0]?.url ?? ''),
291
+ subscriptions: parsed.entries.map((entry) => ({
292
+ name: displayName(entry),
293
+ provider: providerName(entry),
294
+ url: maskToken(entry.url),
295
+ index: entry.index,
296
+ })),
297
+ subscriptionErrors: parsed.errors,
298
+ node: this.config.node,
299
+ mode: this.config.mode,
300
+ autoStart: this.config.autoStart,
301
+ speedTestMinutes: this.config.speedTestMinutes,
302
+ speedTestCount: this.config.speedTestCount,
303
+ healthCheckMinutes: this.config.healthCheckMinutes,
304
+ directDomains: this.config.directDomains,
305
+ proxyDomains: this.config.proxyDomains,
306
+ dnsServers: this.config.dnsServers,
307
+ corePath: this.config.corePath,
308
+ coreVersion: this.config.coreVersion,
309
+ source: 'configured',
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Mask every token in a parsed list, preserving the names and line order.
315
+ *
316
+ * @param entries - parsed subscription entries.
317
+ * @returns one masked `name url` line per entry.
318
+ */
319
+ maskList(entries) {
320
+ return (Array.isArray(entries) ? entries : [])
321
+ .map((entry) => {
322
+ const name = displayName(entry)
323
+ const masked = maskToken(entry.url)
324
+ return entry.name === '' ? masked : `${name} ${masked}`
325
+ })
326
+ .join('\n')
327
+ }
328
+
329
+ /**
330
+ * Persist a configuration change and apply it.
331
+ *
332
+ * The write goes through the config editor, which owns the profile patch: a plugin
333
+ * that rewrote that file itself would drop other plugins' rows and comments. When
334
+ * the editor is unavailable the change still applies to this process and the answer
335
+ * says so, rather than reporting a save that did not happen.
336
+ *
337
+ * @param patch - field subset already validated by the caller.
338
+ * @returns the applied configuration and any warning about persistence.
339
+ */
340
+ async saveConfig(patch) {
341
+ const previous = this.config
342
+ const next = resolveConfig({ ...previous, ...patch })
343
+ const changedCore = [
344
+ 'subscriptionUrls',
345
+ 'subscriptionUrl',
346
+ 'mode',
347
+ 'dnsServers',
348
+ 'directDomains',
349
+ 'proxyDomains',
350
+ 'corePath',
351
+ ].some((key) => next[key] !== previous[key])
352
+ this.config = next
353
+
354
+ const warnings = []
355
+ const editor = this.editor
356
+ // Write the patch as-is. An earlier version additionally blanked the legacy
357
+ // `subscriptionUrl` to stop it shadowing the list on the next read — and that silently
358
+ // destroyed the user's only copy of their subscription when the migration had put it
359
+ // there. Shadowing is handled by `effectiveSubscriptionText` preferring the list, which
360
+ // costs nothing and cannot lose data.
361
+ const written = patch
362
+ if (editor === undefined) {
363
+ warnings.push('not persisted: the profile has no config editor, so this applies until the Harness restarts')
364
+ } else {
365
+ try {
366
+ await editor(written)
367
+ } catch (error) {
368
+ warnings.push(`not persisted: ${error?.message ?? error}`)
369
+ }
370
+ }
371
+
372
+ // A routing-relevant change needs the core restarted; a node or timing change does
373
+ // not, because the group selection and the measurement cycle read live values.
374
+ if (changedCore && this.core?.running === true) {
375
+ try {
376
+ await this.start()
377
+ } catch (error) {
378
+ warnings.push(`routing was not restarted: ${error?.message ?? error}`)
379
+ }
380
+ }
381
+ if (next.speedTestMinutes !== previous.speedTestMinutes) this.requestRearm()
382
+ return { config: this.publicConfig(), warnings }
383
+ }
384
+
385
+ /**
386
+ * Restart the measurement cycle from the current configuration.
387
+ *
388
+ * The interval factory must run in the plugin's own context: a request handler runs
389
+ * in a different fiber, and calling into the timer service from there throws
390
+ * "cannot get required service in inactive context". So this only ever runs from a
391
+ * callback the plugin registered itself.
392
+ *
393
+ * @param schedule - timer factory from the plugin context.
394
+ */
395
+ scheduleSpeedTest(schedule) {
396
+ if (this.timer !== undefined) this.timer()
397
+ this.timer = undefined
398
+ const minutes = this.config.speedTestMinutes
399
+ if (minutes <= 0 || typeof schedule !== 'function') return
400
+ this.timer = schedule(() => {
401
+ void this.nodeDelays({ force: true }).catch((error) => {
402
+ this.log(`speed test failed: ${error?.message ?? error}`)
403
+ })
404
+ }, minutes * 60_000)
405
+ }
406
+
407
+ /**
408
+ * Watch the core and recover from an unexpected exit.
409
+ *
410
+ * A core that dies leaves undici's dispatcher pointed at a closed port, so every
411
+ * outbound request fails with `ECONNREFUSED` while `verify()` still reports `active`
412
+ * — that was the 0.2 behaviour, and it silently broke every foreign request until
413
+ * the user noticed and restarted by hand. Three things happen here instead:
414
+ *
415
+ * 1. an unexpected exit removes the policy, so the process returns to direct
416
+ * connectivity rather than failing every request;
417
+ * 2. one automatic restart is attempted per failure, so a transient crash heals;
418
+ * 3. if the restart also fails, the runtime records {@link degraded} and stops
419
+ * retrying, which the panel and the tool both report.
420
+ *
421
+ * @param schedule - timer factory from the plugin context.
422
+ */
423
+ scheduleWatchdog(schedule) {
424
+ if (this.watchdog !== undefined) this.watchdog()
425
+ this.watchdog = undefined
426
+ const minutes = this.config.healthCheckMinutes
427
+ if (minutes <= 0 || typeof schedule !== 'function') return
428
+ this.watchdog = schedule(() => {
429
+ void this.checkHealth().catch((error) => this.log(`health check failed: ${error?.message ?? error}`))
430
+ }, minutes * 60_000)
431
+ }
432
+
433
+ /**
434
+ * One liveness pass: is the core still listening, and does the policy still route?
435
+ *
436
+ * Exported behaviour is observable through {@link status}; this method exists so the
437
+ * watchdog and a test can drive one pass without timers.
438
+ *
439
+ * @returns what the pass found and, when it acted, what it did.
440
+ */
441
+ async checkHealth() {
442
+ if (this.starting === true) return { state: 'starting' }
443
+ if (this.subscriptionUrl === '') return { state: 'unconfigured' }
444
+
445
+ // A core that arrived after the plugin loaded is picked up here. This is the "fill in
446
+ // the rest later" half of provisioning: nothing has to be re-saved or re-clicked once
447
+ // the download finishes, and a core placed by hand is discovered the same way.
448
+ if (this.binary === undefined) {
449
+ const found = findCoreBinary(this.config.corePath, this.dataDir)
450
+ if (found !== undefined) {
451
+ this.binary = found
452
+ this.core = new Core({ binary: found, workDir: this.dataDir, logger: this.log })
453
+ this.log(`core appeared at ${found}; bringing routing up`)
454
+ try {
455
+ await this.start()
456
+ this.engaged = true
457
+ return { state: 'core-arrived' }
458
+ } catch (error) {
459
+ this.lastError = String(error?.message ?? error)
460
+ return { state: 'failed', reason: this.lastError }
461
+ }
462
+ }
463
+ // Still no core. Start a download if the user allowed automatic provisioning, and
464
+ // never more than one at a time.
465
+ if (this.config.autoFetchCore === true && this.bootstrapping !== true) {
466
+ void this.bootstrapCore()
467
+ .then(() => this.checkHealth())
468
+ .catch((error) => {
469
+ this.lastError = String(error?.message ?? error)
470
+ this.log(`background core download failed: ${this.lastError}`)
471
+ })
472
+ return { state: 'fetching-core' }
473
+ }
474
+ return { state: 'no-core' }
475
+ }
476
+
477
+ if (this.engaged !== true && this.config.autoStart !== true) return { state: 'disabled' }
478
+
479
+ const running = this.core?.running === true
480
+ const policy = this.routing === undefined ? { state: 'none' } : await this.routing.verify()
481
+
482
+ if (running && policy.state === 'active') {
483
+ this.degraded = undefined
484
+ return { state: 'healthy' }
485
+ }
486
+
487
+ // Not running, or running with a policy that something else replaced: a restart
488
+ // repairs both, because `start()` re-installs the policy and re-spawns the core.
489
+ if (running && policy.state !== 'active') {
490
+ this.log(`outbound policy is ${policy.state}; reinstalling it`)
491
+ try {
492
+ await this.applyPolicy()
493
+ return { state: 'policy-reinstalled' }
494
+ } catch (error) {
495
+ this.degraded = `policy could not be reinstalled: ${error?.message ?? error}`
496
+ return { state: 'failed', reason: this.degraded }
497
+ }
498
+ }
499
+
500
+ // The core died. Return to direct first so requests stop failing against a closed
501
+ // port while the restart is in flight.
502
+ if (this.routing !== undefined) await this.routing.releaseToDirect()
503
+ this.log('core stopped unexpectedly; restarting it once')
504
+ try {
505
+ await this.start()
506
+ this.degraded = undefined
507
+ return { state: 'restarted' }
508
+ } catch (error) {
509
+ this.degraded = `restart failed: ${error?.message ?? error}`
510
+ this.lastError = this.degraded
511
+ this.log(this.degraded)
512
+ return { state: 'failed', reason: this.degraded }
513
+ }
514
+ }
515
+
516
+ /**
517
+ * Reinstall the outbound policy against the current core port.
518
+ *
519
+ * @returns the applied variables.
520
+ */
521
+ async applyPolicy() {
522
+ const routing = await this.ensurePolicyModule()
523
+ if (this.core?.mixedPort === undefined) throw new Error('the core has no proxy port')
524
+ return await routing.apply('127.0.0.1', this.core.mixedPort)
525
+ }
526
+
527
+ /**
528
+ * Re-arm the cycle after a configuration change.
529
+ *
530
+ * Called from a request handler, so it cannot touch the timer service itself; it
531
+ * defers to `rearm`, a function the plugin context installed and that hops back into
532
+ * its own fiber through the host's effect boundary.
533
+ */
534
+ requestRearm() {
535
+ if (typeof this.rearm === 'function') this.rearm()
536
+ }
537
+
538
+ /**
539
+ * Probe one subscription URL without changing any state.
540
+ *
541
+ * @param raw - the URL to probe, as typed in the form.
542
+ * @returns a result the form renders as a hint.
543
+ */
544
+ async probe(raw) {
545
+ const text = String(raw ?? '').trim()
546
+ if (text === '') return { ok: false, error: 'subscription URL is empty' }
547
+ // The field now holds several lines; probe every entry so one bad line is named
548
+ // rather than only the first one being checked.
549
+ const parsed = parseSubscriptions(text)
550
+ if (parsed.entries.length === 0) {
551
+ return { ok: false, error: parsed.errors[0]?.reason ?? 'no subscription URL found', errors: parsed.errors }
552
+ }
553
+ try {
554
+ const report = await probeSubscriptions(parsed.entries, { timeoutMs: 15_000 })
555
+ return {
556
+ ...report,
557
+ ok: report.ok,
558
+ maskedUrls: this.maskList(parsed.entries),
559
+ errors: parsed.errors,
560
+ error: report.ok
561
+ ? undefined
562
+ : report.results
563
+ .filter((result) => !result.ok)
564
+ .map((result) => `${result.name}: ${result.error ?? `the server answered ${result.status}`}`)
565
+ .join('; '),
566
+ }
567
+ } catch (error) {
568
+ // The probe runs through whatever policy is installed, so a failure here may
569
+ // mean "not routed yet" rather than "wrong URL"; say which.
570
+ return { ok: false, error: `probe failed: ${String(error?.message ?? error)}` }
571
+ }
572
+ }
573
+
574
+ /** The subscription to use. There is no fallback: an empty value means unconfigured. */
575
+ get subscriptionUrl() {
576
+ return effectiveSubscriptionText(this.config)
577
+ }
578
+
579
+ /** The node preference, empty when the user has not chosen one. */
580
+ get preferredNode() {
581
+ return String(this.config.node ?? '').trim()
582
+ }
583
+
584
+ /**
585
+ * A one-line reason the runtime cannot start, or undefined when it can.
586
+ *
587
+ * The installation root is part of this list on purpose. The first release omitted it,
588
+ * so a packaged build whose layout the locator did not recognise kept `autoStart`
589
+ * firing on every boot and failing at the same throw — with `blocker` still reporting
590
+ * "ready" and the panel showing nothing but a stale lastError.
591
+ */
592
+ get blocker() {
593
+ // A missing core is NOT a blocker. The plugin installs, opens, and stores its
594
+ // configuration without one; the core is fetched in the background and routing comes
595
+ // up when it arrives. Reporting "cannot start" for a state the plugin can repair on
596
+ // its own was making an optional download look like a broken install.
597
+ if (this.installRoot === undefined) {
598
+ return 'cannot locate the dsh installation root: set DSH_INSTALL_ROOT to the directory holding the dsh package.json (a packaged build keeps it inside resources/app.asar)'
599
+ }
600
+ if (this.subscriptionUrl === '') {
601
+ return 'no subscription: paste one or more subscription URLs in Settings → Clash proxy'
602
+ }
603
+ const parsed = this.subscriptions
604
+ if (parsed.entries.length === 0) {
605
+ return `no usable subscription URL: ${parsed.errors[0]?.reason ?? 'the field holds no URL'}`
606
+ }
607
+ return undefined
608
+ }
609
+
610
+ /**
611
+ * Whether this runtime can bring routing up right now.
612
+ *
613
+ * Kept apart from {@link blocker} because a missing core is now a *recoverable*
614
+ * state: the plugin can fetch one. The start path still refuses without a binary,
615
+ * but that refusal is no longer the end of the story.
616
+ *
617
+ * @returns true when the core and the installation root are both present.
618
+ */
619
+ get ready() {
620
+ return this.binary !== undefined && this.installRoot !== undefined
621
+ }
622
+
623
+ /**
624
+ * Download and install a core into this plugin's data directory.
625
+ *
626
+ * This is what makes the plugin independent of a desktop Clash installation. The
627
+ * download is verified against the release's published SHA-256 before anything is
628
+ * unpacked or moved into place, and `binary`/`core` are only reassigned once the
629
+ * executable exists — so a failed attempt leaves the previous core working.
630
+ *
631
+ * @param options - progress callback and an injectable fetch for a test.
632
+ * @returns the install report.
633
+ */
634
+ async bootstrapCore(options = {}) {
635
+ if (this.bootstrapping === true) throw new Error('a core download is already in progress')
636
+ if (platformKey() === undefined) {
637
+ throw new Error(`no released core for ${process.platform}-${process.arch}; set corePath to an existing executable`)
638
+ }
639
+ this.bootstrapping = true
640
+ this.bootstrap = { phase: 'starting' }
641
+ try {
642
+ const report = await installCore({
643
+ dataDir: this.dataDir,
644
+ version: this.config.coreVersion,
645
+ fetch: options.fetch,
646
+ onProgress: (progress) => {
647
+ this.bootstrap = progress
648
+ if (progress.phase === 'downloading' && progress.total > 0) {
649
+ this.log(`core download ${Math.round((progress.received / progress.total) * 100)}%`)
650
+ } else {
651
+ this.log(`core bootstrap: ${progress.phase}${progress.tag === undefined ? '' : ` ${progress.tag}`}`)
652
+ }
653
+ },
654
+ })
655
+ // Re-resolve through the same discovery the constructor used, so the state after
656
+ // a download is indistinguishable from a machine that already had a core.
657
+ this.binary = findCoreBinary(this.config.corePath, this.dataDir)
658
+ this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger: this.log })
659
+ this.bootstrap = { phase: 'done', ...report }
660
+ return report
661
+ } catch (error) {
662
+ this.bootstrap = { phase: 'failed', error: String(error?.message ?? error) }
663
+ throw error
664
+ } finally {
665
+ this.bootstrapping = false
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Install a core from an archive the user already placed on disk.
671
+ *
672
+ * The download path cannot work on a network that will not move 22 MB: measured here,
673
+ * every mirror stalled below the speed gate. An offline install keeps the plugin usable
674
+ * there, and it is verified exactly like a downloaded archive.
675
+ *
676
+ * @param archivePath - the archive to install.
677
+ * @param digest - expected SHA-256; empty accepts any archive and reports what it was.
678
+ * @returns the install report.
679
+ */
680
+ async installCoreFromArchive(archivePath, digest = '') {
681
+ const report = await installCoreFromFile(archivePath, digest, {
682
+ dataDir: this.dataDir,
683
+ onProgress: (progress) => {
684
+ this.bootstrap = progress
685
+ },
686
+ })
687
+ this.binary = findCoreBinary(this.config.corePath, this.dataDir)
688
+ this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger: this.log })
689
+ this.bootstrap = { phase: 'done', ...report }
690
+ return report
691
+ }
692
+
693
+ /**
694
+ * Load the shared policy module once, from the installation the host runs from.
695
+ *
696
+ * Resolution order lives in `lib/install.js`: an explicit environment variable, then
697
+ * the process arguments, then the executable path, then well-known positions beside
698
+ * the executable. A failure here is fatal for routing, so the message names the
699
+ * executable and the variable that fixes it rather than repeating "from the process
700
+ * arguments" — which was the only hint the first release offered, and it was wrong for
701
+ * every packaged build.
702
+ */
703
+ async ensurePolicyModule() {
704
+ if (this.routing !== undefined) return this.routing
705
+ const root = this.installRoot
706
+ if (root === undefined) {
707
+ throw new Error(
708
+ `cannot locate the dsh installation root: no known layout matched process.argv or ${process.execPath}; set DSH_INSTALL_ROOT to the directory holding the dsh package.json`,
709
+ )
710
+ }
711
+ const proxyModule = await loadHttpProxyModule(root)
712
+ const undiciPath = resolveFromInstall(root, 'undici')
713
+ this.log(`policy module from ${root} (${installName(root) ?? 'unnamed'})`)
714
+ this.routing = new Routing({ proxyModule, undiciPath, logger: this.log })
715
+ return this.routing
716
+ }
717
+
718
+ /**
719
+ * Import the subscriptions and bring routing up.
720
+ *
721
+ * @param options - overrides for one start, e.g. a newly pasted URL list.
722
+ * @returns the start report.
723
+ */
724
+ async start(options = {}) {
725
+ this.starting = true
726
+ try {
727
+ return await this.startInner(options)
728
+ } finally {
729
+ this.starting = false
730
+ }
731
+ }
732
+
733
+ /**
734
+ * The body of {@link start}, with {@link starting} already raised.
735
+ *
736
+ * @param options - overrides for one start.
737
+ * @returns the start report.
738
+ */
739
+ /**
740
+ * Make a core available, using the copy that ships with the plugin.
741
+ *
742
+ * This is the "works right after install" half. The vendored archive is unpacked into the
743
+ * data directory on first use and verified both as an archive and as an executable, so the
744
+ * plugin never depends on reaching GitHub before it can proxy anything. Free space and a
745
+ * one-time unpack are the whole cost.
746
+ *
747
+ * A core found by discovery (a desktop Clash install, or a `corePath`) still wins: this
748
+ * only runs when nothing else is available.
749
+ *
750
+ * @param options - platform overrides and a progress callback.
751
+ * @returns the installed path, or undefined when this build has no vendored core.
752
+ */
753
+ async ensureVendoredCore(options = {}) {
754
+ if (vendoredFor(options.platform, options.arch) === undefined) return undefined
755
+ if (this.binary !== undefined) return this.binary
756
+ try {
757
+ const installed = await installVendoredCore(this.dataDir, {
758
+ ...options,
759
+ onProgress: (progress) => {
760
+ this.bootstrap = progress
761
+ if (progress.phase === 'unpacking' || progress.phase === 'installed') this.log(`core ${progress.phase}`)
762
+ },
763
+ })
764
+ this.binary = findCoreBinary(this.config.corePath, this.dataDir)
765
+ this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger: this.log })
766
+ this.bootstrap = { phase: 'ready', path: installed.path, reused: installed.reused }
767
+ return this.binary
768
+ } catch (error) {
769
+ this.bootstrap = { phase: 'failed', error: String(error?.message ?? error) }
770
+ this.log(`the bundled core could not be unpacked: ${this.bootstrap.error}`)
771
+ return undefined
772
+ }
773
+ }
774
+
775
+ /**
776
+ * Kick off the optional GeoIP upgrade in the background.
777
+ *
778
+ * Deliberately fire-and-forget. The upgrade improves accuracy for addresses the embedded
779
+ * list cannot describe; it must never delay or fail a start, and on a machine with no
780
+ * route to either mirror it simply does not happen.
781
+ *
782
+ * @returns nothing; progress goes to {@link geo} and the log.
783
+ */
784
+ scheduleGeoUpgrade() {
785
+ if (this.config.autoFetchGeo === false) {
786
+ this.geo = { phase: 'disabled' }
787
+ return
788
+ }
789
+ // Geo databases are seeded from any desktop Clash install at core start, so ask the disk
790
+ // rather than this runtime's memory: a present database means nothing to do, and an
791
+ // absent one is the only case worth a download.
792
+ if (hasGeoDatabase(this.dataDir)) {
793
+ this.geo = { phase: 'present' }
794
+ return
795
+ }
796
+ if (this.geoUpgrading === true) return
797
+ this.geoUpgrading = true
798
+ this.geo = { phase: 'fetching' }
799
+ void fetchGeoDatabases(this.dataDir)
800
+ .then((report) => {
801
+ this.geo = {
802
+ phase: report.ok ? 'done' : report.fetched.length > 0 ? 'partial' : 'unavailable',
803
+ fetched: report.fetched.map((entry) => ({ name: entry.name, bytes: entry.bytes, source: entry.source })),
804
+ failed: report.failed,
805
+ }
806
+ if (report.fetched.length > 0) {
807
+ this.log(`geoip upgraded: ${report.fetched.map((entry) => entry.name).join(', ')} — applies from the next core start`)
808
+ } else if (report.ok === false) {
809
+ this.log(`geoip upgrade unavailable (domestic routing keeps using the embedded list): ${report.failed.map((entry) => entry.name).join(', ')}`)
810
+ }
811
+ })
812
+ .catch((error) => {
813
+ this.geo = { phase: 'unavailable', error: String(error?.message ?? error) }
814
+ })
815
+ .finally(() => {
816
+ this.geoUpgrading = false
817
+ })
818
+ }
819
+
820
+ async startInner(options = {}) {
821
+ mkdirSync(this.dataDir, { recursive: true })
822
+ // Order matters, and it is the point of this method: configuration is validated and
823
+ // the subscription list is parsed BEFORE the core is required, so a missing core
824
+ // surfaces as "still fetching" rather than as "your configuration is wrong".
825
+ const parsed = parseSubscriptions(String(options.subscriptionUrls ?? this.subscriptionUrl))
826
+ if (parsed.entries.length === 0) {
827
+ throw new Error(`no usable subscription URL: ${parsed.errors[0]?.reason ?? 'the field holds no URL'}`)
828
+ }
829
+ if (this.installRoot === undefined) throw new Error(this.blocker)
830
+ if (this.binary === undefined) {
831
+ // Last chance before reporting a missing core: unpack the copy that ships with the
832
+ // plugin. This is why a fresh install needs no network at all.
833
+ await this.ensureVendoredCore()
834
+ }
835
+ if (this.binary === undefined) {
836
+ // Nothing to spawn yet. Fetching is a background concern, so this returns a state
837
+ // the caller can report instead of throwing: the panel shows "内核准备中", and the
838
+ // watchdog brings routing up once the download lands.
839
+ const error = new Error(
840
+ `no mihomo core yet (${platformKey() ?? `${process.platform}-${process.arch}`}); a download is needed before routing can start`,
841
+ )
842
+ error.code = 'CORE_MISSING'
843
+ throw error
844
+ }
845
+
846
+ const routing = await this.ensurePolicyModule()
847
+ const coreEntries = parsed.entries.map((entry) => ({
848
+ provider: providerName(entry),
849
+ url: entry.url,
850
+ // Only prefix when there is more than one provider: a single subscription keeps
851
+ // the node names exactly as the provider wrote them.
852
+ prefix: nodePrefix(entry, parsed.entries.length),
853
+ }))
854
+ const endpoint = await this.core.start({
855
+ subscriptions: coreEntries,
856
+ mode: this.config.mode,
857
+ dnsServers: splitList(this.config.dnsServers),
858
+ directDomains: this.config.directDomains,
859
+ proxyDomains: this.config.proxyDomains,
860
+ // No geo directories are passed: the core's own data directory is authoritative,
861
+ // and discovery supplies a machine-level fallback only when that copy is absent.
862
+ })
863
+ const variables = await routing.apply(endpoint.host, endpoint.port)
864
+
865
+ // Wait for the providers before probing. The core answers its control API before a
866
+ // provider has downloaded anything, so probing at that point raced the fetch and
867
+ // reported ECONNRESET on a perfectly good subscription — the panel then showed
868
+ // "unreachable" next to 54 working nodes. Probe after the node table arrives, and
869
+ // wait per provider so a large second subscription is not cut short.
870
+ const group = await this.waitForNodes(parsed.entries.length)
871
+ this.lastProbe = await this.probeEntries(parsed.entries)
872
+
873
+ const preferred = String(options.node ?? this.preferredNode ?? '').trim()
874
+ // A fresh group starts on DIRECT, which would route foreign traffic straight out.
875
+ // Selecting a real node is part of bringing routing up, not an optional extra.
876
+ const selected = group.all.some((entry) => entry !== 'DIRECT')
877
+ ? await this.core.autoSelect(preferred).catch(() => undefined)
878
+ : undefined
879
+ this.lastError = undefined
880
+ this.degraded = undefined
881
+ // Routing is now up under this activation's ownership, which is what arms the
882
+ // watchdog. Set last so a failure inside `start()` never arms it.
883
+ this.engaged = true
884
+ // Only now can a GeoIP database be fetched: the tunnel it must travel over exists at
885
+ // this point and not before. The embedded CIDR list already classifies domestic
886
+ // addresses, so this is an upgrade running in the background — never a startup
887
+ // dependency, and a failure is recorded rather than raised.
888
+ this.scheduleGeoUpgrade()
889
+ return {
890
+ endpoint: `http://${endpoint.host}:${endpoint.port}`,
891
+ geo: endpoint.geo,
892
+ providers: endpoint.providers,
893
+ // The rule set the core loaded for the domestic bypass, so a caller can show that the
894
+ // split routing does not depend on a GeoIP database being present.
895
+ cnRuleSet: endpoint.cnRuleSet,
896
+ group: await this.core.group(),
897
+ selected,
898
+ variables,
899
+ probe: this.lastProbe,
900
+ subscriptionErrors: parsed.errors,
901
+ configPath: this.core.configPath,
902
+ }
903
+ }
904
+
905
+ /**
906
+ * Probe every configured subscription, tolerating a failure in any of them.
907
+ *
908
+ * @param entries - parsed subscription entries.
909
+ * @returns the labelled multi-probe report.
910
+ */
911
+ async probeEntries(entries) {
912
+ try {
913
+ return await probeSubscriptions(entries, { timeoutMs: 20_000 })
914
+ } catch (error) {
915
+ return {
916
+ results: [],
917
+ ok: false,
918
+ total: entries.length,
919
+ reachable: 0,
920
+ nodeCount: 0,
921
+ bytes: 0,
922
+ error: String(error?.message ?? error),
923
+ }
924
+ }
925
+ }
926
+
927
+ /**
928
+ * Wait until the subscription providers have contributed their nodes, or time out.
929
+ *
930
+ * An earlier version returned as soon as the group held *any* node, which was right
931
+ * for one subscription and wrong for several: the fast provider satisfied the
932
+ * condition while a large one (a 723 KB, 54-node document takes seconds) was still
933
+ * downloading, so the slow subscription was then reported as `ok: false` with zero
934
+ * nodes — a lie that only appears once you use more than one subscription. So the
935
+ * wait is per provider, and a provider that stays empty is reported by
936
+ * {@link Core.providerStatus} rather than hidden behind a group count.
937
+ *
938
+ * @param total - how many providers are configured.
939
+ * @returns the group snapshot, even when it stayed empty.
940
+ */
941
+ async waitForNodes(total = 1) {
942
+ const deadline = Date.now() + 20_000
943
+ const expected = Math.max(1, Number(total) || 1)
944
+ let group = await this.core.group()
945
+ while (Date.now() < deadline) {
946
+ const status = await this.core.providerStatus().catch(() => ({ providers: [] }))
947
+ const arrived = (status.providers ?? []).filter((row) => row.nodeCount > 0).length
948
+ if (arrived >= expected) break
949
+ // A single provider that answered is enough to stop waiting only when every other
950
+ // one has already answered — the `arrived === expected` test above. Otherwise keep
951
+ // polling, but never longer than the deadline.
952
+ group = await this.core.group()
953
+ await new Promise((resolve) => setTimeout(resolve, 500))
954
+ }
955
+ group = await this.core.group()
956
+ return group
957
+ }
958
+
959
+ /** Stop the measurement cycle. Safe to call when none is running. */
960
+ stopTimer() {
961
+ if (this.timer === undefined) return
962
+ this.timer()
963
+ this.timer = undefined
964
+ }
965
+
966
+ /** Stop the watchdog. Safe to call when none is running. */
967
+ stopWatchdog() {
968
+ if (this.watchdog === undefined) return
969
+ this.watchdog()
970
+ this.watchdog = undefined
971
+ }
972
+
973
+ /** Stop routing first, so nothing is sent to a port that is about to close. */
974
+ async stop() {
975
+ // A stop is the user saying "leave me direct": disarm the watchdog before the port
976
+ // closes, or it would see an unexpected exit and restart what was just stopped.
977
+ this.engaged = false
978
+ if (this.routing !== undefined) await this.routing.releaseToDirect()
979
+ if (this.core !== undefined) await this.core.stop()
980
+ }
981
+
982
+ /** The status the model and the panel both read. */
983
+ async status() {
984
+ const running = this.core?.running === true
985
+ const group = running ? await this.core.group().catch(() => ({ all: [], now: undefined })) : { all: [], now: undefined }
986
+ const provider = running
987
+ ? await this.core.providerStatus()
988
+ : { updatedAt: null, vehicleType: null, providers: [], ok: false, healthy: 0, total: 0 }
989
+ const traffic = running ? await this.core.connections().catch(() => undefined) : undefined
990
+ const policy = this.routing === undefined ? { state: 'none' } : await this.routing.verify()
991
+ const parsed = this.subscriptions
992
+ const providerRows = provider.providers.map((row) => {
993
+ const entry = parsed.entries.find((candidate) => providerName(candidate) === row.provider)
994
+ return {
995
+ ...row,
996
+ name: entry === undefined ? row.provider : displayName(entry),
997
+ url: entry === undefined ? '' : maskToken(entry.url),
998
+ }
999
+ })
1000
+ return {
1001
+ binary: this.binary,
1002
+ dataDir: this.dataDir,
1003
+ running,
1004
+ endpoint: running ? `http://127.0.0.1:${this.core.mixedPort}` : undefined,
1005
+ routing: this.routing?.active === true,
1006
+ /** Whether the installed dispatcher is really this plugin's — see Routing#verify. */
1007
+ routingVerified: policy.state,
1008
+ /**
1009
+ * Whether the installed dispatcher still has something to talk to. `verify()`
1010
+ * answers "is this my dispatcher", not "does it work"; a dead core left it
1011
+ * reporting `active` over a closed port, so the two are reported apart.
1012
+ */
1013
+ routingHealthy: policy.state === 'active' && running,
1014
+ endpointEnvironment: this.routing?.endpoint,
1015
+ childEnvironment: this.routing?.childOverlay() ?? {},
1016
+ node: group.now,
1017
+ nodeCount: Math.max(0, group.all.length - 1),
1018
+ nodes: group.all.filter((entry) => entry !== 'DIRECT').slice(0, 40),
1019
+ provider,
1020
+ providers: providerRows,
1021
+ subscriptions: parsed.entries.map((entry) => ({
1022
+ name: displayName(entry),
1023
+ provider: providerName(entry),
1024
+ url: maskToken(entry.url),
1025
+ index: entry.index,
1026
+ })),
1027
+ subscriptionErrors: parsed.errors,
1028
+ traffic,
1029
+ blocker: this.blocker,
1030
+ ready: this.ready,
1031
+ /** Progress/result of a core download, when one has been attempted. */
1032
+ bootstrap: this.bootstrap,
1033
+ /** Optional GeoIP upgrade state; domestic routing works without it. */
1034
+ geoUpgrade: this.geo,
1035
+ /** Whether the core uses an embedded CIDR rule set for the domestic bypass. */
1036
+ cnRuleSet: this.core?.cnRuleSet === undefined
1037
+ ? undefined
1038
+ : { name: 'cn-cidr', count: this.core.cnRuleSet.count },
1039
+ /** Whether a download could be attempted at all on this platform. */
1040
+ platformSupported: platformKey() !== undefined,
1041
+ degraded: this.degraded,
1042
+ lastError: this.lastError ?? this.core?.lastError,
1043
+ probe: this.lastProbe,
1044
+ delays: Object.fromEntries(this.measured),
1045
+ measuredAt: this.measuredAt === 0 ? null : new Date(this.measuredAt).toISOString(),
1046
+ source: 'configured',
1047
+ }
1048
+ }
1049
+ }
1050
+
1051
+ /**
1052
+ * Mount the plugin.
1053
+ *
1054
+ * @param ctx - registrant context; `tools` is injected.
1055
+ * @param rawConfig - the Loader row's configuration.
1056
+ */
1057
+ export async function apply(ctx, rawConfig) {
1058
+ const config = resolveConfig(rawConfig)
1059
+ const log = (message) => ctx.logger?.info?.(`[clash-proxy] ${message}`) ?? undefined
1060
+ const runtime = new Runtime(config, log)
1061
+
1062
+ ctx.effect(() => () => {
1063
+ runtime.stopTimer()
1064
+ runtime.stopWatchdog()
1065
+ void runtime.stop()
1066
+ })
1067
+
1068
+ // Persistence rides the config editor, which keeps the rest of the profile patch
1069
+ // intact. A profile without one still works: the change applies to this process and
1070
+ // the save answer reports that it was not written.
1071
+ ctx.inject(['configEditor'], (editorCtx) => {
1072
+ editorCtx.effect(() => {
1073
+ const editor = editorCtx.get('configEditor')
1074
+ const entry = editorCtx.fiber?.entry
1075
+ if (editor === undefined || entry === undefined) return () => {}
1076
+ runtime.editor = async (patch) => {
1077
+ await editor.edit(entry, (current) => ({ ...current, ...patch }))
1078
+ }
1079
+ return () => {
1080
+ runtime.editor = undefined
1081
+ }
1082
+ }, 'clash-proxy: config persistence')
1083
+ })
1084
+
1085
+ // The measurement cycle and the liveness watchdog ride the host timer service, so
1086
+ // they are disposed with the plugin and repeated plugin reloads never stack timers.
1087
+ // `rearm` is published here, in plugin context, for the request handler that saves a
1088
+ // new interval to call: it re-enters this context instead of touching the timer
1089
+ // service from a foreign fiber.
1090
+ ctx.inject(['timer'], (timerCtx) => {
1091
+ timerCtx.effect(() => {
1092
+ const schedule = (callback, delay) => timerCtx.timer.interval(callback, delay)
1093
+ runtime.schedule = schedule
1094
+ runtime.rearm = () => {
1095
+ runtime.scheduleSpeedTest(schedule)
1096
+ runtime.scheduleWatchdog(schedule)
1097
+ }
1098
+ runtime.scheduleSpeedTest(schedule)
1099
+ runtime.scheduleWatchdog(schedule)
1100
+ return () => {
1101
+ runtime.rearm = undefined
1102
+ runtime.stopTimer()
1103
+ runtime.stopWatchdog()
1104
+ }
1105
+ }, 'clash-proxy: speed test cycle and watchdog')
1106
+ })
1107
+
1108
+ if (runtime.installRoot === undefined) {
1109
+ // Say it once, at load: everything downstream (the panel, routing, the tool) needs
1110
+ // this root, and a silent failure here is indistinguishable from "not configured".
1111
+ log(`outbound policy unavailable: ${runtime.blocker}`)
1112
+ }
1113
+
1114
+ if (config.autoStart === true && runtime.blocker === undefined) {
1115
+ // Boot in the background: a slow subscription must not delay the Harness' own startup.
1116
+ // `start()` unpacks the bundled core when nothing else is present, so this path works on
1117
+ // a machine with no network and no Clash installation.
1118
+ void runtime.start().catch((error) => {
1119
+ runtime.lastError = String(error?.message ?? error)
1120
+ log(`auto start failed: ${runtime.lastError}`)
1121
+ })
1122
+ } else if (config.autoStart === true) {
1123
+ log(`auto start skipped: ${runtime.blocker}`)
1124
+ }
1125
+ // A missing core is no longer a startup branch of its own: `start()` prefers the bundled
1126
+ // copy, and only a build without one falls back to the download below.
1127
+ if (config.autoFetchCore === true && runtime.binary === undefined && vendoredFor() === undefined) {
1128
+ log('no bundled core for this platform; downloading one because autoFetchCore is on')
1129
+ void runtime.bootstrapCore().catch((error) => {
1130
+ runtime.lastError = String(error?.message ?? error)
1131
+ log(`core download failed: ${runtime.lastError}`)
1132
+ })
1133
+ }
1134
+
1135
+ // Panel routes ride a `webServer` sub-fiber rather than a one-shot `ctx.get`:
1136
+ // loader entries settle concurrently, so reading the service at apply time would
1137
+ // silently skip the mount whenever the web server activates after this plugin.
1138
+ ctx.inject(['webServer'], (webCtx) => {
1139
+ webCtx.effect(() => {
1140
+ const webServer = webCtx.get('webServer')
1141
+ if (webServer === undefined) return () => {}
1142
+ const disposers = mountRoutes(webServer, runtime, log)
1143
+ return () => {
1144
+ for (const dispose of disposers) dispose()
1145
+ }
1146
+ }, 'clash-proxy: panel routes')
1147
+ })
1148
+
1149
+ ctx.tools.register(subscriptionTool(runtime))
1150
+ }
1151
+
1152
+ /**
1153
+ * The single model-facing tool: one action word per operation.
1154
+ *
1155
+ * @param runtime - the activation's runtime.
1156
+ * @returns the raw tool definition.
1157
+ */
1158
+ function subscriptionTool(runtime) {
1159
+ return {
1160
+ name: 'clash_proxy',
1161
+ description: [
1162
+ 'Manage the Harness\' own outbound proxy, backed by a private Clash/mihomo core and one or more user-imported subscriptions.',
1163
+ 'Once it runs, foreign requests from this process (web_fetch, search, LLM transports, shells) are routed through the subscription automatically, while domestic traffic and loopback stay direct — no desktop app, no system proxy, no per-command environment variables.',
1164
+ 'action=status reports the core, the installed policy, every subscription with its node count, the node table and live traffic.',
1165
+ 'action=import takes one or more subscription URLs (one per line, raw https:// or clash://install-config?url=… import links), probes them, restarts the core on them and routes through it. Without append it replaces the list; with append it adds to it.',
1166
+ 'action=start brings routing up on the configured subscriptions; action=stop takes it down and restores direct connections.',
1167
+ 'action=select switches the exit node by name (see the node list from status); action=test measures latency for one node or the current one; action=refresh re-downloads every subscription.',
1168
+ ].join(' '),
1169
+ parameters: {
1170
+ type: 'object',
1171
+ properties: {
1172
+ action: {
1173
+ type: 'string',
1174
+ enum: ['status', 'import', 'start', 'stop', 'select', 'test', 'refresh', 'bootstrap'],
1175
+ description: 'status reports state; import sets or appends subscriptions; start/stop control routing; select switches the exit node; test measures latency; refresh re-downloads every subscription; bootstrap downloads and installs a private mihomo core when the machine has none.',
1176
+ },
1177
+ url: { type: 'string', description: 'One or more subscription URLs for action=import, one per line. A leading "name " is kept as the display name.' },
1178
+ append: { type: 'boolean', description: 'For action=import: add to the existing subscriptions instead of replacing them.' },
1179
+ node: { type: 'string', description: 'Exact node name for action=select or action=test; omit to use the current selection.' },
1180
+ },
1181
+ required: ['action'],
1182
+ },
1183
+ output: {
1184
+ schema: { type: 'object' },
1185
+ render(_args, value) {
1186
+ return [{ type: 'text', text: String(value?.summary ?? JSON.stringify(value)) }]
1187
+ },
1188
+ },
1189
+ timeoutMs: 180_000,
1190
+ async execute(args) {
1191
+ const action = String(args?.action ?? 'status')
1192
+ try {
1193
+ if (action === 'status') {
1194
+ const status = await runtime.status()
1195
+ return { ...status, summary: describeStatus(status) }
1196
+ }
1197
+ if (action === 'stop') {
1198
+ await runtime.stop()
1199
+ const status = await runtime.status()
1200
+ return { ...status, summary: '代理已停止,所有外网请求恢复直连。' }
1201
+ }
1202
+ if (action === 'import') {
1203
+ const incoming = String(args?.url ?? '').trim()
1204
+ if (incoming === '') throw new Error('action=import needs a url')
1205
+ const merged = args?.append === true ? [runtime.subscriptionUrl, incoming].filter((part) => part !== '').join('\n') : incoming
1206
+ const parsed = parseSubscriptions(merged)
1207
+ if (parsed.entries.length === 0) {
1208
+ throw new Error(parsed.errors[0]?.reason ?? 'no usable subscription URL in the request')
1209
+ }
1210
+ // Persist first: a model-driven import must survive a restart exactly like a
1211
+ // save from the panel, which the 0.2 tool path did not do.
1212
+ const saved = await runtime.saveConfig({ subscriptionUrls: merged })
1213
+ const report = await runtime.start({ subscriptionUrls: merged })
1214
+ return {
1215
+ ...report,
1216
+ config: saved.config,
1217
+ warnings: saved.warnings,
1218
+ summary: [
1219
+ `订阅已导入 ${parsed.entries.length} 条${args?.append === true ? '(追加)' : '(替换)'}:`,
1220
+ ...parsed.entries.map((entry) => ` ${displayName(entry)}:${maskToken(entry.url)}`),
1221
+ `内核 ${report.endpoint},当前节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。`,
1222
+ saved.warnings.length === 0 ? '配置已保存。' : `配置保存警告:${saved.warnings.join('; ')}`,
1223
+ ].join('\n'),
1224
+ }
1225
+ }
1226
+ if (action === 'bootstrap') {
1227
+ const report = await runtime.bootstrapCore()
1228
+ return {
1229
+ ...report,
1230
+ binary: runtime.binary,
1231
+ summary: [
1232
+ `已下载并验证内核:${report.tag},${Math.round(report.bytes / 1024 / 1024)} MB。`,
1233
+ `SHA-256 与发布页一致:${report.digest.slice(0, 16)}…`,
1234
+ `落盘位置:${report.path}`,
1235
+ runtime.subscriptionUrl === '' ? '下一步:在设置里填订阅链接,然后 action=start。' : '下一步:action=start 即可启动。',
1236
+ ].join('\n'),
1237
+ }
1238
+ }
1239
+ if (action === 'start') {
1240
+ const report = await runtime.start()
1241
+ return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
1242
+ }
1243
+ if (action === 'select') {
1244
+ const node = String(args?.node ?? '').trim()
1245
+ if (node === '') throw new Error('action=select needs a node name')
1246
+ const group = await runtime.core.select(node)
1247
+ return { group, summary: `已切换到「${group.now}」。` }
1248
+ }
1249
+ if (action === 'test') {
1250
+ const target = String(args?.node ?? '').trim()
1251
+ if (target !== '') {
1252
+ const delay = await runtime.core.delay(target)
1253
+ return { node: target, delay, summary: delay === null ? `「${target}」测速失败。` : `「${target}」延迟 ${delay} ms。` }
1254
+ }
1255
+ const status = await runtime.status()
1256
+ if (status.node === undefined) throw new Error('no node selected')
1257
+ const delay = await runtime.core.delay(status.node)
1258
+ return { node: status.node, delay, summary: delay === null ? `「${status.node}」测速失败。` : `「${status.node}」延迟 ${delay} ms。` }
1259
+ }
1260
+ if (action === 'refresh') {
1261
+ const provider = await runtime.core.updateProvider()
1262
+ const group = await runtime.core.group()
1263
+ return {
1264
+ provider,
1265
+ group,
1266
+ summary: [
1267
+ `订阅已刷新:${provider.healthy}/${provider.total} 条可用,共 ${group.all.length - 1} 个节点。`,
1268
+ ...provider.providers.map((row) => ` ${row.provider}:${row.ok ? `${row.nodeCount} 个节点` : '未拉到节点'}`),
1269
+ ].join('\n'),
1270
+ }
1271
+ }
1272
+ throw new Error(`unknown action "${action}"`)
1273
+ } catch (error) {
1274
+ runtime.lastError = String(error?.message ?? error)
1275
+ return { error: runtime.lastError, summary: `clash_proxy ${action} 失败:${runtime.lastError}` }
1276
+ }
1277
+ },
1278
+ }
1279
+ }
1280
+
1281
+ /**
1282
+ * Compose the human-readable status line.
1283
+ *
1284
+ * @param status - the status object.
1285
+ * @returns the summary text.
1286
+ */
1287
+ function describeStatus(status) {
1288
+ if (status.blocker !== undefined) {
1289
+ const lines = [`未运行:${status.blocker}`]
1290
+ if (status.bootstrap !== undefined) {
1291
+ lines.push(`内核下载:${status.bootstrap.phase}${status.bootstrap.error === undefined ? '' : `(${status.bootstrap.error})`}`)
1292
+ }
1293
+ return lines.join('\n')
1294
+ }
1295
+ const lines = [
1296
+ `内核:${status.running ? `运行中 ${status.endpoint}` : '未运行'}${status.binary === undefined ? '(未找到二进制)' : ''}`,
1297
+ `出网策略:${status.routing ? `已安装 → ${status.endpointEnvironment}` : '未安装(直连)'}${
1298
+ status.routing === true && status.routingHealthy !== true ? '(内核不在,实际不生效)' : ''
1299
+ }`,
1300
+ `当前节点:${status.node ?? '未选择'}(可选 ${status.nodeCount} 个)`,
1301
+ ]
1302
+ const subscriptions = Array.isArray(status.subscriptions) ? status.subscriptions : []
1303
+ if (subscriptions.length > 0) {
1304
+ lines.push(`订阅 ${subscriptions.length} 条:`)
1305
+ for (const subscription of subscriptions) {
1306
+ const row = (status.providers ?? []).find((candidate) => candidate.provider === subscription.provider)
1307
+ const state = row === undefined ? '内核未运行' : row.ok ? `${row.nodeCount} 个节点` : '未拉到节点'
1308
+ lines.push(` ${subscription.name}:${state}`)
1309
+ }
1310
+ }
1311
+ if (status.degraded !== undefined) lines.push(`降级:${status.degraded}`)
1312
+ if (status.lastError !== undefined) lines.push(`最近错误:${status.lastError}`)
1313
+ return lines.join('\n')
1314
+ }