dsh-clash-subscription 0.2.2 → 0.4.2-probe.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -127
- package/index.js +1 -678
- package/package.json +6 -62
- package/LICENSE +0 -21
- package/client.js +0 -786
- package/cordis.patch.yml +0 -5
- package/icon.svg +0 -14
- package/lib/core.js +0 -496
- package/lib/discovery.js +0 -94
- package/lib/install.js +0 -83
- package/lib/routes.js +0 -262
- package/lib/routing.js +0 -173
- package/lib/subscription.js +0 -138
- package/locale/en.json +0 -6
- package/locale/zh.json +0 -6
package/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
|
-
}
|
package/lib/subscription.js
DELETED
|
@@ -1,138 +0,0 @@
|
|
|
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
|
-
* @module dsh-clash-proxy/subscription
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
/** Markers that identify a Clash/mihomo YAML document. */
|
|
16
|
-
const CLASH_MARKERS = ['proxy-groups:', 'proxy-providers:', 'proxies:', 'rules:', 'mixed-port:']
|
|
17
|
-
|
|
18
|
-
/** Share-link schemes a mihomo provider accepts. */
|
|
19
|
-
const SHARE_SCHEMES = ['ss://', 'ssr://', 'vmess://', 'vless://', 'trojan://', 'anytls://', 'hysteria://', 'hysteria2://', 'tuic://', 'wireguard://']
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Convert a Clash Verge import link into the raw subscription URL.
|
|
23
|
-
*
|
|
24
|
-
* Clash Verge and most one-click importers share this `clash://install-config?url=`
|
|
25
|
-
* form, so a URL copied from such a site works without editing.
|
|
26
|
-
*
|
|
27
|
-
* @param input - the URL as the user pasted it.
|
|
28
|
-
* @returns the subscription URL to fetch.
|
|
29
|
-
*/
|
|
30
|
-
export function normalizeSubscriptionUrl(input) {
|
|
31
|
-
const raw = String(input ?? '').trim()
|
|
32
|
-
if (raw === '') throw new Error('subscription URL is empty')
|
|
33
|
-
const nested = /^clash:\/\/install-config\?/i.test(raw) || /^clash:\/\/install-config\//i.test(raw)
|
|
34
|
-
if (nested) {
|
|
35
|
-
const query = raw.slice(raw.indexOf('?') + 1)
|
|
36
|
-
const url = new URLSearchParams(query).get('url')
|
|
37
|
-
if (url === null || url === '') throw new Error('import link carries no url parameter')
|
|
38
|
-
return url
|
|
39
|
-
}
|
|
40
|
-
let parsed
|
|
41
|
-
try {
|
|
42
|
-
parsed = new URL(raw)
|
|
43
|
-
} catch {
|
|
44
|
-
throw new Error(`not an absolute URL: ${raw.slice(0, 60)}`)
|
|
45
|
-
}
|
|
46
|
-
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
47
|
-
throw new Error(`unsupported subscription scheme "${parsed.protocol}"`)
|
|
48
|
-
}
|
|
49
|
-
return parsed.toString()
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Classify a subscription response body.
|
|
54
|
-
*
|
|
55
|
-
* @param text - response text.
|
|
56
|
-
* @returns the detected format and its node count where countable.
|
|
57
|
-
*/
|
|
58
|
-
export function classifyBody(text) {
|
|
59
|
-
const head = text.slice(0, 4000)
|
|
60
|
-
const clash = CLASH_MARKERS.filter((marker) => head.includes(marker) || text.includes(marker))
|
|
61
|
-
if (clash.length >= 2) return { format: 'clash', nodeCount: countClashNodes(text) }
|
|
62
|
-
const schemes = SHARE_SCHEMES.filter((scheme) => text.includes(scheme))
|
|
63
|
-
if (schemes.length > 0) return { format: 'share-links', nodeCount: countShareLinks(text), schemes }
|
|
64
|
-
if (text.trimStart().startsWith('<')) return { format: 'html', nodeCount: 0 }
|
|
65
|
-
return { format: 'unknown', nodeCount: 0 }
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Count entries in a Clash document's `proxies:` block by indentation.
|
|
70
|
-
*
|
|
71
|
-
* @param text - Clash document text.
|
|
72
|
-
* @returns the count, or 0 when the block is absent.
|
|
73
|
-
*/
|
|
74
|
-
function countClashNodes(text) {
|
|
75
|
-
const lines = text.split(/\r?\n/)
|
|
76
|
-
const start = lines.findIndex((line) => /^proxies:\s*$/.test(line))
|
|
77
|
-
if (start < 0) {
|
|
78
|
-
if (/^proxies:\s*\[\s*\]/m.test(text)) return 0
|
|
79
|
-
return 0
|
|
80
|
-
}
|
|
81
|
-
let count = 0
|
|
82
|
-
for (let index = start + 1; index < lines.length; index += 1) {
|
|
83
|
-
const line = lines[index]
|
|
84
|
-
if (/^\S/.test(line)) break
|
|
85
|
-
if (/^\s*-\s/.test(line)) count += 1
|
|
86
|
-
}
|
|
87
|
-
return count
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Count non-empty share-link lines.
|
|
92
|
-
*
|
|
93
|
-
* @param text - response text.
|
|
94
|
-
* @returns the count.
|
|
95
|
-
*/
|
|
96
|
-
function countShareLinks(text) {
|
|
97
|
-
return text
|
|
98
|
-
.split(/\r?\n/)
|
|
99
|
-
.map((line) => line.trim())
|
|
100
|
-
.filter((line) => SHARE_SCHEMES.some((scheme) => line.toLowerCase().startsWith(scheme))).length
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* The user agent a subscription endpoint expects.
|
|
105
|
-
*
|
|
106
|
-
* Subscription services gate their response on client identity: a generic agent is
|
|
107
|
-
* answered with 403 or a marketing page, while a Clash core name is answered with the
|
|
108
|
-
* node list. Measured against a live provider — `clash-verge/2.0` returns 403,
|
|
109
|
-
* `ClashforWindows` returns 421, and `clash.meta` returns the full 723 KB document.
|
|
110
|
-
* Sending the core's own identity makes the probe see exactly what the core fetches.
|
|
111
|
-
*/
|
|
112
|
-
const SUBSCRIPTION_USER_AGENT = 'clash.meta'
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Fetch a subscription once and report what it carries.
|
|
116
|
-
*
|
|
117
|
-
* @param url - normalized subscription URL.
|
|
118
|
-
* @param options - timeout and an optional proxy-free fetch implementation.
|
|
119
|
-
* @returns the probe result.
|
|
120
|
-
*/
|
|
121
|
-
export async function probeSubscription(url, options = {}) {
|
|
122
|
-
const timeoutMs = options.timeoutMs ?? 20_000
|
|
123
|
-
const request = options.fetch ?? fetch
|
|
124
|
-
const response = await request(url, {
|
|
125
|
-
redirect: 'follow',
|
|
126
|
-
headers: { 'user-agent': SUBSCRIPTION_USER_AGENT },
|
|
127
|
-
signal: AbortSignal.timeout(timeoutMs),
|
|
128
|
-
})
|
|
129
|
-
const text = await response.text()
|
|
130
|
-
const classified = classifyBody(text)
|
|
131
|
-
return {
|
|
132
|
-
status: response.status,
|
|
133
|
-
ok: response.ok,
|
|
134
|
-
bytes: Buffer.byteLength(text, 'utf8'),
|
|
135
|
-
...classified,
|
|
136
|
-
hints: response.headers.get('subscription-userinfo') ?? response.headers.get('profile-update-interval') ?? '',
|
|
137
|
-
}
|
|
138
|
-
}
|
package/locale/en.json
DELETED