@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.
Files changed (81) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +277 -2
  4. package/README.zh.md +276 -0
  5. package/cordis.patch.yml +17 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +1830 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +5789 -0
  10. package/lib/types/client/PairEntry.d.ts +16 -0
  11. package/lib/types/client/PairPanel.d.ts +55 -0
  12. package/lib/types/client/icons.d.ts +18 -0
  13. package/lib/types/client/index.d.ts +35 -0
  14. package/lib/types/client/locales.d.ts +42 -0
  15. package/lib/types/client/pair-token.d.ts +73 -0
  16. package/lib/types/client/semantic.d.ts +28 -0
  17. package/lib/types/core/approvals.d.ts +99 -0
  18. package/lib/types/core/connection.d.ts +170 -0
  19. package/lib/types/core/crypto.d.ts +48 -0
  20. package/lib/types/core/delta.d.ts +101 -0
  21. package/lib/types/core/devices.d.ts +72 -0
  22. package/lib/types/core/dsh-frames.d.ts +332 -0
  23. package/lib/types/core/envelope.d.ts +132 -0
  24. package/lib/types/core/extension.d.ts +144 -0
  25. package/lib/types/core/gateway-errors.d.ts +49 -0
  26. package/lib/types/core/hub.d.ts +127 -0
  27. package/lib/types/core/jobs.d.ts +204 -0
  28. package/lib/types/core/loopback.d.ts +35 -0
  29. package/lib/types/core/owner-peer.d.ts +49 -0
  30. package/lib/types/core/pairing.d.ts +61 -0
  31. package/lib/types/core/protocol.d.ts +319 -0
  32. package/lib/types/core/questions.d.ts +294 -0
  33. package/lib/types/core/session-meta.d.ts +105 -0
  34. package/lib/types/core/session-permissions.d.ts +134 -0
  35. package/lib/types/core/wire.d.ts +115 -0
  36. package/lib/types/core/ws-frames.d.ts +72 -0
  37. package/lib/types/host/dsh-home.d.ts +16 -0
  38. package/lib/types/host/pair-origin.d.ts +44 -0
  39. package/lib/types/host/routes.d.ts +27 -0
  40. package/lib/types/host/websocket.d.ts +111 -0
  41. package/lib/types/index.d.ts +55 -0
  42. package/lib/types/mount-once.d.ts +55 -0
  43. package/locale/en.json +6 -0
  44. package/locale/ru.json +6 -0
  45. package/locale/zh.json +6 -0
  46. package/package.json +93 -3
  47. package/src/client/PairEntry.tsx +151 -0
  48. package/src/client/PairPanel.tsx +183 -0
  49. package/src/client/icons.tsx +72 -0
  50. package/src/client/index.ts +81 -0
  51. package/src/client/locales.ts +72 -0
  52. package/src/client/pair-token.ts +104 -0
  53. package/src/client/panel.module.css +344 -0
  54. package/src/client/semantic.ts +37 -0
  55. package/src/core/approvals.ts +173 -0
  56. package/src/core/connection.ts +1906 -0
  57. package/src/core/crypto.ts +113 -0
  58. package/src/core/delta.ts +204 -0
  59. package/src/core/devices.ts +209 -0
  60. package/src/core/dsh-frames.ts +843 -0
  61. package/src/core/envelope.ts +219 -0
  62. package/src/core/extension.ts +197 -0
  63. package/src/core/gateway-errors.ts +92 -0
  64. package/src/core/hub.ts +310 -0
  65. package/src/core/jobs.ts +372 -0
  66. package/src/core/loopback.ts +60 -0
  67. package/src/core/owner-peer.ts +70 -0
  68. package/src/core/pairing.ts +113 -0
  69. package/src/core/protocol.ts +381 -0
  70. package/src/core/questions.ts +630 -0
  71. package/src/core/session-meta.ts +176 -0
  72. package/src/core/session-permissions.ts +266 -0
  73. package/src/core/wire.ts +159 -0
  74. package/src/core/ws-frames.ts +139 -0
  75. package/src/css-modules.d.ts +6 -0
  76. package/src/host/dsh-home.ts +42 -0
  77. package/src/host/pair-origin.ts +77 -0
  78. package/src/host/routes.ts +85 -0
  79. package/src/host/websocket.ts +359 -0
  80. package/src/index.ts +257 -0
  81. package/src/mount-once.ts +142 -0
