@linxin666/dsh-remote-bridge 0.0.0-stage → 0.4.7

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 (69) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +243 -2
  4. package/README.zh.md +244 -0
  5. package/cordis.patch.yml +17 -0
  6. package/lib/client.js +1830 -0
  7. package/lib/client.js.map +1 -0
  8. package/lib/index.js +3744 -0
  9. package/lib/types/client/PairEntry.d.ts +16 -0
  10. package/lib/types/client/PairPanel.d.ts +55 -0
  11. package/lib/types/client/icons.d.ts +18 -0
  12. package/lib/types/client/index.d.ts +35 -0
  13. package/lib/types/client/locales.d.ts +42 -0
  14. package/lib/types/client/pair-token.d.ts +73 -0
  15. package/lib/types/client/semantic.d.ts +28 -0
  16. package/lib/types/core/approvals.d.ts +75 -0
  17. package/lib/types/core/connection.d.ts +119 -0
  18. package/lib/types/core/crypto.d.ts +48 -0
  19. package/lib/types/core/devices.d.ts +72 -0
  20. package/lib/types/core/dsh-frames.d.ts +181 -0
  21. package/lib/types/core/envelope.d.ts +98 -0
  22. package/lib/types/core/gateway-errors.d.ts +49 -0
  23. package/lib/types/core/hub.d.ts +101 -0
  24. package/lib/types/core/loopback.d.ts +35 -0
  25. package/lib/types/core/owner-peer.d.ts +49 -0
  26. package/lib/types/core/pairing.d.ts +61 -0
  27. package/lib/types/core/protocol.d.ts +89 -0
  28. package/lib/types/core/questions.d.ts +246 -0
  29. package/lib/types/core/session-meta.d.ts +105 -0
  30. package/lib/types/core/session-permissions.d.ts +134 -0
  31. package/lib/types/core/wire.d.ts +115 -0
  32. package/lib/types/core/ws-frames.d.ts +61 -0
  33. package/lib/types/host/dsh-home.d.ts +16 -0
  34. package/lib/types/host/pair-origin.d.ts +44 -0
  35. package/lib/types/host/routes.d.ts +27 -0
  36. package/lib/types/host/websocket.d.ts +104 -0
  37. package/lib/types/index.d.ts +40 -0
  38. package/package.json +87 -3
  39. package/src/client/PairEntry.tsx +151 -0
  40. package/src/client/PairPanel.tsx +183 -0
  41. package/src/client/icons.tsx +72 -0
  42. package/src/client/index.ts +81 -0
  43. package/src/client/locales.ts +72 -0
  44. package/src/client/pair-token.ts +104 -0
  45. package/src/client/panel.module.css +344 -0
  46. package/src/client/semantic.ts +37 -0
  47. package/src/core/approvals.ts +142 -0
  48. package/src/core/connection.ts +1090 -0
  49. package/src/core/crypto.ts +113 -0
  50. package/src/core/devices.ts +209 -0
  51. package/src/core/dsh-frames.ts +486 -0
  52. package/src/core/envelope.ts +173 -0
  53. package/src/core/gateway-errors.ts +92 -0
  54. package/src/core/hub.ts +238 -0
  55. package/src/core/loopback.ts +60 -0
  56. package/src/core/owner-peer.ts +70 -0
  57. package/src/core/pairing.ts +113 -0
  58. package/src/core/protocol.ts +120 -0
  59. package/src/core/questions.ts +454 -0
  60. package/src/core/session-meta.ts +176 -0
  61. package/src/core/session-permissions.ts +266 -0
  62. package/src/core/wire.ts +155 -0
  63. package/src/core/ws-frames.ts +125 -0
  64. package/src/css-modules.d.ts +6 -0
  65. package/src/host/dsh-home.ts +42 -0
  66. package/src/host/pair-origin.ts +77 -0
  67. package/src/host/routes.ts +85 -0
  68. package/src/host/websocket.ts +325 -0
  69. package/src/index.ts +205 -0
