@linxin666/dsh-remote-bridge 0.4.12 → 0.4.14

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 (65) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +53 -11
  3. package/README.zh.md +53 -11
  4. package/lib/client.js +112 -90
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18800 -334
  7. package/lib/types/client/PairPanel.d.ts +7 -0
  8. package/lib/types/client/locales.d.ts +13 -10
  9. package/lib/types/core/connection.d.ts +50 -0
  10. package/lib/types/core/devices.d.ts +80 -6
  11. package/lib/types/core/liveactivity.d.ts +7 -0
  12. package/lib/types/core/model-efforts.d.ts +83 -0
  13. package/lib/types/core/protocol.d.ts +24 -0
  14. package/lib/types/core/push.d.ts +70 -3
  15. package/lib/types/host/firewall.d.ts +74 -0
  16. package/lib/types/host/host-bind-capability.d.ts +90 -0
  17. package/lib/types/host/ingress-gate.d.ts +59 -0
  18. package/lib/types/host/ingress-sync.d.ts +429 -0
  19. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  20. package/lib/types/host/lan-bind.d.ts +106 -0
  21. package/lib/types/host/lan-forward.d.ts +112 -0
  22. package/lib/types/host/lan.d.ts +61 -0
  23. package/lib/types/host/pair-origin.d.ts +34 -19
  24. package/lib/types/host/relay-bridge-connector.d.ts +234 -0
  25. package/lib/types/host/relay-connector.d.ts +156 -0
  26. package/lib/types/host/relay-control.d.ts +195 -0
  27. package/lib/types/host/relay-registry.d.ts +123 -0
  28. package/lib/types/host/relay-secondary.d.ts +209 -0
  29. package/lib/types/host/relay.d.ts +170 -0
  30. package/lib/types/host/routes.d.ts +29 -1
  31. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  32. package/lib/types/host/tunnel-plan.d.ts +41 -0
  33. package/lib/types/host/tunnel.d.ts +289 -0
  34. package/lib/types/index.d.ts +488 -1
  35. package/package.json +4 -2
  36. package/src/client/PairPanel.tsx +21 -0
  37. package/src/client/locales.ts +19 -15
  38. package/src/client/panel.module.css +48 -1
  39. package/src/core/connection.ts +316 -11
  40. package/src/core/devices.ts +165 -16
  41. package/src/core/hub.ts +17 -5
  42. package/src/core/liveactivity.ts +16 -2
  43. package/src/core/model-efforts.ts +223 -0
  44. package/src/core/protocol.ts +27 -0
  45. package/src/core/push.ts +90 -5
  46. package/src/host/firewall.ts +230 -0
  47. package/src/host/host-bind-capability.ts +249 -0
  48. package/src/host/ingress-gate.ts +203 -0
  49. package/src/host/ingress-sync.ts +1074 -0
  50. package/src/host/lan-bind-plan.ts +134 -0
  51. package/src/host/lan-bind.ts +250 -0
  52. package/src/host/lan-forward.ts +321 -0
  53. package/src/host/lan.ts +142 -0
  54. package/src/host/pair-origin.ts +44 -38
  55. package/src/host/relay-bridge-connector.ts +849 -0
  56. package/src/host/relay-connector.ts +324 -0
  57. package/src/host/relay-control.ts +315 -0
  58. package/src/host/relay-registry.ts +275 -0
  59. package/src/host/relay-secondary.ts +478 -0
  60. package/src/host/relay.ts +294 -0
  61. package/src/host/routes.ts +57 -3
  62. package/src/host/tunnel-orphan.ts +325 -0
  63. package/src/host/tunnel-plan.ts +58 -0
  64. package/src/host/tunnel.ts +688 -0
  65. package/src/index.ts +1516 -23
