dsh-quay-bot 1.0.2 → 1.0.4

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.
Files changed (59) hide show
  1. package/README.md +28 -105
  2. package/botscreen/requirements.txt +1 -1
  3. package/client.js +3 -2
  4. package/cordis.patch.yml +1 -1
  5. package/host/api.js +4 -0
  6. package/host/remote.js +285 -8
  7. package/host/screen.js +22 -86
  8. package/package.json +35 -32
  9. package/remote/bin/dsh-remote.mjs +435 -0
  10. package/remote/package.json +27 -0
  11. package/remote/src/config.mjs +183 -0
  12. package/remote/src/crypto.mjs +220 -0
  13. package/remote/src/keys.mjs +226 -0
  14. package/remote/src/proxy.mjs +1028 -0
  15. package/remote/src/sessions.mjs +163 -0
  16. package/remote/src/shim.js +838 -0
  17. package/remote/src/supervisor.mjs +207 -0
  18. package/remote/src/tunnel.mjs +533 -0
  19. package/remote/src/upstream.mjs +403 -0
  20. package/remote/src/util.mjs +149 -0
  21. package/remote/src/ws.mjs +313 -0
  22. package/LICENSE +0 -21
  23. package/avatar/build.mjs +0 -81
  24. package/avatar/gallery/droid.json +0 -14
  25. package/avatar/gallery/ghost.json +0 -14
  26. package/avatar/gallery/grok-pod.json +0 -14
  27. package/avatar/gallery/guardian.json +0 -14
  28. package/avatar/gallery/mecha.json +0 -14
  29. package/avatar/gallery/mochi.json +0 -14
  30. package/avatar/gallery/neko.json +0 -14
  31. package/avatar/gallery/orbiter.json +0 -14
  32. package/avatar/gallery/relay.json +0 -14
  33. package/avatar/gallery/spark.json +0 -14
  34. package/avatar/src/bot/clay.ts +0 -135
  35. package/avatar/src/bot/effects.ts +0 -100
  36. package/avatar/src/bot/grok-bot.ts +0 -626
  37. package/avatar/src/bot/index.ts +0 -15
  38. package/avatar/src/bot/palettes.ts +0 -62
  39. package/avatar/src/bot/ring.ts +0 -219
  40. package/avatar/src/bot/scheduler.ts +0 -239
  41. package/avatar/src/bot/shapes.ts +0 -277
  42. package/avatar/src/bot/spring.ts +0 -196
  43. package/avatar/src/core/color.ts +0 -92
  44. package/avatar/src/core/eyes.ts +0 -297
  45. package/avatar/src/core/field.ts +0 -482
  46. package/avatar/src/core/frame.ts +0 -655
  47. package/avatar/src/core/fx.ts +0 -375
  48. package/avatar/src/core/index.ts +0 -49
  49. package/avatar/src/core/paint.ts +0 -331
  50. package/avatar/src/core/path.ts +0 -495
  51. package/avatar/src/core/pose.ts +0 -581
  52. package/avatar/src/core/svg.ts +0 -98
  53. package/avatar/src/core/types.ts +0 -153
  54. package/avatar/src/core/validate.ts +0 -296
  55. package/avatar/src/core/volume.ts +0 -681
  56. package/avatar/src/entry.ts +0 -260
  57. package/bin/doctor.mjs +0 -148
  58. package/botscreen/requirements-offline.txt +0 -11
  59. package/market/index.json +0 -41
