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,533 @@
1
+ /**
2
+ * cloudflared 隧道守护进程。
3
+ *
4
+ * quick 模式:免 Cloudflare 账号,临时域名,URL 变化即重新分发链接;
5
+ * named 模式:固定域名,隧道 token 支持由 refreshCommand 动态取最新值(token 自动续期),
6
+ * token 变化时重启 connector 使其生效。
7
+ */
8
+ import { exec, execFile, spawn } from 'node:child_process'
9
+ import { closeSync, existsSync, openSync, readFile } from 'node:fs'
10
+ import { chmod, rename, rm, stat, writeFile } from 'node:fs/promises'
11
+ import { join } from 'node:path'
12
+ import { promisify } from 'node:util'
13
+ import { ensureDir, httpRequest, readJson, sleep, writeJsonAtomic } from './util.mjs'
14
+
15
+ const execAsync = promisify(exec)
16
+ const execFileAsync = promisify(execFile)
17
+ const URL_RE = /https:\/\/[a-z0-9][a-z0-9-]*\.trycloudflare\.com/giu
18
+
19
+ export function cloudflaredBinaryName(platform = process.platform) {
20
+ return platform === 'win32' ? 'cloudflared.exe' : 'cloudflared'
21
+ }
22
+
23
+ export function cloudflaredAssetName(platform = process.platform, arch = process.arch) {
24
+ if (platform === 'linux') {
25
+ if (arch === 'x64') return { asset: 'cloudflared-linux-amd64', archive: false }
26
+ if (arch === 'arm64') return { asset: 'cloudflared-linux-arm64', archive: false }
27
+ if (arch === 'arm') return { asset: 'cloudflared-linux-arm', archive: false }
28
+ if (arch === 'ia32') return { asset: 'cloudflared-linux-386', archive: false }
29
+ }
30
+ if (platform === 'darwin') {
31
+ if (arch === 'arm64') return { asset: 'cloudflared-darwin-arm64.tgz', archive: true }
32
+ if (arch === 'x64') return { asset: 'cloudflared-darwin-amd64.tgz', archive: true }
33
+ }
34
+ if (platform === 'win32') {
35
+ if (arch === 'x64' || arch === 'arm64') return { asset: 'cloudflared-windows-amd64.exe', archive: false }
36
+ if (arch === 'ia32') return { asset: 'cloudflared-windows-386.exe', archive: false }
37
+ }
38
+ return null
39
+ }
40
+
41
+ function systemCloudflaredCandidates(platform = process.platform, env = process.env) {
42
+ if (platform === 'darwin') {
43
+ return ['/opt/homebrew/bin/cloudflared', '/usr/local/bin/cloudflared', '/usr/bin/cloudflared']
44
+ }
45
+ if (platform === 'linux') {
46
+ return ['/usr/local/bin/cloudflared', '/usr/bin/cloudflared']
47
+ }
48
+ if (platform === 'win32') {
49
+ const pf = env.ProgramFiles || 'C:\\Program Files'
50
+ const pf86 = env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)'
51
+ const list = [
52
+ join(pf, 'cloudflared', 'cloudflared.exe'),
53
+ join(pf86, 'cloudflared', 'cloudflared.exe'),
54
+ ]
55
+ if (env.LOCALAPPDATA) list.push(join(env.LOCALAPPDATA, 'cloudflared', 'cloudflared.exe'))
56
+ return list
57
+ }
58
+ return []
59
+ }
60
+
61
+ async function isRunnableBinary(cmd) {
62
+ try {
63
+ await execFileAsync(cmd, ['--version'], { timeout: 5_000, windowsHide: true })
64
+ return true
65
+ } catch {
66
+ return false
67
+ }
68
+ }
69
+
70
+ /**
71
+ * 解析可用的 cloudflared 可执行文件;宿主机未预装时自动按架构下载到 `<home>/bin/cloudflared(.exe)`,
72
+ * 实现 Linux / macOS / Windows 三端真正零配置即装即用。
73
+ * 可通过 `DSH_REMOTE_AUTO_INSTALL_CLOUDFLARED=0` 关闭自动下载。
74
+ */
75
+ export async function ensureCloudflaredBinary({ configured = 'cloudflared', home, logger } = {}) {
76
+ const defaultName = cloudflaredBinaryName()
77
+ const preferred = String(configured || defaultName).trim() || defaultName
78
+ if (await isRunnableBinary(preferred)) return preferred
79
+ if (preferred !== defaultName && (await isRunnableBinary(defaultName))) return defaultName
80
+
81
+ for (const candidate of systemCloudflaredCandidates()) {
82
+ if (existsSync(candidate) && (await isRunnableBinary(candidate))) return candidate
83
+ }
84
+
85
+ const binDir = join(home, 'bin')
86
+ const localBin = join(binDir, defaultName)
87
+ if (existsSync(localBin) && (await isRunnableBinary(localBin))) return localBin
88
+
89
+ if (process.env.DSH_REMOTE_AUTO_INSTALL_CLOUDFLARED === '0') return preferred
90
+
91
+ const spec = cloudflaredAssetName()
92
+ if (!spec) {
93
+ throw new Error(`未找到 cloudflared 且当前平台暂不支持自动下载 (${process.platform}/${process.arch})`)
94
+ }
95
+ ensureDir(binDir)
96
+ const downloadUrl = `https://github.com/cloudflare/cloudflared/releases/latest/download/${spec.asset}`
97
+ logger?.info?.('cloudflared not found; downloading automatically', { url: downloadUrl, target: localBin })
98
+ const response = await fetch(downloadUrl, {
99
+ redirect: 'follow',
100
+ signal: AbortSignal.timeout(120_000),
101
+ })
102
+ if (!response.ok) {
103
+ throw new Error(`自动下载 cloudflared 失败: HTTP ${response.status} (${downloadUrl})`)
104
+ }
105
+ const bytes = Buffer.from(await response.arrayBuffer())
106
+ if (spec.archive) {
107
+ const tgzPath = `${localBin}.${process.pid}.tgz`
108
+ const tarBin = existsSync('/usr/bin/tar') ? '/usr/bin/tar' : 'tar'
109
+ await writeFile(tgzPath, bytes)
110
+ try {
111
+ await execFileAsync(tarBin, ['-xzf', tgzPath, '-C', binDir], { timeout: 30_000, windowsHide: true })
112
+ } finally {
113
+ await rm(tgzPath, { force: true }).catch(() => {})
114
+ }
115
+ if (process.platform !== 'win32') {
116
+ await chmod(localBin, 0o755).catch(() => {})
117
+ }
118
+ } else {
119
+ const tmpPath = `${localBin}.${process.pid}.tmp`
120
+ await writeFile(tmpPath, bytes, { mode: 0o755 })
121
+ if (process.platform !== 'win32') {
122
+ await chmod(tmpPath, 0o755).catch(() => {})
123
+ } else {
124
+ await rm(localBin, { force: true }).catch(() => {})
125
+ }
126
+ await rename(tmpPath, localBin)
127
+ }
128
+ if (!(await isRunnableBinary(localBin))) {
129
+ throw new Error(`已下载 cloudflared 至 ${localBin} 但无法执行`)
130
+ }
131
+ logger?.info?.('cloudflared ready', { path: localBin })
132
+ return localBin
133
+ }
134
+
135
+ export class Tunnel {
136
+ constructor({ config, logger, onUrl = () => {}, onState = () => {} }) {
137
+ this.config = config
138
+ this.logger = logger
139
+ this.onUrl = onUrl
140
+ this.onState = onState
141
+ this.child = null
142
+ this.currentUrl = null
143
+ this.state = 'idle'
144
+ this.failures = 0
145
+ this.restarts = 0
146
+ this.lastError = null
147
+ this.stopped = false
148
+ this.restartTimer = null
149
+ this.healthTimer = null
150
+ this.tokenRefreshAt = 0
151
+ this.token = config.public.tunnelToken ?? null
152
+ this.readyWaiters = []
153
+ this.attached = false
154
+ this.owner = null
155
+ this.statePath = join(config.stateDir, 'tunnel.json')
156
+ }
157
+
158
+ /** 落盘隧道身份,供 relay 重启后 attach;quick 的 URL 只有原进程还活着才有意义。 */
159
+ #persist(extra = {}) {
160
+ try {
161
+ ensureDir(this.config.stateDir)
162
+ writeJsonAtomic(this.statePath, {
163
+ mode: this.config.public.mode,
164
+ port: this.config.listen.port,
165
+ url: this.currentUrl,
166
+ // attach 场景没有 child 句柄,真正的 pid 存在 owner 里,否则会写出 pid:null 导致之后无法收隧道
167
+ pid: this.child?.pid ?? this.owner ?? null,
168
+ startedAt: new Date().toISOString(),
169
+ attached: this.attached,
170
+ ...extra,
171
+ })
172
+ } catch (error) {
173
+ this.logger.warn('persist tunnel state failed', { error: String(error?.message ?? error) })
174
+ }
175
+ }
176
+
177
+ status() {
178
+ return {
179
+ mode: this.config.public.mode,
180
+ state: this.state,
181
+ url: this.currentUrl,
182
+ hostname: this.config.public.hostname,
183
+ pid: this.child?.pid ?? null,
184
+ attached: this.attached,
185
+ persistAcrossRestart: this.config.tunnel.persistAcrossRestart !== false,
186
+ restarts: this.restarts,
187
+ failures: this.failures,
188
+ tokenSource: this.config.public.refreshCommand ? 'refreshCommand' : this.token ? 'config' : null,
189
+ lastError: this.lastError,
190
+ }
191
+ }
192
+
193
+ async start() {
194
+ this.stopped = false
195
+ const mode = this.config.public.mode
196
+ if (mode === 'none') {
197
+ this.state = 'disabled'
198
+ return null
199
+ }
200
+ if (mode === 'funnel') {
201
+ await this.#startFunnel()
202
+ return this.currentUrl
203
+ }
204
+ if (mode === 'quick' && (await this.#tryAttach())) return this.currentUrl
205
+ await this.#spawn()
206
+ return this.currentUrl
207
+ }
208
+
209
+ /** relay 重启后复用仍在运行的 cloudflared,域名保持不变。 */
210
+ async #tryAttach() {
211
+ const saved = readJson(this.statePath, null)
212
+ if (!saved || saved.mode !== 'quick' || !saved.url || !saved.pid) return false
213
+ if (Number(saved.port) !== Number(this.config.listen.port)) return false
214
+ let alive = false
215
+ try {
216
+ process.kill(saved.pid, 0)
217
+ alive = true
218
+ } catch {}
219
+ if (!alive) return false
220
+ this.currentUrl = saved.url
221
+ this.attached = true
222
+ this.owner = saved.pid
223
+ this.state = 'running'
224
+ this.onState(this.state)
225
+ if (!(await probe(`${saved.url}/__dsh/health`))) {
226
+ this.logger.warn('existing tunnel process is alive but unhealthy; replacing it', { pid: saved.pid, url: saved.url })
227
+ try {
228
+ process.kill(saved.pid, 'SIGTERM')
229
+ } catch {}
230
+ this.currentUrl = null
231
+ this.attached = false
232
+ await sleep(800)
233
+ return false
234
+ }
235
+ this.logger.info('attached to running cloudflared', { pid: saved.pid, url: saved.url })
236
+ this.#persist()
237
+ this.onUrl(saved.url)
238
+ this.#startHealthLoop()
239
+ return true
240
+ }
241
+
242
+ /** Tailscale Funnel:域名固定在 <machine>.<tailnet>.ts.net,relay 重启不影响入口。 */
243
+ async #startFunnel() {
244
+ const dns = await selfDnsName()
245
+ if (!dns) throw new Error('无法从 `tailscale status --json` 读取本机 DNSName')
246
+ this.currentUrl = `https://${dns}`
247
+ this.state = 'starting'
248
+ this.onState(this.state)
249
+ this.logger.info('enabling tailscale funnel', { port: this.config.listen.port, url: this.currentUrl })
250
+ try {
251
+ await execFileAsync('tailscale', ['funnel', '--bg', String(this.config.listen.port)], {
252
+ timeout: 25_000,
253
+ maxBuffer: 1024 * 1024,
254
+ })
255
+ } catch (error) {
256
+ const detail = `${String(error?.stdout ?? '')}${String(error?.stderr ?? '')}`.trim()
257
+ if (/not enabled|enable, visit/i.test(detail)) {
258
+ const enableUrl = /https:\/\/login\.tailscale\.com\S+/u.exec(detail)?.[0] ?? '(见 tailscale 输出)'
259
+ throw new Error(`Tailscale Funnel 未在 tailnet 启用,先打开 ${enableUrl} 启用一次`)
260
+ }
261
+ if (error?.killed || error?.signal) {
262
+ // 命令在启用前会阻塞等待,超时按「未启用」处理
263
+ throw new Error('tailscale funnel 未完成(可能需要在管理后台启用 Funnel)')
264
+ }
265
+ throw new Error(`tailscale funnel 失败:${detail || String(error?.message ?? error)}`)
266
+ }
267
+ this.state = 'running'
268
+ this.onState(this.state)
269
+ this.attached = false
270
+ this.#persist()
271
+ const ok = await waitHealthy(`${this.currentUrl}/__dsh/health`, this.config.tunnel.urlWaitMs)
272
+ if (!ok) this.logger.warn('funnel enabled but health check failed yet', { url: this.currentUrl })
273
+ this.onUrl(this.currentUrl)
274
+ this.#startHealthLoop()
275
+ }
276
+
277
+ async #refreshToken() {
278
+ if (!this.config.public.refreshCommand) return this.token
279
+ try {
280
+ const { stdout } = await execAsync(this.config.public.refreshCommand, { timeout: 30_000, maxBuffer: 1024 * 1024 })
281
+ const value = stdout.trim().split('\n').filter(Boolean).pop() ?? null
282
+ if (value && value !== this.token) {
283
+ this.logger.info('tunnel token refreshed', { length: value.length })
284
+ this.token = value
285
+ }
286
+ this.tokenRefreshAt = Date.now()
287
+ } catch (error) {
288
+ this.logger.warn('tunnel token refresh failed', { error: String(error?.message ?? error) })
289
+ }
290
+ return this.token
291
+ }
292
+
293
+ #args() {
294
+ const target = `http://${this.config.listen.host}:${String(this.config.listen.port)}`
295
+ if (this.config.public.mode === 'quick') {
296
+ return { args: ['tunnel', '--url', target, '--no-autoupdate'], env: {} }
297
+ }
298
+ const args = ['tunnel', '--no-autoupdate', 'run']
299
+ const env = {}
300
+ if (this.config.public.configFile) args.push('--config', this.config.public.configFile)
301
+ if (this.token) args.push('--token', this.token)
302
+ return { args, env }
303
+ }
304
+
305
+ async #spawn() {
306
+ if (this.stopped) return
307
+ this.state = 'starting'
308
+ this.onState(this.state)
309
+ if (this.config.public.mode === 'named' && this.config.public.refreshCommand) await this.#refreshToken()
310
+ const { args, env } = this.#args()
311
+ const command = await ensureCloudflaredBinary({
312
+ configured: this.config.public.cloudflared || 'cloudflared',
313
+ home: this.config.home,
314
+ logger: this.logger,
315
+ })
316
+ this.logger.info('starting cloudflared', { command, mode: this.config.public.mode })
317
+ ensureDir(this.config.logs.dir)
318
+ const logPath = join(this.config.logs.dir, 'tunnel.log')
319
+ let logOffset = 0
320
+ try {
321
+ logOffset = (await stat(logPath)).size
322
+ } catch {}
323
+ // 日志落文件而不是管道:relay 退出后 cloudflared 继续存活,管道关闭不会把它带走
324
+ const fd = openSync(logPath, 'a')
325
+ let child
326
+ try {
327
+ child = spawn(command, args, {
328
+ stdio: ['ignore', fd, fd],
329
+ detached: true,
330
+ windowsHide: true,
331
+ env: { ...process.env, ...stripUndefined(env) },
332
+ })
333
+ } finally {
334
+ closeSync(fd)
335
+ }
336
+ child.unref()
337
+ this.child = child
338
+ this.attached = false
339
+ this.#persist()
340
+ child.on('exit', (code, signal) => {
341
+ if (this.child === child) this.child = null
342
+ if (this.stopped) return
343
+ this.state = 'exited'
344
+ this.lastError = `cloudflared exited code=${code} signal=${signal}`
345
+ this.logger.warn('cloudflared exited', { code, signal })
346
+ this.onState(this.state)
347
+ this.#scheduleRestart()
348
+ })
349
+ child.on('error', (error) => {
350
+ this.lastError = String(error?.message ?? error)
351
+ this.logger.error('cloudflared spawn failed', { error: this.lastError })
352
+ this.#scheduleRestart()
353
+ })
354
+ this.failures = 0
355
+ this.state = 'running'
356
+ this.onState(this.state)
357
+ this.#startHealthLoop()
358
+ if (this.config.public.mode === 'quick') {
359
+ try {
360
+ const url = await this.#waitForUrlFromLog(logPath, logOffset)
361
+ this.currentUrl = url
362
+ this.#persist()
363
+ this.onUrl(url)
364
+ } catch (error) {
365
+ this.lastError = String(error?.message ?? error)
366
+ this.logger.error('cloudflared did not yield a URL', { error: this.lastError })
367
+ this.#restart('no-url')
368
+ }
369
+ } else if (this.config.public.hostname) {
370
+ this.currentUrl = `https://${this.config.public.hostname}`
371
+ this.#persist()
372
+ this.onUrl(this.currentUrl)
373
+ }
374
+ }
375
+
376
+ /** 从 cloudflared 日志文件里等 quick 域名(子进程已 detach,不能依赖管道)。 */
377
+ async #waitForUrlFromLog(logPath, offset = 0, timeoutMs = this.config.tunnel.urlWaitMs) {
378
+ const deadline = Date.now() + timeoutMs
379
+ while (Date.now() < deadline) {
380
+ if (this.stopped) throw new Error('tunnel stopped before URL was assigned')
381
+ const text = await readLogTail(logPath, undefined, offset)
382
+ const matches = [...text.matchAll(URL_RE)]
383
+ if (matches.length > 0) return matches[matches.length - 1][0].replace(/\/+$/u, '')
384
+ if (this.lastError && /failed|error|unauthorized/iu.test(this.lastError)) {
385
+ // 继续等,cloudflared 会重试;只在超时时把最后一行错误带出去
386
+ }
387
+ await sleep(400)
388
+ }
389
+ throw new Error(`等待 cloudflared URL 超时(${timeoutMs}ms),见 ${logPath}`)
390
+ }
391
+
392
+ #startHealthLoop() {
393
+ if (this.healthTimer) clearInterval(this.healthTimer)
394
+ this.healthTimer = setInterval(() => {
395
+ this.#healthCheck().catch((error) => {
396
+ this.logger.warn('health check error', { error: String(error?.message ?? error) })
397
+ })
398
+ }, this.config.tunnel.healthIntervalMs)
399
+ this.healthTimer.unref?.()
400
+ }
401
+
402
+ async #healthCheck() {
403
+ if (this.state !== 'running' || !this.currentUrl || this.stopped) return
404
+ const target = `${this.currentUrl}/__dsh/health`
405
+ try {
406
+ const response = await httpRequest(target, { timeoutMs: this.config.tunnel.healthTimeoutMs })
407
+ if (response.status === 200) {
408
+ this.failures = 0
409
+ return
410
+ }
411
+ throw new Error(`HTTP ${response.status}`)
412
+ } catch (error) {
413
+ this.failures += 1
414
+ this.lastError = String(error?.message ?? error)
415
+ this.logger.warn('tunnel health failed', { failures: this.failures, error: this.lastError })
416
+ if (this.failures >= this.config.tunnel.unhealthyThreshold) this.#restart('unhealthy')
417
+ }
418
+ }
419
+
420
+ #scheduleRestart() {
421
+ if (this.stopped) return
422
+ const delay = Math.min(
423
+ this.config.tunnel.maxBackoffMs,
424
+ this.config.tunnel.restartBackoffMs * 2 ** Math.min(this.restarts, 6),
425
+ )
426
+ this.restarts += 1
427
+ this.state = 'backoff'
428
+ this.onState(this.state)
429
+ if (this.restartTimer) clearTimeout(this.restartTimer)
430
+ this.restartTimer = setTimeout(() => {
431
+ this.restartTimer = null
432
+ this.#spawn().catch((error) => this.logger.error('restart failed', { error: String(error?.message ?? error) }))
433
+ }, delay)
434
+ this.restartTimer.unref?.()
435
+ }
436
+
437
+ #restart(reason) {
438
+ if (this.stopped) return
439
+ this.logger.warn('restarting tunnel', { reason })
440
+ this.currentUrl = null
441
+ const child = this.child
442
+ if (child) {
443
+ try {
444
+ child.kill('SIGTERM')
445
+ } catch {}
446
+ } else {
447
+ this.#scheduleRestart()
448
+ }
449
+ }
450
+
451
+ async stop({ keepProcess = this.config.tunnel.persistAcrossRestart !== false } = {}) {
452
+ this.stopped = true
453
+ clearInterval(this.healthTimer)
454
+ clearTimeout(this.restartTimer)
455
+ if (this.config.public.mode === 'funnel') {
456
+ // Funnel 配置留在 tailscaled 里,重启 relay 直接复用;真正关闭用 `dsh-remote tunnel stop --all`
457
+ if (!keepProcess) {
458
+ await execFileAsync('tailscale', ['funnel', 'reset'], { timeout: 15_000 }).catch(() => {})
459
+ this.#persist({ url: null })
460
+ }
461
+ this.child = null
462
+ return
463
+ }
464
+ const child = this.child
465
+ this.child = null
466
+ if (this.attached || !child) return
467
+ if (keepProcess) {
468
+ // 保留 cloudflared(以及它的固定域名),只退出 relay
469
+ this.logger.info('keeping cloudflared alive for link reuse', { pid: child.pid, url: this.currentUrl })
470
+ return
471
+ }
472
+ child.kill('SIGTERM')
473
+ const exited = await Promise.race([
474
+ new Promise((resolve) => child.once('exit', () => resolve(true))),
475
+ sleep(5000).then(() => false),
476
+ ])
477
+ if (!exited) {
478
+ try {
479
+ child.kill('SIGKILL')
480
+ } catch {}
481
+ }
482
+ }
483
+ }
484
+
485
+ async function probe(url, timeoutMs = 4000) {
486
+ try {
487
+ const response = await httpRequest(url, { timeoutMs })
488
+ return response.status === 200
489
+ } catch {
490
+ return false
491
+ }
492
+ }
493
+
494
+ async function waitHealthy(url, timeoutMs) {
495
+ const deadline = Date.now() + timeoutMs
496
+ while (Date.now() < deadline) {
497
+ if (await probe(url)) return true
498
+ await sleep(1500)
499
+ }
500
+ return false
501
+ }
502
+
503
+ /** 读取本机 Tailscale DNSName(去掉结尾点)。 */
504
+ export async function selfDnsName() {
505
+ try {
506
+ const { stdout } = await execFileAsync('tailscale', ['status', '--json'], { timeout: 10_000, maxBuffer: 4 * 1024 * 1024 })
507
+ const name = JSON.parse(stdout)?.Self?.DNSName
508
+ return typeof name === 'string' && name.length > 0 ? name.replace(/\.$/u, '').toLowerCase() : null
509
+ } catch {
510
+ return null
511
+ }
512
+ }
513
+
514
+ async function readLogTail(path, bytes = 256 * 1024, offset = 0) {
515
+ try {
516
+ const info = await stat(path)
517
+ const from = Math.max(Number(offset) || 0, info.size - bytes, 0)
518
+ const buffer = await new Promise((resolve, reject) => {
519
+ readFile(path, (error, data) => (error ? reject(error) : resolve(data)))
520
+ })
521
+ return buffer.subarray(from).toString('utf8')
522
+ } catch {
523
+ return ''
524
+ }
525
+ }
526
+
527
+ function stripUndefined(object) {
528
+ const out = {}
529
+ for (const [key, value] of Object.entries(object)) {
530
+ if (value !== undefined) out[key] = value
531
+ }
532
+ return out
533
+ }