@linxin666/dsh-remote-bridge 0.4.11 → 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 (61) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +47 -10
  3. package/README.zh.md +47 -10
  4. package/lib/client.js +1 -1
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18238 -416
  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 +3 -1
  12. package/lib/types/core/push.d.ts +51 -2
  13. package/lib/types/core/turn-end-quiet.d.ts +104 -40
  14. package/lib/types/host/firewall.d.ts +74 -0
  15. package/lib/types/host/host-bind-capability.d.ts +90 -0
  16. package/lib/types/host/ingress-gate.d.ts +59 -0
  17. package/lib/types/host/ingress-sync.d.ts +429 -0
  18. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  19. package/lib/types/host/lan-bind.d.ts +106 -0
  20. package/lib/types/host/lan-forward.d.ts +112 -0
  21. package/lib/types/host/lan.d.ts +61 -0
  22. package/lib/types/host/pair-origin.d.ts +34 -19
  23. package/lib/types/host/relay-bridge-connector.d.ts +215 -0
  24. package/lib/types/host/relay-connector.d.ts +152 -0
  25. package/lib/types/host/relay-control.d.ts +124 -0
  26. package/lib/types/host/relay-registry.d.ts +114 -0
  27. package/lib/types/host/relay.d.ts +170 -0
  28. package/lib/types/host/routes.d.ts +24 -1
  29. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  30. package/lib/types/host/tunnel-plan.d.ts +41 -0
  31. package/lib/types/host/tunnel.d.ts +289 -0
  32. package/lib/types/index.d.ts +440 -11
  33. package/package.json +4 -2
  34. package/src/client/panel.module.css +16 -1
  35. package/src/core/connection.ts +244 -13
  36. package/src/core/devices.ts +31 -6
  37. package/src/core/hub.ts +17 -5
  38. package/src/core/liveactivity.ts +16 -2
  39. package/src/core/model-efforts.ts +223 -0
  40. package/src/core/protocol.ts +4 -1
  41. package/src/core/push.ts +70 -4
  42. package/src/core/turn-end-quiet.ts +281 -98
  43. package/src/host/firewall.ts +230 -0
  44. package/src/host/host-bind-capability.ts +249 -0
  45. package/src/host/ingress-gate.ts +203 -0
  46. package/src/host/ingress-sync.ts +1074 -0
  47. package/src/host/lan-bind-plan.ts +134 -0
  48. package/src/host/lan-bind.ts +250 -0
  49. package/src/host/lan-forward.ts +321 -0
  50. package/src/host/lan.ts +142 -0
  51. package/src/host/pair-origin.ts +44 -38
  52. package/src/host/relay-bridge-connector.ts +783 -0
  53. package/src/host/relay-connector.ts +317 -0
  54. package/src/host/relay-control.ts +224 -0
  55. package/src/host/relay-registry.ts +263 -0
  56. package/src/host/relay.ts +294 -0
  57. package/src/host/routes.ts +47 -3
  58. package/src/host/tunnel-orphan.ts +325 -0
  59. package/src/host/tunnel-plan.ts +58 -0
  60. package/src/host/tunnel.ts +688 -0
  61. package/src/index.ts +1303 -39
