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