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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/install.js DELETED
@@ -1,171 +0,0 @@
1
- /**
2
- * Locating the Harness installation root.
3
- *
4
- * A profile-installed plugin resolves modules from `$DSH_PROFILE_DIR/node_modules`,
5
- * which holds only profile packages. The Harness' own building blocks — and the one
6
- * `undici` instance the host process already routes through — live in the dsh
7
- * installation instead. Resolving from the installation's own manifest yields the
8
- * same module instance the host loaded, which is what makes a proxy policy installed
9
- * here visible to `ctx.web`, the LLM transports, and every spawned child.
10
- *
11
- * A packaged Desktop build nests the app package inside `resources/app.asar` (a single
12
- * archive file the Electron runtime exposes as a directory), while a source checkout
13
- * puts it at the checkout root. Neither shape is guaranteed, so the locator walks a
14
- * candidate list instead of testing one hard-coded tail: mistaking the shape stops the
15
- * whole chain before the core is ever spawned, and it does so silently.
16
- *
17
- * @module dsh-clash-proxy/install
18
- */
19
- import { createRequire } from 'node:module'
20
- import { existsSync, readFileSync } from 'node:fs'
21
- import { dirname, join, normalize } from 'node:path'
22
- import { pathToFileURL } from 'node:url'
23
-
24
- /**
25
- * Candidate installation-root tails inside one `argv` entry or an executable path.
26
- *
27
- * Order matters only for reporting; every entry is tried. `app.asar` must come first
28
- * because a packaged build has no unpacked `app` directory, yet the string
29
- * `/resources/app/dsh/` does not occur in its arguments, so the older tails simply miss.
30
- */
31
- const INSTALL_TAILS = [
32
- 'resources/app.asar/dsh',
33
- 'app.asar/dsh',
34
- 'resources/app/dsh',
35
- 'app/dsh',
36
- 'resources/app.asar.unpacked/dsh',
37
- 'app.asar.unpacked/dsh',
38
- ]
39
-
40
- /** Environment variables an operator may set to name the root explicitly. */
41
- const INSTALL_ROOT_ENV = ['DSH_INSTALL_ROOT', 'DSH_APP_ROOT']
42
-
43
- /**
44
- * Whether a directory really is a dsh app package.
45
- *
46
- * `package.json` presence is the only stable signature: it holds both the desktop
47
- * runtime manifest and the `node_modules` the host boots from.
48
- *
49
- * @param candidate - directory to test.
50
- * @returns true when the candidate holds a manifest.
51
- */
52
- function isInstallRoot(candidate) {
53
- if (typeof candidate !== 'string' || candidate === '') return false
54
- try {
55
- return existsSync(join(candidate, 'package.json'))
56
- } catch {
57
- return false
58
- }
59
- }
60
-
61
- /**
62
- * Turn one path into the installation root it contains, if any.
63
- *
64
- * @param entry - argument, executable path, or directory to inspect.
65
- * @returns the root ending in a known tail, or undefined.
66
- */
67
- function rootFromPath(entry) {
68
- if (typeof entry !== 'string' || entry === '') return undefined
69
- const path = normalize(entry).replaceAll('\\', '/')
70
- for (const tail of INSTALL_TAILS) {
71
- const at = path.indexOf(`/${tail}/`)
72
- if (at < 0) continue
73
- const root = path.slice(0, at + tail.length + 1)
74
- if (isInstallRoot(root)) return root
75
- }
76
- // An entry may end exactly at the tail (argv sometimes carries the directory).
77
- for (const tail of INSTALL_TAILS) {
78
- if (path.endsWith(`/${tail}`)) {
79
- const root = `${path}/`
80
- if (isInstallRoot(root)) return root
81
- }
82
- }
83
- return undefined
84
- }
85
-
86
- /**
87
- * Roots implied by an executable path, for a packaged Desktop build.
88
- *
89
- * @param executable - absolute path of the running executable.
90
- * @returns candidate roots, whether or not they exist.
91
- */
92
- function rootsFromExecutable(executable) {
93
- if (typeof executable !== 'string' || executable === '') return []
94
- const home = dirname(executable)
95
- return [
96
- join(home, 'resources', 'app.asar', 'dsh'),
97
- join(home, 'resources', 'app', 'dsh'),
98
- join(home, 'resources', 'app.asar.unpacked', 'dsh'),
99
- ]
100
- }
101
-
102
- /**
103
- * Find the dsh installation root.
104
- *
105
- * Four sources are tried in order, so a packaged build, an unpacked build, a source
106
- * checkout and an exotic launcher all resolve:
107
- *
108
- * 1. an explicit `DSH_INSTALL_ROOT` / `DSH_APP_ROOT`;
109
- * 2. a known tail inside any process argument (the host passes its own entry script);
110
- * 3. a tail inside `process.execPath` (a launcher may omit its entry script);
111
- * 4. well-known positions relative to the executable (packaged Desktop layout).
112
- *
113
- * @param argv - process argument list to inspect.
114
- * @param executable - executable path; defaults to `process.execPath`.
115
- * @returns the absolute installation root, or undefined when nothing matches.
116
- */
117
- export function locateInstallRoot(argv, executable = process.execPath) {
118
- for (const name of INSTALL_ROOT_ENV) {
119
- const value = process.env[name]
120
- if (value !== undefined && isInstallRoot(value)) return normalize(value)
121
- }
122
- for (const entry of Array.isArray(argv) ? argv : []) {
123
- const root = rootFromPath(entry)
124
- if (root !== undefined) return root
125
- }
126
- const fromExe = rootFromPath(executable)
127
- if (fromExe !== undefined) return fromExe
128
- for (const candidate of rootsFromExecutable(executable)) {
129
- if (isInstallRoot(candidate)) return candidate
130
- }
131
- return undefined
132
- }
133
-
134
- /**
135
- * Read the package name of an installation root, for a diagnostic.
136
- *
137
- * @param root - installation root.
138
- * @returns the declared name, or undefined.
139
- */
140
- export function installName(root) {
141
- try {
142
- return JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))?.name
143
- } catch {
144
- return undefined
145
- }
146
- }
147
-
148
- /**
149
- * Resolve one module from the installation, so the plugin shares the host's copy.
150
- *
151
- * @param root - dsh installation root.
152
- * @param id - module specifier to resolve.
153
- * @returns the resolved absolute file path.
154
- */
155
- export function resolveFromInstall(root, id) {
156
- return createRequire(join(root, 'package.json')).resolve(id)
157
- }
158
-
159
- /**
160
- * Load the installation's own proxy-policy module.
161
- *
162
- * Importing through a file URL keeps one module instance: the host boots its policy
163
- * from this same file, so installing here replaces the dispatcher the host already
164
- * set instead of creating a second, invisible one.
165
- *
166
- * @param root - dsh installation root.
167
- * @returns the loaded policy module.
168
- */
169
- export async function loadHttpProxyModule(root) {
170
- return import(pathToFileURL(resolveFromInstall(root, '@deepseek-ai/dsh-http-proxy')).href)
171
- }
package/lib/routes.js DELETED
@@ -1,262 +0,0 @@
1
- /**
2
- * The settings-panel HTTP surface.
3
- *
4
- * The row's configuration form (`plugins.row.config`) can only write declared
5
- * config fields, and three of the controls here need live answers rather than a
6
- * stored value: which nodes the subscription carries, what each one measures, and
7
- * whether a subscription URL is reachable at all. Those ride plain routes on the
8
- * Harness web server, same-origin and JSON-only, so the form stays a form and the
9
- * core stays the source of truth.
10
- *
11
- * @module dsh-clash-proxy/routes
12
- */
13
-
14
- /** Upper bound on a JSON request body from the panel. */
15
- const MAX_BODY_BYTES = 16 * 1024
16
-
17
- /**
18
- * The fields the settings page may write.
19
- *
20
- * A settings section owns its own reads and writes through routes rather than the
21
- * row form, so it must not be able to reach anything outside this list: an arbitrary
22
- * key written into the row config would be passed straight to the loader.
23
- */
24
- export const EDITABLE_FIELDS = [
25
- 'subscriptionUrl',
26
- 'node',
27
- 'corePath',
28
- 'mode',
29
- 'autoStart',
30
- 'dnsServers',
31
- 'directDomains',
32
- 'proxyDomains',
33
- 'speedTestMinutes',
34
- 'speedTestCount',
35
- ]
36
-
37
- /**
38
- * Send one JSON response with caching disabled.
39
- *
40
- * @param response - Node response.
41
- * @param status - HTTP status.
42
- * @param body - JSON-serializable payload.
43
- */
44
- function sendJson(response, status, body) {
45
- const payload = JSON.stringify(body)
46
- response.writeHead(status, {
47
- 'content-type': 'application/json; charset=utf-8',
48
- 'cache-control': 'no-store',
49
- })
50
- response.end(payload)
51
- }
52
-
53
- /**
54
- * Read and parse a JSON request body.
55
- *
56
- * @param request - Node request.
57
- * @param response - Node response, used to answer an oversized body.
58
- * @returns the parsed body, or undefined when it was rejected or absent.
59
- */
60
- async function readJson(request, response) {
61
- const chunks = []
62
- let bytes = 0
63
- for await (const chunk of request) {
64
- bytes += chunk.length
65
- if (bytes > MAX_BODY_BYTES) {
66
- sendJson(response, 413, { error: 'request body is too large' })
67
- return undefined
68
- }
69
- chunks.push(chunk)
70
- }
71
- const text = Buffer.concat(chunks).toString('utf8').trim()
72
- if (text === '') return {}
73
- try {
74
- return JSON.parse(text)
75
- } catch {
76
- sendJson(response, 400, { error: 'body is not valid JSON' })
77
- return undefined
78
- }
79
- }
80
-
81
- /**
82
- * Whether a request comes from the page that served it.
83
- *
84
- * @param request - Node request.
85
- * @returns true when the Origin header is absent or matches the Host.
86
- */
87
- function sameOrigin(request) {
88
- const origin = request.headers.origin
89
- if (typeof origin !== 'string' || origin === '') return true
90
- const host = request.headers.host
91
- if (typeof host !== 'string' || host === '') return false
92
- return origin === `http://${host}` || origin === `https://${host}`
93
- }
94
-
95
- /** The methods a route answers, normalized from a request. */
96
- const methodOf = (request) => String(request.method ?? 'GET').toUpperCase()
97
-
98
- /**
99
- * Mount the panel's routes.
100
- *
101
- * @param webServer - the Harness web server service.
102
- * @param runtime - the activation's runtime.
103
- * @param log - logger for route failures.
104
- * @returns disposers for every registered route.
105
- */
106
- export function mountRoutes(webServer, runtime, log) {
107
- const disposers = []
108
-
109
- const route = (path, handler) => {
110
- disposers.push(
111
- webServer.register({
112
- kind: 'exact',
113
- path,
114
- handler: async (request, response) => {
115
- if (!sameOrigin(request)) {
116
- sendJson(response, 403, { error: 'cross-origin request refused' })
117
- return
118
- }
119
- try {
120
- await handler(request, response)
121
- } catch (error) {
122
- const message = error instanceof Error ? error.message : String(error)
123
- log(`route ${path} failed: ${message}`)
124
- sendJson(response, 500, { error: message })
125
- }
126
- },
127
- }),
128
- )
129
- }
130
-
131
- // Everything the page needs to render: live core state, the node table with
132
- // measured latency, and the effective (possibly discovered) configuration.
133
- route('/clash-proxy/status', async (request, response) => {
134
- if (methodOf(request) !== 'GET') {
135
- sendJson(response, 405, { error: 'GET only' })
136
- return
137
- }
138
- const status = await runtime.status()
139
- const delays = await runtime.nodeDelays()
140
- sendJson(response, 200, {
141
- ...status,
142
- delays,
143
- config: runtime.publicConfig(),
144
- })
145
- })
146
-
147
- // The settings section reads and writes configuration here rather than through the
148
- // row form: a `settings.section` owns its own data, and the form's write path lives
149
- // on a page reached through Plugins → package → row.
150
- route('/clash-proxy/config', async (request, response) => {
151
- const method = methodOf(request)
152
- if (method === 'GET') {
153
- sendJson(response, 200, {
154
- config: runtime.publicConfig(),
155
- editable: EDITABLE_FIELDS,
156
- })
157
- return
158
- }
159
- if (method !== 'POST') {
160
- sendJson(response, 405, { error: 'GET or POST only' })
161
- return
162
- }
163
- const body = await readJson(request, response)
164
- if (body === undefined) return
165
- const patch = body.patch
166
- if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) {
167
- sendJson(response, 400, { error: 'a patch object is required' })
168
- return
169
- }
170
- const unknown = Object.keys(patch).filter((key) => !EDITABLE_FIELDS.includes(key))
171
- if (unknown.length > 0) {
172
- sendJson(response, 400, { error: `unknown field(s): ${unknown.join(', ')}` })
173
- return
174
- }
175
- const saved = await runtime.saveConfig(patch)
176
- sendJson(response, 200, { ok: true, config: saved.config, warnings: saved.warnings })
177
- })
178
-
179
- // Start or stop routing without editing configuration.
180
- route('/clash-proxy/action', async (request, response) => {
181
- if (methodOf(request) !== 'POST') {
182
- sendJson(response, 405, { error: 'POST only' })
183
- return
184
- }
185
- const body = await readJson(request, response)
186
- if (body === undefined) return
187
- const action = String(body.action ?? '')
188
- if (action === 'start') {
189
- const report = await runtime.start()
190
- sendJson(response, 200, { ok: true, endpoint: report.endpoint, node: report.group.now, geo: report.geo })
191
- return
192
- }
193
- if (action === 'stop') {
194
- await runtime.stop()
195
- sendJson(response, 200, { ok: true })
196
- return
197
- }
198
- if (action === 'refresh') {
199
- const provider = await runtime.core.updateProvider()
200
- sendJson(response, 200, { ok: true, provider })
201
- return
202
- }
203
- if (action === 'test') {
204
- // A `node` narrows the run to one node and `all` covers every node; without
205
- // either the cycle measures the configured sample. The panel offers all three.
206
- const target = String(body.node ?? '').trim()
207
- const delays = await runtime.nodeDelays({
208
- force: true,
209
- only: target === '' ? undefined : target,
210
- all: body.all === true,
211
- })
212
- sendJson(response, 200, { ok: true, delays })
213
- return
214
- }
215
- if (action === 'select') {
216
- const name = String(body.node ?? '').trim()
217
- if (name === '') {
218
- sendJson(response, 400, { error: 'node is required' })
219
- return
220
- }
221
- const group = await runtime.core.select(name)
222
- runtime.rememberNode(name)
223
- sendJson(response, 200, { ok: true, now: group.now })
224
- return
225
- }
226
- sendJson(response, 400, { error: `unknown action "${action}"` })
227
- })
228
-
229
- // Probe a subscription before it is saved, so a typo is caught in the form
230
- // rather than in the next activation.
231
- route('/clash-proxy/probe', async (request, response) => {
232
- if (methodOf(request) !== 'POST') {
233
- sendJson(response, 405, { error: 'POST only' })
234
- return
235
- }
236
- const body = await readJson(request, response)
237
- if (body === undefined) return
238
- const answer = await runtime.probe(String(body.url ?? ''))
239
- sendJson(response, answer.ok ? 200 : 400, answer)
240
- })
241
-
242
- return disposers
243
- }
244
-
245
- /**
246
- * Hide the token in a subscription URL so a screenshot of the panel is not a leak.
247
- *
248
- * @param url - the effective subscription URL.
249
- * @returns the URL with any token-like query value masked.
250
- */
251
- export function maskToken(url) {
252
- if (typeof url !== 'string' || url === '') return ''
253
- try {
254
- const parsed = new URL(url)
255
- for (const key of [...parsed.searchParams.keys()]) {
256
- if (/token|key|secret|passwd|password|auth/i.test(key)) parsed.searchParams.set(key, '***')
257
- }
258
- return parsed.toString()
259
- } catch {
260
- return url.replace(/(token|key|secret|password)=[^&]+/gi, '$1=***')
261
- }
262
- }
package/lib/routing.js DELETED
@@ -1,173 +0,0 @@
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
- }