@linxin666/dsh-remote-bridge 0.4.12 → 0.4.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +45 -8
  3. package/README.zh.md +45 -8
  4. package/lib/client.js +1 -1
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18031 -373
  7. package/lib/types/core/connection.d.ts +9 -0
  8. package/lib/types/core/devices.d.ts +27 -6
  9. package/lib/types/core/liveactivity.d.ts +7 -0
  10. package/lib/types/core/model-efforts.d.ts +83 -0
  11. package/lib/types/core/protocol.d.ts +2 -0
  12. package/lib/types/core/push.d.ts +51 -2
  13. package/lib/types/host/firewall.d.ts +74 -0
  14. package/lib/types/host/host-bind-capability.d.ts +90 -0
  15. package/lib/types/host/ingress-gate.d.ts +59 -0
  16. package/lib/types/host/ingress-sync.d.ts +429 -0
  17. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  18. package/lib/types/host/lan-bind.d.ts +106 -0
  19. package/lib/types/host/lan-forward.d.ts +112 -0
  20. package/lib/types/host/lan.d.ts +61 -0
  21. package/lib/types/host/pair-origin.d.ts +34 -19
  22. package/lib/types/host/relay-bridge-connector.d.ts +215 -0
  23. package/lib/types/host/relay-connector.d.ts +152 -0
  24. package/lib/types/host/relay-control.d.ts +124 -0
  25. package/lib/types/host/relay-registry.d.ts +114 -0
  26. package/lib/types/host/relay.d.ts +170 -0
  27. package/lib/types/host/routes.d.ts +24 -1
  28. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  29. package/lib/types/host/tunnel-plan.d.ts +41 -0
  30. package/lib/types/host/tunnel.d.ts +289 -0
  31. package/lib/types/index.d.ts +426 -1
  32. package/package.json +4 -2
  33. package/src/client/panel.module.css +16 -1
  34. package/src/core/connection.ts +206 -11
  35. package/src/core/devices.ts +31 -6
  36. package/src/core/hub.ts +17 -5
  37. package/src/core/liveactivity.ts +16 -2
  38. package/src/core/model-efforts.ts +223 -0
  39. package/src/core/protocol.ts +3 -0
  40. package/src/core/push.ts +70 -4
  41. package/src/host/firewall.ts +230 -0
  42. package/src/host/host-bind-capability.ts +249 -0
  43. package/src/host/ingress-gate.ts +203 -0
  44. package/src/host/ingress-sync.ts +1074 -0
  45. package/src/host/lan-bind-plan.ts +134 -0
  46. package/src/host/lan-bind.ts +250 -0
  47. package/src/host/lan-forward.ts +321 -0
  48. package/src/host/lan.ts +142 -0
  49. package/src/host/pair-origin.ts +44 -38
  50. package/src/host/relay-bridge-connector.ts +783 -0
  51. package/src/host/relay-connector.ts +317 -0
  52. package/src/host/relay-control.ts +224 -0
  53. package/src/host/relay-registry.ts +263 -0
  54. package/src/host/relay.ts +294 -0
  55. package/src/host/routes.ts +47 -3
  56. package/src/host/tunnel-orphan.ts +325 -0
  57. package/src/host/tunnel-plan.ts +58 -0
  58. package/src/host/tunnel.ts +688 -0
  59. package/src/index.ts +1280 -22
