@linxin666/dsh-remote-bridge 0.4.12 → 0.4.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +2 -2
- package/README.md +53 -11
- package/README.zh.md +53 -11
- package/lib/client.js +112 -90
- package/lib/client.js.map +1 -1
- package/lib/index.js +18800 -334
- package/lib/types/client/PairPanel.d.ts +7 -0
- package/lib/types/client/locales.d.ts +13 -10
- package/lib/types/core/connection.d.ts +50 -0
- package/lib/types/core/devices.d.ts +80 -6
- package/lib/types/core/liveactivity.d.ts +7 -0
- package/lib/types/core/model-efforts.d.ts +83 -0
- package/lib/types/core/protocol.d.ts +24 -0
- package/lib/types/core/push.d.ts +70 -3
- package/lib/types/host/firewall.d.ts +74 -0
- package/lib/types/host/host-bind-capability.d.ts +90 -0
- package/lib/types/host/ingress-gate.d.ts +59 -0
- package/lib/types/host/ingress-sync.d.ts +429 -0
- package/lib/types/host/lan-bind-plan.d.ts +96 -0
- package/lib/types/host/lan-bind.d.ts +106 -0
- package/lib/types/host/lan-forward.d.ts +112 -0
- package/lib/types/host/lan.d.ts +61 -0
- package/lib/types/host/pair-origin.d.ts +34 -19
- package/lib/types/host/relay-bridge-connector.d.ts +234 -0
- package/lib/types/host/relay-connector.d.ts +156 -0
- package/lib/types/host/relay-control.d.ts +195 -0
- package/lib/types/host/relay-registry.d.ts +123 -0
- package/lib/types/host/relay-secondary.d.ts +209 -0
- package/lib/types/host/relay.d.ts +170 -0
- package/lib/types/host/routes.d.ts +29 -1
- package/lib/types/host/tunnel-orphan.d.ts +145 -0
- package/lib/types/host/tunnel-plan.d.ts +41 -0
- package/lib/types/host/tunnel.d.ts +289 -0
- package/lib/types/index.d.ts +488 -1
- package/package.json +4 -2
- package/src/client/PairPanel.tsx +21 -0
- package/src/client/locales.ts +19 -15
- package/src/client/panel.module.css +48 -1
- package/src/core/connection.ts +316 -11
- package/src/core/devices.ts +165 -16
- package/src/core/hub.ts +17 -5
- package/src/core/liveactivity.ts +16 -2
- package/src/core/model-efforts.ts +223 -0
- package/src/core/protocol.ts +27 -0
- package/src/core/push.ts +90 -5
- package/src/host/firewall.ts +230 -0
- package/src/host/host-bind-capability.ts +249 -0
- package/src/host/ingress-gate.ts +203 -0
- package/src/host/ingress-sync.ts +1074 -0
- package/src/host/lan-bind-plan.ts +134 -0
- package/src/host/lan-bind.ts +250 -0
- package/src/host/lan-forward.ts +321 -0
- package/src/host/lan.ts +142 -0
- package/src/host/pair-origin.ts +44 -38
- package/src/host/relay-bridge-connector.ts +849 -0
- package/src/host/relay-connector.ts +324 -0
- package/src/host/relay-control.ts +315 -0
- package/src/host/relay-registry.ts +275 -0
- package/src/host/relay-secondary.ts +478 -0
- package/src/host/relay.ts +294 -0
- package/src/host/routes.ts +57 -3
- package/src/host/tunnel-orphan.ts +325 -0
- package/src/host/tunnel-plan.ts +58 -0
- package/src/host/tunnel.ts +688 -0
- package/src/index.ts +1516 -23
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The LAN edge the lan-bind toggle owns (issue #1917).
|
|
3
|
+
*
|
|
4
|
+
* The toggle used to pin the LAN address into the profile's webserver row. That
|
|
5
|
+
* row is the only place the harness takes its bind from, and rewriting it
|
|
6
|
+
* - replaced the official row's whole config (so the row's own
|
|
7
|
+
* `host: !!js ctx.webStartup.host ?? '127.0.0.1'` expression and the CLI
|
|
8
|
+
* `--host`/`--port` never reached it), and
|
|
9
|
+
* - the profile patch is watched by the Host's HMR config watcher, so the
|
|
10
|
+
* write recomposed the running process and rebound the live listener.
|
|
11
|
+
*
|
|
12
|
+
* This module keeps the host bound to loopback and gives LAN clients their own
|
|
13
|
+
* listener: a forwarder on the machine's LAN address, on the same port, that
|
|
14
|
+
* re-issues every request (HTTP and WebSocket upgrade alike) to
|
|
15
|
+
* `127.0.0.1:<port>`. Two consequences are load-bearing:
|
|
16
|
+
*
|
|
17
|
+
* 1. The upstream leg is loopback, so the socket alone would read as "the
|
|
18
|
+
* desktop". The forwarder therefore DROPS whatever Host the client sent and
|
|
19
|
+
* stamps the LAN authority it was reached at, plus `X-Forwarded-For`. Every
|
|
20
|
+
* fence that decides "is this the desktop" (`isLoopbackClient`, the pairing
|
|
21
|
+
* gate, the `/remote` gate) then keeps refusing the forwarded request, while
|
|
22
|
+
* the phone-facing fences still match the LAN authority the QR advertises.
|
|
23
|
+
* 2. A bind that cannot be taken (address gone after a network change, port
|
|
24
|
+
* taken) only loses the LAN edge: the loopback listener is never touched, so
|
|
25
|
+
* the host cannot be bricked and the failure is reported on the status
|
|
26
|
+
* frame.
|
|
27
|
+
*
|
|
28
|
+
* Nothing here writes a file: the forwarder is runtime state, so a network
|
|
29
|
+
* change needs no profile edit and no restart.
|
|
30
|
+
*
|
|
31
|
+
* @module dsh-remote-bridge/host/lan-forward
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import { createServer, request as httpRequest, type ClientRequest, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
|
|
35
|
+
import { connect } from 'node:net'
|
|
36
|
+
import type { Duplex } from 'node:stream'
|
|
37
|
+
|
|
38
|
+
/** The upstream the forwarder re-issues to: the process's own loopback listener. */
|
|
39
|
+
export const FORWARD_UPSTREAM_HOST = '127.0.0.1'
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Headers that describe one hop rather than the request. They are rebuilt for
|
|
43
|
+
* each leg so a keep-alive or upgrade marker from the client never leaks into
|
|
44
|
+
* the loopback leg (and vice versa on the response).
|
|
45
|
+
*/
|
|
46
|
+
const HOP_BY_HOP = new Set([
|
|
47
|
+
'connection',
|
|
48
|
+
'keep-alive',
|
|
49
|
+
'proxy-authenticate',
|
|
50
|
+
'proxy-authorization',
|
|
51
|
+
'proxy-connection',
|
|
52
|
+
'te',
|
|
53
|
+
'trailer',
|
|
54
|
+
'transfer-encoding',
|
|
55
|
+
'upgrade',
|
|
56
|
+
])
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Headers the forwarder owns: a client-supplied value is discarded, never
|
|
60
|
+
* appended to, so a LAN client cannot claim to be the desktop by forging them.
|
|
61
|
+
*/
|
|
62
|
+
const REWRITTEN = new Set(['host', 'x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host', 'cf-connecting-ip'])
|
|
63
|
+
|
|
64
|
+
/** What the forwarder is doing right now, for the status frame and the logs. */
|
|
65
|
+
export interface LanForwardState {
|
|
66
|
+
/** Whether the LAN listener is bound. */
|
|
67
|
+
listening: boolean
|
|
68
|
+
/** The LAN address it listens on (undefined when it never bound). */
|
|
69
|
+
address: string | undefined
|
|
70
|
+
/** The port it listens on (the web server's own port). */
|
|
71
|
+
port: number | undefined
|
|
72
|
+
/** The loopback port it re-issues to. */
|
|
73
|
+
upstreamPort: number | undefined
|
|
74
|
+
/** Why the last bind attempt failed, when it did. */
|
|
75
|
+
error: string | undefined
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The idle state: nothing bound, nothing failed. */
|
|
79
|
+
export const IDLE_FORWARD_STATE: LanForwardState = {
|
|
80
|
+
listening: false,
|
|
81
|
+
address: undefined,
|
|
82
|
+
port: undefined,
|
|
83
|
+
upstreamPort: undefined,
|
|
84
|
+
error: undefined,
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The `Host` authority a listener at `address:port` is reached at. IPv6
|
|
89
|
+
* literals are bracketed like any URL authority.
|
|
90
|
+
* @param address - the listen address (a literal).
|
|
91
|
+
* @param port - the listen port.
|
|
92
|
+
* @returns the authority text a request to that listener carries.
|
|
93
|
+
*/
|
|
94
|
+
export function authorityOf(address: string, port: number): string {
|
|
95
|
+
const host = address.includes(':') ? `[${address}]` : address
|
|
96
|
+
return `${host}:${String(port)}`
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The headers the loopback leg carries for one request: the client's own
|
|
101
|
+
* headers minus the hop-by-hop and forwarder-owned ones, plus the LAN authority
|
|
102
|
+
* the client actually reached and its address.
|
|
103
|
+
* @param request - the request as it arrived on the LAN listener.
|
|
104
|
+
* @param authority - the LAN authority the forwarder listens at.
|
|
105
|
+
* @param clientAddress - the client's socket address, when readable.
|
|
106
|
+
* @returns the headers for the loopback request.
|
|
107
|
+
*/
|
|
108
|
+
export function forwardedHeaders(
|
|
109
|
+
request: IncomingMessage,
|
|
110
|
+
authority: string,
|
|
111
|
+
clientAddress: string | undefined,
|
|
112
|
+
): Record<string, string> {
|
|
113
|
+
const headers: Record<string, string> = {}
|
|
114
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
115
|
+
if (value === undefined) continue
|
|
116
|
+
const lower = name.toLowerCase()
|
|
117
|
+
if (HOP_BY_HOP.has(lower) || REWRITTEN.has(lower)) continue
|
|
118
|
+
headers[lower] = Array.isArray(value) ? value.join(', ') : value
|
|
119
|
+
}
|
|
120
|
+
headers.host = authority
|
|
121
|
+
if (clientAddress !== undefined && clientAddress !== '') headers['x-forwarded-for'] = clientAddress
|
|
122
|
+
headers['x-forwarded-proto'] = 'http'
|
|
123
|
+
return headers
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Rebuild a WebSocket handshake for the loopback leg. The client's own headers
|
|
128
|
+
* travel through verbatim (so `Sec-WebSocket-*` and any application protocol
|
|
129
|
+
* survive) except the ones the forwarder owns.
|
|
130
|
+
* @param request - the upgrade request as it arrived on the LAN listener.
|
|
131
|
+
* @param authority - the LAN authority the forwarder listens at.
|
|
132
|
+
* @param clientAddress - the client's socket address, when readable.
|
|
133
|
+
* @returns the handshake request head to write on the loopback leg.
|
|
134
|
+
*/
|
|
135
|
+
export function forwardedHandshake(
|
|
136
|
+
request: IncomingMessage,
|
|
137
|
+
authority: string,
|
|
138
|
+
clientAddress: string | undefined,
|
|
139
|
+
): string {
|
|
140
|
+
const lines = [`${request.method ?? 'GET'} ${request.url ?? '/'} HTTP/1.1`]
|
|
141
|
+
const raw = request.rawHeaders
|
|
142
|
+
for (let index = 0; index + 1 < raw.length; index += 2) {
|
|
143
|
+
const name = raw[index] ?? ''
|
|
144
|
+
const lower = name.toLowerCase()
|
|
145
|
+
if (REWRITTEN.has(lower)) continue
|
|
146
|
+
lines.push(`${name}: ${raw[index + 1] ?? ''}`)
|
|
147
|
+
}
|
|
148
|
+
lines.push(`Host: ${authority}`)
|
|
149
|
+
if (clientAddress !== undefined && clientAddress !== '') lines.push(`X-Forwarded-For: ${clientAddress}`)
|
|
150
|
+
lines.push('X-Forwarded-Proto: http')
|
|
151
|
+
return `${lines.join('\r\n')}\r\n\r\n`
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** One listener, its live connections, and its last bind outcome. */
|
|
155
|
+
export class LanForwarder {
|
|
156
|
+
private server: Server | undefined
|
|
157
|
+
private config: { address: string; port: number; upstreamPort: number } | undefined
|
|
158
|
+
private state: LanForwardState = IDLE_FORWARD_STATE
|
|
159
|
+
/** Every socket this forwarder opened on either leg. */
|
|
160
|
+
private readonly sockets = new Set<Duplex>()
|
|
161
|
+
/** Every in-flight loopback request, so a teardown cannot leave one running. */
|
|
162
|
+
private readonly upstreams = new Set<ClientRequest>()
|
|
163
|
+
|
|
164
|
+
/** What the forwarder is doing right now. */
|
|
165
|
+
snapshot(): LanForwardState {
|
|
166
|
+
return this.state
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Bind the LAN listener, or report why it could not be bound.
|
|
171
|
+
*
|
|
172
|
+
* Never throws: a bind failure is the ordinary outcome after a network change
|
|
173
|
+
* (the address is gone) or a port collision, and the loopback listener must
|
|
174
|
+
* keep serving regardless.
|
|
175
|
+
* @param address - the LAN address to listen on.
|
|
176
|
+
* @param port - the port to listen on (the web server's own port).
|
|
177
|
+
* @param upstreamPort - the loopback port to re-issue to; defaults to `port`.
|
|
178
|
+
* @returns the settled state.
|
|
179
|
+
*/
|
|
180
|
+
start(address: string, port: number, upstreamPort: number = port): Promise<LanForwardState> {
|
|
181
|
+
if (this.config !== undefined && this.state.listening
|
|
182
|
+
&& this.config.address === address && this.config.port === port && this.config.upstreamPort === upstreamPort) {
|
|
183
|
+
return Promise.resolve(this.state)
|
|
184
|
+
}
|
|
185
|
+
return this.stop().then(() => this.bind(address, port, upstreamPort))
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
private bind(address: string, port: number, upstreamPort: number): Promise<LanForwardState> {
|
|
189
|
+
// The authority the requests are stamped with; re-read after listen so a
|
|
190
|
+
// kernel-assigned port (or a resolved address) is what clients are told.
|
|
191
|
+
let authority = authorityOf(address, port)
|
|
192
|
+
const server = createServer((request, response) => { this.forwardHttp(request, response, upstreamPort, authority) })
|
|
193
|
+
server.on('upgrade', (request, socket, head) => { this.forwardUpgrade(request, socket, head, upstreamPort, authority) })
|
|
194
|
+
server.on('connection', (socket) => {
|
|
195
|
+
this.sockets.add(socket)
|
|
196
|
+
socket.on('close', () => { this.sockets.delete(socket) })
|
|
197
|
+
})
|
|
198
|
+
this.server = server
|
|
199
|
+
this.config = { address, port, upstreamPort }
|
|
200
|
+
return new Promise<LanForwardState>((resolve) => {
|
|
201
|
+
let settled = false
|
|
202
|
+
const settle = (next: LanForwardState): void => {
|
|
203
|
+
if (settled) return
|
|
204
|
+
settled = true
|
|
205
|
+
this.state = next
|
|
206
|
+
resolve(next)
|
|
207
|
+
}
|
|
208
|
+
// A failed bind arrives as an 'error' event (EADDRINUSE, EADDRNOTAVAIL, a
|
|
209
|
+
// permission refusal). It is reported, never re-thrown: an unhandled
|
|
210
|
+
// 'error' on a listening server would take the whole host process down.
|
|
211
|
+
server.on('error', (error: NodeJS.ErrnoException) => {
|
|
212
|
+
const reason = error.code === undefined ? error.message : `${error.code}: ${error.message}`
|
|
213
|
+
if (this.server === server) {
|
|
214
|
+
this.server = undefined
|
|
215
|
+
this.config = undefined
|
|
216
|
+
}
|
|
217
|
+
this.releaseSockets()
|
|
218
|
+
settle({ listening: false, address, port, upstreamPort, error: reason })
|
|
219
|
+
if (!server.listening) return
|
|
220
|
+
server.close(() => undefined)
|
|
221
|
+
})
|
|
222
|
+
server.listen(port, address, () => {
|
|
223
|
+
// Report the address and port the kernel actually bound: a port of 0
|
|
224
|
+
// (and a wildcard-adjacent literal) is resolved by the listen call, and
|
|
225
|
+
// the status frame must name the listener clients can dial.
|
|
226
|
+
const bound = server.address()
|
|
227
|
+
const boundPort = typeof bound === 'object' && bound !== null ? bound.port : port
|
|
228
|
+
const boundAddress = typeof bound === 'object' && bound !== null ? bound.address : address
|
|
229
|
+
authority = authorityOf(boundAddress, boundPort)
|
|
230
|
+
this.config = { address: boundAddress, port: boundPort, upstreamPort }
|
|
231
|
+
settle({ listening: true, address: boundAddress, port: boundPort, upstreamPort, error: undefined })
|
|
232
|
+
})
|
|
233
|
+
})
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Close the LAN listener and every connection it opened, then resolve once the
|
|
238
|
+
* port is released. Safe to call when nothing is bound.
|
|
239
|
+
*/
|
|
240
|
+
stop(): Promise<void> {
|
|
241
|
+
const server = this.server
|
|
242
|
+
this.server = undefined
|
|
243
|
+
this.config = undefined
|
|
244
|
+
this.releaseSockets()
|
|
245
|
+
this.state = IDLE_FORWARD_STATE
|
|
246
|
+
if (server === undefined) return Promise.resolve()
|
|
247
|
+
return new Promise<void>((resolve) => {
|
|
248
|
+
server.close(() => { resolve() })
|
|
249
|
+
// Keep-alive and upgraded connections keep the handle alive; they are
|
|
250
|
+
// already destroyed above, so the close above settles on the next tick.
|
|
251
|
+
server.closeAllConnections?.()
|
|
252
|
+
})
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
private releaseSockets(): void {
|
|
256
|
+
for (const upstream of this.upstreams) upstream.destroy()
|
|
257
|
+
this.upstreams.clear()
|
|
258
|
+
for (const socket of this.sockets) socket.destroy()
|
|
259
|
+
this.sockets.clear()
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private trackUpstream(upstream: ClientRequest): void {
|
|
263
|
+
this.upstreams.add(upstream)
|
|
264
|
+
upstream.on('close', () => { this.upstreams.delete(upstream) })
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
private forwardHttp(request: IncomingMessage, response: ServerResponse, upstreamPort: number, authority: string): void {
|
|
268
|
+
const upstream = httpRequest({
|
|
269
|
+
host: FORWARD_UPSTREAM_HOST,
|
|
270
|
+
port: upstreamPort,
|
|
271
|
+
method: request.method,
|
|
272
|
+
path: request.url,
|
|
273
|
+
headers: forwardedHeaders(request, authority, request.socket.remoteAddress),
|
|
274
|
+
}, (upstreamResponse) => {
|
|
275
|
+
const headers: Record<string, string | string[]> = {}
|
|
276
|
+
for (const [name, value] of Object.entries(upstreamResponse.headers)) {
|
|
277
|
+
if (value === undefined || HOP_BY_HOP.has(name.toLowerCase())) continue
|
|
278
|
+
headers[name] = value
|
|
279
|
+
}
|
|
280
|
+
response.writeHead(upstreamResponse.statusCode ?? 502, headers)
|
|
281
|
+
upstreamResponse.pipe(response)
|
|
282
|
+
upstreamResponse.on('error', () => { response.destroy() })
|
|
283
|
+
// The client left mid-response: stop the loopback leg instead of working
|
|
284
|
+
// on a call nobody will read.
|
|
285
|
+
response.on('close', () => {
|
|
286
|
+
if (!upstreamResponse.readableEnded) upstream.destroy()
|
|
287
|
+
})
|
|
288
|
+
})
|
|
289
|
+
this.trackUpstream(upstream)
|
|
290
|
+
upstream.on('error', () => {
|
|
291
|
+
if (response.headersSent) {
|
|
292
|
+
response.destroy()
|
|
293
|
+
return
|
|
294
|
+
}
|
|
295
|
+
response.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' })
|
|
296
|
+
response.end('remote-bridge: the LAN forwarder could not reach the loopback listener\n')
|
|
297
|
+
})
|
|
298
|
+
request.on('error', () => { upstream.destroy() })
|
|
299
|
+
request.pipe(upstream)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
private forwardUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer, upstreamPort: number, authority: string): void {
|
|
303
|
+
const upstream = connect(upstreamPort, FORWARD_UPSTREAM_HOST)
|
|
304
|
+
this.sockets.add(upstream)
|
|
305
|
+
const tearDown = (): void => {
|
|
306
|
+
this.sockets.delete(upstream)
|
|
307
|
+
upstream.destroy()
|
|
308
|
+
socket.destroy()
|
|
309
|
+
}
|
|
310
|
+
upstream.on('error', tearDown)
|
|
311
|
+
socket.on('error', tearDown)
|
|
312
|
+
upstream.on('close', () => { socket.destroy() })
|
|
313
|
+
socket.on('close', () => { upstream.destroy() })
|
|
314
|
+
upstream.on('connect', () => {
|
|
315
|
+
upstream.write(forwardedHandshake(request, authority, request.socket.remoteAddress))
|
|
316
|
+
if (head.length > 0) upstream.write(head)
|
|
317
|
+
socket.pipe(upstream)
|
|
318
|
+
upstream.pipe(socket)
|
|
319
|
+
})
|
|
320
|
+
}
|
|
321
|
+
}
|
package/src/host/lan.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LAN address derivation: every IPv4 interface literal this machine could
|
|
3
|
+
* advertise to a peer on the local network. Mirrors the dsh CLI's boot-time
|
|
4
|
+
* sampling shape (apps/cli/src/app-cli-entry.ts `resolveLanTrust`) — an
|
|
5
|
+
* external plugin cannot read the CLI's sampled snapshot, so the same
|
|
6
|
+
* non-internal IPv4 derivation is repeated here.
|
|
7
|
+
*
|
|
8
|
+
* The derivation is deliberately narrower than the CLI's: an advertised
|
|
9
|
+
* literal the peer can never reach costs that peer a whole connection attempt.
|
|
10
|
+
* A macOS host running a fake-IP proxy (Clash/Surge/Mihomo) samples its TUN
|
|
11
|
+
* gateway as `198.18.0.1`, which is a benchmarking-range address no LAN peer
|
|
12
|
+
* can route to; the old derivation advertised it like any other interface. The
|
|
13
|
+
* filter below drops the interface kinds and address ranges a peer cannot
|
|
14
|
+
* reach, and keeps everything else — RFC1918, ULA-side IPv4 and a routable
|
|
15
|
+
* public literal (a VPS whose NIC is its only reachable base must stay
|
|
16
|
+
* advertisable).
|
|
17
|
+
*
|
|
18
|
+
* Which trust fence, pairing link or settings surface consumes these literals
|
|
19
|
+
* is not this module's responsibility.
|
|
20
|
+
*
|
|
21
|
+
* @module dsh-remote-bridge/host/lan
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { networkInterfaces } from 'node:os'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Interface-name stems of tunnels and VPN adapters: interfaces whose address
|
|
28
|
+
* is a private point-to-point endpoint on this machine, never an authority a
|
|
29
|
+
* peer on the local network can dial. Matching is case-insensitive and
|
|
30
|
+
* anchored at the start, so `utun0`/`utun4` both match while a hypothetical
|
|
31
|
+
* `en0utun` does not. Windows reports adapter *descriptions* rather than POSIX
|
|
32
|
+
* stems (`Tailscale`, `WireGuard Tunnel`, `OpenVPN Wintun`), which the same
|
|
33
|
+
* list covers by prefix.
|
|
34
|
+
*/
|
|
35
|
+
const TUNNEL_INTERFACE_PREFIXES: readonly string[] = [
|
|
36
|
+
'utun', 'tun', 'tap', 'ppp', 'ipsec', 'wg', 'wireguard', 'tailscale', 'nordlynx', 'proton', 'openvpn', 'zt',
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Interface-name stems of virtual machine and container bridges: `docker0`,
|
|
41
|
+
* `vethXXXX`, `br-<id>`, `virbr0`, `vmnet8`, `vboxnet0` and the Hyper-V
|
|
42
|
+
* `vEthernet` adapters. Their RFC1918 addresses belong to a NAT the host
|
|
43
|
+
* shares with its own guests, so a phone on the physical LAN cannot reach
|
|
44
|
+
* them; `bridge0`/`br0` are deliberately absent because a real bridged LAN
|
|
45
|
+
* (macOS Internet Sharing) is exactly the address a phone does reach.
|
|
46
|
+
*/
|
|
47
|
+
const VIRTUAL_INTERFACE_PREFIXES: readonly string[] = [
|
|
48
|
+
'docker', 'veth', 'virbr', 'vmnet', 'vboxnet', 'vethernet', 'br-',
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* IPv4 ranges no peer on the local network can reach. The list is a denial
|
|
53
|
+
* list rather than an RFC1918 allowlist on purpose: a host whose only
|
|
54
|
+
* interface is a routable public literal (a VPS, a standalone server) would
|
|
55
|
+
* otherwise lose its only constructible base and fall back to the
|
|
56
|
+
* `lan-required` banner.
|
|
57
|
+
* @param octets - the four address octets, in order.
|
|
58
|
+
* @returns true when an address in this range must not be advertised.
|
|
59
|
+
*/
|
|
60
|
+
function isUnreachableIPv4(octets: readonly number[]): boolean {
|
|
61
|
+
const [a = 0, b = 0] = octets
|
|
62
|
+
// 0.0.0.0/8 "this network": never a usable address.
|
|
63
|
+
if (a === 0) return true
|
|
64
|
+
// 127.0.0.0/8 loopback (node already marks it internal; kept as the belt).
|
|
65
|
+
if (a === 127) return true
|
|
66
|
+
// 100.64.0.0/10 carrier-grade NAT: Tailscale and ISP-level NAT hand out
|
|
67
|
+
// addresses here, and a peer on the physical LAN cannot route to them.
|
|
68
|
+
if (a === 100 && b >= 64 && b <= 127) return true
|
|
69
|
+
// 169.254.0.0/16 link-local (APIPA / self-assigned).
|
|
70
|
+
if (a === 169 && b === 254) return true
|
|
71
|
+
// 198.18.0.0/15 benchmarking: the range a fake-IP TUN gateway takes.
|
|
72
|
+
if (a === 198 && (b === 18 || b === 19)) return true
|
|
73
|
+
// 224.0.0.0/4 multicast and 240.0.0.0/4 reserved (includes the broadcast).
|
|
74
|
+
if (a >= 224) return true
|
|
75
|
+
return false
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Whether an interface name belongs to a tunnel, VPN adapter, or virtual
|
|
80
|
+
* machine/container bridge, so its address is not an authority a LAN peer
|
|
81
|
+
* can dial.
|
|
82
|
+
* @param name - the interface name from `os.networkInterfaces()`.
|
|
83
|
+
* @returns true when the interface must not be advertised.
|
|
84
|
+
*/
|
|
85
|
+
export function isUnadvertisableInterface(name: string): boolean {
|
|
86
|
+
const lower = name.toLowerCase()
|
|
87
|
+
return [...TUNNEL_INTERFACE_PREFIXES, ...VIRTUAL_INTERFACE_PREFIXES].some(prefix => lower.startsWith(prefix))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Whether an IPv4 literal can be advertised to a pairing peer.
|
|
92
|
+
* @param address - a dotted-quad IPv4 literal.
|
|
93
|
+
* @returns true when a peer could plausibly reach it.
|
|
94
|
+
*/
|
|
95
|
+
export function isAdvertisableIPv4(address: string): boolean {
|
|
96
|
+
const parts = address.split('.')
|
|
97
|
+
if (parts.length !== 4) return false
|
|
98
|
+
const octets = parts.map(part => (/^\d{1,3}$/.test(part) ? Number(part) : Number.NaN))
|
|
99
|
+
if (octets.some(octet => !Number.isInteger(octet) || octet > 255)) return false
|
|
100
|
+
return !isUnreachableIPv4(octets)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** One sampled interface address. */
|
|
104
|
+
export interface LanCandidate {
|
|
105
|
+
/** The interface name the address was sampled from. */
|
|
106
|
+
iface: string
|
|
107
|
+
/** The IPv4 literal. */
|
|
108
|
+
address: string
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The `networkInterfaces()` shape, injectable so the filter is testable. */
|
|
112
|
+
export type NetworkInterfaceMap = ReturnType<typeof networkInterfaces>
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Every IPv4 interface address this machine can advertise to a pairing peer:
|
|
116
|
+
* non-internal, on a non-tunnel and non-virtual interface, outside the ranges
|
|
117
|
+
* no peer can route to.
|
|
118
|
+
* @param interfaces - the sampled interface map (defaults to the live one).
|
|
119
|
+
* @returns the candidates in interface order (possibly empty).
|
|
120
|
+
*/
|
|
121
|
+
export function lanIPv4Candidates(interfaces: NetworkInterfaceMap = networkInterfaces()): LanCandidate[] {
|
|
122
|
+
const candidates: LanCandidate[] = []
|
|
123
|
+
for (const [name, addresses] of Object.entries(interfaces)) {
|
|
124
|
+
if (isUnadvertisableInterface(name)) continue
|
|
125
|
+
for (const iface of addresses ?? []) {
|
|
126
|
+
if (iface.family !== 'IPv4' || iface.internal) continue
|
|
127
|
+
if (!isAdvertisableIPv4(iface.address)) continue
|
|
128
|
+
candidates.push({ iface: name, address: iface.address })
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return candidates
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Non-internal, reachable IPv4 interface addresses of this machine — the
|
|
136
|
+
* IP-literal authorities an all-interfaces bind is reachable by on the LAN.
|
|
137
|
+
* @param interfaces - the sampled interface map (defaults to the live one).
|
|
138
|
+
* @returns the addresses in interface order (possibly empty).
|
|
139
|
+
*/
|
|
140
|
+
export function lanIPv4Addresses(interfaces: NetworkInterfaceMap = networkInterfaces()): string[] {
|
|
141
|
+
return lanIPv4Candidates(interfaces).map(candidate => candidate.address)
|
|
142
|
+
}
|
package/src/host/pair-origin.ts
CHANGED
|
@@ -3,46 +3,56 @@
|
|
|
3
3
|
*
|
|
4
4
|
* A pairing code is far better when it carries the address too: the phone then
|
|
5
5
|
* needs one scan and no typing. This module is where that address comes from,
|
|
6
|
-
* in the order
|
|
6
|
+
* in the order this bridge can actually vouch for:
|
|
7
7
|
*
|
|
8
|
-
* 1.
|
|
8
|
+
* 1. **This bridge's own live public face**, handed in as a seam: a relay lease
|
|
9
|
+
* plus a landed Worker registration, or a tunnel that reports it is running.
|
|
10
|
+
* It is a fact about this process right now, so it answers first.
|
|
11
|
+
* 2. `DSH_REMOTE_PUBLIC_BASE_URL` — the same environment contract
|
|
9
12
|
* `dsh-remote-web-ui` reads for its own public base.
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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.
|
|
13
|
+
* 3. The LAN literal — this machine's own LAN address plus the bound port. A
|
|
14
|
+
* phone on the same network can dial it, which is the whole point of the
|
|
15
|
+
* pairing code.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
17
|
+
* There is deliberately no fourth source. A relay identity file on disk would
|
|
18
|
+
* only prove that this machine once minted an id; it says nothing about whether
|
|
19
|
+
* the Worker's row points at something reachable (the registration may have
|
|
20
|
+
* failed, the lease may never have been claimed, the relay may be off), so
|
|
21
|
+
* turning it into an origin would hand the QR a subdomain that cannot answer.
|
|
22
|
+
* The live facts above already cover every state the bridge can be in, and
|
|
23
|
+
* dropping the file also drops this package's last data dependency on the
|
|
24
|
+
* sibling plugin's home directory.
|
|
25
|
+
*
|
|
26
|
+
* The live source arrives as a seam: this module stays a pure function of what
|
|
27
|
+
* it is handed and never reads a socket, a timer or a file. Nothing here
|
|
28
|
+
* reaches the network, and nothing here mints or spends anything.
|
|
18
29
|
* @module dsh-remote-bridge/host/pair-origin
|
|
19
30
|
*/
|
|
20
31
|
|
|
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
32
|
/** One discovered origin and the fact that produced it. */
|
|
32
33
|
export interface PairOriginFacts {
|
|
33
34
|
/** Origin only, no path: `wss://<id>.dsh-market.com`. */
|
|
34
35
|
readonly origin: string
|
|
35
36
|
/** Where the answer came from, for the panel and the log. */
|
|
36
|
-
readonly source: 'env' | '
|
|
37
|
+
readonly source: 'realtime' | 'env' | 'lan'
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** This machine's LAN address and the port a peer dials it on. */
|
|
41
|
+
export interface PairOriginLanTarget {
|
|
42
|
+
readonly address: string
|
|
43
|
+
readonly port: number
|
|
37
44
|
}
|
|
38
45
|
|
|
39
46
|
export interface DiscoverPairOriginOptions {
|
|
40
47
|
/** Environment to read; defaults to `process.env`. */
|
|
41
48
|
readonly env?: NodeJS.ProcessEnv
|
|
42
|
-
/**
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
49
|
+
/**
|
|
50
|
+
* This bridge's own live public origin (a relay lease's hostname or a running
|
|
51
|
+
* tunnel's URL); undefined while neither is up. Called at most once.
|
|
52
|
+
*/
|
|
53
|
+
readonly realtime?: () => string | undefined
|
|
54
|
+
/** The LAN literal to fall back to when no public origin is known. */
|
|
55
|
+
readonly lan?: () => PairOriginLanTarget | undefined
|
|
46
56
|
}
|
|
47
57
|
|
|
48
58
|
/** Trim trailing slashes so the caller can append a path unconditionally. */
|
|
@@ -52,26 +62,22 @@ function originOf(base: string): string {
|
|
|
52
62
|
|
|
53
63
|
/**
|
|
54
64
|
* Discover the public origin of this instance.
|
|
55
|
-
* @param options - environment
|
|
65
|
+
* @param options - environment and the two live seams for tests.
|
|
56
66
|
* @returns the origin and its source, or `undefined` when nothing is known.
|
|
57
67
|
*/
|
|
58
68
|
export function discoverPairOrigin(options: DiscoverPairOriginOptions = {}): PairOriginFacts | undefined {
|
|
59
69
|
const env = options.env ?? process.env
|
|
70
|
+
const realtime = options.realtime?.()
|
|
71
|
+
if (realtime !== undefined && realtime.trim() !== '') {
|
|
72
|
+
return { origin: originOf(realtime.trim()), source: 'realtime' }
|
|
73
|
+
}
|
|
74
|
+
|
|
60
75
|
const configured = env.DSH_REMOTE_PUBLIC_BASE_URL?.trim()
|
|
61
76
|
if (configured !== undefined && configured !== '') return { origin: originOf(configured), source: 'env' }
|
|
62
77
|
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
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
|
|
78
|
+
const lan = options.lan?.()
|
|
79
|
+
if (lan !== undefined && lan.address.trim() !== '' && Number.isFinite(lan.port)) {
|
|
80
|
+
return { origin: `http://${lan.address.trim()}:${String(lan.port)}`, source: 'lan' }
|
|
72
81
|
}
|
|
73
|
-
|
|
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' }
|
|
82
|
+
return undefined
|
|
77
83
|
}
|