@@ -0,0 +1,783 @@
1
+ /**
2
+ * The bridge connector: the plugin side of the relay bridge, grown from the
3
+ * shadow-flight probe (`probe/relay-bridge/connector.mjs`).
4
+ *
5
+ * It dials the instance's Durable Object meeting point over WSS and serves
6
+ * every stream the object multiplexes onto that one socket -- HTTP requests
7
+ * with streamed bodies and responses, and the phone's own WebSocket upgrades.
8
+ *
9
+ * Three rules are not negotiable here:
10
+ *
11
+ * 1. The credential is the relay identity's own long-lived id and secret, sent
12
+ * in the upgrade's `authorization` header so it never appears in a URL. A
13
+ * dropped socket is re-dialed with the same credential; the object replaces
14
+ * the socket it already holds, so a reconnect needs no new ticket and no
15
+ * new instance.
16
+ * 2. The connector serves exactly one inbound path, the protocol's `WS_PATH`.
17
+ * Any other HTTP request is answered 404 by the connector itself, any other
18
+ * upgrade is refused the same way, and neither ever dials upstream. That
19
+ * whitelist -- not any header -- is what keeps the host's control plane off
20
+ * the public origin.
21
+ * 3. The connector forwards the public origin the phone dialed and never
22
+ * invents the authority it dials. The object reads the origin from the
23
+ * request URL and puts it in the frame; the fallback is this instance's
24
+ * claimed relay hostname. The loopback `Host` is stamped exactly once, and
25
+ * not here: the upstream this connector dials is the ingress gate, whose
26
+ * whole job is to rewrite the `Host` to the loopback authority and to serve
27
+ * nothing but `WS_PATH`. So the gate is the single place the rewrite
28
+ * happens, and rule 2 is the reason that rewrite cannot expose anything
29
+ * beyond the protocol's own route.
30
+ *
31
+ * Frames mirror `market/worker/src/relay-bridge.js`: control frames are JSON
32
+ * text, payload frames are `[kind:u8][streamId:u32be][payload]`.
33
+ */
34
+
35
+ import { randomBytes } from 'node:crypto'
36
+ import { mkdirSync, renameSync, writeFileSync } from 'node:fs'
37
+ import http from 'node:http'
38
+ import https from 'node:https'
39
+ import { dirname, join } from 'node:path'
40
+ import { WS_PATH } from '../core/protocol.ts'
41
+ import { dshHome } from './dsh-home.ts'
42
+ import type { RelayBridgeStart } from './relay-connector.ts'
43
+
44
+ /** The upgrade carries the lease secret here, never in the URL. */
45
+ export const BRIDGE_AUTH_HEADER = 'authorization'
46
+ /** Response frames this connector will not forward upstream. */
47
+ export const BRIDGE_HOP_BY_HOP = new Set([
48
+ 'host',
49
+ 'connection',
50
+ 'keep-alive',
51
+ 'transfer-encoding',
52
+ 'upgrade',
53
+ 'sec-websocket-key',
54
+ 'sec-websocket-version',
55
+ 'sec-websocket-extensions',
56
+ 'sec-websocket-accept',
57
+ 'cf-connecting-ip',
58
+ 'cf-ipcountry',
59
+ 'cf-visitor',
60
+ 'cf-ray',
61
+ 'cf-ipcity',
62
+ 'x-forwarded-for',
63
+ 'x-forwarded-proto',
64
+ 'x-real-ip',
65
+ ])
66
+
67
+ const HTTP_BODY = 1
68
+ const WS_BINARY = 2
69
+ const WS_TEXT = 3
70
+
71
+ /** Where a dropped socket restarts: fast first, then patient. */
72
+ export const BRIDGE_RETRY_BASE_MS = 1_000
73
+ export const BRIDGE_RETRY_MAX_MS = 30_000
74
+
75
+ /** The body every refused inbound stream is answered with. */
76
+ export const BRIDGE_NOT_FOUND_BODY = '{"error":"not-found"}'
77
+
78
+ /**
79
+ * Whether one bridged stream may reach the upstream at all.
80
+ *
81
+ * Only the protocol's own upgrade path is served. The comparison is on the
82
+ * path, not the whole URL, because the pairing link carries its one-shot
83
+ * ticket in the query (`WS_PATH?token=...`); everything else — another path,
84
+ * a path that merely starts the same way, an empty URL — is refused.
85
+ * @param url - the `url` one bridged frame names.
86
+ * @returns true when the path is exactly `WS_PATH`.
87
+ */
88
+ export function isBridgeInboundPath(url: string): boolean {
89
+ const query = url.indexOf('?')
90
+ return (query === -1 ? url : url.slice(0, query)) === WS_PATH
91
+ }
92
+
93
+ /** One header pair as the frame contract carries it. */
94
+ export type BridgeHeaderPairs = ReadonlyArray<readonly [string, string]>
95
+
96
+ function headerPairs(raw: unknown): Array<[string, string]> {
97
+ const pairs: Array<[string, string]> = []
98
+ if (!Array.isArray(raw)) return pairs
99
+ for (const entry of raw) {
100
+ if (!Array.isArray(entry) || entry.length !== 2) continue
101
+ const [name, value] = entry as [unknown, unknown]
102
+ if (typeof name !== 'string' || typeof value !== 'string') continue
103
+ pairs.push([name, value])
104
+ }
105
+ return pairs
106
+ }
107
+
108
+ /** The upgrade URL one instance dials (the id is not a secret). */
109
+ export function relayBridgeDialUrl(endpoint: string, id: string): string {
110
+ const url = new URL(endpoint)
111
+ url.searchParams.set('id', id)
112
+ return url.href
113
+ }
114
+
115
+ /**
116
+ * The `Host` one bridged request travels with.
117
+ * @param frameHost - the public origin the object read from the request URL.
118
+ * @param hostname - this instance's claimed relay hostname.
119
+ * @returns a public origin, never the upstream authority this connector dials.
120
+ */
121
+ export function bridgeUpstreamHost(frameHost: unknown, hostname: string): string {
122
+ if (typeof frameHost === 'string' && frameHost !== '') return frameHost
123
+ return hostname
124
+ }
125
+
126
+ /**
127
+ * The upstream headers of one bridged request: the phone's own, minus the hops
128
+ * this transport owns, with the public `Host` put back explicitly.
129
+ */
130
+ export function bridgeUpstreamHeaders(frameHeaders: unknown, host: string): Record<string, string> {
131
+ const headers: Record<string, string> = {}
132
+ for (const [name, value] of headerPairs(frameHeaders)) {
133
+ if (BRIDGE_HOP_BY_HOP.has(name.toLowerCase())) continue
134
+ headers[name] = value
135
+ }
136
+ headers.host = host
137
+ return headers
138
+ }
139
+
140
+ /** The headers of the bridge socket's own upgrade. */
141
+ export function bridgeUpgradeHeaders(endpoint: string, secret: string): Record<string, string> {
142
+ return {
143
+ host: new URL(endpoint).host,
144
+ connection: 'Upgrade',
145
+ upgrade: 'websocket',
146
+ 'sec-websocket-key': randomBytes(16).toString('base64'),
147
+ 'sec-websocket-version': '13',
148
+ [BRIDGE_AUTH_HEADER]: 'Bearer ' + secret,
149
+ }
150
+ }
151
+
152
+ function encodeChunk(kind: number, id: number, payload: Uint8Array): Uint8Array {
153
+ const bytes = new Uint8Array(5 + payload.byteLength)
154
+ bytes[0] = kind
155
+ new DataView(bytes.buffer).setUint32(1, id >>> 0)
156
+ bytes.set(payload, 5)
157
+ return bytes
158
+ }
159
+
160
+ function decodeChunk(data: Uint8Array): { kind: number; id: number; payload: Uint8Array } | undefined {
161
+ if (data.byteLength < 5) return undefined
162
+ return {
163
+ kind: data[0],
164
+ id: new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(1),
165
+ payload: data.subarray(5),
166
+ }
167
+ }
168
+
169
+ /** One client frame, masked as RFC 6455 requires of the dialing side. */
170
+ export function encodeBridgeFrame(opcode: number, payload: Uint8Array): Uint8Array {
171
+ const length = payload.byteLength
172
+ const head = length < 126 ? 6 : length < 65_536 ? 8 : 14
173
+ const bytes = new Uint8Array(head + length)
174
+ bytes[0] = 0x80 | opcode
175
+ if (length < 126) {
176
+ bytes[1] = 0x80 | length
177
+ } else if (length < 65_536) {
178
+ bytes[1] = 0x80 | 126
179
+ bytes[2] = (length >>> 8) & 0xff
180
+ bytes[3] = length & 0xff
181
+ } else {
182
+ bytes[1] = 0x80 | 127
183
+ new DataView(bytes.buffer).setUint32(2, 0)
184
+ new DataView(bytes.buffer).setUint32(6, length)
185
+ }
186
+ const mask = randomBytes(4)
187
+ bytes.set(mask, head - 4)
188
+ for (let index = 0; index < length; index += 1) bytes[head + index] = payload[index] ^ mask[index % 4]
189
+ return bytes
190
+ }
191
+
192
+ /** One frame of a WebSocket the connector dialed. */
193
+ export interface BridgeFrame {
194
+ opcode: number
195
+ payload: Buffer
196
+ }
197
+
198
+ /**
199
+ * A frame reader for the connector's own client side, reassembling fragmented
200
+ * messages and unmasking nothing: only servers send unmasked frames here.
201
+ */
202
+ export function createBridgeFrameParser(onFrame: (frame: BridgeFrame) => void): (incoming: Buffer) => void {
203
+ let buffer: Buffer = Buffer.alloc(0)
204
+ let continuation: Buffer | null = null
205
+ let continuationOpcode = 0x1
206
+ return (incoming: Buffer): void => {
207
+ buffer = buffer.length === 0 ? incoming : Buffer.concat([buffer, incoming])
208
+ for (;;) {
209
+ if (buffer.length < 2) return
210
+ const fin = (buffer[0] & 0x80) !== 0
211
+ const opcode = buffer[0] & 0x0f
212
+ const masked = (buffer[1] & 0x80) !== 0
213
+ let length = buffer[1] & 0x7f
214
+ let offset = 2
215
+ if (length === 126) {
216
+ if (buffer.length < 4) return
217
+ length = buffer.readUInt16BE(2)
218
+ offset = 4
219
+ } else if (length === 127) {
220
+ if (buffer.length < 10) return
221
+ length = Number(buffer.readBigUInt64BE(2))
222
+ offset = 10
223
+ }
224
+ const maskAt = offset
225
+ if (masked) offset += 4
226
+ if (buffer.length < offset + length) return
227
+ let payload = Buffer.from(buffer.subarray(offset, offset + length))
228
+ if (masked) {
229
+ const mask = buffer.subarray(maskAt, maskAt + 4)
230
+ for (let index = 0; index < payload.length; index += 1) payload[index] ^= mask[index % 4]
231
+ }
232
+ buffer = buffer.subarray(offset + length)
233
+ if (opcode === 0x0) {
234
+ continuation = continuation === null ? payload : Buffer.concat([continuation, payload])
235
+ if (!fin) continue
236
+ onFrame({ opcode: continuationOpcode, payload: continuation })
237
+ continuation = null
238
+ continue
239
+ }
240
+ if ((opcode === 0x1 || opcode === 0x2) && !fin) {
241
+ continuation = payload
242
+ continuationOpcode = opcode
243
+ continue
244
+ }
245
+ onFrame({ opcode, payload })
246
+ }
247
+ }
248
+ }
249
+
250
+ /** The connector's observable state (logged, and read by the tests). */
251
+ export type RelayBridgeState =
252
+ | { state: 'idle' }
253
+ | { state: 'dialing' }
254
+ | { state: 'connected'; instance: string }
255
+ | { state: 'failed'; error: string }
256
+
257
+ /**
258
+ * What the connector records on disk: its state plus the lease it dials.
259
+ * The Desktop host runs this plugin in a process whose stdout nobody reads, so
260
+ * without this record a connector that never attached (or a lease that never
261
+ * claimed) leaves no trace at all.
262
+ */
263
+ export interface RelayBridgeStateRecord {
264
+ state: RelayBridgeState['state']
265
+ instance: string
266
+ hostname: string
267
+ endpoint: string
268
+ upstream: string
269
+ /** When the record was written (ISO 8601). */
270
+ at: string
271
+ /** The dial failure, for a `failed` record. */
272
+ error?: string
273
+ }
274
+
275
+ /** Where the connector records its state (`$DSH_HOME/remote-web-ui-relay-bridge.json`). */
276
+ export function relayBridgeStateFile(home: string = dshHome()): string {
277
+ return join(home, 'remote-web-ui-relay-bridge.json')
278
+ }
279
+
280
+ /**
281
+ * Record one connector state. Best effort on purpose: a home that cannot be
282
+ * written must never take the socket down with it.
283
+ * @param file - the record path (see `relayBridgeStateFile`).
284
+ * @param record - the state and the lease it belongs to.
285
+ */
286
+ export function writeRelayBridgeState(file: string, record: RelayBridgeStateRecord): void {
287
+ try {
288
+ mkdirSync(dirname(file), { recursive: true })
289
+ const staged = file + '.tmp'
290
+ writeFileSync(staged, JSON.stringify(record, null, 2) + '\n', { mode: 0o600 })
291
+ renameSync(staged, file)
292
+ } catch {
293
+ // A record that cannot land is not worth a broken connector.
294
+ }
295
+ }
296
+
297
+ /** Everything one bridge connector needs to run. */
298
+ export interface RelayBridgeConnectorOptions {
299
+ /** The upgrade endpoint the claim reported. */
300
+ endpoint: string
301
+ /** The relay identity id. */
302
+ id: string
303
+ /** The relay identity secret (the same long-lived credential). */
304
+ secret: string
305
+ /** This instance's relay hostname, the fallback public origin. */
306
+ hostname: string
307
+ /** The local origin the connector serves, `http://127.0.0.1:<port>`. */
308
+ upstream: string
309
+ baseDelayMs?: number
310
+ maxDelayMs?: number
311
+ /** Schedule one retry; defaults to an unref'd node timer. */
312
+ timerFn?: (fn: () => void, ms: number) => { unref?: () => void }
313
+ onState?: (state: RelayBridgeState) => void
314
+ }
315
+
316
+ /** One upstream WebSocket the connector dialed for a phone. */
317
+ interface BridgePeer {
318
+ socket: import('node:net').Socket
319
+ closed: boolean
320
+ close: (code: number, reason: string) => void
321
+ text: (body: string) => void
322
+ binary: (body: Buffer) => void
323
+ }
324
+
325
+ /**
326
+ * The connector itself: one socket to the object, one upstream request or
327
+ * WebSocket per stream id, and a reconnect that keeps the same credential.
328
+ */
329
+ export class RelayBridgeConnector {
330
+ private socket: import('node:net').Socket | undefined
331
+ private parser: ((incoming: Buffer) => void) | undefined
332
+ private timer: { unref?: () => void } | undefined
333
+ private stateValue: RelayBridgeState = { state: 'idle' }
334
+ private attempts = 0
335
+ private disposed = false
336
+ private readonly requests = new Map<number, http.ClientRequest>()
337
+ private readonly peers = new Map<number, BridgePeer>()
338
+
339
+ private readonly options: RelayBridgeConnectorOptions
340
+
341
+ constructor(options: RelayBridgeConnectorOptions) {
342
+ this.options = options
343
+ }
344
+
345
+ /** The connector's current state. */
346
+ get state(): RelayBridgeState {
347
+ return this.stateValue
348
+ }
349
+
350
+ /** Whether a bridge socket is attached right now. */
351
+ get connected(): boolean {
352
+ return this.socket !== undefined
353
+ }
354
+
355
+ /** Dial the object (or schedule the next attempt if the dial fails). */
356
+ start(): void {
357
+ if (this.disposed) return
358
+ this.clearTimer()
359
+ this.teardown()
360
+ this.setState({ state: 'dialing' })
361
+ this.dial()
362
+ }
363
+
364
+ /** Close the socket and stop retrying (the relay half was disposed). */
365
+ stop(): void {
366
+ this.disposed = true
367
+ this.clearTimer()
368
+ this.teardown()
369
+ this.setState({ state: 'idle' })
370
+ }
371
+
372
+ private dial(): void {
373
+ const { endpoint, id, secret } = this.options
374
+ const url = relayBridgeDialUrl(endpoint, id)
375
+ const target = new URL(url)
376
+ const transport = target.protocol === 'wss:' ? https : http
377
+ const request = transport.request({
378
+ host: target.hostname,
379
+ port: target.port === '' ? (target.protocol === 'wss:' ? 443 : 80) : Number(target.port),
380
+ path: target.pathname + target.search,
381
+ method: 'GET',
382
+ headers: bridgeUpgradeHeaders(endpoint, secret),
383
+ })
384
+ request.on('upgrade', (response: http.IncomingMessage, socket: import('node:net').Socket, head: Buffer) => {
385
+ if (response.statusCode !== 101) {
386
+ socket.destroy()
387
+ this.fail('upgrade answered ' + String(response.statusCode))
388
+ return
389
+ }
390
+ this.attach(socket, head)
391
+ })
392
+ request.on('response', (response: http.IncomingMessage) => {
393
+ response.resume()
394
+ this.fail('refused with ' + String(response.statusCode))
395
+ })
396
+ request.on('error', (error: Error) => { this.fail(error.message) })
397
+ request.end()
398
+ }
399
+
400
+ private attach(socket: import('node:net').Socket, head: Buffer): void {
401
+ this.socket = socket
402
+ this.attempts = 0
403
+ this.parser = createBridgeFrameParser((frame) => { this.onBridgeFrame(frame) })
404
+ socket.on('data', (incoming: Buffer) => { this.parser?.(incoming) })
405
+ socket.on('error', () => undefined)
406
+ socket.on('close', () => {
407
+ if (this.socket !== socket) return
408
+ this.socket = undefined
409
+ this.teardown()
410
+ this.fail('socket closed')
411
+ })
412
+ if (head.length > 0) this.parser(head)
413
+ this.setState({ state: 'connected', instance: this.options.id })
414
+ }
415
+
416
+ /** Send one control frame: a text frame, which is how the object tells a
417
+ * control frame from a payload chunk. */
418
+ private sendText(text: string): void {
419
+ this.write(0x1, Buffer.from(text))
420
+ }
421
+
422
+ /** Send one payload frame: a binary frame carrying a chunk. */
423
+ private sendChunk(bytes: Uint8Array): void {
424
+ this.write(0x2, Buffer.from(bytes))
425
+ }
426
+
427
+ private write(opcode: number, body: Buffer): void {
428
+ const socket = this.socket
429
+ if (socket === undefined || socket.destroyed) return
430
+ socket.write(encodeBridgeFrame(opcode, body))
431
+ }
432
+
433
+ private onBridgeFrame(frame: BridgeFrame): void {
434
+ if (frame.opcode === 0x8) {
435
+ this.socket?.destroy()
436
+ return
437
+ }
438
+ if (frame.opcode === 0x9) {
439
+ this.socket?.write(encodeBridgeFrame(0xa, frame.payload))
440
+ return
441
+ }
442
+ if (frame.opcode === 0x1) {
443
+ this.onControl(frame.payload.toString('utf8'))
444
+ return
445
+ }
446
+ if (frame.opcode !== 0x2) return
447
+ const chunk = decodeChunk(frame.payload)
448
+ if (chunk === undefined) return
449
+ if (chunk.kind === HTTP_BODY) {
450
+ this.requests.get(chunk.id)?.write(Buffer.from(chunk.payload))
451
+ return
452
+ }
453
+ const peer = this.peers.get(chunk.id)
454
+ if (peer === undefined) return
455
+ if (chunk.kind === WS_TEXT) peer.text(Buffer.from(chunk.payload).toString('utf8'))
456
+ if (chunk.kind === WS_BINARY) peer.binary(Buffer.from(chunk.payload))
457
+ }
458
+
459
+ private onControl(raw: string): void {
460
+ let frame: Record<string, unknown>
461
+ try {
462
+ frame = JSON.parse(raw) as Record<string, unknown>
463
+ } catch {
464
+ return
465
+ }
466
+ const id = typeof frame.id === 'number' ? frame.id : -1
467
+ switch (frame.t) {
468
+ case 'req':
469
+ this.startHttp(id, frame)
470
+ return
471
+ case 'end':
472
+ this.requests.get(id)?.end()
473
+ return
474
+ case 'ws-open':
475
+ void this.openSocket(id, frame)
476
+ return
477
+ case 'ws-close':
478
+ this.peers.get(id)?.close(typeof frame.code === 'number' ? frame.code : 1000, String(frame.reason ?? ''))
479
+ this.peers.delete(id)
480
+ return
481
+ case 'close': {
482
+ const peer = this.peers.get(id)
483
+ if (peer !== undefined) {
484
+ this.peers.delete(id)
485
+ peer.close(1000, String(frame.reason ?? 'closed'))
486
+ return
487
+ }
488
+ const request = this.requests.get(id)
489
+ if (request !== undefined) {
490
+ this.requests.delete(id)
491
+ request.destroy()
492
+ }
493
+ return
494
+ }
495
+ default:
496
+ }
497
+ }
498
+
499
+ /**
500
+ * Answer one bridged stream with 404 without dialing anything: the refusal is
501
+ * complete here, so a non-whitelisted path costs the upstream nothing.
502
+ * @param id - the stream the object opened.
503
+ */
504
+ private refuseNotFound(id: number): void {
505
+ const body = Buffer.from(BRIDGE_NOT_FOUND_BODY)
506
+ this.sendText(JSON.stringify({
507
+ t: 'res',
508
+ id,
509
+ status: 404,
510
+ statusText: 'Not Found',
511
+ headers: [
512
+ ['content-type', 'application/json'],
513
+ ['content-length', String(body.byteLength)],
514
+ ['connection', 'close'],
515
+ ],
516
+ }))
517
+ this.sendChunk(encodeChunk(HTTP_BODY, id, body))
518
+ this.sendText(JSON.stringify({ t: 'fin', id }))
519
+ }
520
+
521
+ /** Start one upstream HTTP request for a bridged stream. */
522
+ private startHttp(id: number, frame: Record<string, unknown>): void {
523
+ const path = typeof frame.url === 'string' && frame.url !== '' ? frame.url : '/'
524
+ if (!isBridgeInboundPath(path)) {
525
+ this.refuseNotFound(id)
526
+ return
527
+ }
528
+ const upstream = new URL(this.options.upstream)
529
+ const method = typeof frame.method === 'string' ? frame.method : 'GET'
530
+ const host = bridgeUpstreamHost(frame.host, this.options.hostname)
531
+ const request = http.request({
532
+ host: upstream.hostname,
533
+ port: upstream.port === '' ? 80 : Number(upstream.port),
534
+ path,
535
+ method,
536
+ headers: bridgeUpstreamHeaders(frame.headers, host),
537
+ }, (response: http.IncomingMessage) => {
538
+ this.requests.delete(id)
539
+ this.sendText(JSON.stringify({
540
+ t: 'res',
541
+ id,
542
+ status: response.statusCode,
543
+ statusText: response.statusMessage ?? '',
544
+ headers: rawHeaderPairs(response.rawHeaders),
545
+ }))
546
+ response.on('data', (chunk: Buffer) => { this.sendChunk(encodeChunk(HTTP_BODY, id, chunk)) })
547
+ response.on('end', () => { this.sendText(JSON.stringify({ t: 'fin', id })) })
548
+ response.on('error', (error: Error) => { this.sendText(JSON.stringify({ t: 'fail', id, message: error.message })) })
549
+ })
550
+ request.on('error', (error: Error) => {
551
+ this.requests.delete(id)
552
+ this.sendText(JSON.stringify({ t: 'fail', id, message: error.message }))
553
+ })
554
+ this.requests.set(id, request)
555
+ }
556
+
557
+ /** Open one upstream WebSocket for a phone's upgrade. */
558
+ private async openSocket(id: number, frame: Record<string, unknown>): Promise<void> {
559
+ const path = typeof frame.url === 'string' && frame.url !== '' ? frame.url : '/'
560
+ if (!isBridgeInboundPath(path)) {
561
+ // The upgrade is refused with the same 404 an HTTP request gets, and no
562
+ // upstream socket exists to close: nothing was dialed on its behalf.
563
+ this.sendText(JSON.stringify({ t: 'ws-fail', id, message: '404 ' + BRIDGE_NOT_FOUND_BODY }))
564
+ return
565
+ }
566
+ const upstream = new URL(this.options.upstream)
567
+ const host = bridgeUpstreamHost(frame.host, this.options.hostname)
568
+ const headers = bridgeUpstreamHeaders(frame.headers, host)
569
+ headers.connection = 'Upgrade'
570
+ headers.upgrade = 'websocket'
571
+ headers['sec-websocket-key'] = randomBytes(16).toString('base64')
572
+ headers['sec-websocket-version'] = '13'
573
+ try {
574
+ const dialed = await new Promise<{ socket: import('node:net').Socket; head: Buffer }>((resolve, reject) => {
575
+ const request = http.request({
576
+ host: upstream.hostname,
577
+ port: upstream.port === '' ? 80 : Number(upstream.port),
578
+ path,
579
+ method: 'GET',
580
+ headers,
581
+ })
582
+ request.on('upgrade', (response: http.IncomingMessage, socket: import('node:net').Socket, head: Buffer) => {
583
+ resolve({ socket, head })
584
+ })
585
+ request.on('response', (response: http.IncomingMessage) => {
586
+ response.resume()
587
+ reject(new Error('upstream answered ' + String(response.statusCode) + ' instead of 101'))
588
+ })
589
+ request.on('error', (error: Error) => { reject(error) })
590
+ request.end()
591
+ })
592
+ this.sendText(JSON.stringify({ t: 'ws-accept', id }))
593
+ const peer: BridgePeer = {
594
+ socket: dialed.socket,
595
+ closed: false,
596
+ close: (code: number, reason: string) => {
597
+ if (peer.closed) return
598
+ peer.closed = true
599
+ const text = Buffer.from(reason)
600
+ const payload = Buffer.alloc(2 + text.length)
601
+ payload.writeUInt16BE(code, 0)
602
+ text.copy(payload, 2)
603
+ try {
604
+ dialed.socket.write(encodeBridgeFrame(0x8, payload))
605
+ } catch {
606
+ // The socket is already gone.
607
+ }
608
+ dialed.socket.destroy()
609
+ },
610
+ text: (body: string) => {
611
+ if (!peer.closed) dialed.socket.write(encodeBridgeFrame(0x1, Buffer.from(body)))
612
+ },
613
+ binary: (body: Buffer) => {
614
+ if (!peer.closed) dialed.socket.write(encodeBridgeFrame(0x2, body))
615
+ },
616
+ }
617
+ const parse = createBridgeFrameParser((incoming) => {
618
+ if (incoming.opcode === 0x1) {
619
+ this.sendChunk(encodeChunk(WS_TEXT, id, incoming.payload))
620
+ return
621
+ }
622
+ if (incoming.opcode === 0x2) {
623
+ this.sendChunk(encodeChunk(WS_BINARY, id, incoming.payload))
624
+ return
625
+ }
626
+ if (incoming.opcode === 0x8) {
627
+ const code = incoming.payload.length >= 2 ? incoming.payload.readUInt16BE(0) : 1005
628
+ const reason = incoming.payload.length > 2 ? incoming.payload.subarray(2).toString('utf8') : ''
629
+ this.peers.delete(id)
630
+ peer.closed = true
631
+ dialed.socket.destroy()
632
+ this.sendText(JSON.stringify({ t: 'ws-close', id, code, reason }))
633
+ return
634
+ }
635
+ if (incoming.opcode === 0x9) dialed.socket.write(encodeBridgeFrame(0xa, incoming.payload))
636
+ })
637
+ dialed.socket.on('data', parse)
638
+ dialed.socket.on('error', () => undefined)
639
+ dialed.socket.on('close', () => {
640
+ if (!this.peers.delete(id)) return
641
+ if (peer.closed) return
642
+ peer.closed = true
643
+ this.sendText(JSON.stringify({ t: 'ws-close', id, code: 1006, reason: 'upstream-closed' }))
644
+ })
645
+ this.peers.set(id, peer)
646
+ if (dialed.head.length > 0) parse(dialed.head)
647
+ } catch (error) {
648
+ this.sendText(JSON.stringify({ t: 'ws-fail', id, message: error instanceof Error ? error.message : String(error) }))
649
+ }
650
+ }
651
+
652
+ /** Report one failed dial and retry with the same credential. */
653
+ private fail(error: string): void {
654
+ if (this.disposed) return
655
+ this.setState({ state: 'failed', error })
656
+ this.scheduleRetry()
657
+ }
658
+
659
+ private scheduleRetry(): void {
660
+ if (this.disposed) return
661
+ const base = this.options.baseDelayMs ?? BRIDGE_RETRY_BASE_MS
662
+ const max = this.options.maxDelayMs ?? BRIDGE_RETRY_MAX_MS
663
+ const delay = Math.min(base * 2 ** this.attempts, max)
664
+ this.attempts += 1
665
+ const timerFn = this.options.timerFn ?? ((fn: () => void, ms: number) => {
666
+ const timer = setTimeout(fn, ms)
667
+ timer.unref?.()
668
+ return timer
669
+ })
670
+ this.timer = timerFn(() => {
671
+ this.timer = undefined
672
+ this.dial()
673
+ }, delay)
674
+ this.timer.unref?.()
675
+ }
676
+
677
+ private clearTimer(): void {
678
+ if (this.timer === undefined) return
679
+ clearTimeout(this.timer as unknown as NodeJS.Timeout)
680
+ this.timer = undefined
681
+ }
682
+
683
+ /** Drop every stream this socket carried: the object re-opens them. */
684
+ private teardown(): void {
685
+ for (const [id, request] of this.requests) {
686
+ this.requests.delete(id)
687
+ request.destroy()
688
+ }
689
+ for (const [id, peer] of this.peers) {
690
+ this.peers.delete(id)
691
+ peer.close(1000, 'connector-closed')
692
+ }
693
+ }
694
+
695
+ private setState(state: RelayBridgeState): void {
696
+ this.stateValue = state
697
+ try {
698
+ this.options.onState?.(state)
699
+ } catch {
700
+ // A throwing observer must not break the socket lifecycle.
701
+ }
702
+ }
703
+ }
704
+
705
+ /** The plugin-side owner of one bridge connector. */
706
+ export interface RelayBridgeRunner {
707
+ /** Start (or restart) the connector for one accepted lease. */
708
+ start(start: RelayBridgeStart): void
709
+ /** Stop it (the relay half was disposed). */
710
+ stop(): void
711
+ readonly state: RelayBridgeState
712
+ }
713
+
714
+ /**
715
+ * Build the runner the relay pair drives: one connector per accepted lease,
716
+ * rebuilt when a later claim names a different endpoint, and stopped with the
717
+ * relay half. The bridge keeps its socket up while the instance's mode is
718
+ * quick, so a server-side flip needs no plugin restart.
719
+ * @param options - a state observer (logs and the on-disk record).
720
+ */
721
+ export function createRelayBridgeRunner(options: {
722
+ onState?: (state: RelayBridgeState) => void
723
+ /** Where to record the state; `null` keeps the runner in memory only. */
724
+ stateFile?: string | null
725
+ /** The clock the record timestamps with (tests pass a fixed one). */
726
+ now?: () => string
727
+ } = {}): RelayBridgeRunner {
728
+ const stateFile = options.stateFile === undefined ? relayBridgeStateFile() : options.stateFile
729
+ const now = options.now ?? (() => new Date().toISOString())
730
+ let connector: RelayBridgeConnector | undefined
731
+ let lease: { instance: string; hostname: string; endpoint: string; upstream: string } | undefined
732
+ const observe = (state: RelayBridgeState): void => {
733
+ const target = lease
734
+ if (stateFile !== null) {
735
+ writeRelayBridgeState(stateFile, {
736
+ state: state.state,
737
+ instance: target?.instance ?? 'none',
738
+ hostname: target?.hostname ?? 'none',
739
+ endpoint: target?.endpoint ?? 'none',
740
+ upstream: target?.upstream ?? 'none',
741
+ at: now(),
742
+ ...(state.state === 'failed' ? { error: state.error } : {}),
743
+ })
744
+ }
745
+ options.onState?.(state)
746
+ }
747
+ return {
748
+ start(start: RelayBridgeStart): void {
749
+ const grant = start.claim.bridge
750
+ if (grant === undefined) return
751
+ connector?.stop()
752
+ lease = {
753
+ instance: start.identity.id,
754
+ hostname: start.claim.hostname,
755
+ endpoint: grant.endpoint,
756
+ upstream: 'http://127.0.0.1:' + String(start.port),
757
+ }
758
+ connector = new RelayBridgeConnector({
759
+ endpoint: lease.endpoint,
760
+ id: start.identity.id,
761
+ secret: start.identity.secret,
762
+ hostname: lease.hostname,
763
+ upstream: lease.upstream,
764
+ onState: observe,
765
+ })
766
+ connector.start()
767
+ },
768
+ stop(): void {
769
+ connector?.stop()
770
+ connector = undefined
771
+ },
772
+ get state(): RelayBridgeState {
773
+ return connector?.state ?? { state: 'idle' }
774
+ },
775
+ }
776
+ }
777
+
778
+ /** Flatten a node raw header array into frame pairs. */
779
+ function rawHeaderPairs(raw: string[]): Array<[string, string]> {
780
+ const pairs: Array<[string, string]> = []
781
+ for (let index = 0; index + 1 < raw.length; index += 2) pairs.push([raw[index], raw[index + 1]])
782
+ return pairs
783
+ }