@@ -0,0 +1,249 @@
1
+ /**
2
+ * What the installed webserver accepts as a bind address, plus the address
3
+ * classes the LAN-bind decision needs (issue #1893).
4
+ *
5
+ * The managed LAN-bind block used to pin `host: '0.0.0.0'`. Since
6
+ * `@deepseek-ai/dsh-host-webserver@0.2.1-rc.2` the webserver `Config` schema
7
+ * rejects the unspecified (wildcard) address, so such a block is refused at
8
+ * config validation and every later `dsh web` start fails. This module is the
9
+ * one place that asks the installed package instead of assuming, and the block
10
+ * planner reads its answer.
11
+ *
12
+ * The value import below is a devDependency of this package and must stay
13
+ * external in the published bundle: the host process resolves it from the
14
+ * profile tree, which is exactly the module it is about to compose. A host this
15
+ * module cannot interrogate is never assumed permissive - every failure path
16
+ * answers "no wildcard", because an unreadable package must not make the block
17
+ * pin a literal that refuses to boot.
18
+ *
19
+ * @module dsh-remote-bridge/host/host-bind-capability
20
+ */
21
+
22
+ import * as webserver from '@deepseek-ai/dsh-host-webserver'
23
+
24
+ /** A schemastery-style schema: call the factory, throw on refusal. */
25
+ export type ConfigSchemaFactory = (value: unknown) => unknown
26
+
27
+ /** The bind value this probe validates: the wildcard literal and a fixed port. */
28
+ const PROBE_BIND = { host: '0.0.0.0', port: 3080 } as const
29
+
30
+ /**
31
+ * Whether a value can hold a `Config` factory. The package exports the
32
+ * WebServer class itself, a namespace object holding it, and a default export;
33
+ * a class is a function, so both kinds count.
34
+ */
35
+ function isHolder(value: unknown): boolean {
36
+ return (typeof value === 'object' && value !== null) || typeof value === 'function'
37
+ }
38
+
39
+ /**
40
+ * The schema factory of whatever module shape was loaded. The package exposes
41
+ * `WebServer` both as a named export and as the default, and the default may
42
+ * itself be a namespace, so the lookup walks those two links. Anything without
43
+ * a callable `Config` is treated as an unusable shape.
44
+ * @param moduleNamespace - the loaded module object (or any nested holder).
45
+ * @returns the schema factory, or undefined when the shape is unusable.
46
+ */
47
+ export function configSchemaOf(moduleNamespace: unknown): ConfigSchemaFactory | undefined {
48
+ const seen = new Set<unknown>()
49
+ const queue: unknown[] = [moduleNamespace]
50
+ while (queue.length > 0) {
51
+ const current = queue.shift()
52
+ if (!isHolder(current) || seen.has(current)) continue
53
+ seen.add(current)
54
+ let config: unknown
55
+ try {
56
+ config = (current as { Config?: unknown }).Config
57
+ } catch {
58
+ continue
59
+ }
60
+ if (typeof config === 'function') return config as ConfigSchemaFactory
61
+ try {
62
+ const holder = current as { default?: unknown; WebServer?: unknown }
63
+ queue.push(holder.default, holder.WebServer)
64
+ } catch {
65
+ // A throwing accessor is not a shape this probe can read.
66
+ }
67
+ }
68
+ return undefined
69
+ }
70
+
71
+ /**
72
+ * Validate the wildcard bind against one schema factory.
73
+ * @param configOf - the schema factory to interrogate (undefined = unusable shape).
74
+ * @returns true only when the schema accepts the wildcard bind.
75
+ */
76
+ export function probeWildcardBindSupport(configOf: ConfigSchemaFactory | undefined): boolean {
77
+ if (typeof configOf !== 'function') return false
78
+ try {
79
+ configOf({ host: PROBE_BIND.host, port: PROBE_BIND.port })
80
+ return true
81
+ } catch {
82
+ return false
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Memoized answers, keyed by the schema factory itself: the installed module
88
+ * hands over the same function every call, so the schema is interrogated once
89
+ * per process, and an injected factory answers per factory.
90
+ */
91
+ const probeAnswers = new WeakMap<ConfigSchemaFactory, boolean>()
92
+
93
+ /**
94
+ * Whether the host this plugin runs on accepts the wildcard bind. Grounded in
95
+ * the installed package's own schema, so it cannot drift away from the host
96
+ * whatever the version is called; false when the package cannot be read.
97
+ * @param configOf - schema factory override (test seam); by default the
98
+ * installed package's own `WebServer.Config`.
99
+ * @returns true only when the wildcard bind validates.
100
+ */
101
+ export function wildcardBindSupported(configOf?: ConfigSchemaFactory): boolean {
102
+ const factory = configOf ?? configSchemaOf(webserver)
103
+ // A non-callable shape cannot key the WeakMap below; it answers "no
104
+ // wildcard" like every other unreadable path in this module.
105
+ if (typeof factory !== 'function') return false
106
+ const cached = probeAnswers.get(factory)
107
+ if (cached !== undefined) return cached
108
+ const supported = probeWildcardBindSupport(factory)
109
+ probeAnswers.set(factory, supported)
110
+ return supported
111
+ }
112
+
113
+ /**
114
+ * Validate one bind literal against one schema factory, the way the host
115
+ * validates a profile's webserver row.
116
+ * @param configOf - the schema factory to interrogate (undefined = unusable shape).
117
+ * @param host - the bind literal to validate.
118
+ * @returns true only when the schema accepts that literal on a fixed port.
119
+ */
120
+ export function probeBindAccepted(configOf: ConfigSchemaFactory | undefined, host: string): boolean {
121
+ if (typeof configOf !== 'function' || typeof host !== 'string' || host === '') return false
122
+ try {
123
+ configOf({ host, port: PROBE_BIND.port })
124
+ return true
125
+ } catch {
126
+ return false
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Answers already measured per schema factory, keyed by the bind literal: the
132
+ * installed module hands over the same function every call, so each literal is
133
+ * interrogated once per process, and an injected factory answers per factory.
134
+ * The inner map is bounded by the literals a boot can ask about - the CLI flag
135
+ * and the sampled interface addresses.
136
+ */
137
+ const acceptedHostAnswers = new WeakMap<ConfigSchemaFactory, Map<string, boolean>>()
138
+
139
+ /**
140
+ * Whether the running host accepts one bind literal. This is the rule the
141
+ * managed block must follow instead of "is it a wildcard": the block REPLACES
142
+ * the webserver row's config wholesale, so nothing else validates the CLI
143
+ * `--host` that reaches it, and a literal the schema refuses bricks the next
144
+ * start with a block that cannot be fixed from the settings card (issue #1893).
145
+ * @param host - the bind literal to validate (an absent or empty value is never accepted).
146
+ * @param configOf - schema factory override (test seam); by default the
147
+ * installed package's own `WebServer.Config`.
148
+ * @returns true only when the schema accepts the literal; false on every
149
+ * unreadable shape, and never throws.
150
+ */
151
+ export function bindAccepted(host: string | undefined, configOf?: ConfigSchemaFactory): boolean {
152
+ if (typeof host !== 'string' || host === '') return false
153
+ const factory = configOf ?? configSchemaOf(webserver)
154
+ // The shape check sits ahead of the cache: a non-callable value is not a key
155
+ // a WeakMap accepts, and a probe that throws on an unreadable shape would
156
+ // take the boot path down instead of answering "not accepted".
157
+ if (typeof factory !== 'function') return false
158
+ let answers = acceptedHostAnswers.get(factory)
159
+ if (answers === undefined) {
160
+ answers = new Map<string, boolean>()
161
+ acceptedHostAnswers.set(factory, answers)
162
+ }
163
+ const cached = answers.get(host)
164
+ if (cached !== undefined) return cached
165
+ const accepted = probeBindAccepted(factory, host)
166
+ answers.set(host, accepted)
167
+ return accepted
168
+ }
169
+
170
+ /**
171
+ * The host package's own predicate, when it exports a callable one.
172
+ * @param name - the exported predicate's name.
173
+ * @param host - the bind value to classify.
174
+ * @returns its verdict, or undefined when the package cannot answer.
175
+ */
176
+ function hostPredicate(name: 'isWildcardHost' | 'isLoopbackHost', host: string): boolean | undefined {
177
+ try {
178
+ const fn = (webserver as unknown as Record<string, unknown>)[name]
179
+ if (typeof fn !== 'function') return undefined
180
+ return (fn as (value: string) => boolean)(host) === true
181
+ } catch {
182
+ return undefined
183
+ }
184
+ }
185
+
186
+ /** Local fallback for the wildcard classes: IPv4 any, IPv6 any, mapped IPv4 any. */
187
+ function localWildcard(token: string): boolean {
188
+ return token === '0.0.0.0'
189
+ || token === '::'
190
+ || token === '0:0:0:0:0:0:0:0'
191
+ || token === '::ffff:0.0.0.0'
192
+ }
193
+
194
+ /** Local fallback for the loopback classes: 127/8, ::1, mapped and expanded forms. */
195
+ function localLoopback(token: string): boolean {
196
+ if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(token)) return true
197
+ if (token === '::1' || token === '0:0:0:0:0:0:0:1') return true
198
+ return /^::ffff:127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(token)
199
+ }
200
+
201
+ /** Local fallback for an IPv4 literal (the only address class a URL base can be built from bare). */
202
+ function isIPv4Literal(token: string): boolean {
203
+ const parts = token.split('.')
204
+ if (parts.length !== 4) return false
205
+ return parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
206
+ }
207
+
208
+ /**
209
+ * Whether a bind value asks for every interface at once.
210
+ * @param host - the bind value (absent while a recompose pass has not settled).
211
+ * @returns true for the wildcard classes.
212
+ */
213
+ export function isWildcardLiteral(host: string | undefined): boolean {
214
+ if (typeof host !== 'string' || host === '') return false
215
+ return hostPredicate('isWildcardHost', host) ?? localWildcard(host.trim().toLowerCase())
216
+ }
217
+
218
+ /**
219
+ * Whether a bind value names this machine only, so no other device can dial
220
+ * it: the loopback literals of the host package (127/8, ::1 and their mapped
221
+ * forms), the `localhost` token the schema refuses as a literal, and an absent
222
+ * bind. A hostname is treated by the host package's own verdict, not guessed.
223
+ * @param host - the bind value (absent while a recompose pass has not settled).
224
+ * @returns true when nothing off this machine can reach the listener.
225
+ */
226
+ export function isLoopbackBind(host: string | undefined): boolean {
227
+ if (typeof host !== 'string') return true
228
+ const token = host.trim().toLowerCase()
229
+ if (token === '' || token === 'localhost') return true
230
+ return hostPredicate('isLoopbackHost', host) ?? localLoopback(token)
231
+ }
232
+
233
+ /**
234
+ * The URL authority a concrete bind literal is expressed by. The host package
235
+ * owns the canonical form (mapped loopback collapses to dotted quad, IPv6 gets
236
+ * bracketed, a non-loopback zone id has no URL form).
237
+ * @param host - a concrete bind literal.
238
+ * @returns the URL host, or undefined when the literal has no URL form.
239
+ */
240
+ export function bindUrlHostOf(host: string): string | undefined {
241
+ try {
242
+ const fn = (webserver as unknown as { bindUrlHost?: unknown }).bindUrlHost
243
+ if (typeof fn === 'function') return (fn as (value: string) => string | undefined)(host)
244
+ } catch {
245
+ // Fall through to the local rule below.
246
+ }
247
+ const token = host.trim().toLowerCase()
248
+ return isIPv4Literal(token) ? host : undefined
249
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * The inbound ingress gate: one loopback-only HTTP listener that forwards
3
+ * exactly one upgrade path to the host's own protocol port.
4
+ *
5
+ * It exists so a tunnel or the relay bridge can be pointed at a listener whose
6
+ * whole surface is `WS_PATH`. Everything else is refused at this hop instead
7
+ * of being forwarded and judged further in: a request the gate does not serve
8
+ * never opens an upstream connection, so the host's routes, plugins and
9
+ * control plane are not reachable through it even by a misconfigured tunnel.
10
+ *
11
+ * The gate holds no state between two connections: it writes no log line,
12
+ * touches no file, and keeps no token. The only thing it owns is one socket
13
+ * per side, closed together.
14
+ *
15
+ * @module dsh-remote-bridge/host/ingress-gate
16
+ */
17
+
18
+ import http from 'node:http'
19
+ import { connect } from 'node:net'
20
+ import type { AddressInfo, Socket } from 'node:net'
21
+ import { WS_PATH } from '../core/protocol.ts'
22
+
23
+ /** The body every refused request and upgrade is answered with. */
24
+ export const INGRESS_NOT_FOUND_BODY = '{"error":"not-found"}'
25
+
26
+ /**
27
+ * The one address the gate ever binds. It is a loopback listener by
28
+ * construction: nothing outside this machine may reach it directly, which is
29
+ * what keeps the forwarding decision the only way in.
30
+ */
31
+ export const INGRESS_BIND_HOST = '127.0.0.1'
32
+
33
+ /**
34
+ * Whether one inbound URL is the single path this gate forwards.
35
+ *
36
+ * The comparison is on the path, not the whole URL: the pairing link carries
37
+ * its one-shot ticket in the query (`WS_PATH?token=...`), so a strict
38
+ * whole-URL match would refuse the one client the host is waiting for. A path
39
+ * that merely starts the same way, another path, and an empty URL are refused.
40
+ * @param url - the request URL as node reports it.
41
+ * @returns true when the path is exactly `WS_PATH`.
42
+ */
43
+ export function isIngressPath(url: string): boolean {
44
+ const query = url.indexOf('?')
45
+ return (query === -1 ? url : url.slice(0, query)) === WS_PATH
46
+ }
47
+
48
+ /** What the gate needs to know to dial the host's own listener. */
49
+ export interface IngressGateOptions {
50
+ /** The host the upstream protocol listener answers on. */
51
+ upstreamHost: string
52
+ /** The port the upstream protocol listener bound. */
53
+ upstreamPort: number
54
+ }
55
+
56
+ /** The port the gate took. */
57
+ export interface IngressGateStarted {
58
+ port: number
59
+ }
60
+
61
+ /** One ingress gate: bind, report the port, close. */
62
+ export interface IngressGate {
63
+ /** Bind the loopback listener and report the port it took. */
64
+ start(): Promise<IngressGateStarted>
65
+ /** Close the listener and every socket it still holds (idempotent). */
66
+ stop(): void
67
+ }
68
+
69
+ /** The response head of one refused upgrade, which has no `ServerResponse`. */
70
+ function notFoundHead(length: number): string {
71
+ return 'HTTP/1.1 404 Not Found\r\n'
72
+ + 'content-type: application/json\r\n'
73
+ + 'content-length: ' + String(length) + '\r\n'
74
+ + 'connection: close\r\n'
75
+ + '\r\n'
76
+ }
77
+
78
+ /**
79
+ * Rebuild the upgrade request line and headers for the upstream hop: the
80
+ * `Host` the phone dialed is dropped and replaced with the loopback authority
81
+ * the host's own admission gate expects, and every other header travels
82
+ * untouched (the upgrade handshake cannot be reconstructed header by header
83
+ * without losing what the protocol put there).
84
+ * @param request - the inbound upgrade request.
85
+ * @param authority - the `host:port` the upstream listener answers on.
86
+ * @returns the request head, headers included, ending in a blank line.
87
+ */
88
+ function upstreamHead(request: http.IncomingMessage, authority: string): string {
89
+ const lines = ['GET ' + (request.url ?? '/') + ' HTTP/1.1']
90
+ const raw = request.rawHeaders
91
+ for (let index = 0; index + 1 < raw.length; index += 2) {
92
+ if (raw[index].toLowerCase() === 'host') continue
93
+ lines.push(raw[index] + ': ' + raw[index + 1])
94
+ }
95
+ lines.push('Host: ' + authority)
96
+ return lines.join('\r\n') + '\r\n\r\n'
97
+ }
98
+
99
+ /**
100
+ * Build one gate.
101
+ * @param options - the upstream listener the gate forwards to.
102
+ * @returns the gate itself; nothing is bound until `start()` runs.
103
+ */
104
+ export function createIngressGate(options: IngressGateOptions): IngressGate {
105
+ const authority = options.upstreamHost + ':' + String(options.upstreamPort)
106
+ const sockets = new Set<Socket>()
107
+
108
+ const track = (socket: Socket): void => {
109
+ sockets.add(socket)
110
+ socket.once('close', () => { sockets.delete(socket) })
111
+ }
112
+
113
+ /** Refuse one plain request: 404, no upstream dial. */
114
+ const refuse = (response: http.ServerResponse): void => {
115
+ const body = Buffer.from(INGRESS_NOT_FOUND_BODY)
116
+ response.writeHead(404, {
117
+ 'content-type': 'application/json',
118
+ 'content-length': String(body.byteLength),
119
+ connection: 'close',
120
+ })
121
+ response.end(body)
122
+ }
123
+
124
+ /** Refuse one upgrade: the same 404, then the socket is closed. */
125
+ const refuseUpgrade = (socket: Socket): void => {
126
+ const body = Buffer.from(INGRESS_NOT_FOUND_BODY)
127
+ socket.end(notFoundHead(body.byteLength) + INGRESS_NOT_FOUND_BODY)
128
+ }
129
+
130
+ /**
131
+ * Dial the upstream for one admitted upgrade and pipe both directions.
132
+ *
133
+ * The two sockets are piped blind: nothing here inspects the upstream's answer,
134
+ * so a handshake the upstream refuses is relayed as-is instead of becoming a
135
+ * 502. That is sound only because of what the upstream is — this gate always
136
+ * dials the same process's own Node http server, which stops parsing HTTP the
137
+ * moment it emits `upgrade` and never speaks first on that socket. A socket
138
+ * that answers something other than `101` therefore cannot occur today; if the
139
+ * upstream ever becomes a proxy, a TLS terminator or another process, this is
140
+ * the spot that must first read the response head and close both sides when it
141
+ * is not a 101.
142
+ * @param request - the admitted upgrade.
143
+ * @param socket - the client side of it.
144
+ * @param head - bytes the client already sent past the handshake.
145
+ */
146
+ const forward = (request: http.IncomingMessage, socket: Socket, head: Buffer): void => {
147
+ const upstream = connect({ host: options.upstreamHost, port: options.upstreamPort })
148
+ track(upstream)
149
+ upstream.on('error', () => { socket.destroy() })
150
+ socket.on('error', () => { upstream.destroy() })
151
+ // A half-closed pair must not leave the other side holding a connection: a
152
+ // destroyed socket is not an ended one, so the pipe above never delivers it.
153
+ upstream.on('close', () => { socket.destroy() })
154
+ socket.on('close', () => { upstream.destroy() })
155
+ upstream.on('connect', () => {
156
+ upstream.write(upstreamHead(request, authority))
157
+ if (head.byteLength > 0) upstream.write(head)
158
+ upstream.pipe(socket)
159
+ socket.pipe(upstream)
160
+ })
161
+ }
162
+
163
+ const server = http.createServer((_request, response) => {
164
+ // A plain request is never proxied: the gate serves one upgrade path and
165
+ // nothing else, so there is no branch in which this dials upstream.
166
+ refuse(response)
167
+ })
168
+ server.on('connection', track)
169
+ server.on('upgrade', (request, socket: Socket, head: Buffer) => {
170
+ track(socket)
171
+ if (!isIngressPath(request.url ?? '')) {
172
+ refuseUpgrade(socket)
173
+ return
174
+ }
175
+ forward(request, socket, head)
176
+ })
177
+
178
+ return {
179
+ start(): Promise<IngressGateStarted> {
180
+ if (server.listening) {
181
+ return Promise.resolve({ port: (server.address() as AddressInfo).port })
182
+ }
183
+ return new Promise<IngressGateStarted>((resolve, reject) => {
184
+ const onError = (error: Error): void => { reject(error) }
185
+ server.once('error', onError)
186
+ server.listen(0, INGRESS_BIND_HOST, () => {
187
+ server.off('error', onError)
188
+ resolve({ port: (server.address() as AddressInfo).port })
189
+ })
190
+ })
191
+ },
192
+ stop(): void {
193
+ if (!server.listening) {
194
+ for (const socket of sockets) socket.destroy()
195
+ sockets.clear()
196
+ return
197
+ }
198
+ server.close()
199
+ for (const socket of sockets) socket.destroy()
200
+ sockets.clear()
201
+ },
202
+ }
203
+ }