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/LICENSE +21 -0
- package/README.md +188 -2
- package/client.js +980 -0
- package/cordis.patch.yml +5 -0
- package/icon.svg +14 -0
- package/index.js +1314 -1
- package/lib/cn-cidr.js +5526 -0
- package/lib/core.js +734 -0
- package/lib/corefetch.js +618 -0
- package/lib/discovery.js +52 -0
- package/lib/geo.js +130 -0
- package/lib/install.js +171 -0
- package/lib/routes.js +306 -0
- package/lib/routing.js +173 -0
- package/lib/subscription.js +334 -0
- package/lib/vendored.js +167 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +67 -6
- package/vendor/SHA256SUMS.json +7 -0
- package/vendor/mihomo.exe.gz +0 -0
package/lib/geo.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional GeoIP upgrade, performed only after the tunnel works.
|
|
3
|
+
*
|
|
4
|
+
* The plugin already classifies Chinese addresses correctly from its own embedded CIDR
|
|
5
|
+
* list, so a GeoIP database is an *upgrade*, not a requirement. That distinction decides
|
|
6
|
+
* the order of operations: a database can only be fetched over a working connection, and
|
|
7
|
+
* the connection only exists once a subscription is imported and the core is up. Fetching
|
|
8
|
+
* it during startup was the original mistake — the core refused to boot while it tried, and
|
|
9
|
+
* the fallback then sent domestic `.com` sites through a foreign node.
|
|
10
|
+
*
|
|
11
|
+
* So this runs after routing is confirmed healthy, in the background, and a failure is
|
|
12
|
+
* recorded and forgotten rather than surfaced as a fault.
|
|
13
|
+
*
|
|
14
|
+
* @module dsh-clash-proxy/geo
|
|
15
|
+
*/
|
|
16
|
+
import { createHash } from 'node:crypto'
|
|
17
|
+
import { existsSync, mkdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
18
|
+
import { join } from 'node:path'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* GeoIP databases worth having, with the mirror that serves them without GitHub.
|
|
22
|
+
*
|
|
23
|
+
* `Country.mmdb` is the one that matters: it is what `GEOIP,` rules read. The `.dat` files
|
|
24
|
+
* serve `GEOSITE,` rules, which this plugin's generated rule set does not use, so they are
|
|
25
|
+
* listed for completeness and fetched only when a mirror offers them.
|
|
26
|
+
*
|
|
27
|
+
* jsDelivr is tried first because it is reachable from mainland China; the GitHub raw URLs
|
|
28
|
+
* are the fallback for a machine that already has a working tunnel but no jsDelivr route.
|
|
29
|
+
*/
|
|
30
|
+
const GEO_SOURCES = {
|
|
31
|
+
'Country.mmdb': [
|
|
32
|
+
'https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/country.mmdb',
|
|
33
|
+
'https://raw.githubusercontent.com/MetaCubeX/meta-rules-dat/release/country.mmdb',
|
|
34
|
+
],
|
|
35
|
+
'geoip.dat': [
|
|
36
|
+
'https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat',
|
|
37
|
+
'https://raw.githubusercontent.com/MetaCubeX/meta-rules-dat/release/geoip.dat',
|
|
38
|
+
],
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The file names this module manages.
|
|
43
|
+
*
|
|
44
|
+
* @type {readonly string[]}
|
|
45
|
+
*/
|
|
46
|
+
export const GEO_FILES = Object.keys(GEO_SOURCES)
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Whether a usable database is already in place.
|
|
50
|
+
*
|
|
51
|
+
* @param workDir - the core's data directory.
|
|
52
|
+
* @returns true when `Country.mmdb` exists and is not a stub.
|
|
53
|
+
*/
|
|
54
|
+
export function hasGeoDatabase(workDir) {
|
|
55
|
+
const path = join(workDir, 'Country.mmdb')
|
|
56
|
+
try {
|
|
57
|
+
// A zero-byte or tiny file is what a failed download leaves behind; treat it as absent.
|
|
58
|
+
return existsSync(path) && statSync(path).size > 1024
|
|
59
|
+
} catch {
|
|
60
|
+
return false
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Download one database, trying each source in turn.
|
|
66
|
+
*
|
|
67
|
+
* @param name - target file name.
|
|
68
|
+
* @param workDir - destination directory.
|
|
69
|
+
* @param fetchImpl - fetch implementation, injectable for a test.
|
|
70
|
+
* @param timeoutMs - per-attempt budget.
|
|
71
|
+
* @returns the byte count and the source that served it.
|
|
72
|
+
*/
|
|
73
|
+
async function fetchOne(name, workDir, fetchImpl, timeoutMs) {
|
|
74
|
+
const problems = []
|
|
75
|
+
for (const url of GEO_SOURCES[name] ?? []) {
|
|
76
|
+
try {
|
|
77
|
+
const response = await fetchImpl(url, {
|
|
78
|
+
redirect: 'follow',
|
|
79
|
+
headers: { 'user-agent': 'dsh-clash-subscription' },
|
|
80
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
81
|
+
})
|
|
82
|
+
if (!response.ok) throw new Error(`answered ${response.status}`)
|
|
83
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
84
|
+
if (buffer.length < 1024) throw new Error(`only ${buffer.length} bytes`)
|
|
85
|
+
// A database is read by the core at startup, so it must never be half-written: stage
|
|
86
|
+
// it under a temporary name and rename into place.
|
|
87
|
+
const staged = join(workDir, `${name}.part`)
|
|
88
|
+
writeFileSync(staged, buffer)
|
|
89
|
+
const destination = join(workDir, name)
|
|
90
|
+
if (existsSync(destination)) rmSync(destination, { force: true })
|
|
91
|
+
renameSync(staged, destination)
|
|
92
|
+
return { name, bytes: buffer.length, source: new URL(url).host, digest: createHash('sha256').update(buffer).digest('hex').slice(0, 16) }
|
|
93
|
+
} catch (error) {
|
|
94
|
+
problems.push(`${new URL(url).host}: ${String(error?.message ?? error).slice(0, 60)}`)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
throw new Error(`no source served ${name} — ${problems.join(' | ')}`)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Fetch the GeoIP databases into the core's data directory.
|
|
102
|
+
*
|
|
103
|
+
* Called only once routing is healthy. Idempotent: an existing database is left alone
|
|
104
|
+
* unless `force` is set, so this costs nothing on every subsequent start.
|
|
105
|
+
*
|
|
106
|
+
* @param workDir - the core's data directory.
|
|
107
|
+
* @param options - `force` re-downloads, `fetch` and `timeoutMs` for tests.
|
|
108
|
+
* @returns what was fetched, what was skipped, and what failed.
|
|
109
|
+
*/
|
|
110
|
+
export async function fetchGeoDatabases(workDir, options = {}) {
|
|
111
|
+
mkdirSync(workDir, { recursive: true })
|
|
112
|
+
const fetchImpl = options.fetch ?? fetch
|
|
113
|
+
const timeoutMs = options.timeoutMs ?? 60_000
|
|
114
|
+
const fetched = []
|
|
115
|
+
const skipped = []
|
|
116
|
+
const failed = []
|
|
117
|
+
for (const name of GEO_FILES) {
|
|
118
|
+
const present = existsSync(join(workDir, name)) && statSync(join(workDir, name)).size > 1024
|
|
119
|
+
if (present && options.force !== true) {
|
|
120
|
+
skipped.push(name)
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
fetched.push(await fetchOne(name, workDir, fetchImpl, timeoutMs))
|
|
125
|
+
} catch (error) {
|
|
126
|
+
failed.push({ name, reason: String(error?.message ?? error) })
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return { fetched, skipped, failed, ok: failed.length === 0 }
|
|
130
|
+
}
|
package/lib/install.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
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
|
+
'subscriptionUrls',
|
|
26
|
+
'subscriptionUrl',
|
|
27
|
+
'node',
|
|
28
|
+
'corePath',
|
|
29
|
+
'mode',
|
|
30
|
+
'autoStart',
|
|
31
|
+
'dnsServers',
|
|
32
|
+
'directDomains',
|
|
33
|
+
'proxyDomains',
|
|
34
|
+
'speedTestMinutes',
|
|
35
|
+
'speedTestCount',
|
|
36
|
+
'healthCheckMinutes',
|
|
37
|
+
'autoFetchCore',
|
|
38
|
+
'autoFetchGeo',
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Send one JSON response with caching disabled.
|
|
43
|
+
*
|
|
44
|
+
* @param response - Node response.
|
|
45
|
+
* @param status - HTTP status.
|
|
46
|
+
* @param body - JSON-serializable payload.
|
|
47
|
+
*/
|
|
48
|
+
function sendJson(response, status, body) {
|
|
49
|
+
const payload = JSON.stringify(body)
|
|
50
|
+
response.writeHead(status, {
|
|
51
|
+
'content-type': 'application/json; charset=utf-8',
|
|
52
|
+
'cache-control': 'no-store',
|
|
53
|
+
})
|
|
54
|
+
response.end(payload)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Read and parse a JSON request body.
|
|
59
|
+
*
|
|
60
|
+
* @param request - Node request.
|
|
61
|
+
* @param response - Node response, used to answer an oversized body.
|
|
62
|
+
* @returns the parsed body, or undefined when it was rejected or absent.
|
|
63
|
+
*/
|
|
64
|
+
async function readJson(request, response) {
|
|
65
|
+
const chunks = []
|
|
66
|
+
let bytes = 0
|
|
67
|
+
for await (const chunk of request) {
|
|
68
|
+
bytes += chunk.length
|
|
69
|
+
if (bytes > MAX_BODY_BYTES) {
|
|
70
|
+
sendJson(response, 413, { error: 'request body is too large' })
|
|
71
|
+
return undefined
|
|
72
|
+
}
|
|
73
|
+
chunks.push(chunk)
|
|
74
|
+
}
|
|
75
|
+
const text = Buffer.concat(chunks).toString('utf8').trim()
|
|
76
|
+
if (text === '') return {}
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(text)
|
|
79
|
+
} catch {
|
|
80
|
+
sendJson(response, 400, { error: 'body is not valid JSON' })
|
|
81
|
+
return undefined
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Whether a request comes from the page that served it.
|
|
87
|
+
*
|
|
88
|
+
* @param request - Node request.
|
|
89
|
+
* @returns true when the Origin header is absent or matches the Host.
|
|
90
|
+
*/
|
|
91
|
+
function sameOrigin(request) {
|
|
92
|
+
const origin = request.headers.origin
|
|
93
|
+
if (typeof origin !== 'string' || origin === '') return true
|
|
94
|
+
const host = request.headers.host
|
|
95
|
+
if (typeof host !== 'string' || host === '') return false
|
|
96
|
+
return origin === `http://${host}` || origin === `https://${host}`
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The methods a route answers, normalized from a request. */
|
|
100
|
+
const methodOf = (request) => String(request.method ?? 'GET').toUpperCase()
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Mount the panel's routes.
|
|
104
|
+
*
|
|
105
|
+
* @param webServer - the Harness web server service.
|
|
106
|
+
* @param runtime - the activation's runtime.
|
|
107
|
+
* @param log - logger for route failures.
|
|
108
|
+
* @returns disposers for every registered route.
|
|
109
|
+
*/
|
|
110
|
+
export function mountRoutes(webServer, runtime, log) {
|
|
111
|
+
const disposers = []
|
|
112
|
+
|
|
113
|
+
const route = (path, handler) => {
|
|
114
|
+
disposers.push(
|
|
115
|
+
webServer.register({
|
|
116
|
+
kind: 'exact',
|
|
117
|
+
path,
|
|
118
|
+
handler: async (request, response) => {
|
|
119
|
+
if (!sameOrigin(request)) {
|
|
120
|
+
sendJson(response, 403, { error: 'cross-origin request refused' })
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
await handler(request, response)
|
|
125
|
+
} catch (error) {
|
|
126
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
127
|
+
log(`route ${path} failed: ${message}`)
|
|
128
|
+
sendJson(response, 500, { error: message })
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
}),
|
|
132
|
+
)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Everything the page needs to render: live core state, the node table with
|
|
136
|
+
// measured latency, and the effective (possibly discovered) configuration.
|
|
137
|
+
route('/clash-proxy/status', async (request, response) => {
|
|
138
|
+
if (methodOf(request) !== 'GET') {
|
|
139
|
+
sendJson(response, 405, { error: 'GET only' })
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
const status = await runtime.status()
|
|
143
|
+
const delays = await runtime.nodeDelays()
|
|
144
|
+
sendJson(response, 200, {
|
|
145
|
+
...status,
|
|
146
|
+
delays,
|
|
147
|
+
config: runtime.publicConfig(),
|
|
148
|
+
})
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
// The settings section reads and writes configuration here rather than through the
|
|
152
|
+
// row form: a `settings.section` owns its own data, and the form's write path lives
|
|
153
|
+
// on a page reached through Plugins → package → row.
|
|
154
|
+
route('/clash-proxy/config', async (request, response) => {
|
|
155
|
+
const method = methodOf(request)
|
|
156
|
+
if (method === 'GET') {
|
|
157
|
+
sendJson(response, 200, {
|
|
158
|
+
config: runtime.publicConfig(),
|
|
159
|
+
editable: EDITABLE_FIELDS,
|
|
160
|
+
})
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
if (method !== 'POST') {
|
|
164
|
+
sendJson(response, 405, { error: 'GET or POST only' })
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
const body = await readJson(request, response)
|
|
168
|
+
if (body === undefined) return
|
|
169
|
+
const patch = body.patch
|
|
170
|
+
if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) {
|
|
171
|
+
sendJson(response, 400, { error: 'a patch object is required' })
|
|
172
|
+
return
|
|
173
|
+
}
|
|
174
|
+
const unknown = Object.keys(patch).filter((key) => !EDITABLE_FIELDS.includes(key))
|
|
175
|
+
if (unknown.length > 0) {
|
|
176
|
+
sendJson(response, 400, { error: `unknown field(s): ${unknown.join(', ')}` })
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
const saved = await runtime.saveConfig(patch)
|
|
180
|
+
sendJson(response, 200, { ok: true, config: saved.config, warnings: saved.warnings })
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
// Start or stop routing without editing configuration.
|
|
184
|
+
route('/clash-proxy/action', async (request, response) => {
|
|
185
|
+
if (methodOf(request) !== 'POST') {
|
|
186
|
+
sendJson(response, 405, { error: 'POST only' })
|
|
187
|
+
return
|
|
188
|
+
}
|
|
189
|
+
const body = await readJson(request, response)
|
|
190
|
+
if (body === undefined) return
|
|
191
|
+
const action = String(body.action ?? '')
|
|
192
|
+
if (action === 'bootstrap') {
|
|
193
|
+
// Download and verify a private core. Long-running, so the answer carries the
|
|
194
|
+
// final report rather than a progress stream; the panel polls status meanwhile.
|
|
195
|
+
const report = await runtime.bootstrapCore()
|
|
196
|
+
sendJson(response, 200, { ok: true, ...report, binary: runtime.binary })
|
|
197
|
+
return
|
|
198
|
+
}
|
|
199
|
+
if (action === 'start') {
|
|
200
|
+
const report = await runtime.start()
|
|
201
|
+
sendJson(response, 200, {
|
|
202
|
+
ok: true,
|
|
203
|
+
endpoint: report.endpoint,
|
|
204
|
+
node: report.group.now,
|
|
205
|
+
geo: report.geo,
|
|
206
|
+
providers: report.providers,
|
|
207
|
+
})
|
|
208
|
+
return
|
|
209
|
+
}
|
|
210
|
+
if (action === 'stop') {
|
|
211
|
+
await runtime.stop()
|
|
212
|
+
sendJson(response, 200, { ok: true })
|
|
213
|
+
return
|
|
214
|
+
}
|
|
215
|
+
if (action === 'refresh') {
|
|
216
|
+
const provider = await runtime.core.updateProvider()
|
|
217
|
+
sendJson(response, 200, { ok: true, provider })
|
|
218
|
+
return
|
|
219
|
+
}
|
|
220
|
+
if (action === 'refreshOne') {
|
|
221
|
+
// Re-download a single subscription, so a broken provider can be retried without
|
|
222
|
+
// spending the others' interval.
|
|
223
|
+
const provider = String(body.provider ?? '').trim()
|
|
224
|
+
if (provider === '') {
|
|
225
|
+
sendJson(response, 400, { error: 'provider is required' })
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
const failed = []
|
|
229
|
+
try {
|
|
230
|
+
await runtime.core.api(`/providers/proxies/${encodeURIComponent(provider)}`, { method: 'PUT' })
|
|
231
|
+
} catch (error) {
|
|
232
|
+
failed.push({ provider, reason: String(error?.message ?? error) })
|
|
233
|
+
}
|
|
234
|
+
const status = await runtime.core.providerStatus()
|
|
235
|
+
const row = (status.providers ?? []).find((entry) => entry.provider === provider)
|
|
236
|
+
sendJson(response, 200, { ok: failed.length === 0, provider: row, failed })
|
|
237
|
+
return
|
|
238
|
+
}
|
|
239
|
+
if (action === 'probe') {
|
|
240
|
+
// Probe the list as typed, without saving it: the panel checks all lines at once
|
|
241
|
+
// and names the one that failed.
|
|
242
|
+
const answer = await runtime.probe(String(body.url ?? ''))
|
|
243
|
+
sendJson(response, answer.ok ? 200 : 400, answer)
|
|
244
|
+
return
|
|
245
|
+
}
|
|
246
|
+
if (action === 'test') {
|
|
247
|
+
// A `node` narrows the run to one node and `all` covers every node; without
|
|
248
|
+
// either the cycle measures the configured sample. The panel offers all three.
|
|
249
|
+
const target = String(body.node ?? '').trim()
|
|
250
|
+
const delays = await runtime.nodeDelays({
|
|
251
|
+
force: true,
|
|
252
|
+
only: target === '' ? undefined : target,
|
|
253
|
+
all: body.all === true,
|
|
254
|
+
})
|
|
255
|
+
sendJson(response, 200, { ok: true, delays })
|
|
256
|
+
return
|
|
257
|
+
}
|
|
258
|
+
if (action === 'select') {
|
|
259
|
+
const name = String(body.node ?? '').trim()
|
|
260
|
+
if (name === '') {
|
|
261
|
+
sendJson(response, 400, { error: 'node is required' })
|
|
262
|
+
return
|
|
263
|
+
}
|
|
264
|
+
const group = await runtime.core.select(name)
|
|
265
|
+
runtime.rememberNode(name)
|
|
266
|
+
sendJson(response, 200, { ok: true, now: group.now })
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
sendJson(response, 400, { error: `unknown action "${action}"` })
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
// Probe a subscription before it is saved, so a typo is caught in the form
|
|
273
|
+
// rather than in the next activation. The body may carry several lines; each is
|
|
274
|
+
// probed and reported separately.
|
|
275
|
+
route('/clash-proxy/probe', async (request, response) => {
|
|
276
|
+
if (methodOf(request) !== 'POST') {
|
|
277
|
+
sendJson(response, 405, { error: 'POST only' })
|
|
278
|
+
return
|
|
279
|
+
}
|
|
280
|
+
const body = await readJson(request, response)
|
|
281
|
+
if (body === undefined) return
|
|
282
|
+
const answer = await runtime.probe(String(body.url ?? body.urls ?? ''))
|
|
283
|
+
sendJson(response, answer.ok ? 200 : 400, answer)
|
|
284
|
+
})
|
|
285
|
+
|
|
286
|
+
return disposers
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Hide the token in a subscription URL so a screenshot of the panel is not a leak.
|
|
291
|
+
*
|
|
292
|
+
* @param url - the effective subscription URL.
|
|
293
|
+
* @returns the URL with any token-like query value masked.
|
|
294
|
+
*/
|
|
295
|
+
export function maskToken(url) {
|
|
296
|
+
if (typeof url !== 'string' || url === '') return ''
|
|
297
|
+
try {
|
|
298
|
+
const parsed = new URL(url)
|
|
299
|
+
for (const key of [...parsed.searchParams.keys()]) {
|
|
300
|
+
if (/token|key|secret|passwd|password|auth/i.test(key)) parsed.searchParams.set(key, '***')
|
|
301
|
+
}
|
|
302
|
+
return parsed.toString()
|
|
303
|
+
} catch {
|
|
304
|
+
return url.replace(/(token|key|secret|password)=[^&]+/gi, '$1=***')
|
|
305
|
+
}
|
|
306
|
+
}
|