@linxin666/dsh-remote-bridge 0.4.11 → 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.
- package/README.i18n.yaml +2 -2
- package/README.md +47 -10
- package/README.zh.md +47 -10
- package/lib/client.js +1 -1
- package/lib/client.js.map +1 -1
- package/lib/index.js +18238 -416
- package/lib/types/core/connection.d.ts +9 -0
- package/lib/types/core/devices.d.ts +27 -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 +3 -1
- package/lib/types/core/push.d.ts +51 -2
- package/lib/types/core/turn-end-quiet.d.ts +104 -40
- 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 +215 -0
- package/lib/types/host/relay-connector.d.ts +152 -0
- package/lib/types/host/relay-control.d.ts +124 -0
- package/lib/types/host/relay-registry.d.ts +114 -0
- package/lib/types/host/relay.d.ts +170 -0
- package/lib/types/host/routes.d.ts +24 -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 +440 -11
- package/package.json +4 -2
- package/src/client/panel.module.css +16 -1
- package/src/core/connection.ts +244 -13
- package/src/core/devices.ts +31 -6
- 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 +4 -1
- package/src/core/push.ts +70 -4
- package/src/core/turn-end-quiet.ts +281 -98
- 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 +783 -0
- package/src/host/relay-connector.ts +317 -0
- package/src/host/relay-control.ts +224 -0
- package/src/host/relay-registry.ts +263 -0
- package/src/host/relay.ts +294 -0
- package/src/host/routes.ts +47 -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 +1303 -39
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host firewall management for the LAN bind toggle: while LAN access is on,
|
|
3
|
+
* keep one inbound allow rule for the bound port; when it turns off, remove
|
|
4
|
+
* the rule. Windows manages the Windows Defender Firewall rule via netsh;
|
|
5
|
+
* Linux uses the first available manager among firewalld / ufw / iptables.
|
|
6
|
+
* On every other platform (macOS included) the plugin reports the firewall
|
|
7
|
+
* as unmanaged: the port usually needs no rule there, and managing pf or the
|
|
8
|
+
* application firewall is out of scope for a distributable plugin.
|
|
9
|
+
*
|
|
10
|
+
* Ported from the dsh-LAN reference implementation (MIT), adapted to this
|
|
11
|
+
* package's structure and test seams.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { spawnSync } from 'node:child_process'
|
|
15
|
+
|
|
16
|
+
/** Rule name shared by every backend so re-runs recreate the same rule. */
|
|
17
|
+
export const FIREWALL_RULE_NAME = 'remote-web-ui (auto)'
|
|
18
|
+
|
|
19
|
+
/** One command execution result (test seam replaces the runner). */
|
|
20
|
+
export interface ToolResult {
|
|
21
|
+
ok: boolean
|
|
22
|
+
out: string
|
|
23
|
+
err: string
|
|
24
|
+
/** true when the binary could not be spawned at all (ENOENT et al). */
|
|
25
|
+
missing?: boolean
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The command runner seam: spawnSync in production, a stub in tests. */
|
|
29
|
+
export type CommandRunner = (cmd: string, args: readonly string[]) => ToolResult
|
|
30
|
+
|
|
31
|
+
/** Production runner: spawn without a shell, capture text, 20s timeout. */
|
|
32
|
+
export const spawnRunner: CommandRunner = (cmd, args) => {
|
|
33
|
+
const result = spawnSync(cmd, args, {
|
|
34
|
+
shell: false,
|
|
35
|
+
encoding: 'utf8',
|
|
36
|
+
windowsHide: process.platform === 'win32',
|
|
37
|
+
timeout: 20_000,
|
|
38
|
+
})
|
|
39
|
+
return {
|
|
40
|
+
ok: result.status === 0,
|
|
41
|
+
out: result.stdout ?? '',
|
|
42
|
+
err: result.stderr ?? '',
|
|
43
|
+
missing: result.error !== undefined,
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A firewall backend manages one allow rule for a TCP port. */
|
|
48
|
+
export interface FirewallBackend {
|
|
49
|
+
/** Short label surfaced in the settings card (netsh, firewalld, ...). */
|
|
50
|
+
readonly label: string
|
|
51
|
+
ruleExists(port: number): boolean
|
|
52
|
+
addRule(port: number): boolean
|
|
53
|
+
removeRule(port: number): boolean
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function netshBackend(run: CommandRunner): FirewallBackend {
|
|
57
|
+
// `show rule name=` exits 0 even when nothing matches (the localized "no
|
|
58
|
+
// rules match" note), so exit-code-only probes always report the rule as
|
|
59
|
+
// present. The verbose listing echoes the full rule name — the one
|
|
60
|
+
// locale-independent field — and is matched literally instead.
|
|
61
|
+
const show = (): boolean => {
|
|
62
|
+
const result = run('netsh', ['advfirewall', 'firewall', 'show', 'rule', `name=${FIREWALL_RULE_NAME}`, 'verbose'])
|
|
63
|
+
return result.ok && result.out.includes(FIREWALL_RULE_NAME)
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
label: 'netsh',
|
|
67
|
+
ruleExists: show,
|
|
68
|
+
addRule: (port) => run('netsh', [
|
|
69
|
+
'advfirewall', 'firewall', 'add', 'rule', `name=${FIREWALL_RULE_NAME}`,
|
|
70
|
+
'dir=in', 'action=allow', 'protocol=TCP', `localport=${String(port)}`, 'profile=private,domain',
|
|
71
|
+
]).ok,
|
|
72
|
+
removeRule: () => {
|
|
73
|
+
if (!show()) return true
|
|
74
|
+
return run('netsh', ['advfirewall', 'firewall', 'delete', 'rule', `name=${FIREWALL_RULE_NAME}`]).ok
|
|
75
|
+
},
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function firewalldBackend(run: CommandRunner): FirewallBackend {
|
|
80
|
+
return {
|
|
81
|
+
label: 'firewalld',
|
|
82
|
+
ruleExists: (port) => run('firewall-cmd', ['--permanent', '--query-port', `${String(port)}/tcp`]).ok,
|
|
83
|
+
addRule: (port) => {
|
|
84
|
+
const add = run('firewall-cmd', ['--permanent', '--add-port', `${String(port)}/tcp`])
|
|
85
|
+
const reload = run('firewall-cmd', ['--reload'])
|
|
86
|
+
return add.ok && reload.ok
|
|
87
|
+
},
|
|
88
|
+
removeRule: (port) => {
|
|
89
|
+
const del = run('firewall-cmd', ['--permanent', '--remove-port', `${String(port)}/tcp`])
|
|
90
|
+
const reload = run('firewall-cmd', ['--reload'])
|
|
91
|
+
return del.ok && reload.ok
|
|
92
|
+
},
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function ufwBackend(run: CommandRunner): FirewallBackend {
|
|
97
|
+
return {
|
|
98
|
+
label: 'ufw',
|
|
99
|
+
ruleExists: (port) => {
|
|
100
|
+
const result = run('ufw', ['status'])
|
|
101
|
+
// Anchored so a superset port's row (1443/tcp) cannot satisfy the
|
|
102
|
+
// probe for a shorter one (443/tcp).
|
|
103
|
+
return result.ok && new RegExp(`(^|\\s)${String(port)}/tcp\\s+ALLOW`, 'i').test(result.out)
|
|
104
|
+
},
|
|
105
|
+
addRule: (port) => run('ufw', ['allow', `${String(port)}/tcp`]).ok,
|
|
106
|
+
removeRule: (port) => run('ufw', ['delete', 'allow', `${String(port)}/tcp`]).ok,
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function iptablesBackend(run: CommandRunner): FirewallBackend {
|
|
111
|
+
const rule = (port: number): string[] => ['INPUT', '-p', 'tcp', '--dport', String(port), '-j', 'ACCEPT']
|
|
112
|
+
return {
|
|
113
|
+
label: 'iptables',
|
|
114
|
+
ruleExists: (port) => run('iptables', ['-C', ...rule(port)]).ok,
|
|
115
|
+
addRule: (port) => run('iptables', ['-A', ...rule(port)]).ok,
|
|
116
|
+
removeRule: (port) => run('iptables', ['-D', ...rule(port)]).ok,
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function toolAvailable(run: CommandRunner, cmd: string): boolean {
|
|
121
|
+
try {
|
|
122
|
+
// A missing binary reports through the runner's missing flag (spawnSync
|
|
123
|
+
// sets result.error for ENOENT); any graceful answer counts as present.
|
|
124
|
+
return run(cmd, ['--version']).missing !== true
|
|
125
|
+
} catch {
|
|
126
|
+
return false
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Detect the platform firewall manager. Returns undefined when the platform
|
|
132
|
+
* has no supported manager (macOS, unknown Linux without tools): the port
|
|
133
|
+
* then usually needs no rule and the UI reports "unmanaged".
|
|
134
|
+
*/
|
|
135
|
+
export function detectFirewallBackend(
|
|
136
|
+
platform: NodeJS.Platform,
|
|
137
|
+
run: CommandRunner = spawnRunner,
|
|
138
|
+
): FirewallBackend | undefined {
|
|
139
|
+
if (platform === 'win32') return netshBackend(run)
|
|
140
|
+
if (platform !== 'linux') return undefined
|
|
141
|
+
if (toolAvailable(run, 'firewall-cmd')) {
|
|
142
|
+
// firewalld only counts when its daemon answers; an installed-but-idle
|
|
143
|
+
// firewall-cmd would otherwise claim management it cannot exercise.
|
|
144
|
+
if (run('firewall-cmd', ['--state']).ok) return firewalldBackend(run)
|
|
145
|
+
}
|
|
146
|
+
if (toolAvailable(run, 'ufw')) return ufwBackend(run)
|
|
147
|
+
if (toolAvailable(run, 'iptables')) return iptablesBackend(run)
|
|
148
|
+
return undefined
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
let cachedBackend: { platform: NodeJS.Platform; backend: FirewallBackend | undefined } | undefined
|
|
152
|
+
|
|
153
|
+
/** Cached detection for the running platform (per process). */
|
|
154
|
+
export function firewallBackend(): FirewallBackend | undefined {
|
|
155
|
+
const platform = process.platform
|
|
156
|
+
if (cachedBackend === undefined || cachedBackend.platform !== platform) {
|
|
157
|
+
cachedBackend = { platform, backend: detectFirewallBackend(platform) }
|
|
158
|
+
}
|
|
159
|
+
return cachedBackend.backend
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Firewall state reported to the settings card. */
|
|
163
|
+
export interface FirewallSummary {
|
|
164
|
+
/** true when the rule state matches the LAN toggle (or nothing to manage). */
|
|
165
|
+
ok: boolean
|
|
166
|
+
/** false when no supported firewall manager exists on this platform. */
|
|
167
|
+
managed: boolean
|
|
168
|
+
/** Backend label or an explanation for unmanaged platforms. */
|
|
169
|
+
note?: string
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Delete-and-add: recreating the rule is idempotent and locale-proof (netsh
|
|
174
|
+
* output is localized, so parsing the live rule's port is fragile; the Linux
|
|
175
|
+
* backends follow the same recreate pattern).
|
|
176
|
+
*/
|
|
177
|
+
export function ensureFirewallRule(port: number): boolean {
|
|
178
|
+
invalidateFirewallSummary()
|
|
179
|
+
const backend = firewallBackend()
|
|
180
|
+
if (backend === undefined) return true
|
|
181
|
+
backend.removeRule(port)
|
|
182
|
+
return backend.addRule(port)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function removeFirewallRule(port: number): boolean {
|
|
186
|
+
invalidateFirewallSummary()
|
|
187
|
+
const backend = firewallBackend()
|
|
188
|
+
if (backend === undefined) return true
|
|
189
|
+
return backend.removeRule(port)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Human-readable firewall state for the status endpoint. A missing backend
|
|
194
|
+
* means the platform has nothing to manage; detection stays at the call site
|
|
195
|
+
* so an explicit undefined cannot silently re-probe the real OS mid-test.
|
|
196
|
+
*/
|
|
197
|
+
export function computeFirewallSummary(
|
|
198
|
+
port: number,
|
|
199
|
+
lanEnabled: boolean,
|
|
200
|
+
backend: FirewallBackend | undefined,
|
|
201
|
+
): FirewallSummary {
|
|
202
|
+
if (backend === undefined) return { ok: true, managed: false }
|
|
203
|
+
return { ok: lanEnabled ? backend.ruleExists(port) : !backend.ruleExists(port), managed: true, note: backend.label }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** How long a firewallSummary answer is reused before the backend is probed again. */
|
|
207
|
+
export const FIREWALL_SUMMARY_TTL_MS = 30_000
|
|
208
|
+
|
|
209
|
+
let summaryCache: { key: string; at: number; value: FirewallSummary } | undefined
|
|
210
|
+
|
|
211
|
+
/** Forget the cached summary (rule mutations call this). */
|
|
212
|
+
export function invalidateFirewallSummary(): void {
|
|
213
|
+
summaryCache = undefined
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* The settings card polls this every ten seconds; the probes are blocking
|
|
218
|
+
* spawnSync subprocesses on managed platforms, so short-TTL memoization
|
|
219
|
+
* keeps one poll from freezing the host event loop per request.
|
|
220
|
+
*/
|
|
221
|
+
export function firewallSummary(port: number, lanEnabled: boolean): FirewallSummary {
|
|
222
|
+
const key = `${String(port)}|${lanEnabled ? '1' : '0'}`
|
|
223
|
+
const now = Date.now()
|
|
224
|
+
if (summaryCache !== undefined && summaryCache.key === key && now - summaryCache.at < FIREWALL_SUMMARY_TTL_MS) {
|
|
225
|
+
return summaryCache.value
|
|
226
|
+
}
|
|
227
|
+
const value = computeFirewallSummary(port, lanEnabled, firewallBackend())
|
|
228
|
+
summaryCache = { key, at: now, value }
|
|
229
|
+
return value
|
|
230
|
+
}
|
|
@@ -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
|
+
}
|