dsh-remote-go 0.2.0 → 0.3.1
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.md +11 -3
- package/{client.js → dist/client.js} +7144 -8367
- package/dist/index.js +4 -0
- package/dist/src/admission.js +21 -0
- package/dist/src/api.js +380 -0
- package/dist/src/atomic-json.js +201 -0
- package/dist/src/bootstrap.js +96 -0
- package/dist/src/connect/attach.js +21 -0
- package/dist/src/connect/bootstrap.js +8 -0
- package/dist/src/connect/failures.js +29 -0
- package/dist/src/connect/guards.js +36 -0
- package/dist/src/connect/launch.js +70 -0
- package/dist/src/connect/links.js +54 -0
- package/dist/src/connect/ownership.js +139 -0
- package/dist/src/connect/pipeline.js +376 -0
- package/dist/src/connect/reattach.js +191 -0
- package/dist/src/connect/registry.js +10 -0
- package/dist/src/connect/repair.js +97 -0
- package/dist/src/connect/restart.js +255 -0
- package/dist/src/connect/stop.js +164 -0
- package/dist/src/connect/transport.js +101 -0
- package/dist/src/connect/verify.js +30 -0
- package/dist/src/connect/watchdog.js +44 -0
- package/dist/src/connect-log.js +137 -0
- package/dist/src/connect-progress.js +110 -0
- package/dist/src/constants.js +29 -0
- package/dist/src/context.js +96 -0
- package/dist/src/diagnostics.js +133 -0
- package/dist/src/download-jobs.js +221 -0
- package/dist/src/errors.js +228 -0
- package/dist/src/events.js +326 -0
- package/dist/src/host-lifecycle.js +368 -0
- package/dist/src/host-registry.js +181 -0
- package/dist/src/host-runtime.js +77 -0
- package/dist/src/host-view.js +52 -0
- package/dist/src/index.js +196 -0
- package/dist/src/kernel-adapter.js +388 -0
- package/dist/src/key-files.js +39 -0
- package/dist/src/known-hosts.js +104 -0
- package/dist/src/layout.js +26 -0
- package/dist/src/local-download.js +311 -0
- package/dist/src/local-ssh.js +23 -0
- package/dist/src/local-version.js +87 -0
- package/dist/src/node/download.js +157 -0
- package/dist/src/node-runtime.js +327 -0
- package/dist/src/probe.js +95 -0
- package/dist/src/prompts.js +198 -0
- package/dist/src/proxy/cookies.js +102 -0
- package/dist/src/proxy/headers.js +167 -0
- package/dist/src/proxy/http.js +134 -0
- package/dist/src/proxy/index.js +121 -0
- package/dist/src/proxy/limits.js +6 -0
- package/dist/src/proxy/routes.js +32 -0
- package/dist/src/proxy/upgrade.js +160 -0
- package/dist/src/redact.js +85 -0
- package/dist/src/remote-files.js +60 -0
- package/dist/src/remote-path.js +82 -0
- package/dist/src/remote-proc.js +271 -0
- package/dist/src/remote-web/registry.js +107 -0
- package/dist/src/remote-web/resolve.js +229 -0
- package/dist/src/remote-web/start.js +190 -0
- package/dist/src/remote-web/stop.js +74 -0
- package/dist/src/request-trust.js +70 -0
- package/dist/src/runtime/dispatch.js +200 -0
- package/dist/src/runtime/effects.js +81 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +70 -0
- package/dist/src/runtime/rules.js +480 -0
- package/dist/src/secrets.js +119 -0
- package/dist/src/service.js +300 -0
- package/dist/src/settings.js +143 -0
- package/dist/src/ssh-config.js +257 -0
- package/dist/src/ssh-failures.js +71 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +258 -0
- package/dist/src/ssh.js +395 -0
- package/dist/src/store.js +174 -0
- package/dist/src/tool-shared.js +146 -0
- package/dist/src/tools-exec-policy.js +121 -0
- package/dist/src/tools-exec.js +307 -0
- package/dist/src/tools-report.js +357 -0
- package/dist/src/tools.js +337 -0
- package/dist/src/tunnel.js +111 -0
- package/dist/src/util.js +112 -0
- package/dist/src/version.js +108 -0
- package/dist/src/watchdog-bus.js +21 -0
- package/dist/src/watchdog.js +116 -0
- package/index.js +5 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +37 -19
- package/src/admission.js +0 -43
- package/src/api.js +0 -536
- package/src/atomic-json.js +0 -225
- package/src/bootstrap.js +0 -113
- package/src/connect-log.js +0 -176
- package/src/connect-pipeline.js +0 -1900
- package/src/connect-progress.js +0 -155
- package/src/constants.js +0 -93
- package/src/diagnostics.js +0 -160
- package/src/download-jobs.js +0 -234
- package/src/errors.js +0 -412
- package/src/host-lifecycle.js +0 -604
- package/src/host-registry.js +0 -217
- package/src/host-runtime.js +0 -127
- package/src/host-view.js +0 -75
- package/src/index.js +0 -206
- package/src/key-files.js +0 -54
- package/src/known-hosts.js +0 -133
- package/src/layout.js +0 -53
- package/src/local-download.js +0 -381
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -101
- package/src/prompts.js +0 -229
- package/src/redact.js +0 -68
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -137
- package/src/remote-proc.js +0 -343
- package/src/remote-proxy.js +0 -815
- package/src/remote-web.js +0 -751
- package/src/request-trust.js +0 -89
- package/src/secrets.js +0 -109
- package/src/service.js +0 -459
- package/src/settings.js +0 -163
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -731
- package/src/store.js +0 -193
- package/src/tools.js +0 -386
- package/src/tunnel.js +0 -132
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -43
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
package/src/remote-proxy.js
DELETED
|
@@ -1,815 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Same-origin reverse proxy for a connected host's remote DSH web UI.
|
|
3
|
-
*
|
|
4
|
-
* The browser half shows the remote UI in a same-origin frame. This module makes that frame work
|
|
5
|
-
* without handing the browser a second origin:
|
|
6
|
-
*
|
|
7
|
-
* - every request under `REMOTE_VIEW_PREFIX<hostId>/` is stripped of the prefix and forwarded to
|
|
8
|
-
* that host's loopback tunnel;
|
|
9
|
-
* - the remote's session cookies stay in a per-host jar here, never in the local GUI's cookie jar
|
|
10
|
-
* (both GUIs answer on 127.0.0.1, so browser cookies are shared across ports);
|
|
11
|
-
* - `Host`/`Origin` are rewritten to the remote's own loopback authority, so the remote's
|
|
12
|
-
* authority-bound cookie and same-origin fence keep working;
|
|
13
|
-
* - the only WebSocket route a remote DSH owns (`/api/remote.mux`) gets one exact upgrade route
|
|
14
|
-
* per connected host, because the local web server matches upgrades by exact pathname.
|
|
15
|
-
*
|
|
16
|
-
* It proxies nothing but a host that is currently connected: an unknown or disconnected host id
|
|
17
|
-
* is a 404, DSH's own admission decides whether the caller may use the seat at all, and the
|
|
18
|
-
* same-origin fence rejects cross-site requests, matching the local API.
|
|
19
|
-
*/
|
|
20
|
-
import http from 'node:http'
|
|
21
|
-
import net from 'node:net'
|
|
22
|
-
import { REMOTE_VIEW_PREFIX } from './constants.js'
|
|
23
|
-
import { trustedRequest } from './request-trust.js'
|
|
24
|
-
|
|
25
|
-
/** How long the remote may take to accept a connection and answer; see `createRemoteProxy`. */
|
|
26
|
-
export const UPSTREAM_TIMEOUT_MS = 30_000
|
|
27
|
-
|
|
28
|
-
/** A handshake response head larger than this is not a WebSocket upgrade; it is dropped. */
|
|
29
|
-
const MAX_UPSTREAM_HEAD_BYTES = 64 * 1024
|
|
30
|
-
|
|
31
|
-
/** How long the remote web UI's own stream route is (the only upgrade a DSH web serves). */
|
|
32
|
-
const REMOTE_STREAM_PATH = '/api/remote.mux'
|
|
33
|
-
|
|
34
|
-
const HOST_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/
|
|
35
|
-
|
|
36
|
-
/** Headers that describe one hop and must not be copied to the other connection. */
|
|
37
|
-
const HOP_BY_HOP = new Set([
|
|
38
|
-
'connection',
|
|
39
|
-
'keep-alive',
|
|
40
|
-
'proxy-authenticate',
|
|
41
|
-
'proxy-authorization',
|
|
42
|
-
'te',
|
|
43
|
-
'trailer',
|
|
44
|
-
'transfer-encoding',
|
|
45
|
-
'upgrade',
|
|
46
|
-
])
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* The request headers this proxy forwards. This is an allowlist on purpose: the browser's own
|
|
50
|
-
* credentials belong to the *local* origin (`authorization`, `cookie`, `x-dsh-*`) and the
|
|
51
|
-
* traffic-shaping headers belong to this hop (`forwarded`, `x-forwarded-*`, `sec-fetch-*`).
|
|
52
|
-
* A blacklist forwarded them all to a host that the remote controls.
|
|
53
|
-
*/
|
|
54
|
-
const FORWARDED_REQUEST_HEADERS = new Set([
|
|
55
|
-
'accept',
|
|
56
|
-
'accept-encoding',
|
|
57
|
-
'accept-language',
|
|
58
|
-
'cache-control',
|
|
59
|
-
'content-length',
|
|
60
|
-
'content-type',
|
|
61
|
-
'range',
|
|
62
|
-
'user-agent',
|
|
63
|
-
'x-requested-with',
|
|
64
|
-
])
|
|
65
|
-
|
|
66
|
-
/** Conditional-request headers: `if-match`, `if-none-match`, `if-modified-since`, `if-range`, … */
|
|
67
|
-
const FORWARDED_REQUEST_PREFIX = 'if-'
|
|
68
|
-
|
|
69
|
-
/** The fields a WebSocket handshake needs, forwarded only on an upgrade. */
|
|
70
|
-
const UPGRADE_REQUEST_HEADERS = new Set([
|
|
71
|
-
'connection',
|
|
72
|
-
'upgrade',
|
|
73
|
-
'sec-websocket-key',
|
|
74
|
-
'sec-websocket-version',
|
|
75
|
-
'sec-websocket-protocol',
|
|
76
|
-
'sec-websocket-extensions',
|
|
77
|
-
])
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Response headers a remote page may not set on the local origin. `clear-site-data` would let a
|
|
81
|
-
* compromised remote wipe this GUI's own cookies and storage, `access-control-*` would open the
|
|
82
|
-
* local origin to other sites, and `refresh` / `content-location` / `report-to` / `nel` /
|
|
83
|
-
* `permissions-policy` / `alt-svc` redirect or reshape the browser's view of a server it does
|
|
84
|
-
* not own.
|
|
85
|
-
*/
|
|
86
|
-
const BLOCKED_RESPONSE_HEADERS = new Set([
|
|
87
|
-
'clear-site-data',
|
|
88
|
-
'refresh',
|
|
89
|
-
'content-location',
|
|
90
|
-
'report-to',
|
|
91
|
-
'nel',
|
|
92
|
-
'permissions-policy',
|
|
93
|
-
'alt-svc',
|
|
94
|
-
])
|
|
95
|
-
|
|
96
|
-
/** Every `access-control-*` response header belongs to the remote's origin, not this one. */
|
|
97
|
-
const BLOCKED_RESPONSE_PREFIX = 'access-control-'
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Whether one browser request header may reach the remote.
|
|
101
|
-
* @param {string} name - lowercase header name.
|
|
102
|
-
* @param {boolean} preserveUpgrade - whether this is a WebSocket handshake.
|
|
103
|
-
* @returns {boolean}
|
|
104
|
-
*/
|
|
105
|
-
export function forwardableRequestHeader(name, preserveUpgrade = false) {
|
|
106
|
-
if (FORWARDED_REQUEST_HEADERS.has(name)) return true
|
|
107
|
-
if (name.startsWith(FORWARDED_REQUEST_PREFIX)) return true
|
|
108
|
-
return preserveUpgrade === true && UPGRADE_REQUEST_HEADERS.has(name)
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Whether one upstream response header may reach the browser.
|
|
113
|
-
* @param {string} name - lowercase header name.
|
|
114
|
-
* @returns {boolean}
|
|
115
|
-
*/
|
|
116
|
-
export function forwardableResponseHeader(name) {
|
|
117
|
-
if (BLOCKED_RESPONSE_HEADERS.has(name)) return false
|
|
118
|
-
if (name.startsWith(BLOCKED_RESPONSE_PREFIX)) return false
|
|
119
|
-
return true
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Split `/dsh-remote-go/remote/<hostId>/<rest>` into its host and the upstream path.
|
|
124
|
-
* Returns null for anything that is not one well-formed view path (encoded slashes included).
|
|
125
|
-
* @param {string} pathname - URL pathname.
|
|
126
|
-
* @returns {{ hostId: string, path: string } | null}
|
|
127
|
-
*/
|
|
128
|
-
export function parseViewPath(pathname) {
|
|
129
|
-
if (typeof pathname !== 'string' || !pathname.startsWith(REMOTE_VIEW_PREFIX)) return null
|
|
130
|
-
const rest = pathname.slice(REMOTE_VIEW_PREFIX.length)
|
|
131
|
-
const slash = rest.indexOf('/')
|
|
132
|
-
const rawId = slash === -1 ? rest : rest.slice(0, slash)
|
|
133
|
-
let hostId
|
|
134
|
-
try {
|
|
135
|
-
hostId = decodeURIComponent(rawId)
|
|
136
|
-
} catch {
|
|
137
|
-
return null
|
|
138
|
-
}
|
|
139
|
-
if (!HOST_ID_PATTERN.test(hostId)) return null
|
|
140
|
-
// The seat is always `<prefix><hostId>/`: the bare id is not a page.
|
|
141
|
-
if (slash === -1) return null
|
|
142
|
-
const upstream = rest.slice(slash)
|
|
143
|
-
return { hostId, path: upstream === '' ? '/' : upstream }
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/** Exact pathname the remote's stream upgrade arrives on. */
|
|
147
|
-
export function upgradePath(hostId) {
|
|
148
|
-
return `${REMOTE_VIEW_PREFIX}${hostId}${REMOTE_STREAM_PATH}`
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Bounds of one host's cookie jar. The remote decides what to set, so the jar needs a ceiling:
|
|
153
|
-
* 64 cookies of at most 4 KiB keep a hostile or simply broken remote from growing the process,
|
|
154
|
-
* and a cookie the remote marks `Secure` never lands in this plaintext, in-memory jar at all.
|
|
155
|
-
*/
|
|
156
|
-
export const MAX_JAR_COOKIES = 64
|
|
157
|
-
export const MAX_COOKIE_VALUE = 4096
|
|
158
|
-
export const MAX_COOKIE_NAME = 128
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Parse one `Set-Cookie` line into the jar entry it should replace.
|
|
162
|
-
* Only the attributes that decide whether and where the value is sent are kept.
|
|
163
|
-
* @param {string} line - one Set-Cookie header value.
|
|
164
|
-
* @returns {{ name: string, value: string, path: string, expiresAt: number, secure: boolean } | null}
|
|
165
|
-
*/
|
|
166
|
-
export function parseSetCookie(line) {
|
|
167
|
-
const [pair, ...attributes] = String(line ?? '').split(';')
|
|
168
|
-
const equals = pair.indexOf('=')
|
|
169
|
-
if (equals <= 0) return null
|
|
170
|
-
const name = pair.slice(0, equals).trim()
|
|
171
|
-
const value = pair.slice(equals + 1).trim()
|
|
172
|
-
if (name === '' || name.length > MAX_COOKIE_NAME) return null
|
|
173
|
-
if (value.length > MAX_COOKIE_VALUE) return null
|
|
174
|
-
let cookiePath = '/'
|
|
175
|
-
let expiresAt = Number.POSITIVE_INFINITY
|
|
176
|
-
let secure = false
|
|
177
|
-
for (const attribute of attributes) {
|
|
178
|
-
const at = attribute.indexOf('=')
|
|
179
|
-
const key = (at === -1 ? attribute : attribute.slice(0, at)).trim().toLowerCase()
|
|
180
|
-
const raw = at === -1 ? '' : attribute.slice(at + 1).trim()
|
|
181
|
-
if (key === 'path' && raw.startsWith('/')) cookiePath = raw
|
|
182
|
-
if (key === 'secure') secure = true
|
|
183
|
-
if (key === 'max-age') {
|
|
184
|
-
const seconds = Number(raw)
|
|
185
|
-
if (Number.isFinite(seconds)) expiresAt = seconds <= 0 ? 0 : Date.now() + seconds * 1000
|
|
186
|
-
}
|
|
187
|
-
if (key === 'expires' && expiresAt === Number.POSITIVE_INFINITY) {
|
|
188
|
-
const parsed = Date.parse(raw)
|
|
189
|
-
if (Number.isFinite(parsed)) expiresAt = parsed
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
return { name, value, path: cookiePath, expiresAt, secure }
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/** One host's cookies, keyed by name; values never leave this process. */
|
|
196
|
-
function createCookieJar() {
|
|
197
|
-
return new Map()
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* Store every non-expired cookie from one response and drop the ones it cleared.
|
|
202
|
-
* @param {Map<string, { value: string, path: string, expiresAt: number, secure?: boolean }>} jar - host jar.
|
|
203
|
-
* @param {string | string[] | undefined} setCookie - raw Set-Cookie value(s).
|
|
204
|
-
*/
|
|
205
|
-
export function storeCookies(jar, setCookie) {
|
|
206
|
-
if (setCookie === undefined) return
|
|
207
|
-
for (const line of Array.isArray(setCookie) ? setCookie : [setCookie]) {
|
|
208
|
-
const entry = parseSetCookie(line)
|
|
209
|
-
if (entry === null) continue
|
|
210
|
-
if (entry.value === '' || entry.expiresAt <= Date.now()) {
|
|
211
|
-
jar.delete(entry.name)
|
|
212
|
-
continue
|
|
213
|
-
}
|
|
214
|
-
// The tunnel is plain HTTP to 127.0.0.1, so a `Secure` cookie is not one this jar may
|
|
215
|
-
// keep: storing and replaying it would downgrade a flag the remote asked for.
|
|
216
|
-
if (entry.secure) {
|
|
217
|
-
jar.delete(entry.name)
|
|
218
|
-
continue
|
|
219
|
-
}
|
|
220
|
-
if (!jar.has(entry.name) && jar.size >= MAX_JAR_COOKIES) continue
|
|
221
|
-
jar.set(entry.name, { name: entry.name, value: entry.value, path: entry.path, expiresAt: entry.expiresAt })
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
/**
|
|
226
|
-
* Cookies whose path covers the upstream path, as one Cookie header value.
|
|
227
|
-
* @param {Map<string, { value: string, path: string, expiresAt: number }>} jar - host jar.
|
|
228
|
-
* @param {string} path - upstream request path.
|
|
229
|
-
* @returns {string}
|
|
230
|
-
*/
|
|
231
|
-
export function cookieHeader(jar, path) {
|
|
232
|
-
const now = Date.now()
|
|
233
|
-
const parts = []
|
|
234
|
-
for (const [name, entry] of jar) {
|
|
235
|
-
if (entry.expiresAt <= now) {
|
|
236
|
-
jar.delete(name)
|
|
237
|
-
continue
|
|
238
|
-
}
|
|
239
|
-
const covers =
|
|
240
|
-
entry.path === '/' ||
|
|
241
|
-
path === entry.path ||
|
|
242
|
-
path.startsWith(`${entry.path.endsWith('/') ? entry.path.slice(0, -1) : entry.path}/`)
|
|
243
|
-
if (covers) parts.push(`${name}=${entry.value}`)
|
|
244
|
-
}
|
|
245
|
-
return parts.join('; ')
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
/** Absolute origin of the remote's own listener, as the remote sees itself through the tunnel. */
|
|
249
|
-
function remoteOrigin(target) {
|
|
250
|
-
const port = Number(target.remotePort)
|
|
251
|
-
return `http://127.0.0.1:${Number.isInteger(port) && port > 0 ? port : target.localPort}`
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
function remoteAuthority(target) {
|
|
255
|
-
return remoteOrigin(target).slice('http://'.length)
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
/** Rewrite an absolute URL from the local origin to the remote's origin, keeping its path. */
|
|
259
|
-
function rewriteSameOrigin(value, localOrigin, target) {
|
|
260
|
-
const local = typeof localOrigin === 'string' ? localOrigin.replace(/\/$/, '') : ''
|
|
261
|
-
const text = String(value)
|
|
262
|
-
if (local !== '' && (text === local || text.startsWith(`${local}/`))) {
|
|
263
|
-
return remoteOrigin(target) + text.slice(local.length)
|
|
264
|
-
}
|
|
265
|
-
return text
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* Request headers for the upstream: only the allowlisted content headers are copied, the two
|
|
270
|
-
* authority fields are rewritten, and only this host's own cookies are added.
|
|
271
|
-
* @param {string[]} rawHeaders - node raw header list.
|
|
272
|
-
* @param {{ target: object, localOrigin: string, path: string, jar: Map }} input
|
|
273
|
-
* @returns {Record<string, string | string[]>}
|
|
274
|
-
*/
|
|
275
|
-
export function upstreamHeaders(rawHeaders, input) {
|
|
276
|
-
const out = {}
|
|
277
|
-
const preserveUpgrade = input.preserveUpgrade === true
|
|
278
|
-
for (let at = 0; at < rawHeaders.length; at += 2) {
|
|
279
|
-
const name = String(rawHeaders[at]).toLowerCase()
|
|
280
|
-
const value = rawHeaders[at + 1]
|
|
281
|
-
if (name === 'host' || name === 'cookie') continue
|
|
282
|
-
if (name === 'origin') {
|
|
283
|
-
out.origin = remoteOrigin(input.target)
|
|
284
|
-
continue
|
|
285
|
-
}
|
|
286
|
-
if (name === 'referer') {
|
|
287
|
-
out.referer = rewriteSameOrigin(value, input.localOrigin, input.target)
|
|
288
|
-
continue
|
|
289
|
-
}
|
|
290
|
-
if (!forwardableRequestHeader(name, preserveUpgrade)) continue
|
|
291
|
-
out[name] = out[name] === undefined ? value : [].concat(out[name], value)
|
|
292
|
-
}
|
|
293
|
-
out.host = remoteAuthority(input.target)
|
|
294
|
-
const cookies = cookieHeader(input.jar, input.path)
|
|
295
|
-
if (cookies !== '') out.cookie = cookies
|
|
296
|
-
return out
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
/**
|
|
300
|
-
* Drop only the `frame-ancestors` directive of a CSP: the proxy exists to frame that one page,
|
|
301
|
-
* and a hostile-looking directive would otherwise make a hardened remote unusable in a browser.
|
|
302
|
-
* Every other directive stays exactly as the remote sent it.
|
|
303
|
-
* @param {string} value - one Content-Security-Policy value.
|
|
304
|
-
* @returns {string}
|
|
305
|
-
*/
|
|
306
|
-
export function withoutFrameAncestors(value) {
|
|
307
|
-
return String(value)
|
|
308
|
-
.split(';')
|
|
309
|
-
.filter((directive) => !/^\s*frame-ancestors\b/i.test(directive))
|
|
310
|
-
.map((directive) => directive.trim())
|
|
311
|
-
.filter((directive) => directive !== '')
|
|
312
|
-
.join('; ')
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
/**
|
|
316
|
-
* Rewrite one upstream `Location` for the browser.
|
|
317
|
-
*
|
|
318
|
-
* A redirect that names the remote's own loopback listener is folded back under the view
|
|
319
|
-
* prefix, so a form post or a token exchange stays inside the frame. Everything else that is an
|
|
320
|
-
* absolute URL — another host, another scheme, a protocol-relative `//evil.example`, or a
|
|
321
|
-
* different loopback port — is refused (`null`): the header is dropped, because navigation
|
|
322
|
-
* inside this same-origin frame must never leave the seat the user opened. A relative
|
|
323
|
-
* reference (`.`, `./next`, `/assets/app.js`) is already resolved against that seat, so it is
|
|
324
|
-
* passed through untouched.
|
|
325
|
-
* @param {string} value - one upstream Location header value.
|
|
326
|
-
* @param {{ hostId?: string, remoteOrigin?: string }} [input]
|
|
327
|
-
* @returns {string | null} the header value to send, or null to drop the header.
|
|
328
|
-
*/
|
|
329
|
-
export function safeLocation(value, input = {}) {
|
|
330
|
-
const text = String(value ?? '')
|
|
331
|
-
.replace(/[\r\n]/g, '')
|
|
332
|
-
.trim()
|
|
333
|
-
if (text === '') return null
|
|
334
|
-
if (input.hostId && input.remoteOrigin) {
|
|
335
|
-
if (text === input.remoteOrigin) return `${REMOTE_VIEW_PREFIX}${input.hostId}/`
|
|
336
|
-
if (text.startsWith(`${input.remoteOrigin}/`)) {
|
|
337
|
-
return `${REMOTE_VIEW_PREFIX}${input.hostId}${text.slice(input.remoteOrigin.length)}`
|
|
338
|
-
}
|
|
339
|
-
if (text.startsWith(`${input.remoteOrigin}?`) || text.startsWith(`${input.remoteOrigin}#`)) {
|
|
340
|
-
return `${REMOTE_VIEW_PREFIX}${input.hostId}/${text.slice(input.remoteOrigin.length)}`
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
// Any scheme (`https:`, `javascript:`, `data:`…) is an absolute target.
|
|
344
|
-
if (/^[a-z][a-z0-9+.-]*:/i.test(text)) return null
|
|
345
|
-
// A backslash is a slash to the URL parser for special schemes: `/\evil.example/x` and
|
|
346
|
-
// `\/evil.example` both resolve to `http://evil.example/`, so a surviving backslash in what
|
|
347
|
-
// looks like a relative reference is an off-origin escape. (`%5c` stays percent-encoded and is
|
|
348
|
-
// not a separator, so it is not caught here.)
|
|
349
|
-
if (text.includes('\\')) return null
|
|
350
|
-
// `//host/…`: a browser reads it as protocol-relative, i.e. off-origin.
|
|
351
|
-
if (text.startsWith('//')) return null
|
|
352
|
-
return text
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
/**
|
|
356
|
-
* Response headers to hand the browser: drop hop-by-hop fields, this connection's framing, the
|
|
357
|
-
* remote's cookies (they go to the jar), any frame denial the remote inherited from another
|
|
358
|
-
* deployment, and browser-policy headers the remote must not set on the local origin. A
|
|
359
|
-
* `Location` that names the remote's own listener is folded back under the view prefix; any
|
|
360
|
-
* other absolute target is dropped so a redirect cannot slip out of the frame.
|
|
361
|
-
* @param {string[]} rawHeaders - upstream raw header list.
|
|
362
|
-
* @param {{ hostId?: string, remoteOrigin?: string }} [input]
|
|
363
|
-
* @returns {string[]} flat [name, value, …] pairs.
|
|
364
|
-
*/
|
|
365
|
-
export function responseHeaders(rawHeaders, input = {}) {
|
|
366
|
-
const out = []
|
|
367
|
-
const preserveUpgrade = input.preserveUpgrade === true
|
|
368
|
-
for (let at = 0; at < rawHeaders.length; at += 2) {
|
|
369
|
-
const name = String(rawHeaders[at]).toLowerCase()
|
|
370
|
-
// `Connection`/`Upgrade` are hop-by-hop, except in the response to a WebSocket handshake:
|
|
371
|
-
// dropping them there would turn a valid 101 into a protocol error.
|
|
372
|
-
if (HOP_BY_HOP.has(name) && !(preserveUpgrade && (name === 'connection' || name === 'upgrade'))) continue
|
|
373
|
-
if (name === 'set-cookie' || name === 'x-frame-options') continue
|
|
374
|
-
if (!forwardableResponseHeader(name)) continue
|
|
375
|
-
if (name === 'content-security-policy') {
|
|
376
|
-
out.push(rawHeaders[at], withoutFrameAncestors(String(rawHeaders[at + 1])))
|
|
377
|
-
continue
|
|
378
|
-
}
|
|
379
|
-
if (name === 'location') {
|
|
380
|
-
const location = safeLocation(rawHeaders[at + 1], input)
|
|
381
|
-
if (location === null) continue
|
|
382
|
-
out.push(rawHeaders[at], location)
|
|
383
|
-
continue
|
|
384
|
-
}
|
|
385
|
-
out.push(rawHeaders[at], rawHeaders[at + 1])
|
|
386
|
-
}
|
|
387
|
-
return out
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
/**
|
|
391
|
-
* Rewrite one raw upstream response head (status line + headers, without the final blank line).
|
|
392
|
-
*
|
|
393
|
-
* The upgrade path forwards a 101 byte-for-byte if left alone, which also forwarded
|
|
394
|
-
* `Set-Cookie` and every browser-policy header the remote chose to attach to the handshake. The
|
|
395
|
-
* same policy as `responseHeaders` applies here; only the status line and the header block are
|
|
396
|
-
* touched, never the frames that follow.
|
|
397
|
-
* @param {string} headText - latin1-decoded head, `HTTP/1.1 101 …\r\nkey: value…`.
|
|
398
|
-
* @param {{ hostId?: string, remoteOrigin?: string }} [input]
|
|
399
|
-
* @returns {string} the filtered head (without the trailing blank line), or '' when unparseable.
|
|
400
|
-
*/
|
|
401
|
-
export function filterResponseHead(headText, input = {}) {
|
|
402
|
-
const lines = String(headText ?? '').split('\r\n')
|
|
403
|
-
const statusLine = lines.shift() ?? ''
|
|
404
|
-
if (!/^HTTP\/1\.[01] \d{3}(?: .*)?$/.test(statusLine)) return ''
|
|
405
|
-
const raw = []
|
|
406
|
-
for (const line of lines) {
|
|
407
|
-
const colon = line.indexOf(':')
|
|
408
|
-
if (colon <= 0) continue
|
|
409
|
-
raw.push(line.slice(0, colon).trim(), line.slice(colon + 1).trim())
|
|
410
|
-
}
|
|
411
|
-
const filtered = responseHeaders(raw, { ...input, preserveUpgrade: true })
|
|
412
|
-
let out = `${statusLine}\r\n`
|
|
413
|
-
for (let at = 0; at < filtered.length; at += 2) out += `${filtered[at]}: ${filtered[at + 1]}\r\n`
|
|
414
|
-
return out
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
function plain(res, status, text) {
|
|
418
|
-
const body = String(text)
|
|
419
|
-
try {
|
|
420
|
-
res.writeHead(status, {
|
|
421
|
-
'content-type': 'text/plain; charset=utf-8',
|
|
422
|
-
'cache-control': 'no-store',
|
|
423
|
-
'content-length': Buffer.byteLength(body),
|
|
424
|
-
})
|
|
425
|
-
res.end(body)
|
|
426
|
-
} catch {
|
|
427
|
-
// swallow-ok: the client may already have closed the response
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
/**
|
|
432
|
-
* Create the proxy. `resolveHost` is the single pivot: it returns the loopback target for one
|
|
433
|
-
* connected host (`{ localPort, remotePort }`) or null. Nothing else in this module knows how a
|
|
434
|
-
* tunnel was made.
|
|
435
|
-
* @param {object} options
|
|
436
|
-
* @param {object} options.webServer - local DSH web server (register/registerUpgrade/getOrigin).
|
|
437
|
-
* @param {() => string | null} options.getOrigin - local origin, read per request.
|
|
438
|
-
* @param {(hostId: string) => ({ localPort: number, remotePort: number } | null)} options.resolveHost
|
|
439
|
-
* @param {(req: object) => (number | undefined)} [options.admit] - DSH admission
|
|
440
|
-
* (`ctx.connection.requestRejection`): the rejection status for a request, or undefined when it may
|
|
441
|
-
* proceed. Absent on kernels without the Connection service, where the fence below is the gate.
|
|
442
|
-
* @param {(hostId: string) => void} [options.onUpstreamError] - called once per failed upstream
|
|
443
|
-
* connection so the Host can confirm a suspected remote restart (the browser still gets a 502).
|
|
444
|
-
* @param {{ warn?: Function, debug?: Function, error?: Function }} [options.logger]
|
|
445
|
-
*/
|
|
446
|
-
export function createRemoteProxy(options) {
|
|
447
|
-
const logger = options.logger ?? console
|
|
448
|
-
const webServer = options.webServer
|
|
449
|
-
const getOrigin = options.getOrigin
|
|
450
|
-
const resolveHost = options.resolveHost
|
|
451
|
-
const admit = typeof options.admit === 'function' ? options.admit : () => undefined
|
|
452
|
-
const onUpstreamError = options.onUpstreamError
|
|
453
|
-
const upstreamTimeoutMs =
|
|
454
|
-
Number.isSafeInteger(options.upstreamTimeoutMs) && options.upstreamTimeoutMs > 0
|
|
455
|
-
? options.upstreamTimeoutMs
|
|
456
|
-
: UPSTREAM_TIMEOUT_MS
|
|
457
|
-
const jars = new Map()
|
|
458
|
-
const upgrades = new Map()
|
|
459
|
-
const sockets = new Set()
|
|
460
|
-
let disposed = false
|
|
461
|
-
/** Report one failed upstream without letting the reporter break the proxy. */
|
|
462
|
-
function reportUpstreamFailure(hostId) {
|
|
463
|
-
try {
|
|
464
|
-
onUpstreamError?.(hostId)
|
|
465
|
-
} catch {
|
|
466
|
-
// swallow-ok: reporting only feeds the liveness confirmation, it must never fail a request
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
/**
|
|
471
|
-
* The per-host cookie jar is bound to the remote authority it was filled from: after a
|
|
472
|
-
* restart or a re-attach the remote comes back on a new random port, and cookies issued
|
|
473
|
-
* by the old instance must not be sent to the new one (nor kept after the host is gone).
|
|
474
|
-
*/
|
|
475
|
-
function jarOf(hostId, target) {
|
|
476
|
-
const authority = remoteAuthority(target)
|
|
477
|
-
let entry = jars.get(hostId)
|
|
478
|
-
if (entry === undefined || entry.authority !== authority) {
|
|
479
|
-
entry = { authority, jar: createCookieJar() }
|
|
480
|
-
jars.set(hostId, entry)
|
|
481
|
-
}
|
|
482
|
-
return entry.jar
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
function localOrigin() {
|
|
486
|
-
try {
|
|
487
|
-
const origin = getOrigin()
|
|
488
|
-
return typeof origin === 'string' && origin !== '' ? new URL(origin) : null
|
|
489
|
-
} catch {
|
|
490
|
-
return null
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
function targetOf(hostId) {
|
|
495
|
-
try {
|
|
496
|
-
const target = resolveHost(hostId)
|
|
497
|
-
return target && Number.isInteger(Number(target.localPort)) && Number(target.localPort) > 0 ? target : null
|
|
498
|
-
} catch {
|
|
499
|
-
return null
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
function handle(req, res) {
|
|
504
|
-
if (disposed) {
|
|
505
|
-
plain(res, 503, 'proxy disposed')
|
|
506
|
-
return
|
|
507
|
-
}
|
|
508
|
-
// DSH's own admission gate runs before anything this module decides: the proxy reaches a
|
|
509
|
-
// connected host's remote session (its cookie jar), so only an admitted caller may use it.
|
|
510
|
-
const rejection = admit(req)
|
|
511
|
-
if (rejection !== undefined) {
|
|
512
|
-
plain(res, rejection, 'request rejected by DSH admission')
|
|
513
|
-
return
|
|
514
|
-
}
|
|
515
|
-
const origin = localOrigin()
|
|
516
|
-
if (origin === null) {
|
|
517
|
-
plain(res, 503, 'local origin is not ready')
|
|
518
|
-
return
|
|
519
|
-
}
|
|
520
|
-
if (!trustedRequest(req, origin)) {
|
|
521
|
-
plain(res, 403, 'cross-site request rejected')
|
|
522
|
-
return
|
|
523
|
-
}
|
|
524
|
-
let pathname
|
|
525
|
-
let search
|
|
526
|
-
try {
|
|
527
|
-
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
528
|
-
pathname = url.pathname
|
|
529
|
-
search = url.search
|
|
530
|
-
} catch {
|
|
531
|
-
plain(res, 400, 'bad request path')
|
|
532
|
-
return
|
|
533
|
-
}
|
|
534
|
-
const parsed = parseViewPath(pathname)
|
|
535
|
-
if (parsed === null) {
|
|
536
|
-
plain(res, 404, 'unknown remote view')
|
|
537
|
-
return
|
|
538
|
-
}
|
|
539
|
-
const target = targetOf(parsed.hostId)
|
|
540
|
-
if (target === null) {
|
|
541
|
-
plain(res, 404, 'host is not connected')
|
|
542
|
-
return
|
|
543
|
-
}
|
|
544
|
-
const jar = jarOf(parsed.hostId, target)
|
|
545
|
-
const upstreamPath = parsed.path + search
|
|
546
|
-
const headers = upstreamHeaders(req.rawHeaders, {
|
|
547
|
-
target,
|
|
548
|
-
localOrigin: origin.origin,
|
|
549
|
-
path: parsed.path,
|
|
550
|
-
jar,
|
|
551
|
-
})
|
|
552
|
-
// The remote is reached over a tunnel; a listener that accepts and never answers used to
|
|
553
|
-
// hang the local request forever. The deadline covers the wait for response headers only —
|
|
554
|
-
// once the response started, an idle stream (SSE, a large asset) is legitimate.
|
|
555
|
-
let answered = false
|
|
556
|
-
let failed = false
|
|
557
|
-
const upstream = http.request(
|
|
558
|
-
{
|
|
559
|
-
host: '127.0.0.1',
|
|
560
|
-
port: target.localPort,
|
|
561
|
-
path: upstreamPath,
|
|
562
|
-
method: req.method,
|
|
563
|
-
headers,
|
|
564
|
-
timeout: upstreamTimeoutMs,
|
|
565
|
-
},
|
|
566
|
-
(response) => {
|
|
567
|
-
answered = true
|
|
568
|
-
upstream.setTimeout(0)
|
|
569
|
-
storeCookies(jar, response.headers['set-cookie'])
|
|
570
|
-
try {
|
|
571
|
-
res.writeHead(
|
|
572
|
-
response.statusCode ?? 502,
|
|
573
|
-
responseHeaders(response.rawHeaders, {
|
|
574
|
-
hostId: parsed.hostId,
|
|
575
|
-
remoteOrigin: remoteOrigin(target),
|
|
576
|
-
}),
|
|
577
|
-
)
|
|
578
|
-
} catch {
|
|
579
|
-
response.destroy()
|
|
580
|
-
return
|
|
581
|
-
}
|
|
582
|
-
// A browser that leaves the page mid-load must not keep the tunneled response alive.
|
|
583
|
-
res.once('close', () => response.destroy())
|
|
584
|
-
response.pipe(res)
|
|
585
|
-
},
|
|
586
|
-
)
|
|
587
|
-
/**
|
|
588
|
-
* One failed upstream: report it once and answer 502 (or nothing, when the response has
|
|
589
|
-
* already started). Nothing from the failure reaches the log line: the emitter is
|
|
590
|
-
* request-driven, so CodeQL treats its error as user-controlled (log injection). The
|
|
591
|
-
* loopback port names the host to an operator, and the browser only ever sees the 502.
|
|
592
|
-
*/
|
|
593
|
-
const upstreamFailed = () => {
|
|
594
|
-
if (failed) return
|
|
595
|
-
failed = true
|
|
596
|
-
logger.debug?.(`[dsh-remote-go] remote proxy upstream 127.0.0.1:${target.localPort} failed`)
|
|
597
|
-
plain(res, 502, 'remote UI is unreachable')
|
|
598
|
-
reportUpstreamFailure(parsed.hostId)
|
|
599
|
-
}
|
|
600
|
-
upstream.on('timeout', () => {
|
|
601
|
-
if (answered) return
|
|
602
|
-
answered = true
|
|
603
|
-
upstream.destroy()
|
|
604
|
-
upstreamFailed()
|
|
605
|
-
})
|
|
606
|
-
upstream.on('error', () => {
|
|
607
|
-
// A failure after the response started is still worth reporting (the Host confirms it
|
|
608
|
-
// with probes); `plain` is a no-op once the headers are out.
|
|
609
|
-
upstreamFailed()
|
|
610
|
-
})
|
|
611
|
-
req.once('aborted', () => upstream.destroy())
|
|
612
|
-
req.pipe(upstream)
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
/** One exact upgrade route per host: the only WebSocket a DSH web serves is its stream mux. */
|
|
616
|
-
function handleUpgrade(hostId, req, socket, head) {
|
|
617
|
-
if (disposed) {
|
|
618
|
-
socket.destroy()
|
|
619
|
-
return
|
|
620
|
-
}
|
|
621
|
-
const rejection = admit(req)
|
|
622
|
-
if (rejection !== undefined) {
|
|
623
|
-
// An upgrade owns its socket: answer the handshake with the status, then close it.
|
|
624
|
-
socket.on('error', () => {})
|
|
625
|
-
socket.end(
|
|
626
|
-
`HTTP/1.1 ${rejection} ${http.STATUS_CODES[rejection] ?? 'Rejected'}\r\n` +
|
|
627
|
-
'connection: close\r\ncontent-length: 0\r\n\r\n',
|
|
628
|
-
)
|
|
629
|
-
return
|
|
630
|
-
}
|
|
631
|
-
const origin = localOrigin()
|
|
632
|
-
if (origin === null || !trustedRequest(req, origin)) {
|
|
633
|
-
socket.destroy()
|
|
634
|
-
return
|
|
635
|
-
}
|
|
636
|
-
const target = targetOf(hostId)
|
|
637
|
-
if (target === null) {
|
|
638
|
-
socket.destroy()
|
|
639
|
-
return
|
|
640
|
-
}
|
|
641
|
-
// A malformed request target (absolute-form, broken escape) must not throw out of the upgrade
|
|
642
|
-
// handler: the HTTP path already degrades to a 400, this one just drops the socket.
|
|
643
|
-
let parsed = null
|
|
644
|
-
try {
|
|
645
|
-
parsed = parseViewPath(new URL(req.url ?? '/', 'http://127.0.0.1').pathname)
|
|
646
|
-
} catch {
|
|
647
|
-
parsed = null
|
|
648
|
-
}
|
|
649
|
-
if (parsed === null) {
|
|
650
|
-
socket.destroy()
|
|
651
|
-
return
|
|
652
|
-
}
|
|
653
|
-
const jar = jarOf(hostId, target)
|
|
654
|
-
const headers = upstreamHeaders(req.rawHeaders, {
|
|
655
|
-
target,
|
|
656
|
-
localOrigin: origin.origin,
|
|
657
|
-
path: parsed.path,
|
|
658
|
-
jar,
|
|
659
|
-
preserveUpgrade: true,
|
|
660
|
-
})
|
|
661
|
-
let raw = `${req.method} ${parsed.path} HTTP/1.1\r\n`
|
|
662
|
-
for (const [name, value] of Object.entries(headers)) {
|
|
663
|
-
for (const item of Array.isArray(value) ? value : [value]) raw += `${name}: ${item}\r\n`
|
|
664
|
-
}
|
|
665
|
-
raw += '\r\n'
|
|
666
|
-
const upstream = net.connect({ port: target.localPort, host: '127.0.0.1', timeout: upstreamTimeoutMs })
|
|
667
|
-
// An upgrade owns its socket, so the deadline covers the handshake only: an upstream that
|
|
668
|
-
// accepts and never answers would otherwise leave both sockets dangling forever.
|
|
669
|
-
let settled = false
|
|
670
|
-
const handshakeTimer = setTimeout(() => failUpgrade(), upstreamTimeoutMs)
|
|
671
|
-
handshakeTimer.unref?.()
|
|
672
|
-
function failUpgrade() {
|
|
673
|
-
clearTimeout(handshakeTimer)
|
|
674
|
-
if (settled) return
|
|
675
|
-
settled = true
|
|
676
|
-
upstream.destroy()
|
|
677
|
-
socket.destroy()
|
|
678
|
-
reportUpstreamFailure(hostId)
|
|
679
|
-
}
|
|
680
|
-
sockets.add(socket)
|
|
681
|
-
// The upstream's response head is filtered before the browser sees it: a 101 used to be
|
|
682
|
-
// forwarded byte-for-byte, which also handed the remote's `Set-Cookie` and policy headers to
|
|
683
|
-
// the local origin. Only the head is parsed; everything after it streams untouched.
|
|
684
|
-
let upstreamHead = Buffer.alloc(0)
|
|
685
|
-
let headForwarded = false
|
|
686
|
-
const writeToClient = (chunk) => {
|
|
687
|
-
if (!socket.write(chunk)) upstream.pause()
|
|
688
|
-
}
|
|
689
|
-
const forwardUpstreamData = (chunk) => {
|
|
690
|
-
if (settled) return
|
|
691
|
-
clearTimeout(handshakeTimer)
|
|
692
|
-
upstream.setTimeout(0)
|
|
693
|
-
if (headForwarded) {
|
|
694
|
-
writeToClient(chunk)
|
|
695
|
-
return
|
|
696
|
-
}
|
|
697
|
-
upstreamHead = upstreamHead.length === 0 ? Buffer.from(chunk) : Buffer.concat([upstreamHead, chunk])
|
|
698
|
-
if (upstreamHead.length > MAX_UPSTREAM_HEAD_BYTES) {
|
|
699
|
-
// Nothing legitimate answers a handshake with a head this large.
|
|
700
|
-
failUpgrade()
|
|
701
|
-
return
|
|
702
|
-
}
|
|
703
|
-
const end = upstreamHead.indexOf('\r\n\r\n')
|
|
704
|
-
if (end === -1) return
|
|
705
|
-
const filtered = filterResponseHead(upstreamHead.subarray(0, end).toString('latin1'), {
|
|
706
|
-
hostId,
|
|
707
|
-
remoteOrigin: remoteOrigin(target),
|
|
708
|
-
})
|
|
709
|
-
if (filtered === '') {
|
|
710
|
-
failUpgrade()
|
|
711
|
-
return
|
|
712
|
-
}
|
|
713
|
-
headForwarded = true
|
|
714
|
-
writeToClient(`${filtered}\r\n`)
|
|
715
|
-
const rest = upstreamHead.subarray(end + 4)
|
|
716
|
-
upstreamHead = Buffer.alloc(0)
|
|
717
|
-
if (rest.length > 0) writeToClient(rest)
|
|
718
|
-
}
|
|
719
|
-
upstream.on('data', forwardUpstreamData)
|
|
720
|
-
socket.on('drain', () => upstream.resume())
|
|
721
|
-
upstream.on('timeout', () => failUpgrade())
|
|
722
|
-
upstream.on('error', () => failUpgrade())
|
|
723
|
-
/**
|
|
724
|
-
* The remote ended the stream. `upstream.pipe(socket)` used to forward that EOF implicitly;
|
|
725
|
-
* the head is parsed here, so the end of the upstream must still close the browser side or
|
|
726
|
-
* the page would hold a dead socket forever.
|
|
727
|
-
*/
|
|
728
|
-
const endClient = () => {
|
|
729
|
-
if (settled) return
|
|
730
|
-
settled = true
|
|
731
|
-
clearTimeout(handshakeTimer)
|
|
732
|
-
try {
|
|
733
|
-
socket.end()
|
|
734
|
-
} catch {}
|
|
735
|
-
}
|
|
736
|
-
upstream.on('end', endClient)
|
|
737
|
-
upstream.on('close', endClient)
|
|
738
|
-
socket.once('close', () => {
|
|
739
|
-
settled = true
|
|
740
|
-
clearTimeout(handshakeTimer)
|
|
741
|
-
sockets.delete(socket)
|
|
742
|
-
upstream.destroy()
|
|
743
|
-
})
|
|
744
|
-
socket.on('error', () => {
|
|
745
|
-
settled = true
|
|
746
|
-
clearTimeout(handshakeTimer)
|
|
747
|
-
upstream.destroy()
|
|
748
|
-
})
|
|
749
|
-
upstream.once('connect', () => {
|
|
750
|
-
if (settled) return
|
|
751
|
-
upstream.write(raw)
|
|
752
|
-
if (head && head.length > 0) upstream.write(head)
|
|
753
|
-
socket.pipe(upstream)
|
|
754
|
-
})
|
|
755
|
-
}
|
|
756
|
-
|
|
757
|
-
/**
|
|
758
|
-
* Keep one upgrade route per configured host. Called on init and on every state change; a host
|
|
759
|
-
* that disappears loses its route and its cookies.
|
|
760
|
-
* @param {string[]} hostIds
|
|
761
|
-
*/
|
|
762
|
-
function sync(hostIds) {
|
|
763
|
-
if (disposed) return
|
|
764
|
-
const wanted = new Set((Array.isArray(hostIds) ? hostIds : []).filter((id) => HOST_ID_PATTERN.test(String(id))))
|
|
765
|
-
for (const [hostId, dispose] of upgrades) {
|
|
766
|
-
if (wanted.has(hostId)) continue
|
|
767
|
-
dispose()
|
|
768
|
-
upgrades.delete(hostId)
|
|
769
|
-
jars.delete(hostId)
|
|
770
|
-
}
|
|
771
|
-
for (const hostId of wanted) {
|
|
772
|
-
if (upgrades.has(hostId)) continue
|
|
773
|
-
try {
|
|
774
|
-
upgrades.set(
|
|
775
|
-
hostId,
|
|
776
|
-
webServer.registerUpgrade({
|
|
777
|
-
path: upgradePath(hostId),
|
|
778
|
-
handler: (req, socket, head) => handleUpgrade(hostId, req, socket, head),
|
|
779
|
-
}),
|
|
780
|
-
)
|
|
781
|
-
} catch (error) {
|
|
782
|
-
logger.warn?.(
|
|
783
|
-
`[dsh-remote-go] could not register the stream route for ${hostId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
784
|
-
)
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
return {
|
|
790
|
-
prefix: REMOTE_VIEW_PREFIX,
|
|
791
|
-
/**
|
|
792
|
-
* The route registration path. The web server matches a prefix as `pathname === prefix ||
|
|
793
|
-
* pathname.startsWith(prefix + '/')`, so registering the trailing-slash seat prefix verbatim
|
|
794
|
-
* would never match a real view URL.
|
|
795
|
-
*/
|
|
796
|
-
routePath: REMOTE_VIEW_PREFIX.replace(/\/$/, ''),
|
|
797
|
-
handle,
|
|
798
|
-
handleUpgrade,
|
|
799
|
-
sync,
|
|
800
|
-
/** One host's current cookie header, for diagnostics and tests. */
|
|
801
|
-
cookies(hostId) {
|
|
802
|
-
const entry = jars.get(hostId)
|
|
803
|
-
return entry === undefined ? '' : cookieHeader(entry.jar, '/')
|
|
804
|
-
},
|
|
805
|
-
dispose() {
|
|
806
|
-
if (disposed) return
|
|
807
|
-
disposed = true
|
|
808
|
-
for (const dispose of upgrades.values()) dispose()
|
|
809
|
-
upgrades.clear()
|
|
810
|
-
jars.clear()
|
|
811
|
-
for (const socket of sockets) socket.destroy()
|
|
812
|
-
sockets.clear()
|
|
813
|
-
},
|
|
814
|
-
}
|
|
815
|
-
}
|