@@ -0,0 +1,435 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-remote CLI
4
+ *
5
+ * dsh-remote up [--foreground|--detach] 启动整条链路(relay + tunnel)
6
+ * dsh-remote stop [--all] 停止
7
+ * dsh-remote status [--json] 运行态
8
+ * dsh-remote link [--rotate] [--legacy|--app] 打印/轮换公网加密链接
9
+ * dsh-remote rotate [--psk|--identity|--app] 立即轮换密钥
10
+ * dsh-remote tunnel [status|--stop --all]
11
+ dsh-remote doctor 自检
12
+ */
13
+ import { spawn } from 'node:child_process'
14
+ import { closeSync, existsSync, openSync } from 'node:fs'
15
+ import { join } from 'node:path'
16
+ import { execFile } from 'node:child_process'
17
+ import { fileURLToPath } from 'node:url'
18
+ import { promisify } from 'node:util'
19
+ import { loadConfig, assertConfig } from '../src/config.mjs'
20
+ import { createLogger, ensureDir, httpRequest, readJson, sleep, writeJsonAtomic } from '../src/util.mjs'
21
+ import { KeyRing, keyRingPath } from '../src/keys.mjs'
22
+ import { startSupervisor } from '../src/supervisor.mjs'
23
+ import { parseLaunchEndpoint } from '../src/upstream.mjs'
24
+ import { readFile } from 'node:fs/promises'
25
+
26
+ const args = process.argv.slice(2)
27
+ const command = args[0] && !args[0].startsWith('-') ? args[0] : 'help'
28
+ const flags = new Set(args.filter((arg) => arg.startsWith('--')))
29
+ const option = (name) => {
30
+ const index = args.indexOf(`--${name}`)
31
+ return index === -1 ? undefined : args[index + 1]
32
+ }
33
+
34
+ const config = loadConfig({
35
+ configPath: option('config'),
36
+ cli: option('port') ? { listen: { port: Number(option('port')) } } : {},
37
+ })
38
+
39
+ const execFileAsync = promisify(execFile)
40
+ const logger = createLogger({ name: 'dsh-remote' })
41
+ const runtimeDir = config.stateDir
42
+ const runtimePath = join(runtimeDir, 'runtime.json')
43
+ const pidPath = join(runtimeDir, 'relay.pid')
44
+ const linkPath = join(config.home, 'link.txt')
45
+
46
+ function readRuntime() {
47
+ return readJson(runtimePath, null)
48
+ }
49
+
50
+ async function isAlive(pid) {
51
+ if (!Number.isInteger(pid) || pid <= 0) return false
52
+ try {
53
+ process.kill(pid, 0)
54
+ return true
55
+ } catch {
56
+ return false
57
+ }
58
+ }
59
+
60
+ async function cmdUp() {
61
+ assertConfig(config)
62
+ if (!flags.has('--foreground')) {
63
+ const runtime = readRuntime()
64
+ if (runtime && (await isAlive(runtime.pid))) {
65
+ const health = await httpRequest(`http://127.0.0.1:${String(runtime.listen.port)}/__dsh/health`, {
66
+ timeoutMs: 2000,
67
+ }).catch(() => null)
68
+ if (health?.status === 200) {
69
+ console.log(`已在运行 pid=${runtime.pid}`)
70
+ console.log(`链接: ${runtime.link ?? '(隧道尚未就绪)'}`)
71
+ return
72
+ }
73
+ console.log(`实例 pid=${runtime.pid} 仍在退出中,稍后重试`)
74
+ return
75
+ }
76
+ ensureDir(config.logs.dir)
77
+ const logFile = join(config.logs.dir, 'relay.log')
78
+ const out = openSync(logFile, 'a')
79
+ const scriptPath = fileURLToPath(import.meta.url)
80
+ const childEnv = process.versions?.electron
81
+ ? { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
82
+ : process.env
83
+ let child
84
+ try {
85
+ child = spawn(
86
+ process.execPath,
87
+ [scriptPath, 'up', '--foreground', '--config', config.configPath ?? join(config.home, 'config.json')],
88
+ {
89
+ detached: true,
90
+ windowsHide: true,
91
+ stdio: ['ignore', out, out],
92
+ env: childEnv,
93
+ },
94
+ )
95
+ } finally {
96
+ closeSync(out)
97
+ }
98
+ child.unref()
99
+ await sleep(1200)
100
+ const started = readRuntime()
101
+ if (started?.pid) {
102
+ console.log(`已后台启动 pid=${started.pid}`)
103
+ if (started.link) console.log(`链接: ${started.link}`)
104
+ console.log(`日志: ${logFile}`)
105
+ } else {
106
+ console.log(`已后台启动 pid=${child.pid},日志: ${logFile}(隧道就绪后 link.txt 会更新)`)
107
+ }
108
+ return
109
+ }
110
+
111
+ const supervisor = await startSupervisor({ config, logger })
112
+ process.stdout.write(`relay: http://${config.listen.host}:${String(supervisor.runtime.listen.port)}\n`)
113
+ if (supervisor.runtime.link) process.stdout.write(`link: ${supervisor.runtime.link}\n`)
114
+ else process.stdout.write('link: 等待隧道分配域名…\n')
115
+ await new Promise(() => {})
116
+ }
117
+
118
+ async function stopTunnelProcess({ config, logger }) {
119
+ const tunnelFile = join(config.stateDir, 'tunnel.json')
120
+ const saved = readJson(tunnelFile, null)
121
+ if (config.public.mode === 'funnel') {
122
+ await execFileAsync('tailscale', ['funnel', 'reset'], { timeout: 15_000 }).catch(() => {})
123
+ writeJsonAtomic(tunnelFile, { mode: 'funnel', port: config.listen.port, url: null })
124
+ return
125
+ }
126
+ let pid = saved?.pid ?? null
127
+ if (!pid) pid = await findCloudflaredForPort(config)
128
+ if (!pid) return
129
+ try {
130
+ process.kill(pid, 'SIGTERM')
131
+ console.log(`已停止隧道进程 pid=${pid}`)
132
+ } catch {}
133
+ writeJsonAtomic(tunnelFile, { ...saved, pid: null, url: null })
134
+ }
135
+
136
+ async function cmdStop() {
137
+ const runtime = readRuntime()
138
+ if (!runtime) {
139
+ console.log('未发现运行中的实例')
140
+ return
141
+ }
142
+ if (!(await isAlive(runtime.pid))) {
143
+ console.log(`pid ${runtime.pid} 已不存在,清理运行态`)
144
+ writeJsonAtomic(runtimePath, { ...runtime, stoppedAt: new Date().toISOString() })
145
+ return
146
+ }
147
+ try {
148
+ process.kill(runtime.pid, 'SIGTERM')
149
+ } catch {}
150
+ if (flags.has('--all')) {
151
+ // 等待 relay 退出后再收隧道,避免它自己在退出流程里又重启
152
+ for (let i = 0; i < 50; i += 1) {
153
+ if (!(await isAlive(runtime.pid))) break
154
+ await sleep(100)
155
+ }
156
+ await stopTunnelProcess({ config, logger })
157
+ }
158
+ for (let i = 0; i < 100; i += 1) {
159
+ if (!(await isAlive(runtime.pid))) break
160
+ await sleep(100)
161
+ }
162
+ if (existsSync(runtimePath) && !(await isAlive(runtime.pid))) writeJsonAtomic(runtimePath, null)
163
+ console.log(`已停止 pid=${runtime.pid}`)
164
+ }
165
+
166
+ /** state 里丢了 pid 时,按命令行匹配兜底找到本端口的 cloudflared。 */
167
+ async function findCloudflaredForPort(config) {
168
+ if (process.platform !== 'linux') return null
169
+ const needle = `--url http://${config.listen.host}:${String(config.listen.port)}`
170
+ try {
171
+ const { readdir, readFile } = await import('node:fs/promises')
172
+ for (const entry of await readdir('/proc')) {
173
+ if (!/^\d+$/u.test(entry)) continue
174
+ let cmd = ''
175
+ try {
176
+ cmd = (await readFile(`/proc/${entry}/cmdline`)).toString('utf8').split('\0').join(' ')
177
+ } catch {
178
+ continue
179
+ }
180
+ if (cmd.includes('cloudflared') && cmd.includes(needle)) return Number(entry)
181
+ }
182
+ } catch {}
183
+ return null
184
+ }
185
+
186
+ async function cmdTunnel() {
187
+ const tunnelFile = join(config.stateDir, 'tunnel.json')
188
+ const saved = readJson(tunnelFile, null)
189
+ if (flags.has('--stop') || args[1] === 'stop') {
190
+ if (!flags.has('--all')) {
191
+ console.log('保留隧道(链接不变)。要真正关闭请加 --all。')
192
+ return
193
+ }
194
+ await stopTunnelProcess({ config, logger })
195
+ return
196
+ }
197
+ const alive = saved?.pid ? await isAlive(saved.pid) : false
198
+ console.log(JSON.stringify({
199
+ mode: config.public.mode,
200
+ persistAcrossRestart: config.tunnel.persistAcrossRestart !== false,
201
+ state: saved ?? null,
202
+ pidAlive: alive,
203
+ }, null, 2))
204
+ }
205
+
206
+ async function cmdStatus() {
207
+ const runtime = readRuntime()
208
+ if (!runtime) {
209
+ console.log(JSON.stringify({ running: false }))
210
+ return
211
+ }
212
+ const alive = await isAlive(runtime.pid)
213
+ const local = await httpRequest(`http://127.0.0.1:${String(runtime.listen.port)}/__dsh/health`, { timeoutMs: 2000 }).catch(
214
+ () => null,
215
+ )
216
+ const remote = runtime.publicUrl
217
+ ? await httpRequest(`${runtime.publicUrl}/__dsh/health`, { timeoutMs: 8000 }).catch(() => null)
218
+ : null
219
+ const report = {
220
+ running: alive,
221
+ pid: runtime.pid,
222
+ startedAt: runtime.startedAt,
223
+ listen: runtime.listen,
224
+ publicUrl: runtime.publicUrl,
225
+ link: runtime.link,
226
+ appLink: runtime.appLink ?? null,
227
+ localHealth: local?.status === 200,
228
+ remoteHealth: remote?.status === 200,
229
+ tunnel: runtime.tunnel,
230
+ pskKid: runtime.pskKid,
231
+ }
232
+ if (flags.has('--json')) {
233
+ console.log(JSON.stringify(report, null, 2))
234
+ return
235
+ }
236
+ const line = (key, value) => console.log(`${key.padEnd(14)} ${value}`)
237
+ line('运行', alive ? '是' : '否')
238
+ line('pid', report.pid)
239
+ line('本地监听', `http://127.0.0.1:${String(report.listen.port)}`)
240
+ line('公网地址', report.publicUrl ?? '(未就绪)')
241
+ line('访问链接', report.link ?? '(未就绪)')
242
+ if (report.appLink) line('App 链接', report.appLink)
243
+ line('本地健康', report.localHealth ? 'OK' : 'FAIL')
244
+ line('公网健康', report.remoteHealth ? 'OK' : 'FAIL')
245
+ line('隧道', `${report.tunnel?.mode ?? '-'} / ${report.tunnel?.state ?? '-'}`)
246
+ line('PSK kid', report.pskKid ?? '-')
247
+ }
248
+
249
+ async function cmdLink() {
250
+ const runtime = readRuntime()
251
+ const publicUrl = runtime?.publicUrl ?? config.proxy.publicUrl
252
+ const keyring = new KeyRing({
253
+ statePath: keyRingPath(runtimeDir),
254
+ rotateHours: config.tokens.rotateHours,
255
+ graceMinutes: config.tokens.graceMinutes,
256
+ })
257
+ if (flags.has('--rotate')) {
258
+ const next = keyring.rotatePsk(Date.now(), { force: true })
259
+ console.log(`PSK 已轮换: kid=${next.kid}`)
260
+ }
261
+ if (!publicUrl) {
262
+ console.log('隧道尚未就绪:先运行 dsh-remote up,或设置 proxy.publicUrl')
263
+ return
264
+ }
265
+ if (flags.has('--app')) {
266
+ if (!config.proxy.appBridge) {
267
+ console.log('App 直连通道未启用:config.proxy.appBridge=true 后再试')
268
+ return
269
+ }
270
+ console.log(keyring.appLink(publicUrl))
271
+ return
272
+ }
273
+ if (flags.has('--legacy')) {
274
+ if (!config.proxy.legacyToken) {
275
+ console.log('legacy 通道未启用:config.proxy.legacyToken=true 后再试')
276
+ return
277
+ }
278
+ console.log(keyring.legacyLink(publicUrl))
279
+ return
280
+ }
281
+ const link = keyring.link(publicUrl)
282
+ console.log(link)
283
+ if (runtime) {
284
+ writeJsonAtomic(runtimePath, { ...runtime, link, pskKid: keyring.activePsk()?.kid ?? null })
285
+ }
286
+ }
287
+
288
+ async function cmdRotate() {
289
+ const keyring = new KeyRing({
290
+ statePath: keyRingPath(runtimeDir),
291
+ rotateHours: config.tokens.rotateHours,
292
+ graceMinutes: config.tokens.graceMinutes,
293
+ relayRotateHours: config.e2e.relayKeyRotateHours,
294
+ })
295
+ if (flags.has('--app')) {
296
+ if (!config.proxy.appBridge) {
297
+ console.log('App 直连通道未启用:config.proxy.appBridge=true 后再试')
298
+ return
299
+ }
300
+ const token = keyring.rotateAppToken()
301
+ const runtime = readRuntime()
302
+ const base = runtime?.publicUrl ?? config.proxy.publicUrl
303
+ console.log(token ? `${base}/?token=${token}` : '(隧道未就绪)')
304
+ return
305
+ }
306
+ if (flags.has('--identity')) {
307
+ keyring.rotateRelayIdentityIfDue(Date.now() + config.e2e.relayKeyRotateHours * 3_600_000)
308
+ console.log(`relay 身份已轮换: kid=${keyring.identity.kid}`)
309
+ return
310
+ }
311
+ const next = keyring.rotatePsk(Date.now(), { force: true })
312
+ console.log(`PSK 已轮换: kid=${next.kid}, 旧密钥进入 ${config.tokens.graceMinutes} 分钟宽限`)
313
+ const runtime = readRuntime()
314
+ if (runtime?.publicUrl) console.log(`新链接: ${keyring.link(runtime.publicUrl)}(长驻进程会在 60s 内装载并推送)`)
315
+ }
316
+
317
+ async function cmdDoctor() {
318
+ const checks = []
319
+ const add = (name, ok, detail) => checks.push({ name, ok, detail })
320
+
321
+ add('node', Number(process.versions.node.split('.')[0]) >= 22, `node ${process.versions.node}`)
322
+ const cloudflared = await new Promise((resolve) => {
323
+ const child = spawn(config.public.cloudflared ?? 'cloudflared', ['--version'], {
324
+ stdio: ['ignore', 'pipe', 'ignore'],
325
+ windowsHide: true,
326
+ })
327
+ let text = ''
328
+ child.stdout?.on('data', (chunk) => {
329
+ text += chunk
330
+ })
331
+ child.on('error', () => resolve({ ok: false, text: 'not found' }))
332
+ child.on('exit', (code) => resolve({ ok: code === 0, text: text.trim() }))
333
+ })
334
+ add('cloudflared', cloudflared.ok, cloudflared.text)
335
+
336
+ try {
337
+ assertConfig(config)
338
+ add('config', true, config.configPath ?? '(defaults)')
339
+ } catch (error) {
340
+ add('config', false, String(error?.message ?? error))
341
+ }
342
+
343
+ const keyring = new KeyRing({
344
+ statePath: keyRingPath(runtimeDir),
345
+ rotateHours: config.tokens.rotateHours,
346
+ graceMinutes: config.tokens.graceMinutes,
347
+ })
348
+ const active = keyring.activePsk()
349
+ add(
350
+ 'psk',
351
+ Boolean(active) && active.expiresAt > Date.now(),
352
+ active ? `kid=${active.kid} 到期 ${new Date(active.expiresAt).toISOString()}` : '无可用 PSK',
353
+ )
354
+
355
+ let found = { host: null, port: null, launchToken: null }
356
+ if (config.upstream.mode === 'fixed') {
357
+ found = { host: config.upstream.host, port: config.upstream.port, launchToken: config.upstream.launchToken }
358
+ } else {
359
+ const logs = config.upstream.log ? [config.upstream.log] : (config.upstream.logs ?? [])
360
+ for (const logPath of logs) {
361
+ if (!logPath || !existsSync(logPath)) continue
362
+ const tail = await readFile(logPath, 'utf8').catch(() => '')
363
+ const parsed = parseLaunchEndpoint(tail)
364
+ if (parsed) { found = parsed; break }
365
+ }
366
+ }
367
+ add('upstream', Boolean(found?.port && found?.launchToken), found?.port ? `${found.host ?? '127.0.0.1'}:${found.port} token=${String(found.launchToken).slice(0, 6)}…` : '未发现')
368
+
369
+ const runtime = readRuntime()
370
+ add('runtime', Boolean(runtime && (await isAlive(runtime.pid))), runtime ? `pid=${runtime.pid}` : '未启动')
371
+
372
+ if (runtime) {
373
+ const local = await httpRequest(`http://127.0.0.1:${String(runtime.listen.port)}/__dsh/health`, { timeoutMs: 2000 }).catch(
374
+ () => null,
375
+ )
376
+ add('local-health', local?.status === 200, local ? `HTTP ${local.status}` : 'unreachable')
377
+ if (runtime.publicUrl) {
378
+ const remote = await httpRequest(`${runtime.publicUrl}/__dsh/health`, { timeoutMs: 8000 }).catch(() => null)
379
+ add('public-health', remote?.status === 200, remote ? `HTTP ${remote.status}` : 'unreachable')
380
+ const link = runtime.link ?? keyring.link(runtime.publicUrl)
381
+ const unlock = await httpRequest(link.replace(/#.*$/u, '/'), {
382
+ timeoutMs: 8000,
383
+ headers: { accept: 'text/html' },
384
+ }).catch(() => null)
385
+ add('unlock-page', unlock?.status === 401, unlock ? `HTTP ${unlock.status}(401 表示需要密钥,符合预期)` : 'unreachable')
386
+ }
387
+ }
388
+
389
+ for (const check of checks) {
390
+ console.log(`${check.ok ? '✔' : '✖'} ${check.name.padEnd(15)} ${check.detail}`)
391
+ }
392
+ const failed = checks.filter((check) => !check.ok)
393
+ if (failed.length > 0) process.exitCode = 1
394
+ }
395
+
396
+ async function main() {
397
+ switch (command) {
398
+ case 'up':
399
+ return cmdUp()
400
+ case 'stop':
401
+ return cmdStop()
402
+ case 'tunnel':
403
+ return cmdTunnel()
404
+ case 'status':
405
+ return cmdStatus()
406
+ case 'link':
407
+ return cmdLink()
408
+ case 'rotate':
409
+ return cmdRotate()
410
+ case 'doctor':
411
+ return cmdDoctor()
412
+ default:
413
+ console.log(`dsh-remote — DSH 网关 → Cloudflare 隧道(自动续期 + 端到端加密)
414
+
415
+ 用法:
416
+ dsh-remote up [--foreground|--detach] [--config <file>] [--port <n>]
417
+ dsh-remote stop [--all] [--all] # 默认保留隧道,重启后链接不变
418
+ dsh-remote status [--json]
419
+ dsh-remote link [--rotate] [--legacy|--app]
420
+ dsh-remote rotate [--psk|--identity|--app]
421
+ dsh-remote tunnel [status|--stop --all]
422
+ dsh-remote doctor
423
+
424
+ 环境变量:
425
+ DSH_REMOTE_HOME, DSH_REMOTE_LISTEN_PORT, DSH_REMOTE_TUNNEL_MODE,
426
+ DSH_REMOTE_PUBLIC_HOSTNAME, DSH_REMOTE_TUNNEL_TOKEN, DSH_REMOTE_UPSTREAM_LOG,
427
+ DSH_REMOTE_UPSTREAM_PORT, DSH_REMOTE_UPSTREAM_TOKEN, DSH_REMOTE_E2E
428
+ `)
429
+ }
430
+ }
431
+
432
+ main().catch((error) => {
433
+ console.error(`dsh-remote: ${String(error?.message ?? error)}`)
434
+ process.exitCode = 1
435
+ })
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "dsh-remote",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "description": "把本地 DeepSeek Harness 网关经 Cloudflare Tunnel 暴露到公网:自动续期 token + 端到端加密传输",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "bin": {
11
+ "dsh-remote": "./bin/dsh-remote.mjs"
12
+ },
13
+ "scripts": {
14
+ "start": "node ./bin/dsh-remote.mjs up --foreground",
15
+ "test": "node --test --test-reporter=spec test/",
16
+ "status": "node ./bin/dsh-remote.mjs status",
17
+ "doctor": "node ./bin/dsh-remote.mjs doctor"
18
+ },
19
+ "files": [
20
+ "bin",
21
+ "src",
22
+ "docs",
23
+ "deploy",
24
+ "scripts"
25
+ ],
26
+ "license": "MIT"
27
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * 配置装载:defaults < 配置文件 < 环境变量 < CLI 覆盖。
3
+ */
4
+ import { existsSync } from 'node:fs'
5
+ import { homedir } from 'node:os'
6
+ import { isAbsolute, join, resolve } from 'node:path'
7
+ import { readJson } from './util.mjs'
8
+
9
+ export const DEFAULTS = Object.freeze({
10
+ version: 1,
11
+ home: '~/.dsh-remote',
12
+ listen: { host: '127.0.0.1', port: 44691 },
13
+ public: {
14
+ // quick: 免账号 trycloudflare 临时域名;named: 需要 CF 账号/域名/隧道 token
15
+ mode: 'quick', // quick | named | funnel | none
16
+ hostname: null,
17
+ tunnelToken: null,
18
+ /** 可选:隧道重启前执行的命令,stdout 即最新 tunnel token(用于 token 自动续期) */
19
+ refreshCommand: null,
20
+ cloudflared: 'cloudflared',
21
+ configFile: null,
22
+ },
23
+ upstream: {
24
+ // auto: 检索已启动的 dsh web 网关(从候选日志 + /proc 匹配存活进程,绝不新开网关);fixed: 使用显式配置
25
+ mode: 'auto',
26
+ host: '127.0.0.1',
27
+ port: null,
28
+ launchToken: null,
29
+ log: null,
30
+ logs: [
31
+ '~/logs/dsh-web.log',
32
+ '~/.dsh/logs/dsh-web.log',
33
+ '~/.dsh-app-remote/web.log',
34
+ ],
35
+ discoverIntervalMs: 5000,
36
+ /** 上游 cookie 提前多少秒续期 */
37
+ cookieRenewSkewSeconds: 600,
38
+ },
39
+ e2e: {
40
+ enabled: true,
41
+ relayKeyRotateHours: 24,
42
+ sessionTtlHours: 12,
43
+ handshakeTtlSeconds: 120,
44
+ maxFrameBytes: 262144,
45
+ maxInflightBytes: 64 * 1024 * 1024,
46
+ },
47
+ tokens: {
48
+ rotateHours: 12,
49
+ graceMinutes: 60,
50
+ /** 对外链接(含 #k= 密钥)的展示有效期,过期仍可用但不再主动分发 */
51
+ linkTtlDays: 30,
52
+ },
53
+ proxy: {
54
+ maxBodyBytes: 64 * 1024 * 1024,
55
+ legacyToken: false,
56
+ /** App 直连通道:`?token=` 明文握手(Cloudflare 可见),供 Android 客户端扫码连接 */
57
+ appBridge: true,
58
+ hostRewrite: true,
59
+ publicUrl: null,
60
+ },
61
+ tunnel: {
62
+ /** 重启网关(relay)时保留底层隧道进程,链接不变;`stop --all` 才真正关闭 */
63
+ persistAcrossRestart: true,
64
+ healthIntervalMs: 20_000,
65
+ healthTimeoutMs: 15_000,
66
+ unhealthyThreshold: 3,
67
+ restartBackoffMs: 1_000,
68
+ maxBackoffMs: 30_000,
69
+ urlWaitMs: 45_000,
70
+ },
71
+ logs: { dir: 'logs', keepFiles: 14 },
72
+ })
73
+
74
+ export function expandHome(path) {
75
+ if (typeof path !== 'string' || path === '') return path
76
+ if (path === '~') return homedir()
77
+ if (path.startsWith('~/')) return join(homedir(), path.slice(2))
78
+ return isAbsolute(path) ? path : resolve(process.cwd(), path)
79
+ }
80
+
81
+ function deepMerge(base, override) {
82
+ if (override === undefined) return base
83
+ if (Array.isArray(override)) return override.slice()
84
+ if (override === null || typeof override !== 'object') return override
85
+ const out = { ...base }
86
+ for (const [key, value] of Object.entries(override)) {
87
+ out[key] = deepMerge(base?.[key], value)
88
+ }
89
+ return out
90
+ }
91
+
92
+ function envOverrides(env) {
93
+ const out = {}
94
+ const put = (path, value, cast = (v) => v) => {
95
+ if (value === undefined || value === '') return
96
+ let cursor = out
97
+ for (let i = 0; i < path.length - 1; i += 1) {
98
+ cursor[path[i]] ??= {}
99
+ cursor = cursor[path[i]]
100
+ }
101
+ cursor[path[path.length - 1]] = cast(value)
102
+ }
103
+ put(['home'], env.DSH_REMOTE_HOME)
104
+ put(['listen', 'host'], env.DSH_REMOTE_LISTEN_HOST)
105
+ put(['listen', 'port'], env.DSH_REMOTE_LISTEN_PORT, Number)
106
+ put(['public', 'mode'], env.DSH_REMOTE_TUNNEL_MODE)
107
+ put(['public', 'hostname'], env.DSH_REMOTE_PUBLIC_HOSTNAME)
108
+ put(['public', 'tunnelToken'], env.DSH_REMOTE_TUNNEL_TOKEN)
109
+ put(['public', 'refreshCommand'], env.DSH_REMOTE_TUNNEL_REFRESH_COMMAND)
110
+ put(['upstream', 'host'], env.DSH_REMOTE_UPSTREAM_HOST)
111
+ put(['upstream', 'port'], env.DSH_REMOTE_UPSTREAM_PORT, Number)
112
+ put(['upstream', 'launchToken'], env.DSH_REMOTE_UPSTREAM_TOKEN)
113
+ put(['upstream', 'log'], env.DSH_REMOTE_UPSTREAM_LOG)
114
+ put(['proxy', 'publicUrl'], env.DSH_REMOTE_PUBLIC_URL)
115
+ put(['e2e', 'enabled'], env.DSH_REMOTE_E2E, (v) => v !== '0' && v !== 'false')
116
+ put(['proxy', 'legacyToken'], env.DSH_REMOTE_LEGACY_TOKEN, (v) => v === '1' || v === 'true')
117
+ put(['proxy', 'appBridge'], env.DSH_REMOTE_APP_BRIDGE, (v) => v !== '0' && v !== 'false')
118
+ return out
119
+ }
120
+
121
+ export function loadConfig({ configPath, cli = {}, env = process.env } = {}) {
122
+ const candidates = []
123
+ if (configPath) candidates.push(expandHome(configPath))
124
+ if (env.DSH_REMOTE_CONFIG) candidates.push(expandHome(env.DSH_REMOTE_CONFIG))
125
+ candidates.push(resolve(process.cwd(), 'dsh-remote.config.json'))
126
+
127
+ let fileConfig = {}
128
+ let usedPath = null
129
+ for (const candidate of candidates) {
130
+ if (existsSync(candidate)) {
131
+ fileConfig = readJson(candidate, {}) ?? {}
132
+ usedPath = candidate
133
+ break
134
+ }
135
+ }
136
+
137
+ const homeEarly = fileConfig.home ?? env.DSH_REMOTE_HOME ?? DEFAULTS.home
138
+ const home = expandHome(homeEarly)
139
+ const homeConfig = join(home, 'config.json')
140
+ if (!usedPath && existsSync(homeConfig)) {
141
+ fileConfig = readJson(homeConfig, {}) ?? {}
142
+ usedPath = homeConfig
143
+ }
144
+
145
+ const merged = deepMerge(deepMerge(DEFAULTS, fileConfig), envOverrides(env))
146
+ const config = deepMerge(merged, cli)
147
+
148
+ config.home = expandHome(config.home)
149
+ config.configPath = usedPath
150
+ config.stateDir = join(config.home, 'state')
151
+ const rawLogsDir = String(config.logs.dir ?? 'logs')
152
+ config.logs.dir = isAbsolute(rawLogsDir) || rawLogsDir.startsWith('~')
153
+ ? expandHome(rawLogsDir)
154
+ : join(config.home, rawLogsDir)
155
+ config.upstream.log = config.upstream.log ? expandHome(config.upstream.log) : null
156
+ const rawUpstreamLogs = Array.isArray(config.upstream.logs) ? config.upstream.logs : []
157
+ config.upstream.logs = [...new Set(rawUpstreamLogs.filter(Boolean).map(expandHome))]
158
+ config.listen.port = Number(config.listen.port)
159
+ return config
160
+ }
161
+
162
+ export function assertConfig(config) {
163
+ if (!Number.isInteger(config.listen.port) || config.listen.port < 0 || config.listen.port > 65535) {
164
+ throw new Error(`listen.port 非法: ${config.listen.port}`)
165
+ }
166
+ if (!['quick', 'named', 'funnel', 'none'].includes(config.public.mode)) {
167
+ throw new Error(`public.mode 必须是 quick|named|funnel|none,收到 ${config.public.mode}`)
168
+ }
169
+ if (config.public.mode === 'funnel') {
170
+ config.public.hostname = config.public.hostname ?? null
171
+ }
172
+ if (config.public.mode === 'named' && !config.public.tunnelToken && !config.public.refreshCommand) {
173
+ throw new Error('named 模式需要 public.tunnelToken 或 public.refreshCommand')
174
+ }
175
+ if (!['auto', 'fixed'].includes(config.upstream.mode)) {
176
+ throw new Error(`upstream.mode 必须是 auto|fixed,收到 ${config.upstream.mode}`)
177
+ }
178
+ if (config.upstream.mode === 'fixed' && (!config.upstream.port || !config.upstream.launchToken)) {
179
+ throw new Error('fixed 模式需要 upstream.port 与 upstream.launchToken')
180
+ }
181
+ if (!(config.tokens.graceMinutes >= 0)) throw new Error('tokens.graceMinutes 不能为负')
182
+ return config
183
+ }