@linxin666/dsh-remote-bridge 0.4.12 → 0.4.13

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.i18n.yaml +2 -2
  2. package/README.md +45 -8
  3. package/README.zh.md +45 -8
  4. package/lib/client.js +1 -1
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18031 -373
  7. package/lib/types/core/connection.d.ts +9 -0
  8. package/lib/types/core/devices.d.ts +27 -6
  9. package/lib/types/core/liveactivity.d.ts +7 -0
  10. package/lib/types/core/model-efforts.d.ts +83 -0
  11. package/lib/types/core/protocol.d.ts +2 -0
  12. package/lib/types/core/push.d.ts +51 -2
  13. package/lib/types/host/firewall.d.ts +74 -0
  14. package/lib/types/host/host-bind-capability.d.ts +90 -0
  15. package/lib/types/host/ingress-gate.d.ts +59 -0
  16. package/lib/types/host/ingress-sync.d.ts +429 -0
  17. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  18. package/lib/types/host/lan-bind.d.ts +106 -0
  19. package/lib/types/host/lan-forward.d.ts +112 -0
  20. package/lib/types/host/lan.d.ts +61 -0
  21. package/lib/types/host/pair-origin.d.ts +34 -19
  22. package/lib/types/host/relay-bridge-connector.d.ts +215 -0
  23. package/lib/types/host/relay-connector.d.ts +152 -0
  24. package/lib/types/host/relay-control.d.ts +124 -0
  25. package/lib/types/host/relay-registry.d.ts +114 -0
  26. package/lib/types/host/relay.d.ts +170 -0
  27. package/lib/types/host/routes.d.ts +24 -1
  28. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  29. package/lib/types/host/tunnel-plan.d.ts +41 -0
  30. package/lib/types/host/tunnel.d.ts +289 -0
  31. package/lib/types/index.d.ts +426 -1
  32. package/package.json +4 -2
  33. package/src/client/panel.module.css +16 -1
  34. package/src/core/connection.ts +206 -11
  35. package/src/core/devices.ts +31 -6
  36. package/src/core/hub.ts +17 -5
  37. package/src/core/liveactivity.ts +16 -2
  38. package/src/core/model-efforts.ts +223 -0
  39. package/src/core/protocol.ts +3 -0
  40. package/src/core/push.ts +70 -4
  41. package/src/host/firewall.ts +230 -0
  42. package/src/host/host-bind-capability.ts +249 -0
  43. package/src/host/ingress-gate.ts +203 -0
  44. package/src/host/ingress-sync.ts +1074 -0
  45. package/src/host/lan-bind-plan.ts +134 -0
  46. package/src/host/lan-bind.ts +250 -0
  47. package/src/host/lan-forward.ts +321 -0
  48. package/src/host/lan.ts +142 -0
  49. package/src/host/pair-origin.ts +44 -38
  50. package/src/host/relay-bridge-connector.ts +783 -0
  51. package/src/host/relay-connector.ts +317 -0
  52. package/src/host/relay-control.ts +224 -0
  53. package/src/host/relay-registry.ts +263 -0
  54. package/src/host/relay.ts +294 -0
  55. package/src/host/routes.ts +47 -3
  56. package/src/host/tunnel-orphan.ts +325 -0
  57. package/src/host/tunnel-plan.ts +58 -0
  58. package/src/host/tunnel.ts +688 -0
  59. package/src/index.ts +1280 -22
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Crash recovery for the tunnel's cloudflared child. A host that dies without
3
+ * tearing its tunnel down hands the child over to launchd/systemd, where it
4
+ * keeps its edge registration forever: the next host then runs a second
5
+ * connector beside an orphan nobody serves, and the old process holds a
6
+ * hostname no tunnel answers on any more.
7
+ *
8
+ * The manager records the spawned child under the DSH home right after the
9
+ * spawn (pid plus the exact command line ps/proc reports) and drops the record
10
+ * when that child is stopped, so a record only outlives the process that wrote
11
+ * it when that process crashed. The next start reaps exactly that pid, and
12
+ * only while it is still alive AND its command line still equals the recorded
13
+ * one: a recycled pid or a rewritten record can therefore never make the
14
+ * plugin signal a process it did not spawn. Nothing here matches by pattern,
15
+ * by process name, or by any pid this plugin did not record itself.
16
+ *
17
+ * A record also carries the pid of the host that spawned the child. Two live
18
+ * hosts can share one DSH home (two profiles, or a plugin reload inside one
19
+ * host), and each owns its own child; only a host that is gone leaves a child
20
+ * behind, so a record whose owner is still running is left untouched.
21
+ */
22
+
23
+ import { execFile } from 'node:child_process'
24
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
25
+ import { dirname, join } from 'node:path'
26
+ import { dshHome } from './dsh-home.ts'
27
+
28
+ /**
29
+ * The spawned child as its tunnel handle exposes it (node's `ChildProcess`
30
+ * fits: `pid` plus the argv it was spawned with).
31
+ */
32
+ export interface TunnelChildProcess {
33
+ /** The child's pid. */
34
+ pid?: number
35
+ /** The argv the child was spawned with, executable first. */
36
+ spawnargs?: readonly string[]
37
+ }
38
+
39
+ /** What the plugin records about one child it spawned. */
40
+ export interface TunnelChildRecord {
41
+ /** The child's pid. */
42
+ pid: number
43
+ /**
44
+ * The child's full argv joined with single spaces — the same line `ps`
45
+ * prints. Anything else (a wrapper, a rewritten command) is a mismatch.
46
+ */
47
+ command: string
48
+ /** The host process that spawned the child; a live owner keeps it. */
49
+ ownerPid: number
50
+ /** ISO timestamp of the recording (diagnostics only). */
51
+ recordedAt: string
52
+ }
53
+
54
+ /** How one recorded leftover was settled. */
55
+ export type TunnelOrphanVerdict =
56
+ /** There was no usable record. */
57
+ | 'none'
58
+ /** The record did not identify a live child this plugin spawned: only the file was dropped. */
59
+ | 'stale'
60
+ /** The recorded child still belongs to a running host: it was left alone. */
61
+ | 'owned'
62
+ /** The recorded orphan was signalled away and the record dropped. */
63
+ | 'reaped'
64
+
65
+ /** Injectable seams of the reaper (defaults read the real process table). */
66
+ export interface TunnelOrphanSeams {
67
+ /** Whether a pid is still alive. */
68
+ alive?: (pid: number) => boolean
69
+ /** Read a pid's exact command line, or undefined when it cannot be read. */
70
+ command?: (pid: number) => Promise<string | undefined>
71
+ /** Signal one recorded pid (never a pattern). */
72
+ signal?: (pid: number, signal: NodeJS.Signals) => void
73
+ /** Bounded wait between liveness polls. */
74
+ wait?: (ms: number) => Promise<void>
75
+ /** How long the signalled child gets to honour SIGTERM before SIGKILL. */
76
+ graceMs?: number
77
+ }
78
+
79
+ /** The crash-recovery face the tunnel manager drives. */
80
+ export interface TunnelChildGuard {
81
+ /** Reap the leftover child a crashed host recorded; resolves once settled. */
82
+ reap(): Promise<TunnelOrphanVerdict>
83
+ /**
84
+ * Record a freshly spawned child so the next host start can reap it.
85
+ * @returns whether a record was written (a handle without its OS process, or
86
+ * an unwritable home, writes nothing and must not clear a sibling's record).
87
+ */
88
+ record(child: TunnelChildProcess | undefined): boolean
89
+ /** Drop the record: the child is stopped, so nothing is left to reap. */
90
+ clear(): void
91
+ }
92
+
93
+ /** How long an orphan gets to honour SIGTERM before it is killed. */
94
+ export const DEFAULT_ORPHAN_GRACE_MS = 3_000
95
+
96
+ /** Liveness poll interval while that grace elapses. */
97
+ const ORPHAN_POLL_STEP_MS = 100
98
+
99
+ /** The record file this plugin owns: `$DSH_HOME/remote-web-ui-tunnel-child.json`. */
100
+ export function tunnelChildRecordFile(home: string = dshHome()): string {
101
+ return join(home, 'remote-web-ui-tunnel-child.json')
102
+ }
103
+
104
+ /**
105
+ * Read one record, ignoring a file that cannot identify a child (`pid` and
106
+ * `command` absent or malformed): only a well-formed record may ever lead to a
107
+ * signal.
108
+ * @param file - the record file.
109
+ * @returns the record, or undefined when there is none to trust.
110
+ */
111
+ export function readTunnelChildRecord(file: string): TunnelChildRecord | undefined {
112
+ try {
113
+ if (!existsSync(file)) return undefined
114
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<TunnelChildRecord>
115
+ if (typeof parsed.pid !== 'number' || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return undefined
116
+ if (typeof parsed.command !== 'string' || parsed.command === '') return undefined
117
+ // A record without a live-owner pid cannot be told apart from one a
118
+ // running host still owns, so it is not trusted with a signal.
119
+ if (typeof parsed.ownerPid !== 'number' || !Number.isInteger(parsed.ownerPid) || parsed.ownerPid <= 0) return undefined
120
+ return {
121
+ pid: parsed.pid,
122
+ command: parsed.command,
123
+ ownerPid: parsed.ownerPid,
124
+ recordedAt: typeof parsed.recordedAt === 'string' ? parsed.recordedAt : '',
125
+ }
126
+ } catch {
127
+ return undefined
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Write one record owner-only, creating the DSH home when it is missing.
133
+ * @param file - the record file.
134
+ * @param record - what to record about the spawned child.
135
+ */
136
+ export function recordTunnelChild(file: string, record: TunnelChildRecord): void {
137
+ mkdirSync(dirname(file), { recursive: true })
138
+ writeFileSync(file, JSON.stringify(record, null, 2) + '\n', { mode: 0o600 })
139
+ }
140
+
141
+ /** Drop one record; an absent file is not an error. */
142
+ export function clearTunnelChildRecord(file: string): void {
143
+ rmSync(file, { force: true })
144
+ }
145
+
146
+ /**
147
+ * Whether a pid is still in the process table. `EPERM` means the process
148
+ * exists but belongs to another user, which still counts as alive.
149
+ * @param pid - the pid to probe.
150
+ * @returns whether the pid exists.
151
+ */
152
+ export function processAlive(pid: number): boolean {
153
+ // pid 0 and negative pids address process groups; this reaper only ever
154
+ // probes one recorded pid.
155
+ if (!Number.isInteger(pid) || pid <= 0) return false
156
+ try {
157
+ process.kill(pid, 0)
158
+ return true
159
+ } catch (error) {
160
+ return (error as NodeJS.ErrnoException).code === 'EPERM'
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Read one pid's exact command line: `/proc/<pid>/cmdline` on Linux,
166
+ * `ps -ww -o command=` elsewhere. Arguments are joined with single spaces in
167
+ * both cases, which is exactly how a recorded argv is stored.
168
+ * @param pid - the pid to read.
169
+ * @returns the command line, or undefined when it cannot be read.
170
+ */
171
+ export async function processCommandLine(pid: number): Promise<string | undefined> {
172
+ if (process.platform === 'linux') {
173
+ try {
174
+ return parseProcCommandLine(readFileSync(`/proc/${String(pid)}/cmdline`, 'utf8'))
175
+ } catch {
176
+ return undefined
177
+ }
178
+ }
179
+ return await psCommandLine(pid)
180
+ }
181
+
182
+ /**
183
+ * Turn one `/proc/<pid>/cmdline` read (argv, NUL-separated, usually with a
184
+ * trailing NUL) into the line `ps` prints, so both platforms compare against
185
+ * the same recorded shape.
186
+ * @param raw - the raw `/proc/<pid>/cmdline` text.
187
+ * @returns the joined command line, or undefined for an empty file.
188
+ */
189
+ export function parseProcCommandLine(raw: string): string | undefined {
190
+ const argv = raw.split('\0').filter(part => part !== '')
191
+ return argv.length === 0 ? undefined : argv.join(' ')
192
+ }
193
+
194
+ /** The `ps` fallback (unlimited width, so a long cloudflared line is not cut). */
195
+ function psCommandLine(pid: number): Promise<string | undefined> {
196
+ return new Promise((resolvePromise) => {
197
+ execFile('ps', ['-ww', '-p', String(pid), '-o', 'command='], { maxBuffer: 1 << 20 }, (error, stdout) => {
198
+ if (error !== null) {
199
+ resolvePromise(undefined)
200
+ return
201
+ }
202
+ const line = stdout.replace(/\s+$/, '')
203
+ resolvePromise(line === '' ? undefined : line)
204
+ })
205
+ })
206
+ }
207
+
208
+ /** Signal one recorded pid, ignoring a child that is already gone. */
209
+ function nodeSignal(pid: number, signal: NodeJS.Signals): void {
210
+ try {
211
+ process.kill(pid, signal)
212
+ } catch {
213
+ // The child left between the liveness probe and the signal.
214
+ }
215
+ }
216
+
217
+ /** Node timers. */
218
+ function nodeWait(ms: number): Promise<void> {
219
+ return new Promise((resolvePromise) => { setTimeout(resolvePromise, ms) })
220
+ }
221
+
222
+ /**
223
+ * Wait up to `graceMs` for a signalled pid to disappear, polling so a child
224
+ * that exits at once does not cost the whole grace.
225
+ * @returns whether the pid is gone.
226
+ */
227
+ async function waitForGone(
228
+ pid: number,
229
+ alive: (pid: number) => boolean,
230
+ wait: (ms: number) => Promise<void>,
231
+ graceMs: number,
232
+ ): Promise<boolean> {
233
+ if (graceMs <= 0) return !alive(pid)
234
+ const step = Math.min(ORPHAN_POLL_STEP_MS, graceMs)
235
+ for (let elapsed = 0; elapsed < graceMs; elapsed += step) {
236
+ if (!alive(pid)) return true
237
+ await wait(step)
238
+ }
239
+ return !alive(pid)
240
+ }
241
+
242
+ /**
243
+ * Settle one recorded leftover: reap exactly the recorded child when it is
244
+ * still the process that record describes, and leave every other process
245
+ * strictly alone.
246
+ * @param file - the record file.
247
+ * @param seams - process-table and signal seams (defaults read the real table).
248
+ * @returns which way the record was settled.
249
+ */
250
+ export async function reapRecordedTunnelChild(
251
+ file: string,
252
+ seams: TunnelOrphanSeams = {},
253
+ ): Promise<TunnelOrphanVerdict> {
254
+ const record = readTunnelChildRecord(file)
255
+ if (record === undefined) {
256
+ clearTunnelChildRecord(file)
257
+ return 'none'
258
+ }
259
+ const alive = seams.alive ?? processAlive
260
+ const command = seams.command ?? processCommandLine
261
+ if (!alive(record.pid) || (await command(record.pid)) !== record.command) {
262
+ // Gone, unreadable, or the pid now carries a different command: the
263
+ // record does not identify a child this plugin spawned, so the process is
264
+ // not touched and only the record is dropped.
265
+ clearTunnelChildRecord(file)
266
+ return 'stale'
267
+ }
268
+ if (record.ownerPid === process.pid || alive(record.ownerPid)) return 'owned'
269
+ const signal = seams.signal ?? nodeSignal
270
+ const wait = seams.wait ?? nodeWait
271
+ const graceMs = seams.graceMs ?? DEFAULT_ORPHAN_GRACE_MS
272
+ signal(record.pid, 'SIGTERM')
273
+ if (!(await waitForGone(record.pid, alive, wait, graceMs))) signal(record.pid, 'SIGKILL')
274
+ clearTunnelChildRecord(file)
275
+ return 'reaped'
276
+ }
277
+
278
+ /** Seams of the file-backed guard (the record file defaults to the DSH home). */
279
+ export interface TunnelChildGuardOptions extends TunnelOrphanSeams {
280
+ /** The record file; resolved per call so a changed DSH home is honoured. */
281
+ file?: string
282
+ }
283
+
284
+ /**
285
+ * Build the file-backed crash-recovery guard the tunnel manager uses: the
286
+ * record lives at {@link tunnelChildRecordFile} unless a file is given.
287
+ * @param options - record file and process seams (all optional).
288
+ * @returns the guard.
289
+ */
290
+ export function createTunnelChildGuard(options: TunnelChildGuardOptions = {}): TunnelChildGuard {
291
+ const file = (): string => options.file ?? tunnelChildRecordFile()
292
+ return {
293
+ async reap(): Promise<TunnelOrphanVerdict> {
294
+ return await reapRecordedTunnelChild(file(), options)
295
+ },
296
+ record(child: TunnelChildProcess | undefined): boolean {
297
+ const pid = child?.pid
298
+ const argv = child?.spawnargs
299
+ // A handle that does not expose its OS process (test fakes, a future
300
+ // package shape) has nothing to record; that is not an error.
301
+ if (pid === undefined || argv === undefined || argv.length === 0) return false
302
+ try {
303
+ recordTunnelChild(file(), {
304
+ pid,
305
+ command: argv.join(' '),
306
+ ownerPid: process.pid,
307
+ recordedAt: new Date().toISOString(),
308
+ })
309
+ return true
310
+ } catch (error) {
311
+ // The record is crash recovery only: an unwritable DSH home must never
312
+ // fail the tunnel that is already running.
313
+ console.warn(`remote-bridge: could not record the tunnel child (${error instanceof Error ? error.message : String(error)})`)
314
+ return false
315
+ }
316
+ },
317
+ clear(): void {
318
+ try {
319
+ clearTunnelChildRecord(file())
320
+ } catch {
321
+ // Best effort: a stale record is harmless, it is validated on read.
322
+ }
323
+ },
324
+ }
325
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Pure planner for the settings-sync tunnel branch: given the resolved
3
+ * settings slice, decide which tunnel mode runs and with what target. Kept
4
+ * free of cordis types so the precedence matrix is unit-testable without a
5
+ * host context.
6
+ */
7
+
8
+ /** Whether a configured public base is a parseable http(s) URL with a host. */
9
+ export function isHttpUrl(value: string): boolean {
10
+ try {
11
+ const url = new URL(value)
12
+ return (url.protocol === 'http:' || url.protocol === 'https:') && url.hostname !== ''
13
+ } catch {
14
+ return false
15
+ }
16
+ }
17
+
18
+ /** How the settings sync should drive the tunnel for one resolved value. */
19
+ export type TunnelPlan =
20
+ | { mode: 'off' }
21
+ | { mode: 'quick'; targetUrl: string; ignored: Array<'tunnelToken' | 'publicBaseUrl'> }
22
+ | { mode: 'named'; token: string; publicUrl: string }
23
+
24
+ /**
25
+ * Decide the tunnel mode and target from one resolved settings value.
26
+ * Precedence: the quick tunnel wins when `autoTunnel` is on (anything else
27
+ * configured is reported as ignored); the named tunnel runs only with a
28
+ * token AND a valid public hostname (the token does not carry the hostname,
29
+ * so the plan would have no public URL to report without it); otherwise no
30
+ * tunnel and the manual public base applies.
31
+ *
32
+ * The quick target URL names the local webServer port, so a plan made before
33
+ * the listener binds cannot be quick: it comes back `off` and the caller —
34
+ * which can observe the port settle — re-plans. The planner itself never
35
+ * emits an `http://127.0.0.1:undefined` target.
36
+ * @param value - the resolved settings slice that drives the tunnel.
37
+ * @param port - the local webServer port the tunnel forwards to (undefined
38
+ * before the listener binds).
39
+ */
40
+ export function tunnelPlanOf(
41
+ value: { autoTunnel?: boolean; tunnelToken?: string; publicBaseUrl?: string },
42
+ port: number | undefined,
43
+ ): TunnelPlan {
44
+ if (value.autoTunnel === true) {
45
+ if (port === undefined) return { mode: 'off' }
46
+ const ignored: Array<'tunnelToken' | 'publicBaseUrl'> = []
47
+ if (value.tunnelToken !== undefined && value.tunnelToken !== '') ignored.push('tunnelToken')
48
+ if (value.publicBaseUrl !== undefined && value.publicBaseUrl !== '') ignored.push('publicBaseUrl')
49
+ return { mode: 'quick', targetUrl: `http://127.0.0.1:${String(port)}`, ignored }
50
+ }
51
+ if (value.tunnelToken !== undefined && value.tunnelToken !== '') {
52
+ if (value.publicBaseUrl !== undefined && isHttpUrl(value.publicBaseUrl)) {
53
+ return { mode: 'named', token: value.tunnelToken, publicUrl: value.publicBaseUrl }
54
+ }
55
+ return { mode: 'off' }
56
+ }
57
+ return { mode: 'off' }
58
+ }