@@ -0,0 +1,688 @@
1
+ /**
2
+ * Auto-tunnel manager: spawns a Cloudflare tunnel through the `cloudflared`
3
+ * npm package — its postinstall downloads the platform binary and the
4
+ * readiness policy below validates it and re-fetches when it cannot run (the
5
+ * desktop payload stages one tree for every shipped OS/arch), so no
6
+ * user-side tooling is involved — surfaces the public URL, and restarts the
7
+ * process after unexpected exits with exponential backoff. Two modes: the
8
+ * accountless quick tunnel (`https://xxx.trycloudflare.com`, hostname minted
9
+ * per start) and an account named tunnel (`cloudflared tunnel run --token`,
10
+ * fixed public hostname — the mode that lets a paired phone keep its
11
+ * bookmark and pairing cookie across restarts).
12
+ *
13
+ * The cloudflared package's Tunnel is a thin spawn wrapper; this manager
14
+ * owns the lifecycle policy (binary readiness, URL timeout, restart
15
+ * backoff, and the public-URL readiness watchdog) around it. All seams — the
16
+ * tunnel factory, binary readiness, the URL probe, timers — are injectable
17
+ * so the whole lifecycle is unit-testable without a real binary or network.
18
+ *
19
+ * 'running' is not a terminal state: the connector can lose its edge
20
+ * registration while the process keeps living, which leaves a hostname that
21
+ * no longer resolves. The watchdog below probes the public URL of a running
22
+ * tunnel and reuses the crash-restart path when it stops answering, so the
23
+ * relay is re-registered against a freshly minted URL instead of proxying a
24
+ * dead one (issue #1723).
25
+ *
26
+ * A host crash is the one exit the manager cannot cover in-process: the child
27
+ * is reparented and keeps running, holding a hostname nobody serves. Every
28
+ * spawn is therefore recorded under the DSH home (pid plus its exact command
29
+ * line) and the record is dropped when that child is stopped, so the next
30
+ * start reaps exactly the child a dead host left behind — see
31
+ * ./tunnel-orphan.ts.
32
+ */
33
+
34
+ import { existsSync } from 'node:fs'
35
+ import { spawn } from 'node:child_process'
36
+ import { EventEmitter } from 'node:events'
37
+ import { bin, install, Tunnel } from 'cloudflared'
38
+ import { createTunnelChildGuard, type TunnelChildGuard, type TunnelChildProcess } from './tunnel-orphan.ts'
39
+
40
+ /** The observable tunnel lifecycle the settings/panel surfaces render. */
41
+ export type TunnelPhase = 'stopped' | 'starting' | 'running' | 'failed'
42
+
43
+ /**
44
+ * What the manager should run. `quick` is the accountless trycloudflare
45
+ * tunnel whose hostname is minted per start (and dies with the process);
46
+ * `named` is an account tunnel whose public hostname is fixed — the point
47
+ * of the named mode is that a paired phone keeps its bookmark and its
48
+ * pairing cookie across restarts.
49
+ */
50
+ export type TunnelTarget =
51
+ | { kind: 'quick'; targetUrl: string; originHostHeader?: string }
52
+ | { kind: 'named'; token: string; publicUrl: string }
53
+
54
+ /** Compare two targets for the start idempotence check. */
55
+ function sameTarget(left: TunnelTarget | undefined, right: TunnelTarget): boolean {
56
+ if (left === undefined) return false
57
+ return JSON.stringify(left) === JSON.stringify(right)
58
+ }
59
+
60
+ /** The event face the named adapter wraps (a cloudflared package Tunnel). */
61
+ interface NamedTunnelProcess {
62
+ on(event: 'connected', listener: () => void): unknown
63
+ on(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): unknown
64
+ on(event: 'error', listener: (value: Error) => void): unknown
65
+ off(event: string, listener: (...args: any[]) => void): unknown
66
+ stop(): boolean
67
+ /** The spawned OS process, when the wrapper exposes it. */
68
+ readonly process?: TunnelChildProcess
69
+ }
70
+
71
+ /**
72
+ * Wrap a named-tunnel process so it fits the quick-tunnel handle shape: the
73
+ * fixed public URL is reported through the same `url` event once the first
74
+ * edge connection registers (cloudflared fires `connected` per connection,
75
+ * so only the first is taken), and exit/error pass through. The manager's
76
+ * URL timeout, crash-restart backoff, and stop semantics then stay fully
77
+ * mode-agnostic.
78
+ * @param inner - the running named-tunnel process.
79
+ * @param publicUrl - the fixed public hostname ingress maps to this server.
80
+ * @returns a handle emitting `url` once the tunnel is reachable.
81
+ */
82
+ export function namedTunnelHandle(inner: NamedTunnelProcess, publicUrl: string): TunnelHandle {
83
+ const handle = new EventEmitter() as unknown as TunnelHandle & {
84
+ emit(event: string, ...args: any[]): boolean
85
+ }
86
+ let registered = false
87
+ const onConnected = (): void => {
88
+ // cloudflared fires `connected` per edge connection (four on a healthy
89
+ // registration); the fixed URL only needs reporting once.
90
+ if (registered) return
91
+ registered = true
92
+ handle.emit('url', publicUrl)
93
+ }
94
+ const onExit = (code: number | null, signal: NodeJS.Signals | null): void => {
95
+ handle.emit('exit', code, signal)
96
+ }
97
+ const onError = (value: Error): void => {
98
+ handle.emit('error', value)
99
+ }
100
+ inner.on('connected', onConnected)
101
+ inner.on('exit', onExit)
102
+ inner.on('error', onError)
103
+ // The named process is a spawn wrapper too: pass its OS process through so
104
+ // crash recovery records this child exactly like a quick one.
105
+ if (inner.process !== undefined) handle.process = inner.process
106
+ handle.stop = (): boolean => {
107
+ inner.off('connected', onConnected)
108
+ inner.off('exit', onExit)
109
+ inner.off('error', onError)
110
+ return inner.stop()
111
+ }
112
+ return handle
113
+ }
114
+
115
+ /** One tunnel status frame. */
116
+ export interface TunnelInfo {
117
+ phase: TunnelPhase
118
+ /** The minted public URL, once the tunnel reports it. */
119
+ url?: string
120
+ /** Human-readable failure detail (binary install, URL timeout, spawn error). */
121
+ error?: string
122
+ }
123
+
124
+ /** The tunnel handle subset this manager uses (the package's Tunnel fits). */
125
+ export interface TunnelHandle {
126
+ on(event: string, listener: (...args: any[]) => void): unknown
127
+ off(event: string, listener: (...args: any[]) => void): unknown
128
+ stop(): boolean
129
+ /**
130
+ * The spawned OS process. Crash recovery records its pid and exact command
131
+ * line, so a host that dies without stopping it can be reaped by the next
132
+ * start; a handle that does not expose one is simply never recorded.
133
+ */
134
+ process?: TunnelChildProcess
135
+ }
136
+
137
+ /**
138
+ * Probe one public tunnel URL from the host. Resolves true when the URL is
139
+ * served (any HTTP answer below 500 — a harness without credentials answers
140
+ * 401/403, which is a healthy round trip), false for a DNS failure, a refused
141
+ * connection, a timeout, or a Cloudflare 5xx (530 "Origin DNS error" / 1033)
142
+ * — the shapes a tunnel that lost its edge registration produces.
143
+ *
144
+ * The probe must never reject: the watchdog reads a rejection as a dead
145
+ * tunnel and restarts on it, so a local programming error would otherwise
146
+ * recycle working tunnels forever.
147
+ * @param url - the tunnel's public URL.
148
+ * @param timeoutMs - how long one probe may take.
149
+ * @returns whether the URL answered as a live origin.
150
+ */
151
+ export async function probeTunnelUrl(url: string, timeoutMs: number): Promise<boolean> {
152
+ const controller = new AbortController()
153
+ const timer = setTimeout(() => { controller.abort() }, timeoutMs)
154
+ try {
155
+ const response = await fetch(url, {
156
+ method: 'GET',
157
+ redirect: 'manual',
158
+ cache: 'no-store',
159
+ signal: controller.signal,
160
+ })
161
+ // Drain so the connection is reusable instead of half-read.
162
+ await response.body?.cancel().catch(() => undefined)
163
+ return response.status < 500
164
+ } catch {
165
+ return false
166
+ } finally {
167
+ clearTimeout(timer)
168
+ }
169
+ }
170
+
171
+ /** Default probe: the real network round trip. */
172
+ async function defaultProbe(url: string, timeoutMs: number): Promise<boolean> {
173
+ return await probeTunnelUrl(url, timeoutMs)
174
+ }
175
+
176
+ /** Injectable seams (defaults are the real cloudflared package + node timers). */
177
+ export interface TunnelManagerOptions {
178
+ /** Spawn one tunnel process for the target (quick or named). */
179
+ factory?: (target: TunnelTarget) => TunnelHandle
180
+ /** Make sure the cloudflared binary exists, downloading it when absent. */
181
+ ensureBinary?: () => Promise<void>
182
+ /** Wait up to this long for the tunnel URL before failing the attempt. */
183
+ urlTimeoutMs?: number
184
+ /** First restart delay after an unexpected failure (exponential base). */
185
+ restartBaseMs?: number
186
+ /** Cap on the exponential restart delay. */
187
+ restartMaxMs?: number
188
+ /** Timer source (injected in tests). */
189
+ timer?: { setTimeout(fn: () => void, ms: number): unknown; clearTimeout(t: unknown): void }
190
+ /** Probe one public URL; false means the tunnel stopped answering. */
191
+ probe?: (url: string, timeoutMs: number) => Promise<boolean>
192
+ /** How often to probe the public URL of a running tunnel (0 disables it). */
193
+ healthCheckIntervalMs?: number
194
+ /** Consecutive probe failures after which the tunnel is restarted. */
195
+ healthCheckFailures?: number
196
+ /** How long one probe may take. */
197
+ probeTimeoutMs?: number
198
+ /**
199
+ * Crash recovery for the spawned child: reap the leftover a crashed host
200
+ * recorded, and record this one. Defaults to the file-backed guard under the
201
+ * DSH home (see ./tunnel-orphan.ts).
202
+ */
203
+ orphan?: TunnelChildGuard
204
+ }
205
+
206
+ /** Time box for the `--version` probe that validates a staged binary. */
207
+ const BINARY_PROBE_TIMEOUT_MS = 10_000
208
+
209
+ /**
210
+ * Probe whether the binary at `path` actually executes on this machine. The
211
+ * desktop payload stages one dependency tree for every shipped OS/arch, so a
212
+ * binary can exist with the wrong architecture (the arm64 darwin
213
+ * `bin/cloudflared` on an x64 mac); existence alone must not skip the
214
+ * reinstall.
215
+ */
216
+ export function binaryRuns(executable: string): Promise<boolean> {
217
+ return new Promise((resolvePromise) => {
218
+ const child = spawn(executable, ['--version'], { stdio: 'ignore' })
219
+ const timer = setTimeout(() => {
220
+ child.kill('SIGKILL')
221
+ resolvePromise(false)
222
+ }, BINARY_PROBE_TIMEOUT_MS)
223
+ child.once('error', () => { clearTimeout(timer); resolvePromise(false) })
224
+ child.once('exit', (code) => { clearTimeout(timer); resolvePromise(code === 0) })
225
+ })
226
+ }
227
+
228
+ /** Injectable seams of the default binary readiness (tests swap them all). */
229
+ export interface BinaryReadinessSeams {
230
+ exists?: (path: string) => boolean
231
+ runs?: (executable: string) => Promise<boolean>
232
+ install?: (path: string) => Promise<unknown>
233
+ }
234
+
235
+ /**
236
+ * Build the default readiness policy over a binary path: skip when the
237
+ * binary has already proven runnable in this process, validate an existing
238
+ * file before trusting it (a stale or wrong-arch binary must not disable
239
+ * the reinstall), and re-fetch the current platform binary otherwise.
240
+ */
241
+ export function createBinaryReadiness(executable: string, seams: BinaryReadinessSeams = {}): () => Promise<void> {
242
+ const exists = seams.exists ?? existsSync
243
+ const runs = seams.runs ?? binaryRuns
244
+ const installBinary = seams.install ?? install
245
+ const validated = new Set<string>()
246
+ let installs = 0
247
+ let lastFailure: Error | undefined
248
+ return async () => {
249
+ if (validated.has(executable)) return
250
+ // The manager retries forever with backoff, so a permanently unrunnable
251
+ // binary must not re-download the whole platform archive on every attempt
252
+ // (a wrong-arch payload would otherwise fetch it once per restart round).
253
+ // A transient install failure still gets its retries; past the cap the
254
+ // remembered error is rethrown until the process restarts.
255
+ if (installs >= MAX_BINARY_INSTALL_ATTEMPTS && lastFailure !== undefined) throw lastFailure
256
+ if (exists(executable) && await runs(executable)) {
257
+ validated.add(executable)
258
+ return
259
+ }
260
+ installs += 1
261
+ try {
262
+ await installBinary(executable)
263
+ if (!(await runs(executable))) {
264
+ throw new Error(`the cloudflared binary at ${executable} still does not run after the reinstall`)
265
+ }
266
+ } catch (error) {
267
+ lastFailure = error instanceof Error ? error : new Error(String(error))
268
+ throw lastFailure
269
+ }
270
+ validated.add(executable)
271
+ }
272
+ }
273
+
274
+ /** How many archive downloads one process may attempt before giving up. */
275
+ export const MAX_BINARY_INSTALL_ATTEMPTS = 3
276
+
277
+ /** How often a running tunnel's public URL is probed (issue #1723). */
278
+ export const DEFAULT_HEALTH_CHECK_INTERVAL_MS = 60_000
279
+ /** Consecutive failed probes before the tunnel is declared dead. */
280
+ export const DEFAULT_HEALTH_CHECK_FAILURES = 2
281
+ /** How long one public-URL probe may take. */
282
+ export const DEFAULT_PROBE_TIMEOUT_MS = 10_000
283
+
284
+ /** The readiness policy the manager uses by default: the package's real binary path. */
285
+ const defaultBinaryReadiness = createBinaryReadiness(bin)
286
+
287
+ /** Default binary readiness: keep a working platform binary at `bin`. */
288
+ async function defaultEnsureBinary(): Promise<void> {
289
+ await defaultBinaryReadiness()
290
+ }
291
+
292
+ /** The flags every tunnel mode shares (see the quick factory comment). */
293
+ const SHARED_TUNNEL_FLAGS = { '--no-autoupdate': true, '--protocol': 'http2' } as const
294
+
295
+ /**
296
+ * Spawn flags for one quick target. `originHostHeader` stamps the Host the
297
+ * local webserver sees: the Workers relay cannot control the origin-side Host
298
+ * at all (fetch forces it to the URL authority), so a caller that needs one
299
+ * exact public origin restamps it here. What any trust fence or pairing rule
300
+ * makes of that Host is not this module's responsibility.
301
+ */
302
+ export function quickTunnelFlags(originHostHeader?: string): Record<string, string | boolean> {
303
+ return originHostHeader === undefined
304
+ ? { ...SHARED_TUNNEL_FLAGS }
305
+ : { ...SHARED_TUNNEL_FLAGS, '--http-host-header': originHostHeader }
306
+ }
307
+
308
+ /**
309
+ * Command-line arguments for a named tunnel. The account token is deliberately
310
+ * NOT part of the argv: `--token <t>` would expose an account credential to any
311
+ * local user through ps/proc for the whole tunnel lifetime, while the flag's own
312
+ * environment variable (TUNNEL_TOKEN, see cloudflared's tunnel run flags) is not
313
+ * readable that way. Note: `--no-autoupdate` and `--protocol` are flags for the
314
+ * `tunnel` command and must appear BEFORE the `run` subcommand. Putting them
315
+ * after `run` causes cloudflared to exit immediately with "flag provided but not
316
+ * defined: -no-autoupdate" (issues #1432, #1433).
317
+ */
318
+ export function namedTunnelArgs(): string[] {
319
+ return ['tunnel', '--no-autoupdate', '--protocol', 'http2', 'run']
320
+ }
321
+
322
+ /**
323
+ * Run one spawn call with TUNNEL_TOKEN set, restoring the previous value
324
+ * afterwards. The cloudflared package's Tunnel spawns with the inherited
325
+ * environment inside its constructor, so the variable only has to exist for
326
+ * that call; the child keeps its own copy of the environment.
327
+ * @param token - the named-tunnel token.
328
+ * @param spawnTunnel - the call that creates the child process.
329
+ * @returns whatever the spawn call returns.
330
+ */
331
+ export function withTunnelTokenEnv<T>(token: string, spawnTunnel: () => T): T {
332
+ const previous = process.env.TUNNEL_TOKEN
333
+ process.env.TUNNEL_TOKEN = token
334
+ try {
335
+ return spawnTunnel()
336
+ } finally {
337
+ if (previous === undefined) delete process.env.TUNNEL_TOKEN
338
+ else process.env.TUNNEL_TOKEN = previous
339
+ }
340
+ }
341
+
342
+ /** Spawn one named tunnel without putting its token in the child's argv. */
343
+ function spawnNamedTunnel(token: string): NamedTunnelProcess {
344
+ return withTunnelTokenEnv(token, () => new Tunnel(namedTunnelArgs()))
345
+ }
346
+
347
+ /** Default factory: the cloudflared package's quick and named tunnels. */
348
+ function defaultFactory(target: TunnelTarget): TunnelHandle {
349
+ // `--no-autoupdate`: the binary must never upgrade itself out from under
350
+ // the manager (a self-updated binary would break the pinned lifecycle).
351
+ // `--protocol http2`: the default `auto` prefers QUIC (UDP 7844), which
352
+ // wedges on fake-ip TUN proxies and QUIC-hostile networks — the connector
353
+ // holds the hostname but reports readyConnections: 0 forever (edge 1033),
354
+ // and the auto fallback never fires on a half-open QUIC handshake. http2
355
+ // rides TCP through the same paths reliably (verified live: auto stuck at
356
+ // ready 0 on two fresh registrations; http2 ready immediately).
357
+ if (target.kind === 'quick') {
358
+ return Tunnel.quick(target.targetUrl, quickTunnelFlags(target.originHostHeader))
359
+ }
360
+ return namedTunnelHandle(spawnNamedTunnel(target.token), target.publicUrl)
361
+ }
362
+
363
+ /** Node timers. */
364
+ const nodeTimer = { setTimeout, clearTimeout }
365
+
366
+ /**
367
+ * Own the lifecycle of one auto-tunnel: start/stop, URL surfacing, and
368
+ * crash-restart backoff.
369
+ */
370
+ export class TunnelManager {
371
+ private readonly factory: (target: TunnelTarget) => TunnelHandle
372
+ private readonly ensureBinary: () => Promise<void>
373
+ private readonly urlTimeoutMs: number
374
+ private readonly restartBaseMs: number
375
+ private readonly restartMaxMs: number
376
+ private readonly timer: { setTimeout(fn: () => void, ms: number): unknown; clearTimeout(t: unknown): void }
377
+ private readonly probe: (url: string, timeoutMs: number) => Promise<boolean>
378
+ private readonly healthCheckIntervalMs: number
379
+ private readonly healthCheckFailures: number
380
+ private readonly probeTimeoutMs: number
381
+ private readonly orphan: TunnelChildGuard
382
+
383
+ private phase: TunnelPhase = 'stopped'
384
+ private url: string | undefined
385
+ private error: string | undefined
386
+ private target: TunnelTarget | undefined
387
+ private handle: TunnelHandle | undefined
388
+ private urlTimer: unknown | undefined
389
+ private restartTimer: unknown | undefined
390
+ private healthTimer: unknown | undefined
391
+ private healthFailures = 0
392
+ private attempts = 0
393
+ // Whether the current handler owns the crash-recovery record: only a record
394
+ // this manager wrote is ever cleared.
395
+ private recordedChild = false
396
+ // Generation counter: a stale ensureBinary resolution from an earlier
397
+ // start() must not spawn a second handle after a stop/start cycle.
398
+ private generation = 0
399
+ private stopping = false
400
+ private readonly urlListeners = new Set<(url: string) => void>()
401
+ private readonly phaseListeners = new Set<(info: TunnelInfo) => void>()
402
+
403
+ /**
404
+ * @param options - seams; defaults spawn the real quick tunnel.
405
+ */
406
+ constructor(options: TunnelManagerOptions = {}) {
407
+ this.factory = options.factory ?? defaultFactory
408
+ this.ensureBinary = options.ensureBinary ?? defaultEnsureBinary
409
+ this.urlTimeoutMs = options.urlTimeoutMs ?? 30_000
410
+ this.restartBaseMs = options.restartBaseMs ?? 5_000
411
+ this.restartMaxMs = options.restartMaxMs ?? 60_000
412
+ this.timer = options.timer ?? nodeTimer
413
+ this.probe = options.probe ?? defaultProbe
414
+ this.healthCheckIntervalMs = options.healthCheckIntervalMs ?? DEFAULT_HEALTH_CHECK_INTERVAL_MS
415
+ this.healthCheckFailures = options.healthCheckFailures ?? DEFAULT_HEALTH_CHECK_FAILURES
416
+ this.probeTimeoutMs = options.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS
417
+ this.orphan = options.orphan ?? createTunnelChildGuard()
418
+ }
419
+
420
+ /** The current status frame. */
421
+ get info(): TunnelInfo {
422
+ return {
423
+ phase: this.phase,
424
+ ...(this.url !== undefined ? { url: this.url } : {}),
425
+ ...(this.error !== undefined ? { error: this.error } : {}),
426
+ }
427
+ }
428
+
429
+ /**
430
+ * Start (or keep) a tunnel toward `target`. Restarting with a different
431
+ * target tears the old tunnel down first; restarting with the same target
432
+ * while running is a no-op. A string is the quick mode's local target URL.
433
+ *
434
+ * In quick mode the URL surfaces when cloudflared mints the ephemeral
435
+ * trycloudflare hostname; in named mode the fixed `publicUrl` surfaces
436
+ * once the first edge connection registers (see {@link namedTunnelHandle}).
437
+ * @param target - what to run (a string means quick toward that local URL).
438
+ */
439
+ start(target: TunnelTarget | string): void {
440
+ const resolved: TunnelTarget = typeof target === 'string' ? { kind: 'quick', targetUrl: target } : target
441
+ if (sameTarget(this.target, resolved) && (this.phase === 'starting' || this.phase === 'running')) return
442
+ this.teardown()
443
+ this.stopping = false
444
+ this.target = resolved
445
+ this.attempts = 0
446
+ this.generation += 1
447
+ this.attempt()
448
+ }
449
+
450
+ /** Stop the tunnel for good: no restarts, no state. */
451
+ stop(): void {
452
+ this.teardown()
453
+ this.stopping = false
454
+ this.target = undefined
455
+ this.setPhase('stopped')
456
+ }
457
+
458
+ /** Alias of {@link stop} for plugin-effect disposal. */
459
+ dispose(): void {
460
+ this.stop()
461
+ }
462
+
463
+ /** Subscribe to minted tunnel URLs (fire-and-forget duplicates dropped). */
464
+ onUrl(listener: (url: string) => void): () => void {
465
+ this.urlListeners.add(listener)
466
+ return () => { this.urlListeners.delete(listener) }
467
+ }
468
+
469
+ /** Subscribe to every phase change. */
470
+ onPhase(listener: (info: TunnelInfo) => void): () => void {
471
+ this.phaseListeners.add(listener)
472
+ return () => { this.phaseListeners.delete(listener) }
473
+ }
474
+
475
+ private attempt(): void {
476
+ if (this.stopping || this.target === undefined) return
477
+ const gen = this.generation
478
+ this.setPhase('starting')
479
+ this.handle = undefined
480
+ this.url = undefined
481
+ this.error = undefined
482
+ void this.ensureBinary().then(async () => {
483
+ // A host that died without tearing its tunnel down left its child
484
+ // recorded; reap exactly that process before a second connector is
485
+ // spawned beside it. The reap settles before the spawn by design.
486
+ await this.reapLeftoverChild()
487
+ if (this.stopping || this.target === undefined || gen !== this.generation) return
488
+ const handle = this.factory(this.target)
489
+ this.handle = handle
490
+ // Recorded as the first thing after the spawn: a crash from here on
491
+ // leaves a child the next start can identify and reap.
492
+ this.recordedChild = this.orphan.record(handle.process)
493
+ this.urlTimer = this.timer.setTimeout(() => {
494
+ // The tunnel never reported a URL: kill it and retry with backoff.
495
+ this.fail('timed out waiting for the tunnel URL')
496
+ }, this.urlTimeoutMs)
497
+ handle.on('url', (value: string) => {
498
+ if (this.handle !== handle) return
499
+ this.handleUrl(value)
500
+ })
501
+ handle.on('exit', () => {
502
+ if (this.handle !== handle) return
503
+ this.handleExit()
504
+ })
505
+ handle.on('error', (value: unknown) => {
506
+ // Spawn/connection errors usually precede an exit; the exit path owns
507
+ // restart, this only records diagnostics while the process still lives.
508
+ if (this.handle !== handle || this.phase !== 'starting') return
509
+ this.error = value instanceof Error ? value.message : String(value)
510
+ })
511
+ }).catch((value: unknown) => {
512
+ // Binary install failed (no network, no platform build): report it.
513
+ if (this.stopping || this.target === undefined || gen !== this.generation) return
514
+ const message = value instanceof Error ? value.message : String(value)
515
+ this.fail(`could not obtain the cloudflared binary: ${message}`)
516
+ })
517
+ }
518
+
519
+ private handleUrl(value: string): void {
520
+ if (this.urlTimer !== undefined) {
521
+ this.timer.clearTimeout(this.urlTimer)
522
+ this.urlTimer = undefined
523
+ }
524
+ this.url = value
525
+ this.error = undefined
526
+ this.attempts = 0
527
+ this.setPhase('running')
528
+ // The URL is out; from here the connector can still lose its edge
529
+ // registration without the process exiting, so readiness is supervised.
530
+ this.startHealthWatch(value)
531
+ for (const listener of this.urlListeners) {
532
+ try {
533
+ listener(value)
534
+ } catch {
535
+ // A throwing subscriber must not break the emit loop.
536
+ }
537
+ }
538
+ }
539
+
540
+ /**
541
+ * Watch the readiness of a running tunnel. cloudflared can keep its process
542
+ * (and its metrics port) alive while every edge connection is gone, leaving
543
+ * a minted hostname that no longer resolves: the manager used to report
544
+ * 'running' forever and the relay kept forwarding to that dead address, so
545
+ * the phone hit Cloudflare 1016 instead of the relay's offline page
546
+ * (issue #1723). A bounded number of consecutive probe failures ends the
547
+ * attempt through the ordinary fail/backoff path, which mints a new URL and
548
+ * re-announces the relay.
549
+ */
550
+ private startHealthWatch(url: string): void {
551
+ this.stopHealthWatch()
552
+ // A phase listener may have stopped the tunnel or replaced its target
553
+ // while this URL was being announced; only a live running phase schedules.
554
+ if (this.stopping || this.phase !== 'running') return
555
+ if (this.healthCheckIntervalMs <= 0 || this.healthCheckFailures <= 0) return
556
+ this.healthFailures = 0
557
+ const schedule = (): void => {
558
+ this.healthTimer = this.timer.setTimeout(() => {
559
+ this.healthTimer = undefined
560
+ void this.healthCheck(url)
561
+ }, this.healthCheckIntervalMs)
562
+ }
563
+ schedule()
564
+ }
565
+
566
+ /** One probe round of the running tunnel's public URL. */
567
+ private async healthCheck(url: string): Promise<void> {
568
+ // The tunnel may have been stopped, failed, or replaced while the probe
569
+ // was in flight; only a still-running tunnel toward this same URL is
570
+ // judged by the result.
571
+ if (this.stopping || this.phase !== 'running' || this.url !== url) return
572
+ let alive = false
573
+ try {
574
+ alive = await this.probe(url, this.probeTimeoutMs)
575
+ } catch {
576
+ alive = false
577
+ }
578
+ if (this.stopping || this.phase !== 'running' || this.url !== url) return
579
+ if (alive) {
580
+ this.healthFailures = 0
581
+ } else {
582
+ this.healthFailures += 1
583
+ if (this.healthFailures >= this.healthCheckFailures) {
584
+ this.fail('the tunnel stopped answering on its public URL')
585
+ return
586
+ }
587
+ }
588
+ this.healthTimer = this.timer.setTimeout(() => {
589
+ this.healthTimer = undefined
590
+ void this.healthCheck(url)
591
+ }, this.healthCheckIntervalMs)
592
+ }
593
+
594
+ /** Cancel the readiness watchdog (teardown, restart, stop). */
595
+ private stopHealthWatch(): void {
596
+ if (this.healthTimer !== undefined) {
597
+ this.timer.clearTimeout(this.healthTimer)
598
+ this.healthTimer = undefined
599
+ }
600
+ this.healthFailures = 0
601
+ }
602
+
603
+ private handleExit(): void {
604
+ // The exit handler is detached during teardown, so reaching this point
605
+ // means an unexpected death: fail the current phase and schedule a retry.
606
+ if (this.stopping) return
607
+ this.fail('the tunnel process exited unexpectedly')
608
+ }
609
+
610
+ private fail(message: string): void {
611
+ if (this.stopping) return
612
+ this.url = undefined
613
+ this.error = message
614
+ this.stopHandle()
615
+ if (this.urlTimer !== undefined) {
616
+ this.timer.clearTimeout(this.urlTimer)
617
+ this.urlTimer = undefined
618
+ }
619
+ this.stopHealthWatch()
620
+ this.setPhase('failed')
621
+ this.attempts += 1
622
+ const delay = Math.min(this.restartBaseMs * 2 ** (this.attempts - 1), this.restartMaxMs)
623
+ this.restartTimer = this.timer.setTimeout(() => {
624
+ this.restartTimer = undefined
625
+ this.attempt()
626
+ }, delay)
627
+ }
628
+
629
+ /**
630
+ * Reap the child a crashed host recorded (see ./tunnel-orphan.ts). A failed
631
+ * recovery only loses the cleanup, so it must never fail the attempt.
632
+ */
633
+ private async reapLeftoverChild(): Promise<void> {
634
+ try {
635
+ await this.orphan.reap()
636
+ } catch (error) {
637
+ console.warn(`remote-bridge: could not clear a leftover tunnel child (${error instanceof Error ? error.message : String(error)})`)
638
+ }
639
+ }
640
+
641
+ /**
642
+ * Stop the current child and drop its crash-recovery record: the process the
643
+ * record describes is gone, so a later start must not reap it again (and a
644
+ * healthy host never reaps its own live child).
645
+ */
646
+ private stopHandle(): void {
647
+ if (this.handle === undefined) return
648
+ const handle = this.handle
649
+ this.handle = undefined
650
+ try {
651
+ handle.stop()
652
+ } finally {
653
+ // Only a record this manager wrote is ours to drop: a record a sibling
654
+ // host still owns (another profile under one DSH home) is left alone.
655
+ if (this.recordedChild) {
656
+ this.recordedChild = false
657
+ this.orphan.clear()
658
+ }
659
+ }
660
+ }
661
+
662
+ /** Stop the current process and cancel every pending timer (no phase change). */
663
+ private teardown(): void {
664
+ this.stopping = true
665
+ this.stopHealthWatch()
666
+ if (this.urlTimer !== undefined) {
667
+ this.timer.clearTimeout(this.urlTimer)
668
+ this.urlTimer = undefined
669
+ }
670
+ if (this.restartTimer !== undefined) {
671
+ this.timer.clearTimeout(this.restartTimer)
672
+ this.restartTimer = undefined
673
+ }
674
+ this.stopHandle()
675
+ }
676
+
677
+ private setPhase(phase: TunnelPhase): void {
678
+ this.phase = phase
679
+ const info = this.info
680
+ for (const listener of this.phaseListeners) {
681
+ try {
682
+ listener(info)
683
+ } catch {
684
+ // A throwing subscriber must not break the emit loop.
685
+ }
686
+ }
687
+ }
688
+ }