@@ -0,0 +1,125 @@
1
+ /**
2
+ * RFC 6455 server-side framing, kept as pure functions so the length, mask and
3
+ * opcode rules are unit-tested without a socket.
4
+ *
5
+ * Only what a server must accept is implemented: client frames are always
6
+ * masked, one logical message may arrive as a text frame or as a fragmented
7
+ * sequence, and anything the protocol forbids answers with the close code that
8
+ * names the violation instead of being ignored.
9
+ * @module dsh-remote-bridge/core/ws-frames
10
+ */
11
+
12
+ import { createHash } from 'node:crypto'
13
+
14
+ /** The magic GUID every WebSocket handshake is keyed with. */
15
+ export const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
16
+
17
+ export const OPCODE_CONTINUATION = 0x0
18
+ export const OPCODE_TEXT = 0x1
19
+ export const OPCODE_BINARY = 0x2
20
+ export const OPCODE_CLOSE = 0x8
21
+ export const OPCODE_PING = 0x9
22
+ export const OPCODE_PONG = 0xa
23
+
24
+ /** Close code for a protocol violation. */
25
+ export const CLOSE_PROTOCOL_ERROR = 1002
26
+ /** Close code for a message this bridge will not carry. */
27
+ export const CLOSE_UNSUPPORTED_DATA = 1003
28
+ /** Close code for a message past the size this bridge will carry. */
29
+ export const CLOSE_TOO_LARGE = 1009
30
+
31
+ /** @returns the `Sec-WebSocket-Accept` value for a client's key. */
32
+ export function webSocketAccept(secWebSocketKey: string): string {
33
+ return createHash('sha1').update(`${secWebSocketKey}${WS_GUID}`).digest('base64')
34
+ }
35
+
36
+ /** One decoded frame header plus its payload. */
37
+ export interface DecodedFrame {
38
+ readonly fin: boolean
39
+ readonly opcode: number
40
+ readonly payload: Buffer
41
+ /** Bytes this frame occupies in the stream. */
42
+ readonly consumed: number
43
+ }
44
+
45
+ export type FrameParseOutcome =
46
+ | { readonly status: 'incomplete' }
47
+ | { readonly status: 'frame'; readonly frame: DecodedFrame }
48
+ | { readonly status: 'fault'; readonly closeCode: number; readonly reason: string }
49
+
50
+ /**
51
+ * Decode one frame from the head of a buffer.
52
+ * @param buffer - the bytes received so far.
53
+ * @param maxBytes - largest payload this bridge accepts.
54
+ */
55
+ export function parseClientFrame(buffer: Buffer, maxBytes: number): FrameParseOutcome {
56
+ if (buffer.length < 2) return { status: 'incomplete' }
57
+ const first = buffer[0] ?? 0
58
+ const second = buffer[1] ?? 0
59
+ const fin = (first & 0x80) !== 0
60
+ // RSV1-3 are only meaningful with an extension this bridge never negotiates.
61
+ if ((first & 0x70) !== 0) return fault(CLOSE_PROTOCOL_ERROR, 'reserved bits set')
62
+ const opcode = first & 0x0f
63
+ const masked = (second & 0x80) !== 0
64
+ if (!masked) return fault(CLOSE_PROTOCOL_ERROR, 'client frames must be masked')
65
+ let length = second & 0x7f
66
+ let offset = 2
67
+ if (length === 126) {
68
+ if (buffer.length < offset + 2) return { status: 'incomplete' }
69
+ length = buffer.readUInt16BE(offset)
70
+ offset += 2
71
+ } else if (length === 127) {
72
+ if (buffer.length < offset + 8) return { status: 'incomplete' }
73
+ const wide = buffer.readBigUInt64BE(offset)
74
+ if (wide > BigInt(Number.MAX_SAFE_INTEGER)) return fault(CLOSE_TOO_LARGE, 'frame length out of range')
75
+ length = Number(wide)
76
+ offset += 8
77
+ }
78
+ if (length > maxBytes) return fault(CLOSE_TOO_LARGE, `frame payload exceeds ${maxBytes} bytes`)
79
+ if (buffer.length < offset + 4 + length) return { status: 'incomplete' }
80
+ const mask = buffer.subarray(offset, offset + 4)
81
+ offset += 4
82
+ const payload = Buffer.allocUnsafe(length)
83
+ for (let index = 0; index < length; index += 1) payload[index] = (buffer[offset + index] ?? 0) ^ (mask[index % 4] ?? 0)
84
+ return { status: 'frame', frame: { fin, opcode, payload, consumed: offset + length } }
85
+ }
86
+
87
+ function fault(closeCode: number, reason: string): FrameParseOutcome {
88
+ return { status: 'fault', closeCode, reason }
89
+ }
90
+
91
+ /**
92
+ * Encode one server frame. Server frames are never masked.
93
+ * @param opcode - the frame opcode.
94
+ * @param payload - already-serialized payload bytes.
95
+ * @param fin - whether this frame completes the message.
96
+ */
97
+ export function encodeServerFrame(opcode: number, payload: Buffer, fin = true): Buffer {
98
+ const length = payload.length
99
+ const header = length < 126
100
+ ? Buffer.from([(fin ? 0x80 : 0) | opcode, length])
101
+ : length <= 0xffff
102
+ ? Buffer.from([(fin ? 0x80 : 0) | opcode, 126, length >> 8, length & 0xff])
103
+ : (() => {
104
+ const wide = Buffer.alloc(10)
105
+ wide[0] = (fin ? 0x80 : 0) | opcode
106
+ wide[1] = 127
107
+ wide.writeBigUInt64BE(BigInt(length), 2)
108
+ return wide
109
+ })()
110
+ return Buffer.concat([header, payload])
111
+ }
112
+
113
+ /** Encode one text message. */
114
+ export function encodeTextFrame(text: string): Buffer {
115
+ return encodeServerFrame(OPCODE_TEXT, Buffer.from(text, 'utf8'))
116
+ }
117
+
118
+ /** Encode one close frame with a code and a short reason. */
119
+ export function encodeCloseFrame(code: number, reason: string): Buffer {
120
+ const text = Buffer.from(reason, 'utf8').subarray(0, 123)
121
+ const payload = Buffer.alloc(2 + text.length)
122
+ payload.writeUInt16BE(code, 0)
123
+ text.copy(payload, 2)
124
+ return encodeServerFrame(OPCODE_CLOSE, payload)
125
+ }
@@ -0,0 +1,6 @@
1
+ declare module '*.module.css' {
2
+ const classes: Record<string, string>
3
+ export default classes
4
+ }
5
+
6
+ declare module '*.css'
@@ -0,0 +1,42 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/host/dsh-home.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * DSH_HOME resolution shared by the plugin family's Host halves: the
4
+ * environment override wins, the platform home fallback follows. Mirrors
5
+ * what dsh-pet and dsh-liangshen each used to implement locally.
6
+ */
7
+
8
+ import { homedir } from 'node:os'
9
+ import { isAbsolute, join } from 'node:path'
10
+ import { isAbsolute as posixIsAbsolute, join as posixJoin } from 'node:path/posix'
11
+
12
+ /** Expand a leading ~ (or ~user) in a path, platform-style. */
13
+ export function expandHome(path: string, home: string = homedir()): string {
14
+ const isPosix = home.startsWith('/')
15
+ const j = isPosix ? posixJoin : join
16
+ if (path === '~') return home
17
+ if (path.startsWith('~/') || path.startsWith('~\\')) return j(home, path.slice(2))
18
+ return path
19
+ }
20
+
21
+ /**
22
+ * Resolve the DSH home directory.
23
+ * @param env - process environment to read DSH_HOME from.
24
+ * @param home - platform home directory fallback (test seam).
25
+ * @returns the absolute DSH home path.
26
+ */
27
+ export function resolveDshHome(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
28
+ const isPosix = home.startsWith('/')
29
+ const j = isPosix ? posixJoin : join
30
+ const isAbs = isPosix ? posixIsAbsolute : isAbsolute
31
+ const raw = env.DSH_HOME
32
+ if (raw !== undefined && raw.trim() !== '') {
33
+ const expanded = expandHome(raw.trim(), home)
34
+ return isAbs(expanded) ? expanded : j(process.cwd(), expanded)
35
+ }
36
+ return j(home, '.dsh')
37
+ }
38
+
39
+ /** Resolve the DSH home directory from the live environment. */
40
+ export function dshHome(): string {
41
+ return resolveDshHome()
42
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The public origin a phone should dial, discovered rather than asked for.
3
+ *
4
+ * A pairing code is far better when it carries the address too: the phone then
5
+ * needs one scan and no typing. This module is where that address comes from,
6
+ * in the order the family already trusts:
7
+ *
8
+ * 1. `DSH_REMOTE_PUBLIC_BASE_URL` — the same environment contract
9
+ * `dsh-remote-web-ui` reads for its own public base.
10
+ * 2. The relay registry row `$DSH_HOME/remote-web-ui-registry/<profile>.json`,
11
+ * whose `id` is the stable `<id>.<relay>` subdomain that plugin registers
12
+ * for this profile (see its `relay-registry.ts`). Reading that row is a
13
+ * deliberate, documented data dependency: it is one small JSON file per
14
+ * profile, it is written by the machine itself, and a missing or unreadable
15
+ * row simply means "no origin known" rather than an error.
16
+ *
17
+ * Nothing here reaches the network, and nothing here mints or spends anything.
18
+ * @module dsh-remote-bridge/host/pair-origin
19
+ */
20
+
21
+ import { readFileSync } from 'node:fs'
22
+ import { join } from 'node:path'
23
+ import { resolveDshHome } from './dsh-home.ts'
24
+
25
+ /** The relay's worker domain; a profile's stable origin is `<id>.<this>`. */
26
+ export const RELAY_DOMAIN = 'dsh-market.com'
27
+
28
+ /** The registry directory `dsh-remote-web-ui` keeps its per-profile row in. */
29
+ export const RELAY_REGISTRY_DIR = 'remote-web-ui-registry'
30
+
31
+ /** One discovered origin and the fact that produced it. */
32
+ export interface PairOriginFacts {
33
+ /** Origin only, no path: `wss://<id>.dsh-market.com`. */
34
+ readonly origin: string
35
+ /** Where the answer came from, for the panel and the log. */
36
+ readonly source: 'env' | 'registry'
37
+ }
38
+
39
+ export interface DiscoverPairOriginOptions {
40
+ /** Environment to read; defaults to `process.env`. */
41
+ readonly env?: NodeJS.ProcessEnv
42
+ /** DSH home to look in; defaults to `resolveDshHome(env)`. */
43
+ readonly home?: string
44
+ /** Profile whose registry row to read; defaults to `$DSH_PROFILE` or `desktop`. */
45
+ readonly profile?: string
46
+ }
47
+
48
+ /** Trim trailing slashes so the caller can append a path unconditionally. */
49
+ function originOf(base: string): string {
50
+ return base.replace(/\/+$/, '')
51
+ }
52
+
53
+ /**
54
+ * Discover the public origin of this instance.
55
+ * @param options - environment, home and profile seams for tests.
56
+ * @returns the origin and its source, or `undefined` when nothing is known.
57
+ */
58
+ export function discoverPairOrigin(options: DiscoverPairOriginOptions = {}): PairOriginFacts | undefined {
59
+ const env = options.env ?? process.env
60
+ const configured = env.DSH_REMOTE_PUBLIC_BASE_URL?.trim()
61
+ if (configured !== undefined && configured !== '') return { origin: originOf(configured), source: 'env' }
62
+
63
+ const home = options.home ?? resolveDshHome(env)
64
+ const profile = options.profile ?? env.DSH_PROFILE?.trim() ?? 'desktop'
65
+ if (profile === '') return undefined
66
+
67
+ let row: unknown
68
+ try {
69
+ row = JSON.parse(readFileSync(join(home, RELAY_REGISTRY_DIR, `${profile}.json`), 'utf8'))
70
+ } catch {
71
+ return undefined
72
+ }
73
+ if (typeof row !== 'object' || row === null) return undefined
74
+ const id = (row as { id?: unknown }).id
75
+ if (typeof id !== 'string' || id === '') return undefined
76
+ return { origin: `wss://${id}.${RELAY_DOMAIN}`, source: 'registry' }
77
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The bootstrap token endpoint an operator reaches from the Host itself.
3
+ *
4
+ * It is a named route on the host web server at one exact path, and it is the
5
+ * only place a bootstrap token is ever minted. Admission is the two-condition
6
+ * loopback gate in `core/loopback.ts` (socket address AND Host header); the
7
+ * token itself is one-shot with a 30 s lifetime, and the same link is printed
8
+ * to the Host log so an operator can open it from the machine.
9
+ * @module dsh-remote-bridge/host/routes
10
+ */
11
+
12
+ import type { IncomingMessage, ServerResponse } from 'node:http'
13
+ import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
14
+ import { loopbackDenialOf } from '../core/loopback.ts'
15
+ import { PAIR_TOKEN_PATH, WS_PATH } from '../core/protocol.ts'
16
+ import type { PairingService } from '../core/pairing.ts'
17
+ import { discoverPairOrigin, type PairOriginFacts } from './pair-origin.ts'
18
+
19
+ export interface PairTokenRouteDeps {
20
+ readonly pairing: PairingService
21
+ readonly log: (message: string) => void
22
+ /** Origin discovery seam; defaults to {@link discoverPairOrigin}. */
23
+ readonly pairOrigin?: () => PairOriginFacts | undefined
24
+ }
25
+
26
+ /** Write one JSON response. The family's shared reader/writer is not copied into this package. */
27
+ function writeJson(res: ServerResponse, status: number, body: unknown): void {
28
+ const text = JSON.stringify(body)
29
+ res.writeHead(status, {
30
+ 'content-type': 'application/json; charset=utf-8',
31
+ 'content-length': Buffer.byteLength(text),
32
+ 'cache-control': 'no-store',
33
+ 'referrer-policy': 'no-referrer',
34
+ })
35
+ res.end(text)
36
+ }
37
+
38
+ /**
39
+ * Build the handler for `GET /remote-bridge/pair/token`.
40
+ * @param deps - the pairing service that mints the token, plus the Host log.
41
+ * @returns the handler; the caller owns route registration.
42
+ */
43
+ export function makePairTokenHandler(deps: PairTokenRouteDeps): WebRoute['handler'] {
44
+ return (req: IncomingMessage, res: ServerResponse): void => {
45
+ const denial = loopbackDenialOf(req)
46
+ if (denial !== undefined) {
47
+ writeJson(res, 403, { ok: false, error: 'forbidden', reason: denial })
48
+ return
49
+ }
50
+ if ((req.method ?? 'GET') !== 'GET') {
51
+ res.writeHead(405, { allow: 'GET' })
52
+ res.end()
53
+ return
54
+ }
55
+ const ticket = deps.pairing.issueToken()
56
+ // The link a client ON THIS MACHINE can open directly. The token rides the
57
+ // query because a WebSocket handshake started from a share sheet cannot set
58
+ // a header; the connection it opens is UNPAIRED, which is exactly what
59
+ // `pair.begin` needs.
60
+ const host = req.headers.host ?? '127.0.0.1'
61
+ const url = `ws://${host}${WS_PATH}?token=${ticket.value}`
62
+ // The link the PHONE should dial, when this machine knows its own public
63
+ // origin. `pairingUrl` is what a QR should carry: the iOS client parses
64
+ // `{token, url}` and adopts the origin from `url`, so one scan sets both.
65
+ const discovered = (deps.pairOrigin ?? discoverPairOrigin)()
66
+ const pairingUrl = discovered === undefined ? undefined : `${discovered.origin}${WS_PATH}?token=${ticket.value}`
67
+ deps.log(
68
+ pairingUrl === undefined
69
+ ? `pair a device with ${url}`
70
+ : `pair a device with ${url} (phone: ${pairingUrl})`,
71
+ )
72
+ writeJson(res, 200, {
73
+ token: ticket.value,
74
+ expiresAt: ticket.expiresAt,
75
+ url,
76
+ ...(discovered === undefined ? {} : { origin: discovered.origin, originSource: discovered.source }),
77
+ ...(pairingUrl === undefined ? {} : { pairingUrl }),
78
+ })
79
+ }
80
+ }
81
+
82
+ /** The route as the host web server takes it: one exact path, no trailing slash. */
83
+ export function makePairTokenRoute(deps: PairTokenRouteDeps): WebRoute {
84
+ return { kind: 'exact', path: PAIR_TOKEN_PATH, handler: makePairTokenHandler(deps) }
85
+ }
@@ -0,0 +1,325 @@
1
+ /**
2
+ * The WebSocket carrier of `/ios/v1`: RFC 6455 negotiation plus the frame loop.
3
+ *
4
+ * This is the only WebSocket in the family that terminates the protocol
5
+ * itself — the other remote plugin proxies its upgrades to the host mux — so
6
+ * the framing rules are implemented here against `core/ws-frames.ts` and every
7
+ * socket failure funnels into one teardown path that the hub observes exactly
8
+ * once.
9
+ * @module dsh-remote-bridge/host/websocket
10
+ */
11
+
12
+ import type { IncomingMessage } from 'node:http'
13
+ import type { Duplex } from 'node:stream'
14
+ import type { BridgeTransport, ConnectionAuth } from '../core/connection.ts'
15
+ import { MAX_FRAME_BYTES } from '../core/envelope.ts'
16
+ import type { BridgeHub } from '../core/hub.ts'
17
+ import {
18
+ CLOSE_PROTOCOL_ERROR,
19
+ CLOSE_TOO_LARGE,
20
+ CLOSE_UNSUPPORTED_DATA,
21
+ OPCODE_BINARY,
22
+ OPCODE_CLOSE,
23
+ OPCODE_CONTINUATION,
24
+ OPCODE_PING,
25
+ OPCODE_PONG,
26
+ OPCODE_TEXT,
27
+ encodeCloseFrame,
28
+ encodeServerFrame,
29
+ encodeTextFrame,
30
+ parseClientFrame,
31
+ webSocketAccept,
32
+ } from '../core/ws-frames.ts'
33
+
34
+ /** Close code a well-behaved peer sends when it goes away. */
35
+ const CLOSE_NORMAL = 1000
36
+
37
+ /**
38
+ * Messages one carrier buffers while no handler is registered. The mounted
39
+ * wiring registers one synchronously, so this only ever absorbs bytes that were
40
+ * handed over before the handler existed; past it the socket is closed instead of
41
+ * buffering a conversation nobody is reading.
42
+ */
43
+ export const PENDING_MESSAGE_LIMIT = 32
44
+
45
+ /** @returns whether this request asks for a WebSocket upgrade. */
46
+ export function isWebSocketUpgrade(req: IncomingMessage): boolean {
47
+ const upgrade = req.headers.upgrade
48
+ return typeof upgrade === 'string' && upgrade.toLowerCase() === 'websocket'
49
+ }
50
+
51
+ /** @returns the client's `Sec-WebSocket-Key`, or undefined when the handshake is incomplete. */
52
+ export function readSecWebSocketKey(req: IncomingMessage): string | undefined {
53
+ const key = req.headers['sec-websocket-key']
54
+ if (typeof key !== 'string') return undefined
55
+ const trimmed = key.trim()
56
+ return trimmed === '' ? undefined : trimmed
57
+ }
58
+
59
+ /** @returns the device token on `Authorization: Bearer …`, if the client sent one. */
60
+ export function bearerTokenOf(req: IncomingMessage): string | undefined {
61
+ const header = req.headers.authorization
62
+ if (typeof header !== 'string') return undefined
63
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim())
64
+ const value = match?.[1]?.trim()
65
+ return value === undefined || value === '' ? undefined : value
66
+ }
67
+
68
+ /**
69
+ * @returns the token on `?token=…`, the fallback for clients whose handshake
70
+ * cannot set a header (share sheets, `wscat`, plain scripts).
71
+ */
72
+ export function queryTokenOf(requestUrl: string | undefined): string | undefined {
73
+ if (requestUrl === undefined || requestUrl === '') return undefined
74
+ let value: string | null
75
+ try {
76
+ value = new URL(requestUrl, 'http://127.0.0.1').searchParams.get('token')
77
+ } catch {
78
+ return undefined
79
+ }
80
+ return value === null || value === '' ? undefined : value
81
+ }
82
+
83
+ /**
84
+ * @returns the token this upgrade presents: the header first, then the query.
85
+ * A bootstrap token presented here is simply not a device token, which leaves
86
+ * the connection unpaired — the state `pair.begin` needs.
87
+ */
88
+ export function presentedTokenOf(req: IncomingMessage): string | undefined {
89
+ return bearerTokenOf(req) ?? queryTokenOf(req.url)
90
+ }
91
+
92
+ /**
93
+ * Answer an upgrade this endpoint will not take, and close the write side.
94
+ *
95
+ * The refusal rides `end()`, which flushes the response before the FIN. Writing
96
+ * and then destroying in the same tick aborts the in-flight write on Linux, and
97
+ * that abort surfaces as the socket's own `error` event - which nothing on a
98
+ * refused socket listens for, because the carrier's subscriptions only exist
99
+ * once an upgrade is accepted. One malformed upgrade therefore reached the host
100
+ * as an uncaught exception. The listener absorbs the transport's own failures: a
101
+ * peer that vanished mid-refusal is the client's problem, never the host's.
102
+ */
103
+ export function refuseUpgrade(socket: Duplex, status: number, reason: string): void {
104
+ socket.on('error', () => {})
105
+ socket.end(`HTTP/1.1 ${status} ${reason}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`)
106
+ }
107
+
108
+ /**
109
+ * One accepted upgrade handed to the bridge.
110
+ */
111
+ export interface UpgradeHandoff {
112
+ /** The upgraded socket; the carrier both reads from and writes to it. */
113
+ readonly socket: Duplex
114
+ /** The client's `Sec-WebSocket-Key`, already read from the handshake. */
115
+ readonly secWebSocketKey: string
116
+ /** Bytes that arrived with the upgrade request itself. */
117
+ readonly head: Buffer
118
+ readonly hub: BridgeHub
119
+ /** The device the handshake token proved, when it proved one. */
120
+ readonly auth?: ConnectionAuth
121
+ }
122
+
123
+ /**
124
+ * Hand one accepted upgrade to the hub, in the one order that is correct.
125
+ *
126
+ * Every step here is synchronous, which is what makes the carrier's own
127
+ * pre-handler buffer unnecessary in practice — and the buffer is there anyway,
128
+ * so the bytes of `head` (and anything that beats the handler) are delivered
129
+ * instead of dropped. The order is the point of this function: reading the
130
+ * socket without a handler, or attaching a connection whose carrier is never
131
+ * written to, both end in a client that waits forever.
132
+ * @param handoff - the socket, its handshake facts, and the hub to join.
133
+ * @returns the carrier, for a caller that needs to observe it.
134
+ */
135
+ export function serveUpgrade(handoff: UpgradeHandoff): WebSocketCarrier {
136
+ const { socket, secWebSocketKey, head, hub, auth } = handoff
137
+ const carrier = new WebSocketCarrier(socket)
138
+ carrier.handshake(secWebSocketKey)
139
+ const connection = hub.attach(carrier, auth)
140
+ carrier.onMessage(text => { void connection.handleText(text) })
141
+ carrier.onClose(() => { hub.detach(connection) })
142
+ if (head.length > 0) carrier.feed(head)
143
+ return carrier
144
+ }
145
+
146
+ /**
147
+ * One accepted socket, framed.
148
+ *
149
+ * Frames are buffered until a whole one has arrived; a fragmented message is
150
+ * reassembled up to {@link MAX_FRAME_BYTES} and anything larger closes the
151
+ * socket with the code that names the violation. The carrier is inert until
152
+ * {@link handshake} runs, so a caller can refuse a connection without having
153
+ * written a byte of the protocol.
154
+ */
155
+ export class WebSocketCarrier implements BridgeTransport {
156
+ readonly #socket: Duplex
157
+ #buffer: Buffer = Buffer.alloc(0)
158
+ #fragments: Buffer[] = []
159
+ #fragmentOpcode = 0
160
+ #fragmentBytes = 0
161
+ #opened = false
162
+ #closed = false
163
+ #onMessage: ((text: string) => void) | undefined
164
+ #onClose: (() => void) | undefined
165
+ /** Messages that arrived before a handler was registered; see {@link deliver}. */
166
+ readonly #pending: string[] = []
167
+
168
+ constructor(socket: Duplex) {
169
+ this.#socket = socket
170
+ // The socket is this endpoint's ONLY source of bytes. Without this
171
+ // subscription every frame a client sends after the handshake sits in the
172
+ // socket's read buffer forever: the upgrade's leftover `head` is normally
173
+ // empty, so the frame loop would never see a single byte — the client sees a
174
+ // socket that stays open, answers nothing and never closes.
175
+ socket.on('data', (chunk: Buffer) => { this.feed(chunk) })
176
+ socket.on('error', () => { this.#shut() })
177
+ socket.on('close', () => { this.#shut() })
178
+ socket.on('end', () => { this.#shut() })
179
+ }
180
+
181
+ /** Write the 101 handshake carrying the accept value for the client's key. */
182
+ handshake(secWebSocketKey: string): void {
183
+ if (this.#opened || this.#closed) return
184
+ this.#opened = true
185
+ this.#socket.write([
186
+ 'HTTP/1.1 101 Switching Protocols',
187
+ 'upgrade: websocket',
188
+ 'connection: Upgrade',
189
+ `sec-websocket-accept: ${webSocketAccept(secWebSocketKey)}`,
190
+ '',
191
+ '',
192
+ ].join('\r\n'))
193
+ }
194
+
195
+ /** Register the handler for every complete text message. */
196
+ onMessage(handler: (text: string) => void): void {
197
+ this.#onMessage = handler
198
+ for (const text of this.#pending.splice(0)) handler(text)
199
+ }
200
+
201
+ /** Register the one teardown hook; it runs exactly once. */
202
+ onClose(handler: () => void): void {
203
+ this.#onClose = handler
204
+ }
205
+
206
+ /** Feed raw bytes from the socket into the frame loop. */
207
+ feed(chunk: Buffer): void {
208
+ if (this.#closed) return
209
+ this.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk])
210
+ for (;;) {
211
+ const outcome = parseClientFrame(this.#buffer, MAX_FRAME_BYTES)
212
+ if (outcome.status === 'incomplete') return
213
+ if (outcome.status === 'fault') {
214
+ this.close(outcome.closeCode, outcome.reason)
215
+ return
216
+ }
217
+ this.#buffer = this.#buffer.subarray(outcome.frame.consumed)
218
+ if (!this.#accept(outcome.frame.fin, outcome.frame.opcode, outcome.frame.payload)) return
219
+ }
220
+ }
221
+
222
+ /** Send one text frame. */
223
+ send(text: string): void {
224
+ if (this.#closed) return
225
+ this.#socket.write(encodeTextFrame(text))
226
+ }
227
+
228
+ /** Send a close frame and end the socket. Idempotent. */
229
+ close(code: number, reason: string): void {
230
+ if (this.#closed) return
231
+ this.#closed = true
232
+ this.#socket.write(encodeCloseFrame(code, reason))
233
+ this.#socket.end()
234
+ this.#notifyClose()
235
+ }
236
+
237
+ /** @returns whether the carrier has been torn down. */
238
+ get closed(): boolean {
239
+ return this.#closed
240
+ }
241
+
242
+ #accept(fin: boolean, opcode: number, payload: Buffer): boolean {
243
+ switch (opcode) {
244
+ case OPCODE_TEXT:
245
+ case OPCODE_BINARY: {
246
+ if (this.#fragmentOpcode !== 0) {
247
+ this.close(CLOSE_PROTOCOL_ERROR, 'a new message started before the previous one finished')
248
+ return false
249
+ }
250
+ if (fin) return this.#deliver(opcode, payload)
251
+ this.#fragmentOpcode = opcode
252
+ this.#fragments = [payload]
253
+ this.#fragmentBytes = payload.length
254
+ return true
255
+ }
256
+ case OPCODE_CONTINUATION: {
257
+ if (this.#fragmentOpcode === 0) {
258
+ this.close(CLOSE_PROTOCOL_ERROR, 'continuation frame without a started message')
259
+ return false
260
+ }
261
+ this.#fragmentBytes += payload.length
262
+ if (this.#fragmentBytes > MAX_FRAME_BYTES) {
263
+ this.close(CLOSE_TOO_LARGE, `a message may not exceed ${MAX_FRAME_BYTES} bytes`)
264
+ return false
265
+ }
266
+ this.#fragments.push(payload)
267
+ if (!fin) return true
268
+ const message = Buffer.concat(this.#fragments, this.#fragmentBytes)
269
+ const opcodeOfMessage = this.#fragmentOpcode
270
+ this.#fragments = []
271
+ this.#fragmentBytes = 0
272
+ this.#fragmentOpcode = 0
273
+ return this.#deliver(opcodeOfMessage, message)
274
+ }
275
+ case OPCODE_PING:
276
+ this.#socket.write(encodeServerFrame(OPCODE_PONG, payload))
277
+ return true
278
+ case OPCODE_PONG:
279
+ return true
280
+ case OPCODE_CLOSE:
281
+ this.close(CLOSE_NORMAL, '')
282
+ return false
283
+ default:
284
+ this.close(CLOSE_PROTOCOL_ERROR, `unsupported opcode ${opcode}`)
285
+ return false
286
+ }
287
+ }
288
+
289
+ #deliver(opcode: number, payload: Buffer): boolean {
290
+ if (opcode !== OPCODE_TEXT) {
291
+ this.close(CLOSE_UNSUPPORTED_DATA, 'this endpoint carries text frames only')
292
+ return false
293
+ }
294
+ const text = payload.toString('utf8')
295
+ if (this.#onMessage === undefined) {
296
+ // The mounted wiring order (handshake → attach → onMessage → feed(head)) is
297
+ // synchronous, so this queue is never needed for it: `data` can only fire on
298
+ // a later turn. It is here so that guarantee does not rest on a caller's tick
299
+ // discipline — bytes the carrier is handed first are delivered the moment a
300
+ // handler arrives, instead of being dropped. The bound turns a carrier nobody
301
+ // ever wired into a closed socket rather than a growing buffer.
302
+ if (this.#pending.length >= PENDING_MESSAGE_LIMIT) {
303
+ this.close(CLOSE_TOO_LARGE, 'this connection has no message handler')
304
+ return false
305
+ }
306
+ this.#pending.push(text)
307
+ return true
308
+ }
309
+ this.#onMessage(text)
310
+ return true
311
+ }
312
+
313
+ /** The socket went away without a close frame: tear down without writing. */
314
+ #shut(): void {
315
+ if (this.#closed) return
316
+ this.#closed = true
317
+ this.#notifyClose()
318
+ }
319
+
320
+ #notifyClose(): void {
321
+ const handler = this.#onClose
322
+ this.#onClose = undefined
323
+ handler?.()
324
+ }
325
+ }