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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/routing.js ADDED
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Installation of the process-wide outbound policy.
3
+ *
4
+ * The Harness already owns this mechanism: `@deepseek-ai/dsh-http-proxy` resolves a
5
+ * proxy policy from the launch environment and installs it as undici's global
6
+ * dispatcher. Node's `fetch` — which `ctx.web`, the search/fetch providers and the
7
+ * LLM transports all use — resolves that dispatcher, and `dsh-subprocess` asks the
8
+ * same module for the environment a child needs.
9
+ *
10
+ * So this plugin does not invent routing. It hands that module a policy pointing at
11
+ * its own local core, and every outbound request in the process is covered without
12
+ * any caller knowing. The policy is therefore loaded from the installation path, not
13
+ * from the profile: one module instance, one policy.
14
+ *
15
+ * @module dsh-clash-proxy/routing
16
+ */
17
+
18
+ /**
19
+ * Owns the installed policy and swaps it as the local core moves.
20
+ */
21
+ export class Routing {
22
+ /**
23
+ * @param options - the loaded policy module, the installation root, and a logger.
24
+ */
25
+ constructor({ proxyModule, undiciPath, logger }) {
26
+ this.proxyModule = proxyModule
27
+ this.undiciPath = undiciPath
28
+ this.log = logger ?? (() => {})
29
+ this.dispose = undefined
30
+ this.endpoint = undefined
31
+ /** The dispatcher instance installed by this plugin, for {@link verify}. */
32
+ this.installed = undefined
33
+ }
34
+
35
+ /** Whether this plugin installed a policy (ownership, not proof it still routes). */
36
+ get active() {
37
+ return this.endpoint !== undefined
38
+ }
39
+
40
+ /**
41
+ * Route every outbound request through one loopback proxy port.
42
+ *
43
+ * @param host - core host.
44
+ * @param port - core mixed port.
45
+ * @param extraBypass - additional no-proxy host entries.
46
+ * @returns the applied variable map.
47
+ */
48
+ async apply(host, port, extraBypass = []) {
49
+ this.release()
50
+ const variables = buildVariables(host, port, extraBypass)
51
+ const env = viewOf(variables)
52
+ this.dispose = await this.proxyModule.installProxyFromEnvironment(env, (message) => this.log(`proxy policy: ${message}`))
53
+ this.endpoint = `http://${host}:${port}`
54
+ try {
55
+ const { pathToFileURL } = await import('node:url')
56
+ const undici = await import(pathToFileURL(this.undiciPath).href)
57
+ this.installed = undici.getGlobalDispatcher()
58
+ } catch {
59
+ this.installed = undefined
60
+ }
61
+ return variables
62
+ }
63
+
64
+ /**
65
+ * Detach this plugin's policy handle without touching the installed dispatcher.
66
+ *
67
+ * undici keeps exactly one global dispatcher. The host installs its own from the
68
+ * launch environment at boot, and this plugin replaced it with one pointing at the
69
+ * local core. Releasing on plugin reload would restore *the pre-release* dispatcher,
70
+ * which for a boot with no proxy variables is a direct agent — so a reload (an HMR
71
+ * pass, or a settings save that restarts the entry) would silently return the whole
72
+ * process to direct connectivity while the profile still says the plugin is enabled.
73
+ *
74
+ * So a reload only forgets the handle: the installed dispatcher stays in place until
75
+ * the user explicitly stops the plugin, or a new `apply` installs over it.
76
+ */
77
+ release() {
78
+ this.dispose = undefined
79
+ this.endpoint = undefined
80
+ }
81
+
82
+ /**
83
+ * Remove the policy and leave the process directly connected.
84
+ *
85
+ * The single path that intentionally returns to direct: the user asked to stop.
86
+ */
87
+ async releaseToDirect() {
88
+ const dispose = this.dispose
89
+ this.dispose = undefined
90
+ this.endpoint = undefined
91
+ if (dispose === undefined) return
92
+ try {
93
+ await dispose()
94
+ } catch (error) {
95
+ this.log(`proxy policy release failed: ${error?.message ?? error}`)
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Whether outbound requests really go through the endpoint this plugin installed.
101
+ *
102
+ * `dispose` being set only says the plugin believes it installed a policy; the host
103
+ * may have installed another one since (a restart, another plugin, a manual reset).
104
+ * Reading undici's live dispatcher is the only honest answer, so the panel reports
105
+ * what is actually routing rather than a status flag that can lie.
106
+ *
107
+ * @returns `active` when this plugin's dispatcher is live, `lost` when something else
108
+ * replaced it, and `none` when no policy was installed.
109
+ */
110
+ async verify() {
111
+ if (this.installed === undefined) return { state: 'none' }
112
+ try {
113
+ const { pathToFileURL } = await import('node:url')
114
+ const undici = await import(pathToFileURL(this.undiciPath).href)
115
+ const live = undici.getGlobalDispatcher()
116
+ return live === this.installed ? { state: 'active' } : { state: 'lost' }
117
+ } catch (error) {
118
+ return { state: 'unknown', reason: String(error?.message ?? error) }
119
+ }
120
+ }
121
+
122
+ /** What a spawned child will be given, straight from the shared policy module. */
123
+ childOverlay() {
124
+ try {
125
+ return this.proxyModule.proxyEnvironmentForChild()
126
+ } catch {
127
+ return {}
128
+ }
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Build the environment names undici and child tools read.
134
+ *
135
+ * @param host - core host.
136
+ * @param port - core mixed port.
137
+ * @param extraBypass - additional bypass entries.
138
+ * @returns the variable map, both casings written together.
139
+ */
140
+ export function buildVariables(host, port, extraBypass = []) {
141
+ const url = `http://${host}:${port}`
142
+ const bypass = ['localhost', '127.0.0.1', '::1', '[::1]', ...extraBypass].filter(
143
+ (entry, index, all) => entry !== '' && all.indexOf(entry) === index,
144
+ )
145
+ const noProxy = bypass.join(',')
146
+ return {
147
+ http_proxy: url,
148
+ HTTP_PROXY: url,
149
+ https_proxy: url,
150
+ HTTPS_PROXY: url,
151
+ no_proxy: noProxy,
152
+ NO_PROXY: noProxy,
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Adapt a variable map to the `get(name)` view the policy module reads.
158
+ *
159
+ * @param variables - environment name to value.
160
+ * @returns the view.
161
+ */
162
+ export function viewOf(variables) {
163
+ const wanted = new Map()
164
+ for (const [name, value] of Object.entries(variables)) {
165
+ if (typeof value === 'string' && value !== '') wanted.set(name.toLowerCase(), value)
166
+ }
167
+ return {
168
+ get(name) {
169
+ const value = wanted.get(String(name).toLowerCase())
170
+ return value === undefined ? undefined : { value }
171
+ },
172
+ }
173
+ }
@@ -0,0 +1,334 @@
1
+ /**
2
+ * Subscription intake.
3
+ *
4
+ * A subscription URL is fetched exactly once here, only to answer three questions
5
+ * the plugin needs before it can route: is this URL reachable, does it return a
6
+ * Clash document or a share-link list, and how many nodes does it carry. The core
7
+ * then re-fetches it through its own `proxy-providers` entry, which is where the
8
+ * real parsing happens — including share-link formats (`ss://`, `vmess://`,
9
+ * `vless://`, `trojan://`, `anytls://`, `hysteria2://`) that a Clash document
10
+ * cannot express and no plugin-side parser should try to re-implement.
11
+ *
12
+ * Several subscriptions may be configured at once. Each one becomes its own
13
+ * `proxy-providers` entry and contributes its nodes to the single `PROXY` group, so
14
+ * the node table shows every provider's nodes side by side and one dead provider
15
+ * never stops the core from booting.
16
+ *
17
+ * @module dsh-clash-proxy/subscription
18
+ */
19
+
20
+ /** Markers that identify a Clash/mihomo YAML document. */
21
+ const CLASH_MARKERS = ['proxy-groups:', 'proxy-providers:', 'proxies:', 'rules:', 'mixed-port:']
22
+
23
+ /** Share-link schemes a mihomo provider accepts. */
24
+ const SHARE_SCHEMES = ['ss://', 'ssr://', 'vmess://', 'vless://', 'trojan://', 'anytls://', 'hysteria://', 'hysteria2://', 'tuic://', 'wireguard://']
25
+
26
+ /**
27
+ * One subscription entry as the configuration holds it.
28
+ *
29
+ * @typedef {object} SubscriptionEntry
30
+ * @property {string} url - normalized subscription URL.
31
+ * @property {string} name - display name; empty means "subscription N".
32
+ * @property {number} index - stable position, used for the provider name.
33
+ */
34
+
35
+ /**
36
+ * Convert a Clash Verge import link into the raw subscription URL.
37
+ *
38
+ * Clash Verge and most one-click importers share this `clash://install-config?url=`
39
+ * form, so a URL copied from such a site works without editing.
40
+ *
41
+ * @param input - the URL as the user pasted it.
42
+ * @returns the subscription URL to fetch.
43
+ */
44
+ export function normalizeSubscriptionUrl(input) {
45
+ const raw = String(input ?? '').trim()
46
+ if (raw === '') throw new Error('subscription URL is empty')
47
+ const nested = /^clash:\/\/install-config\?/i.test(raw) || /^clash:\/\/install-config\//i.test(raw)
48
+ if (nested) {
49
+ const query = raw.slice(raw.indexOf('?') + 1)
50
+ const url = new URLSearchParams(query).get('url')
51
+ if (url === null || url === '') throw new Error('import link carries no url parameter')
52
+ return url
53
+ }
54
+ let parsed
55
+ try {
56
+ parsed = new URL(raw)
57
+ } catch {
58
+ throw new Error(`not an absolute URL: ${raw.slice(0, 60)}`)
59
+ }
60
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
61
+ throw new Error(`unsupported subscription scheme "${parsed.protocol}"`)
62
+ }
63
+ return parsed.toString()
64
+ }
65
+
66
+ /**
67
+ * Split the multi-line subscription field into raw entries.
68
+ *
69
+ * Accepted forms, one per line:
70
+ *
71
+ * - `https://…/subscribe?token=…` — a bare URL
72
+ * - `clash://install-config?url=…` — an importer link
73
+ * - `主用 https://…` — a display name, whitespace, then the URL
74
+ * - `#` or `//` at the start of a line — a comment, skipped
75
+ *
76
+ * Blank lines and comments are dropped so a user may group entries visually. The
77
+ * name is optional everywhere; without one the entry is called "订阅 N" by the panel.
78
+ *
79
+ * @param text - the field value, possibly with several lines.
80
+ * @returns the raw entries, in the order they were written.
81
+ */
82
+ export function parseSubscriptionLines(text) {
83
+ const entries = []
84
+ for (const line of String(text ?? '').split(/\r?\n/)) {
85
+ const trimmed = line.trim()
86
+ if (trimmed === '' || trimmed.startsWith('#') || trimmed.startsWith('//')) continue
87
+ // A name is any leading token without a scheme separator; everything after the
88
+ // first whitespace is the URL. A name containing "://" would be a URL, so this
89
+ // only treats the prefix as a name when it clearly is not one.
90
+ const split = trimmed.match(/^(\S+)\s+(\S.*)$/)
91
+ if (split !== null && !split[1].includes('://') && split[2].includes('://')) {
92
+ entries.push({ name: split[1], raw: split[2].trim() })
93
+ continue
94
+ }
95
+ entries.push({ name: '', raw: trimmed })
96
+ }
97
+ return entries
98
+ }
99
+
100
+ /**
101
+ * Parse the configuration field into validated subscription entries.
102
+ *
103
+ * Duplicates are dropped by normalized URL: the same subscription listed twice would
104
+ * add every node twice under two provider prefixes, which looks like a bug to the
105
+ * user and doubles every latency measurement.
106
+ *
107
+ * @param text - the multi-line field value.
108
+ * @returns `{ entries, errors }`; a bad line is reported, never silently skipped.
109
+ */
110
+ export function parseSubscriptions(text) {
111
+ const entries = []
112
+ const errors = []
113
+ const seen = new Set()
114
+ for (const [at, line] of parseSubscriptionLines(text).entries()) {
115
+ let url
116
+ try {
117
+ url = normalizeSubscriptionUrl(line.raw)
118
+ } catch (error) {
119
+ errors.push({ line: at + 1, reason: String(error?.message ?? error), raw: line.raw.slice(0, 120) })
120
+ continue
121
+ }
122
+ if (seen.has(url)) {
123
+ errors.push({ line: at + 1, reason: 'duplicate subscription URL, ignored', raw: line.raw.slice(0, 120) })
124
+ continue
125
+ }
126
+ seen.add(url)
127
+ entries.push({
128
+ url,
129
+ name: String(line.name ?? '').trim().slice(0, 40),
130
+ index: entries.length,
131
+ // The provider name is derived here, not at the call site: `start()` and `status()`
132
+ // both read it, and a caller that forgot to derive it silently produced
133
+ // `provider: undefined` in the parsed list.
134
+ provider: `sub${entries.length}`,
135
+ })
136
+ }
137
+ return { entries, errors }
138
+ }
139
+
140
+ /**
141
+ * Migrate the single-URL field into the multi-line one.
142
+ *
143
+ * An existing profile carries `subscriptionUrl`; reading it as the first line keeps
144
+ * that profile working with no edit. The old field is never written back, so a
145
+ * user's next save naturally moves them onto the list form.
146
+ *
147
+ * @param config - the resolved configuration.
148
+ * @returns the effective multi-line text.
149
+ */
150
+ export function effectiveSubscriptionText(config) {
151
+ const list = String(config?.subscriptionUrls ?? '').trim()
152
+ if (list !== '') return list
153
+ const single = String(config?.subscriptionUrl ?? '').trim()
154
+ return single
155
+ }
156
+
157
+ /**
158
+ * The provider name one entry contributes.
159
+ *
160
+ * mihomo names a provider's proxy namespace after the provider, so this is also the
161
+ * namespace `/providers/proxies/<name>` addresses. The index keeps it stable across
162
+ * a reorder-free edit.
163
+ *
164
+ * @param entry - a parsed entry.
165
+ * @returns the provider name.
166
+ */
167
+ export function providerName(entry) {
168
+ const named = String(entry?.provider ?? '').trim()
169
+ if (named !== '') return named
170
+ return `sub${Number(entry?.index ?? 0)}`
171
+ }
172
+
173
+ /**
174
+ * The display name one entry carries.
175
+ *
176
+ * @param entry - a parsed entry.
177
+ * @returns the user's name, or a positional fallback.
178
+ */
179
+ export function displayName(entry) {
180
+ const named = String(entry?.name ?? '').trim()
181
+ return named !== '' ? named : `订阅 ${Number(entry?.index ?? 0) + 1}`
182
+ }
183
+
184
+ /**
185
+ * The node prefix one provider's nodes carry.
186
+ *
187
+ * Two subscriptions routinely list the same node names ("香港01", "日本02"). Without a
188
+ * per-provider prefix the group holds duplicate names, and selecting "香港01" cannot
189
+ * say which provider it meant — measured: `PROXY.all` came back with each name twice.
190
+ * `override.additional-prefix` makes them unique; the prefix is only applied when more
191
+ * than one subscription is configured, so a single subscription keeps its clean names.
192
+ *
193
+ * @param entry - a parsed entry.
194
+ * @param total - how many subscriptions are configured.
195
+ * @returns the prefix, or an empty string for a single subscription.
196
+ */
197
+ export function nodePrefix(entry, total) {
198
+ if (Number(total) <= 1) return ''
199
+ return `${displayName(entry)} · `
200
+ }
201
+
202
+ /**
203
+ * Classify a subscription response body.
204
+ *
205
+ * @param text - response text.
206
+ * @returns the detected format and its node count where countable.
207
+ */
208
+ export function classifyBody(text) {
209
+ const head = text.slice(0, 4000)
210
+ const clash = CLASH_MARKERS.filter((marker) => head.includes(marker) || text.includes(marker))
211
+ if (clash.length >= 2) return { format: 'clash', nodeCount: countClashNodes(text) }
212
+ const schemes = SHARE_SCHEMES.filter((scheme) => text.includes(scheme))
213
+ if (schemes.length > 0) return { format: 'share-links', nodeCount: countShareLinks(text), schemes }
214
+ if (text.trimStart().startsWith('<')) return { format: 'html', nodeCount: 0 }
215
+ return { format: 'unknown', nodeCount: 0 }
216
+ }
217
+
218
+ /**
219
+ * Count entries in a Clash document's `proxies:` block by indentation.
220
+ *
221
+ * @param text - Clash document text.
222
+ * @returns the count, or 0 when the block is absent.
223
+ */
224
+ function countClashNodes(text) {
225
+ const lines = text.split(/\r?\n/)
226
+ const start = lines.findIndex((line) => /^proxies:\s*$/.test(line))
227
+ if (start < 0) {
228
+ if (/^proxies:\s*\[\s*\]/m.test(text)) return 0
229
+ return 0
230
+ }
231
+ let count = 0
232
+ for (let index = start + 1; index < lines.length; index += 1) {
233
+ const line = lines[index]
234
+ if (/^\S/.test(line)) break
235
+ if (/^\s*-\s/.test(line)) count += 1
236
+ }
237
+ return count
238
+ }
239
+
240
+ /**
241
+ * Count non-empty share-link lines.
242
+ *
243
+ * @param text - response text.
244
+ * @returns the count.
245
+ */
246
+ function countShareLinks(text) {
247
+ return text
248
+ .split(/\r?\n/)
249
+ .map((line) => line.trim())
250
+ .filter((line) => SHARE_SCHEMES.some((scheme) => line.toLowerCase().startsWith(scheme))).length
251
+ }
252
+
253
+ /**
254
+ * The user agent a subscription endpoint expects.
255
+ *
256
+ * Subscription services gate their response on client identity: a generic agent is
257
+ * answered with 403 or a marketing page, while a Clash core name is answered with the
258
+ * node list. Measured against a live provider — `clash-verge/2.0` returns 403,
259
+ * `ClashforWindows` returns 421, and `clash.meta` returns the full 723 KB document.
260
+ * Sending the core's own identity makes the probe see exactly what the core fetches.
261
+ */
262
+ const SUBSCRIPTION_USER_AGENT = 'clash.meta'
263
+
264
+ /**
265
+ * Fetch a subscription once and report what it carries.
266
+ *
267
+ * @param url - normalized subscription URL.
268
+ * @param options - timeout and an optional proxy-free fetch implementation.
269
+ * @returns the probe result.
270
+ */
271
+ export async function probeSubscription(url, options = {}) {
272
+ const timeoutMs = options.timeoutMs ?? 20_000
273
+ const request = options.fetch ?? fetch
274
+ const response = await request(url, {
275
+ redirect: 'follow',
276
+ headers: { 'user-agent': SUBSCRIPTION_USER_AGENT },
277
+ signal: AbortSignal.timeout(timeoutMs),
278
+ })
279
+ const text = await response.text()
280
+ const classified = classifyBody(text)
281
+ return {
282
+ status: response.status,
283
+ ok: response.ok,
284
+ bytes: Buffer.byteLength(text, 'utf8'),
285
+ ...classified,
286
+ hints: response.headers.get('subscription-userinfo') ?? response.headers.get('profile-update-interval') ?? '',
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Probe several subscriptions at once and label each answer.
292
+ *
293
+ * Probes run concurrently: a slow provider must not delay the report on a fast one,
294
+ * and the panel shows one row per subscription either way. A failure carries the
295
+ * entry it belongs to, so the panel can point at the exact line.
296
+ *
297
+ * @param entries - parsed entries.
298
+ * @param options - per-probe timeout and an optional fetch implementation.
299
+ * @returns one labelled result per entry, in the configured order.
300
+ */
301
+ export async function probeSubscriptions(entries, options = {}) {
302
+ const list = Array.isArray(entries) ? entries : []
303
+ const results = await Promise.all(
304
+ list.map(async (entry) => {
305
+ try {
306
+ const answer = await probeSubscription(entry.url, options)
307
+ return { ...answer, name: displayName(entry), provider: providerName(entry), url: entry.url }
308
+ } catch (error) {
309
+ return {
310
+ ok: false,
311
+ status: 0,
312
+ bytes: 0,
313
+ format: 'unreachable',
314
+ nodeCount: 0,
315
+ error: String(error?.message ?? error),
316
+ name: displayName(entry),
317
+ provider: providerName(entry),
318
+ url: entry.url,
319
+ }
320
+ }
321
+ }),
322
+ )
323
+ const reachable = results.filter((result) => result.ok)
324
+ return {
325
+ results,
326
+ ok: results.length > 0 && reachable.length === results.length,
327
+ total: results.length,
328
+ reachable: reachable.length,
329
+ nodeCount: results.reduce((sum, result) => sum + (Number(result.nodeCount) || 0), 0),
330
+ bytes: results.reduce((sum, result) => sum + (Number(result.bytes) || 0), 0),
331
+ /** Present when some, but not all, subscriptions answered. */
332
+ partial: results.length > 0 && reachable.length > 0 && reachable.length < results.length,
333
+ }
334
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * The core that ships inside this plugin.
3
+ *
4
+ * The core is what makes the plugin a working proxy, and the core itself can only be
5
+ * obtained from the internet. That makes it the wrong thing to download lazily: a machine
6
+ * that installs this plugin because it cannot reach the internet would then need the
7
+ * internet to become able to reach the internet. So the archive is vendored in
8
+ * `vendor/` and unpacked on first use.
9
+ *
10
+ * A vendored binary is not trusted just because it shipped here: its SHA-256 is recorded
11
+ * at build time, checked before unpacking, and the unpacked file is checked again after.
12
+ * If the recorded digest and the shipped archive ever disagree, the plugin refuses to use
13
+ * it rather than executing bytes it cannot account for.
14
+ *
15
+ * @module dsh-clash-proxy/vendored
16
+ */
17
+ import { createHash } from 'node:crypto'
18
+ import { spawn } from 'node:child_process'
19
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs'
20
+ import { dirname, join } from 'node:path'
21
+ import { fileURLToPath } from 'node:url'
22
+
23
+ /** This module's directory, so `vendor/` resolves regardless of the process cwd. */
24
+ const HERE = dirname(fileURLToPath(import.meta.url))
25
+
26
+ /**
27
+ * What ships in `vendor/`, per platform.
28
+ *
29
+ * The digests live in `vendor/SHA256SUMS.json`, which is generated when the plugin is
30
+ * packaged, so the shipped file and the code cannot drift apart without the manifest
31
+ * disagreeing with itself. The values here are the fallback used only when the manifest is
32
+ * absent — which means a broken package, and the checks then fail closed.
33
+ *
34
+ * Regenerating: gzip the release binary, hash both, rewrite the manifest.
35
+ *
36
+ * @type {Record<string, {archive: string, binary: string, digest: string, binaryDigest: string, size: number}>}
37
+ */
38
+ export const VENDORED = {
39
+ 'win32-x64': {
40
+ archive: 'mihomo.exe.gz',
41
+ binary: 'mihomo.exe',
42
+ // SHA-256 of vendor/mihomo.exe.gz — mihomo v1.19.34, windows-amd64-compatible build.
43
+ digest: '275a5ed94fb78ea57b49f3e7a7859fca65aed213171450b0a45b5e43c224f7f7',
44
+ // SHA-256 of the unpacked executable.
45
+ binaryDigest: '5a0231811a80b27477ebdee15684b41946d01afbd2114534e9a4b256125ca147',
46
+ size: 22332744,
47
+ },
48
+ }
49
+
50
+ /**
51
+ * The vendored entry for this machine.
52
+ *
53
+ * @param platform - `process.platform`.
54
+ * @param arch - `process.arch`.
55
+ * @returns the entry, or undefined when this build has no vendored core for the pair.
56
+ */
57
+ export function vendoredFor(platform = process.platform, arch = process.arch) {
58
+ return VENDORED[`${platform}-${arch}`]
59
+ }
60
+
61
+ /**
62
+ * Read the digest manifest that sits beside the vendored archive.
63
+ *
64
+ * The manifest is generated when the plugin is packaged, so the digests in code and in the
65
+ * shipped file cannot drift apart silently.
66
+ *
67
+ * @returns `{ archive, binary }` hex digests, or undefined when the manifest is absent.
68
+ */
69
+ export function readVendorManifest() {
70
+ try {
71
+ const text = readFileSync(join(HERE, '..', 'vendor', 'SHA256SUMS.json'), 'utf8')
72
+ const parsed = JSON.parse(text)
73
+ if (typeof parsed?.archive === 'string' && typeof parsed?.binary === 'string') return parsed
74
+ } catch {
75
+ return undefined
76
+ }
77
+ return undefined
78
+ }
79
+
80
+ /**
81
+ * Unpack one gzip archive.
82
+ *
83
+ * @param archivePath - the `.gz` file.
84
+ * @param destination - directory to unpack into.
85
+ * @returns nothing; throws on failure.
86
+ */
87
+ function gunzip(archivePath, destination) {
88
+ return new Promise((resolve, reject) => {
89
+ const child = spawn('tar', ['-xzf', archivePath, '-C', destination], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
90
+ let stderr = ''
91
+ child.stderr?.on('data', (chunk) => {
92
+ stderr += String(chunk)
93
+ })
94
+ child.once('error', reject)
95
+ child.once('exit', (code) => {
96
+ if (code === 0) resolve(undefined)
97
+ else reject(new Error(`tar exited ${code}: ${stderr.trim().slice(0, 200)}`))
98
+ })
99
+ })
100
+ }
101
+
102
+ /**
103
+ * Unpack the vendored core into `dataDir/bin`, verifying both hashes.
104
+ *
105
+ * Idempotent: an already-unpacked core whose digest matches is left alone, so this can run
106
+ * on every start without rewriting 60 MB.
107
+ *
108
+ * @param dataDir - the plugin's data directory.
109
+ * @param options - `platform`/`arch` overrides and a progress callback.
110
+ * @returns the installed path, its size and the digests used.
111
+ */
112
+ export async function installVendoredCore(dataDir, options = {}) {
113
+ const entry = vendoredFor(options.platform, options.arch)
114
+ if (entry === undefined) {
115
+ throw new Error(`no vendored core for ${options.platform ?? process.platform}-${options.arch ?? process.arch}`)
116
+ }
117
+ const report = options.onProgress ?? (() => {})
118
+ const vendorDir = join(HERE, '..', 'vendor')
119
+ const archivePath = join(vendorDir, entry.archive)
120
+ if (!existsSync(archivePath)) throw new Error(`the vendored archive is missing: ${archivePath}`)
121
+
122
+ const manifest = readVendorManifest()
123
+ const wantArchive = String(manifest?.archive ?? entry.digest)
124
+ const wantBinary = String(manifest?.binary ?? entry.binaryDigest)
125
+
126
+ const finalPath = join(dataDir, 'bin', entry.binary)
127
+ // Already unpacked and still the right bytes: nothing to do.
128
+ if (existsSync(finalPath)) {
129
+ const present = createHash('sha256').update(readFileSync(finalPath)).digest('hex')
130
+ if (present === wantBinary) {
131
+ report({ phase: 'already', path: finalPath })
132
+ return { path: finalPath, bytes: statSync(finalPath).size, digest: present, reused: true }
133
+ }
134
+ }
135
+
136
+ const archiveBytes = readFileSync(archivePath)
137
+ const archiveDigest = createHash('sha256').update(archiveBytes).digest('hex')
138
+ if (wantArchive !== '0000000000000000000000000000000000000000000000000000000000000000' && archiveDigest !== wantArchive) {
139
+ throw new Error(`the vendored archive does not match its manifest: expected ${wantArchive}, found ${archiveDigest}`)
140
+ }
141
+ report({ phase: 'unpacking', archiveDigest })
142
+
143
+ const stageDir = join(dataDir, 'bin-stage')
144
+ mkdirSync(stageDir, { recursive: true })
145
+ try {
146
+ await gunzip(archivePath, stageDir)
147
+ const unpacked = join(stageDir, entry.binary)
148
+ if (!existsSync(unpacked)) throw new Error(`the archive did not contain ${entry.binary}`)
149
+ const binaryDigest = createHash('sha256').update(readFileSync(unpacked)).digest('hex')
150
+ if (wantBinary !== '0000000000000000000000000000000000000000000000000000000000000000' && binaryDigest !== wantBinary) {
151
+ throw new Error(`the unpacked core does not match its manifest: expected ${wantBinary}, found ${binaryDigest}`)
152
+ }
153
+ mkdirSync(join(dataDir, 'bin'), { recursive: true })
154
+ if (existsSync(finalPath)) rmSync(finalPath, { force: true })
155
+ const { renameSync } = await import('node:fs')
156
+ renameSync(unpacked, finalPath)
157
+ if (process.platform !== 'win32') chmodSync(finalPath, 0o755)
158
+ report({ phase: 'installed', path: finalPath, bytes: statSync(finalPath).size })
159
+ return { path: finalPath, bytes: statSync(finalPath).size, digest: binaryDigest, archiveDigest, reused: false }
160
+ } finally {
161
+ try {
162
+ rmSync(stageDir, { recursive: true, force: true })
163
+ } catch {
164
+ // A locked file only costs disk space.
165
+ }
166
+ }
167
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Clash subscription proxy",
4
+ "description": "Import one or more Clash/mihomo subscriptions, run a private core, and route only foreign outbound traffic through it."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Clash 订阅代理",
4
+ "description": "导入一条或多条 Clash/mihomo 订阅,起一个私有内核,只把访问外网的流量走代理,国内网站保持直连。"
5
+ }
6
+ }