@linxin666/dsh-remote-bridge 0.0.0-stage → 0.4.8
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.
- package/LICENSE +202 -0
- package/README.i18n.yaml +6 -0
- package/README.md +277 -2
- package/README.zh.md +276 -0
- package/cordis.patch.yml +17 -0
- package/icon.svg +3 -0
- package/lib/client.js +1830 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +5789 -0
- package/lib/types/client/PairEntry.d.ts +16 -0
- package/lib/types/client/PairPanel.d.ts +55 -0
- package/lib/types/client/icons.d.ts +18 -0
- package/lib/types/client/index.d.ts +35 -0
- package/lib/types/client/locales.d.ts +42 -0
- package/lib/types/client/pair-token.d.ts +73 -0
- package/lib/types/client/semantic.d.ts +28 -0
- package/lib/types/core/approvals.d.ts +99 -0
- package/lib/types/core/connection.d.ts +170 -0
- package/lib/types/core/crypto.d.ts +48 -0
- package/lib/types/core/delta.d.ts +101 -0
- package/lib/types/core/devices.d.ts +72 -0
- package/lib/types/core/dsh-frames.d.ts +332 -0
- package/lib/types/core/envelope.d.ts +132 -0
- package/lib/types/core/extension.d.ts +144 -0
- package/lib/types/core/gateway-errors.d.ts +49 -0
- package/lib/types/core/hub.d.ts +127 -0
- package/lib/types/core/jobs.d.ts +204 -0
- package/lib/types/core/loopback.d.ts +35 -0
- package/lib/types/core/owner-peer.d.ts +49 -0
- package/lib/types/core/pairing.d.ts +61 -0
- package/lib/types/core/protocol.d.ts +319 -0
- package/lib/types/core/questions.d.ts +294 -0
- package/lib/types/core/session-meta.d.ts +105 -0
- package/lib/types/core/session-permissions.d.ts +134 -0
- package/lib/types/core/wire.d.ts +115 -0
- package/lib/types/core/ws-frames.d.ts +72 -0
- package/lib/types/host/dsh-home.d.ts +16 -0
- package/lib/types/host/pair-origin.d.ts +44 -0
- package/lib/types/host/routes.d.ts +27 -0
- package/lib/types/host/websocket.d.ts +111 -0
- package/lib/types/index.d.ts +55 -0
- package/lib/types/mount-once.d.ts +55 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +93 -3
- package/src/client/PairEntry.tsx +151 -0
- package/src/client/PairPanel.tsx +183 -0
- package/src/client/icons.tsx +72 -0
- package/src/client/index.ts +81 -0
- package/src/client/locales.ts +72 -0
- package/src/client/pair-token.ts +104 -0
- package/src/client/panel.module.css +344 -0
- package/src/client/semantic.ts +37 -0
- package/src/core/approvals.ts +173 -0
- package/src/core/connection.ts +1906 -0
- package/src/core/crypto.ts +113 -0
- package/src/core/delta.ts +204 -0
- package/src/core/devices.ts +209 -0
- package/src/core/dsh-frames.ts +843 -0
- package/src/core/envelope.ts +219 -0
- package/src/core/extension.ts +197 -0
- package/src/core/gateway-errors.ts +92 -0
- package/src/core/hub.ts +310 -0
- package/src/core/jobs.ts +372 -0
- package/src/core/loopback.ts +60 -0
- package/src/core/owner-peer.ts +70 -0
- package/src/core/pairing.ts +113 -0
- package/src/core/protocol.ts +381 -0
- package/src/core/questions.ts +630 -0
- package/src/core/session-meta.ts +176 -0
- package/src/core/session-permissions.ts +266 -0
- package/src/core/wire.ts +159 -0
- package/src/core/ws-frames.ts +139 -0
- package/src/css-modules.d.ts +6 -0
- package/src/host/dsh-home.ts +42 -0
- package/src/host/pair-origin.ts +77 -0
- package/src/host/routes.ts +85 -0
- package/src/host/websocket.ts +359 -0
- package/src/index.ts +257 -0
- package/src/mount-once.ts +142 -0
|
@@ -0,0 +1,359 @@
|
|
|
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, outboundPayloadOf } 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
|
+
encodeBinaryFrame,
|
|
28
|
+
encodeCloseFrame,
|
|
29
|
+
encodeServerFrame,
|
|
30
|
+
encodeTextFrame,
|
|
31
|
+
parseClientFrame,
|
|
32
|
+
webSocketAccept,
|
|
33
|
+
} from '../core/ws-frames.ts'
|
|
34
|
+
|
|
35
|
+
/** Close code a well-behaved peer sends when it goes away. */
|
|
36
|
+
const CLOSE_NORMAL = 1000
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Messages one carrier buffers while no handler is registered. The mounted
|
|
40
|
+
* wiring registers one synchronously, so this only ever absorbs bytes that were
|
|
41
|
+
* handed over before the handler existed; past it the socket is closed instead of
|
|
42
|
+
* buffering a conversation nobody is reading.
|
|
43
|
+
*/
|
|
44
|
+
export const PENDING_MESSAGE_LIMIT = 32
|
|
45
|
+
|
|
46
|
+
/** @returns whether this request asks for a WebSocket upgrade. */
|
|
47
|
+
export function isWebSocketUpgrade(req: IncomingMessage): boolean {
|
|
48
|
+
const upgrade = req.headers.upgrade
|
|
49
|
+
return typeof upgrade === 'string' && upgrade.toLowerCase() === 'websocket'
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** @returns the client's `Sec-WebSocket-Key`, or undefined when the handshake is incomplete. */
|
|
53
|
+
export function readSecWebSocketKey(req: IncomingMessage): string | undefined {
|
|
54
|
+
const key = req.headers['sec-websocket-key']
|
|
55
|
+
if (typeof key !== 'string') return undefined
|
|
56
|
+
const trimmed = key.trim()
|
|
57
|
+
return trimmed === '' ? undefined : trimmed
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** @returns the device token on `Authorization: Bearer …`, if the client sent one. */
|
|
61
|
+
export function bearerTokenOf(req: IncomingMessage): string | undefined {
|
|
62
|
+
const header = req.headers.authorization
|
|
63
|
+
if (typeof header !== 'string') return undefined
|
|
64
|
+
const match = /^Bearer\s+(.+)$/i.exec(header.trim())
|
|
65
|
+
const value = match?.[1]?.trim()
|
|
66
|
+
return value === undefined || value === '' ? undefined : value
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @returns the token on `?token=…`, the fallback for clients whose handshake
|
|
71
|
+
* cannot set a header (share sheets, `wscat`, plain scripts).
|
|
72
|
+
*/
|
|
73
|
+
export function queryTokenOf(requestUrl: string | undefined): string | undefined {
|
|
74
|
+
if (requestUrl === undefined || requestUrl === '') return undefined
|
|
75
|
+
let value: string | null
|
|
76
|
+
try {
|
|
77
|
+
value = new URL(requestUrl, 'http://127.0.0.1').searchParams.get('token')
|
|
78
|
+
} catch {
|
|
79
|
+
return undefined
|
|
80
|
+
}
|
|
81
|
+
return value === null || value === '' ? undefined : value
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @returns the token this upgrade presents: the header first, then the query.
|
|
86
|
+
* A bootstrap token presented here is simply not a device token, which leaves
|
|
87
|
+
* the connection unpaired — the state `pair.begin` needs.
|
|
88
|
+
*/
|
|
89
|
+
export function presentedTokenOf(req: IncomingMessage): string | undefined {
|
|
90
|
+
return bearerTokenOf(req) ?? queryTokenOf(req.url)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Answer an upgrade this endpoint will not take, and close the write side.
|
|
95
|
+
*
|
|
96
|
+
* The refusal rides `end()`, which flushes the response before the FIN. Writing
|
|
97
|
+
* and then destroying in the same tick aborts the in-flight write on Linux, and
|
|
98
|
+
* that abort surfaces as the socket's own `error` event - which nothing on a
|
|
99
|
+
* refused socket listens for, because the carrier's subscriptions only exist
|
|
100
|
+
* once an upgrade is accepted. One malformed upgrade therefore reached the host
|
|
101
|
+
* as an uncaught exception. The listener absorbs the transport's own failures: a
|
|
102
|
+
* peer that vanished mid-refusal is the client's problem, never the host's.
|
|
103
|
+
*/
|
|
104
|
+
export function refuseUpgrade(socket: Duplex, status: number, reason: string): void {
|
|
105
|
+
socket.on('error', () => {})
|
|
106
|
+
socket.end(`HTTP/1.1 ${status} ${reason}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The Nagle switch a `net.Socket` carries; the bare duplexes of a suite need not have one. */
|
|
110
|
+
interface DelayableSocket extends Duplex {
|
|
111
|
+
setNoDelay?: (noDelay: boolean) => void
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Ask the kernel to write each frame out as it is handed over.
|
|
116
|
+
*
|
|
117
|
+
* Every frame on this route is already one whole application message, and a
|
|
118
|
+
* phone pays a round trip for each answer, so Nagle's coalescing window only
|
|
119
|
+
* delays bytes that nothing else is waiting to join. It is set on acceptance
|
|
120
|
+
* because that is the last moment the socket is still ours alone: once the
|
|
121
|
+
* upgrade has been answered, a peer's frame can already be on the way.
|
|
122
|
+
*/
|
|
123
|
+
function stopNagleDelay(socket: Duplex): void {
|
|
124
|
+
const delayable: DelayableSocket = socket
|
|
125
|
+
if (typeof delayable.setNoDelay === 'function') delayable.setNoDelay(true)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* One accepted upgrade handed to the bridge.
|
|
130
|
+
*/
|
|
131
|
+
export interface UpgradeHandoff {
|
|
132
|
+
/** The upgraded socket; the carrier both reads from and writes to it. */
|
|
133
|
+
readonly socket: Duplex
|
|
134
|
+
/** The client's `Sec-WebSocket-Key`, already read from the handshake. */
|
|
135
|
+
readonly secWebSocketKey: string
|
|
136
|
+
/** Bytes that arrived with the upgrade request itself. */
|
|
137
|
+
readonly head: Buffer
|
|
138
|
+
readonly hub: BridgeHub
|
|
139
|
+
/** The device the handshake token proved, when it proved one. */
|
|
140
|
+
readonly auth?: ConnectionAuth
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Hand one accepted upgrade to the hub, in the one order that is correct.
|
|
145
|
+
*
|
|
146
|
+
* Every step here is synchronous, which is what makes the carrier's own
|
|
147
|
+
* pre-handler buffer unnecessary in practice — and the buffer is there anyway,
|
|
148
|
+
* so the bytes of `head` (and anything that beats the handler) are delivered
|
|
149
|
+
* instead of dropped. The order is the point of this function: reading the
|
|
150
|
+
* socket without a handler, or attaching a connection whose carrier is never
|
|
151
|
+
* written to, both end in a client that waits forever.
|
|
152
|
+
* @param handoff - the socket, its handshake facts, and the hub to join.
|
|
153
|
+
* @returns the carrier, for a caller that needs to observe it.
|
|
154
|
+
*/
|
|
155
|
+
export function serveUpgrade(handoff: UpgradeHandoff): WebSocketCarrier {
|
|
156
|
+
const { socket, secWebSocketKey, head, hub, auth } = handoff
|
|
157
|
+
stopNagleDelay(socket)
|
|
158
|
+
const carrier = new WebSocketCarrier(socket)
|
|
159
|
+
carrier.handshake(secWebSocketKey)
|
|
160
|
+
const connection = hub.attach(carrier, auth)
|
|
161
|
+
carrier.onMessage(text => { void connection.handleText(text) })
|
|
162
|
+
carrier.onClose(() => { hub.detach(connection) })
|
|
163
|
+
if (head.length > 0) carrier.feed(head)
|
|
164
|
+
return carrier
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* One accepted socket, framed.
|
|
169
|
+
*
|
|
170
|
+
* Frames are buffered until a whole one has arrived; a fragmented message is
|
|
171
|
+
* reassembled up to {@link MAX_FRAME_BYTES} and anything larger closes the
|
|
172
|
+
* socket with the code that names the violation. The carrier is inert until
|
|
173
|
+
* {@link handshake} runs, so a caller can refuse a connection without having
|
|
174
|
+
* written a byte of the protocol.
|
|
175
|
+
*/
|
|
176
|
+
export class WebSocketCarrier implements BridgeTransport {
|
|
177
|
+
readonly #socket: Duplex
|
|
178
|
+
#buffer: Buffer = Buffer.alloc(0)
|
|
179
|
+
#fragments: Buffer[] = []
|
|
180
|
+
#fragmentOpcode = 0
|
|
181
|
+
#fragmentBytes = 0
|
|
182
|
+
#opened = false
|
|
183
|
+
#closed = false
|
|
184
|
+
#onMessage: ((text: string) => void) | undefined
|
|
185
|
+
#onClose: (() => void) | undefined
|
|
186
|
+
/** Whether the peer declared it can inflate a compressed frame; see {@link frameDeflate}. */
|
|
187
|
+
#deflate = false
|
|
188
|
+
/** Messages that arrived before a handler was registered; see {@link deliver}. */
|
|
189
|
+
readonly #pending: string[] = []
|
|
190
|
+
|
|
191
|
+
constructor(socket: Duplex) {
|
|
192
|
+
this.#socket = socket
|
|
193
|
+
// The socket is this endpoint's ONLY source of bytes. Without this
|
|
194
|
+
// subscription every frame a client sends after the handshake sits in the
|
|
195
|
+
// socket's read buffer forever: the upgrade's leftover `head` is normally
|
|
196
|
+
// empty, so the frame loop would never see a single byte — the client sees a
|
|
197
|
+
// socket that stays open, answers nothing and never closes.
|
|
198
|
+
socket.on('data', (chunk: Buffer) => { this.feed(chunk) })
|
|
199
|
+
socket.on('error', () => { this.#shut() })
|
|
200
|
+
socket.on('close', () => { this.#shut() })
|
|
201
|
+
socket.on('end', () => { this.#shut() })
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Write the 101 handshake carrying the accept value for the client's key. */
|
|
205
|
+
handshake(secWebSocketKey: string): void {
|
|
206
|
+
if (this.#opened || this.#closed) return
|
|
207
|
+
this.#opened = true
|
|
208
|
+
this.#socket.write([
|
|
209
|
+
'HTTP/1.1 101 Switching Protocols',
|
|
210
|
+
'upgrade: websocket',
|
|
211
|
+
'connection: Upgrade',
|
|
212
|
+
`sec-websocket-accept: ${webSocketAccept(secWebSocketKey)}`,
|
|
213
|
+
'',
|
|
214
|
+
'',
|
|
215
|
+
].join('\r\n'))
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Register the handler for every complete text message. */
|
|
219
|
+
onMessage(handler: (text: string) => void): void {
|
|
220
|
+
this.#onMessage = handler
|
|
221
|
+
for (const text of this.#pending.splice(0)) handler(text)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Register the one teardown hook; it runs exactly once. */
|
|
225
|
+
onClose(handler: () => void): void {
|
|
226
|
+
this.#onClose = handler
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Feed raw bytes from the socket into the frame loop. */
|
|
230
|
+
feed(chunk: Buffer): void {
|
|
231
|
+
if (this.#closed) return
|
|
232
|
+
this.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk])
|
|
233
|
+
for (;;) {
|
|
234
|
+
const outcome = parseClientFrame(this.#buffer, MAX_FRAME_BYTES)
|
|
235
|
+
if (outcome.status === 'incomplete') return
|
|
236
|
+
if (outcome.status === 'fault') {
|
|
237
|
+
this.close(outcome.closeCode, outcome.reason)
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
this.#buffer = this.#buffer.subarray(outcome.frame.consumed)
|
|
241
|
+
if (!this.#accept(outcome.frame.fin, outcome.frame.opcode, outcome.frame.payload)) return
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Record the peer's `frame.deflate.v1` declaration, as `hello` reported it.
|
|
247
|
+
*
|
|
248
|
+
* It defaults to off, so a connection that never declares the capability keeps
|
|
249
|
+
* the text frame this carrier always wrote, byte for byte.
|
|
250
|
+
*/
|
|
251
|
+
frameDeflate(declared: boolean): void {
|
|
252
|
+
this.#deflate = declared
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Send one frame: the text itself, or raw DEFLATE of it as a binary frame. */
|
|
256
|
+
send(text: string): void {
|
|
257
|
+
if (this.#closed) return
|
|
258
|
+
const payload = outboundPayloadOf(text, this.#deflate)
|
|
259
|
+
this.#socket.write(payload.binary ? encodeBinaryFrame(payload.deflated) : encodeTextFrame(payload.text))
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Send a close frame and end the socket. Idempotent. */
|
|
263
|
+
close(code: number, reason: string): void {
|
|
264
|
+
if (this.#closed) return
|
|
265
|
+
this.#closed = true
|
|
266
|
+
this.#socket.write(encodeCloseFrame(code, reason))
|
|
267
|
+
this.#socket.end()
|
|
268
|
+
this.#notifyClose()
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** @returns whether the carrier has been torn down. */
|
|
272
|
+
get closed(): boolean {
|
|
273
|
+
return this.#closed
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
#accept(fin: boolean, opcode: number, payload: Buffer): boolean {
|
|
277
|
+
switch (opcode) {
|
|
278
|
+
case OPCODE_TEXT:
|
|
279
|
+
case OPCODE_BINARY: {
|
|
280
|
+
if (this.#fragmentOpcode !== 0) {
|
|
281
|
+
this.close(CLOSE_PROTOCOL_ERROR, 'a new message started before the previous one finished')
|
|
282
|
+
return false
|
|
283
|
+
}
|
|
284
|
+
if (fin) return this.#deliver(opcode, payload)
|
|
285
|
+
this.#fragmentOpcode = opcode
|
|
286
|
+
this.#fragments = [payload]
|
|
287
|
+
this.#fragmentBytes = payload.length
|
|
288
|
+
return true
|
|
289
|
+
}
|
|
290
|
+
case OPCODE_CONTINUATION: {
|
|
291
|
+
if (this.#fragmentOpcode === 0) {
|
|
292
|
+
this.close(CLOSE_PROTOCOL_ERROR, 'continuation frame without a started message')
|
|
293
|
+
return false
|
|
294
|
+
}
|
|
295
|
+
this.#fragmentBytes += payload.length
|
|
296
|
+
if (this.#fragmentBytes > MAX_FRAME_BYTES) {
|
|
297
|
+
this.close(CLOSE_TOO_LARGE, `a message may not exceed ${MAX_FRAME_BYTES} bytes`)
|
|
298
|
+
return false
|
|
299
|
+
}
|
|
300
|
+
this.#fragments.push(payload)
|
|
301
|
+
if (!fin) return true
|
|
302
|
+
const message = Buffer.concat(this.#fragments, this.#fragmentBytes)
|
|
303
|
+
const opcodeOfMessage = this.#fragmentOpcode
|
|
304
|
+
this.#fragments = []
|
|
305
|
+
this.#fragmentBytes = 0
|
|
306
|
+
this.#fragmentOpcode = 0
|
|
307
|
+
return this.#deliver(opcodeOfMessage, message)
|
|
308
|
+
}
|
|
309
|
+
case OPCODE_PING:
|
|
310
|
+
this.#socket.write(encodeServerFrame(OPCODE_PONG, payload))
|
|
311
|
+
return true
|
|
312
|
+
case OPCODE_PONG:
|
|
313
|
+
return true
|
|
314
|
+
case OPCODE_CLOSE:
|
|
315
|
+
this.close(CLOSE_NORMAL, '')
|
|
316
|
+
return false
|
|
317
|
+
default:
|
|
318
|
+
this.close(CLOSE_PROTOCOL_ERROR, `unsupported opcode ${opcode}`)
|
|
319
|
+
return false
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
#deliver(opcode: number, payload: Buffer): boolean {
|
|
324
|
+
if (opcode !== OPCODE_TEXT) {
|
|
325
|
+
this.close(CLOSE_UNSUPPORTED_DATA, 'this endpoint carries text frames only')
|
|
326
|
+
return false
|
|
327
|
+
}
|
|
328
|
+
const text = payload.toString('utf8')
|
|
329
|
+
if (this.#onMessage === undefined) {
|
|
330
|
+
// The mounted wiring order (handshake → attach → onMessage → feed(head)) is
|
|
331
|
+
// synchronous, so this queue is never needed for it: `data` can only fire on
|
|
332
|
+
// a later turn. It is here so that guarantee does not rest on a caller's tick
|
|
333
|
+
// discipline — bytes the carrier is handed first are delivered the moment a
|
|
334
|
+
// handler arrives, instead of being dropped. The bound turns a carrier nobody
|
|
335
|
+
// ever wired into a closed socket rather than a growing buffer.
|
|
336
|
+
if (this.#pending.length >= PENDING_MESSAGE_LIMIT) {
|
|
337
|
+
this.close(CLOSE_TOO_LARGE, 'this connection has no message handler')
|
|
338
|
+
return false
|
|
339
|
+
}
|
|
340
|
+
this.#pending.push(text)
|
|
341
|
+
return true
|
|
342
|
+
}
|
|
343
|
+
this.#onMessage(text)
|
|
344
|
+
return true
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** The socket went away without a close frame: tear down without writing. */
|
|
348
|
+
#shut(): void {
|
|
349
|
+
if (this.#closed) return
|
|
350
|
+
this.#closed = true
|
|
351
|
+
this.#notifyClose()
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
#notifyClose(): void {
|
|
355
|
+
const handler = this.#onClose
|
|
356
|
+
this.#onClose = undefined
|
|
357
|
+
handler?.()
|
|
358
|
+
}
|
|
359
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@linxin666/dsh-remote-bridge` — the Host half of the DSH remote bridge.
|
|
3
|
+
*
|
|
4
|
+
* One plugin row exposes the frozen protocol v1 to a paired remote client:
|
|
5
|
+
*
|
|
6
|
+
* - `/ios/v1` (WebSocket upgrade) carries the whole protocol. Admission is
|
|
7
|
+
* unconditional: a connection without a valid device token is UNPAIRED and
|
|
8
|
+
* may only call `hello`, `pair.begin` and `pair.finish` — even from loopback.
|
|
9
|
+
* - `/remote-bridge/pair/token` (exact HTTP route) mints the one-shot bootstrap
|
|
10
|
+
* token. It is admitted only when the request arrives from this machine AND
|
|
11
|
+
* its `Host` header names this machine: a tunneled request reaches the origin
|
|
12
|
+
* from loopback too, so the socket address alone is not a loopback proof.
|
|
13
|
+
* - `approval/request` is claimed in-process while a paired device is connected,
|
|
14
|
+
* and delegated (`next()`) in every other case, which the Host normalizes to
|
|
15
|
+
* the fail-closed `'unavailable'`.
|
|
16
|
+
* - `user-questions/request` is claimed the same way and published as
|
|
17
|
+
* `question.request` to the devices that declared `questions.v1`; their
|
|
18
|
+
* `question.answer` settles the host's own ask while it is open, or reaches a
|
|
19
|
+
* continued question through the host's Remote `answer`. Every other case
|
|
20
|
+
* delegates, and the question keeps the Host's own deadline.
|
|
21
|
+
*
|
|
22
|
+
* The browser half lives in `src/client/` and is declared by `dsh.client`: one
|
|
23
|
+
* sidebar-foot panel that reads the same loopback-gated token route over a
|
|
24
|
+
* same-origin request and renders the secret as a QR symbol beside its
|
|
25
|
+
* plaintext. It is display-only — it cannot mint, spend, list or revoke
|
|
26
|
+
* anything — and this module does not import it.
|
|
27
|
+
* @module @linxin666/dsh-remote-bridge
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import type { IncomingMessage } from 'node:http'
|
|
31
|
+
import { join } from 'node:path'
|
|
32
|
+
import type { Duplex } from 'node:stream'
|
|
33
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
34
|
+
import type {} from '@deepseek-ai/dsh-api-gateway'
|
|
35
|
+
import type {} from '@deepseek-ai/dsh-host-webserver'
|
|
36
|
+
import type {} from '@deepseek-ai/dsh-session'
|
|
37
|
+
import type {} from '@deepseek-ai/dsh-user-approval'
|
|
38
|
+
import { ApprovalRegistry } from './core/approvals.ts'
|
|
39
|
+
import type { ConnectionAuth } from './core/connection.ts'
|
|
40
|
+
import { DeviceRoster } from './core/devices.ts'
|
|
41
|
+
import { createRemoteBridgeFace, RemoteBridgeRegistry, REMOTE_BRIDGE_SERVICE } from './core/extension.ts'
|
|
42
|
+
import { JobRoster, type JobRegistryFace } from './core/jobs.ts'
|
|
43
|
+
import { BridgeHub } from './core/hub.ts'
|
|
44
|
+
import { createOwnerPeer } from './core/owner-peer.ts'
|
|
45
|
+
import { PairingService } from './core/pairing.ts'
|
|
46
|
+
import { QuestionClaims } from './core/questions.ts'
|
|
47
|
+
import { WS_PATH } from './core/protocol.ts'
|
|
48
|
+
import { SessionMeta, type ArchiveSetFace, type SessionStoreFace, type SessionTitleFace } from './core/session-meta.ts'
|
|
49
|
+
import { SessionPermissions, type ApprovalPolicyFace, type PermissionPresetsFace, type SandboxPolicyFace } from './core/session-permissions.ts'
|
|
50
|
+
import { dshHome } from './host/dsh-home.ts'
|
|
51
|
+
import { mountOnce } from './mount-once.ts'
|
|
52
|
+
import { makePairTokenRoute } from './host/routes.ts'
|
|
53
|
+
import { isWebSocketUpgrade, presentedTokenOf, readSecWebSocketKey, refuseUpgrade, serveUpgrade } from './host/websocket.ts'
|
|
54
|
+
|
|
55
|
+
/** Loader row identity of this plugin. */
|
|
56
|
+
export const name = 'remote-bridge'
|
|
57
|
+
|
|
58
|
+
/** The Host services this plugin cannot run without. */
|
|
59
|
+
export const inject = ['typertGateway', 'webServer']
|
|
60
|
+
|
|
61
|
+
/** Where the paired-device roster lives inside the DSH home. */
|
|
62
|
+
export const ROSTER_PATH = 'remote-bridge/devices.json'
|
|
63
|
+
|
|
64
|
+
/** This machine's IANA time zone, or undefined when the platform has none. */
|
|
65
|
+
function localTimeZone(): string | undefined {
|
|
66
|
+
try {
|
|
67
|
+
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
|
|
68
|
+
return zone === '' ? undefined : zone
|
|
69
|
+
} catch {
|
|
70
|
+
return undefined
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The `/ios/v1` upgrade handler.
|
|
76
|
+
*
|
|
77
|
+
* A bad, absent or bootstrap token is NOT a refusal: the connection is simply
|
|
78
|
+
* unpaired, which is the state the pairing handshake starts from. Only a
|
|
79
|
+
* malformed handshake is refused.
|
|
80
|
+
*/
|
|
81
|
+
function makeUpgradeHandler(hub: BridgeHub, roster: DeviceRoster, log: (message: string) => void) {
|
|
82
|
+
return async (req: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> => {
|
|
83
|
+
if (!isWebSocketUpgrade(req)) {
|
|
84
|
+
refuseUpgrade(socket, 400, 'Bad Request')
|
|
85
|
+
return
|
|
86
|
+
}
|
|
87
|
+
const key = readSecWebSocketKey(req)
|
|
88
|
+
if (key === undefined) {
|
|
89
|
+
refuseUpgrade(socket, 400, 'Bad Request')
|
|
90
|
+
return
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
await roster.load()
|
|
94
|
+
} catch (error) {
|
|
95
|
+
// An unreadable roster leaves every candidate unpaired. Refusing the upgrade
|
|
96
|
+
// says so; letting the handler's promise reject instead would hand the host's
|
|
97
|
+
// upgrade dispatcher a failure it has no answer for and no client would ever see.
|
|
98
|
+
log(`could not read the device roster: ${String(error)}`)
|
|
99
|
+
refuseUpgrade(socket, 503, 'Service Unavailable')
|
|
100
|
+
return
|
|
101
|
+
}
|
|
102
|
+
const token = presentedTokenOf(req)
|
|
103
|
+
const device = token === undefined ? undefined : roster.authenticate(token)
|
|
104
|
+
const auth: ConnectionAuth | undefined = device === undefined ? undefined : { deviceId: device.deviceId }
|
|
105
|
+
serveUpgrade({
|
|
106
|
+
socket,
|
|
107
|
+
secWebSocketKey: key,
|
|
108
|
+
head,
|
|
109
|
+
hub,
|
|
110
|
+
...(auth === undefined ? {} : { auth }),
|
|
111
|
+
})
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Resolve the host services session metadata is read from, now.
|
|
117
|
+
*
|
|
118
|
+
* All three are read per call rather than captured at mount: none of them is in
|
|
119
|
+
* this plugin's `inject` list, because requiring them would let the title or
|
|
120
|
+
* workspace plugin's absence take the whole bridge down with it. An unmounted
|
|
121
|
+
* service simply reads as undefined, and the protocol degrades one key of one
|
|
122
|
+
* row instead of failing a method. The faces are structural — this package
|
|
123
|
+
* imports no part of those services' own types.
|
|
124
|
+
* @param ctx - the plugin's context.
|
|
125
|
+
* @returns the metadata faces as they stand right now.
|
|
126
|
+
*/
|
|
127
|
+
function sessionMetaFaces(ctx: Context) {
|
|
128
|
+
return {
|
|
129
|
+
sessions: ctx.get('sessions') as SessionStoreFace | undefined,
|
|
130
|
+
titles: ctx.get('sessionTitle') as SessionTitleFace | undefined,
|
|
131
|
+
archive: ctx.get('workspaceRegistry') as ArchiveSetFace | undefined,
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Resolve the host services permission presets are read and switched through, now.
|
|
137
|
+
*
|
|
138
|
+
* Read per call, never captured at mount, for the reason the metadata faces are:
|
|
139
|
+
* none of these is in this plugin's `inject` list, and a host that composes no
|
|
140
|
+
* permission plugin answers `unknown-method` instead of failing to start. The
|
|
141
|
+
* `Session` object the preset service needs is the store's own live instance —
|
|
142
|
+
* the same object `sessionTitle` already takes — so no second lookup path exists
|
|
143
|
+
* for it.
|
|
144
|
+
* @param ctx - the plugin's context.
|
|
145
|
+
* @returns the permission faces as they stand right now.
|
|
146
|
+
*/
|
|
147
|
+
function permissionFaces(ctx: Context) {
|
|
148
|
+
return {
|
|
149
|
+
sessions: ctx.get('sessions') as SessionStoreFace | undefined,
|
|
150
|
+
presets: ctx.get('permissionPresets') as PermissionPresetsFace | undefined,
|
|
151
|
+
sandbox: ctx.get('sandboxPolicy') as SandboxPolicyFace | undefined,
|
|
152
|
+
approval: ctx.get('approval') as ApprovalPolicyFace | undefined,
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Resolve the host's job registry, now.
|
|
158
|
+
*
|
|
159
|
+
* Read per call, never captured at mount, for the reason the metadata faces
|
|
160
|
+
* are: `jobs` is not in this plugin's `inject` list, so a host that composes
|
|
161
|
+
* no job plugin still serves protocol v1 — `jobs.list` answers
|
|
162
|
+
* `jobs-unavailable` instead of the bridge failing to start. The face is
|
|
163
|
+
* structural: this package imports no part of the registry's own types.
|
|
164
|
+
* @param ctx - the plugin's context.
|
|
165
|
+
* @returns the job faces as they stand right now.
|
|
166
|
+
*/
|
|
167
|
+
function jobFaces(ctx: Context) {
|
|
168
|
+
return {
|
|
169
|
+
jobs: ctx.get('jobs') as JobRegistryFace | undefined,
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Mount the bridge.
|
|
175
|
+
*
|
|
176
|
+
* Guarded by the family's single-instance rule: the aggregate row
|
|
177
|
+
* (`web-ui-remote-bridge`) and a standalone install of this same package can
|
|
178
|
+
* both be live in one profile, and the second mount would otherwise register
|
|
179
|
+
* `/ios/v1` and the token route a second time. Whichever source mounts first
|
|
180
|
+
* owns the package name; the other is queued and replayed when that owner
|
|
181
|
+
* disposes.
|
|
182
|
+
* @param ctx - the plugin's context, carrying the gateway and web server.
|
|
183
|
+
*/
|
|
184
|
+
function applyImpl(ctx: Context): void {
|
|
185
|
+
const log = (message: string): void => { console.log(`[remote-bridge] ${message}`) }
|
|
186
|
+
const roster = new DeviceRoster({ file: join(dshHome(), ROSTER_PATH), log })
|
|
187
|
+
const pairing = new PairingService()
|
|
188
|
+
const approvals = new ApprovalRegistry()
|
|
189
|
+
// The owner peer is the full-control credential the gateway demands since
|
|
190
|
+
// 0.2.1; it is safe to hold from mount because every call that can trigger
|
|
191
|
+
// it is gated by the bridge's own pairing check (see core/owner-peer.ts).
|
|
192
|
+
const ownerPeer = createOwnerPeer(ctx)
|
|
193
|
+
const questions = new QuestionClaims({ gateway: ctx.typertGateway, peer: ownerPeer, log })
|
|
194
|
+
// One roster per mount, shared by every connection: a background job is a fact
|
|
195
|
+
// about the host, not about the device that asked about it.
|
|
196
|
+
const jobs = new JobRoster({ faces: () => jobFaces(ctx), log })
|
|
197
|
+
const sessionMeta = new SessionMeta(() => sessionMetaFaces(ctx), () => Date.now(), log)
|
|
198
|
+
const permissions = new SessionPermissions(() => permissionFaces(ctx), log)
|
|
199
|
+
// The extension seam publishes no protocol vocabulary of its own: another
|
|
200
|
+
// plugin registers the method names, payloads and topics it owns, and this
|
|
201
|
+
// package only dispatches and fans out what it was handed.
|
|
202
|
+
const extensions = new RemoteBridgeRegistry()
|
|
203
|
+
const hub = new BridgeHub({
|
|
204
|
+
extensions,
|
|
205
|
+
gateway: ctx.typertGateway,
|
|
206
|
+
pairing,
|
|
207
|
+
roster,
|
|
208
|
+
approvals,
|
|
209
|
+
questions,
|
|
210
|
+
jobs,
|
|
211
|
+
sessionMeta,
|
|
212
|
+
permissions,
|
|
213
|
+
ownerPeer,
|
|
214
|
+
now: () => Date.now(),
|
|
215
|
+
clientTimeZone: localTimeZone,
|
|
216
|
+
log,
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
// A capture-only test context implements no service registry; a Host always
|
|
220
|
+
// does. Without it the bridge still serves protocol v1, minus other plugins'
|
|
221
|
+
// methods, which is exactly what not publishing the seam means.
|
|
222
|
+
if (typeof (ctx as { provide?: unknown }).provide === 'function') {
|
|
223
|
+
ctx.provide(REMOTE_BRIDGE_SERVICE, createRemoteBridgeFace(extensions, hub))
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
ctx.effect(() => {
|
|
227
|
+
void roster.load()
|
|
228
|
+
const disposeUpgrade = ctx.webServer.registerUpgrade({
|
|
229
|
+
path: WS_PATH,
|
|
230
|
+
handler: makeUpgradeHandler(hub, roster, log),
|
|
231
|
+
})
|
|
232
|
+
const disposeRoute = ctx.webServer.register(makePairTokenRoute({ pairing, log }))
|
|
233
|
+
log(`protocol v1 listening on ${WS_PATH}`)
|
|
234
|
+
return () => {
|
|
235
|
+
disposeUpgrade()
|
|
236
|
+
disposeRoute()
|
|
237
|
+
hub.dispose()
|
|
238
|
+
jobs.dispose()
|
|
239
|
+
}
|
|
240
|
+
}, 'remote-bridge: protocol v1 routes')
|
|
241
|
+
|
|
242
|
+
ctx.on('approval/request', (request, next) => hub.approve(request, next))
|
|
243
|
+
// Prepended: the host's waterfall is first-come, and the desktop client's own
|
|
244
|
+
// answerer would otherwise claim every question before this listener is
|
|
245
|
+
// consulted. The claim starts the rest of the chain itself, so prepending does
|
|
246
|
+
// not take the desktop panel away — both surfaces show the question and the
|
|
247
|
+
// first answer settles it.
|
|
248
|
+
ctx.on('user-questions/request', (request, next) => hub.question(request, next), { prepend: true })
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* The plugin's mount point: {@link applyImpl} behind the family's
|
|
253
|
+
* single-instance guard. The name is the npm package identity, which every
|
|
254
|
+
* install source of this plugin shares — the aggregate's `web-ui-remote-bridge`
|
|
255
|
+
* row and the standalone `remote-bridge` row alike.
|
|
256
|
+
*/
|
|
257
|
+
export const apply = mountOnce('@linxin666/dsh-remote-bridge', applyImpl)
|