@@ -0,0 +1,139 @@
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
+ * Close code for a peer that stopped answering: a liveness ping went out and no
32
+ * frame at all came back before its deadline.
33
+ *
34
+ * It is an application-range code (4000-4999), so a client can tell a peer that
35
+ * went silent from a protocol fault, from a frame this bridge will not carry,
36
+ * and from the ordinary 1001 teardown of a bridge that is unloading.
37
+ */
38
+ export const CLOSE_LIVENESS_TIMEOUT = 4000
39
+
40
+ /** @returns the `Sec-WebSocket-Accept` value for a client's key. */
41
+ export function webSocketAccept(secWebSocketKey: string): string {
42
+ return createHash('sha1').update(`${secWebSocketKey}${WS_GUID}`).digest('base64')
43
+ }
44
+
45
+ /** One decoded frame header plus its payload. */
46
+ export interface DecodedFrame {
47
+ readonly fin: boolean
48
+ readonly opcode: number
49
+ readonly payload: Buffer
50
+ /** Bytes this frame occupies in the stream. */
51
+ readonly consumed: number
52
+ }
53
+
54
+ export type FrameParseOutcome =
55
+ | { readonly status: 'incomplete' }
56
+ | { readonly status: 'frame'; readonly frame: DecodedFrame }
57
+ | { readonly status: 'fault'; readonly closeCode: number; readonly reason: string }
58
+
59
+ /**
60
+ * Decode one frame from the head of a buffer.
61
+ * @param buffer - the bytes received so far.
62
+ * @param maxBytes - largest payload this bridge accepts.
63
+ */
64
+ export function parseClientFrame(buffer: Buffer, maxBytes: number): FrameParseOutcome {
65
+ if (buffer.length < 2) return { status: 'incomplete' }
66
+ const first = buffer[0] ?? 0
67
+ const second = buffer[1] ?? 0
68
+ const fin = (first & 0x80) !== 0
69
+ // RSV1-3 are only meaningful with an extension this bridge never negotiates.
70
+ if ((first & 0x70) !== 0) return fault(CLOSE_PROTOCOL_ERROR, 'reserved bits set')
71
+ const opcode = first & 0x0f
72
+ const masked = (second & 0x80) !== 0
73
+ if (!masked) return fault(CLOSE_PROTOCOL_ERROR, 'client frames must be masked')
74
+ let length = second & 0x7f
75
+ let offset = 2
76
+ if (length === 126) {
77
+ if (buffer.length < offset + 2) return { status: 'incomplete' }
78
+ length = buffer.readUInt16BE(offset)
79
+ offset += 2
80
+ } else if (length === 127) {
81
+ if (buffer.length < offset + 8) return { status: 'incomplete' }
82
+ const wide = buffer.readBigUInt64BE(offset)
83
+ if (wide > BigInt(Number.MAX_SAFE_INTEGER)) return fault(CLOSE_TOO_LARGE, 'frame length out of range')
84
+ length = Number(wide)
85
+ offset += 8
86
+ }
87
+ if (length > maxBytes) return fault(CLOSE_TOO_LARGE, `frame payload exceeds ${maxBytes} bytes`)
88
+ if (buffer.length < offset + 4 + length) return { status: 'incomplete' }
89
+ const mask = buffer.subarray(offset, offset + 4)
90
+ offset += 4
91
+ const payload = Buffer.allocUnsafe(length)
92
+ for (let index = 0; index < length; index += 1) payload[index] = (buffer[offset + index] ?? 0) ^ (mask[index % 4] ?? 0)
93
+ return { status: 'frame', frame: { fin, opcode, payload, consumed: offset + length } }
94
+ }
95
+
96
+ function fault(closeCode: number, reason: string): FrameParseOutcome {
97
+ return { status: 'fault', closeCode, reason }
98
+ }
99
+
100
+ /**
101
+ * Encode one server frame. Server frames are never masked.
102
+ * @param opcode - the frame opcode.
103
+ * @param payload - already-serialized payload bytes.
104
+ * @param fin - whether this frame completes the message.
105
+ */
106
+ export function encodeServerFrame(opcode: number, payload: Buffer, fin = true): Buffer {
107
+ const length = payload.length
108
+ const header = length < 126
109
+ ? Buffer.from([(fin ? 0x80 : 0) | opcode, length])
110
+ : length <= 0xffff
111
+ ? Buffer.from([(fin ? 0x80 : 0) | opcode, 126, length >> 8, length & 0xff])
112
+ : (() => {
113
+ const wide = Buffer.alloc(10)
114
+ wide[0] = (fin ? 0x80 : 0) | opcode
115
+ wide[1] = 127
116
+ wide.writeBigUInt64BE(BigInt(length), 2)
117
+ return wide
118
+ })()
119
+ return Buffer.concat([header, payload])
120
+ }
121
+
122
+ /** Encode one text message. */
123
+ export function encodeTextFrame(text: string): Buffer {
124
+ return encodeServerFrame(OPCODE_TEXT, Buffer.from(text, 'utf8'))
125
+ }
126
+
127
+ /** Encode one binary message: already-encoded payload bytes, never a text frame. */
128
+ export function encodeBinaryFrame(payload: Buffer): Buffer {
129
+ return encodeServerFrame(OPCODE_BINARY, payload)
130
+ }
131
+
132
+ /** Encode one close frame with a code and a short reason. */
133
+ export function encodeCloseFrame(code: number, reason: string): Buffer {
134
+ const text = Buffer.from(reason, 'utf8').subarray(0, 123)
135
+ const payload = Buffer.alloc(2 + text.length)
136
+ payload.writeUInt16BE(code, 0)
137
+ text.copy(payload, 2)
138
+ return encodeServerFrame(OPCODE_CLOSE, payload)
139
+ }
@@ -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
+ }