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
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** Bounds of one host's cookie jar: the remote decides what to set, so the jar needs a ceiling and a hostile or broken
|
|
2
|
+
* remote must not grow the process. A `Secure` cookie never lands in this plaintext, in-memory jar at all. */
|
|
3
|
+
export const MAX_JAR_COOKIES = 64;
|
|
4
|
+
export const MAX_COOKIE_VALUE = 4096;
|
|
5
|
+
export const MAX_COOKIE_NAME = 128;
|
|
6
|
+
/** Parse one `Set-Cookie` line into the jar entry it should replace: only the attributes that decide whether and where
|
|
7
|
+
* the value is sent are kept. */
|
|
8
|
+
export function parseSetCookie(line) {
|
|
9
|
+
const [pair, ...attributes] = String(line ?? '').split(';');
|
|
10
|
+
const equals = pair.indexOf('=');
|
|
11
|
+
if (equals <= 0)
|
|
12
|
+
return null;
|
|
13
|
+
const name = pair.slice(0, equals).trim();
|
|
14
|
+
const value = pair.slice(equals + 1).trim();
|
|
15
|
+
if (name === '' || name.length > MAX_COOKIE_NAME || value.length > MAX_COOKIE_VALUE)
|
|
16
|
+
return null;
|
|
17
|
+
let cookiePath = '/';
|
|
18
|
+
let expiresAt = Number.POSITIVE_INFINITY;
|
|
19
|
+
let secure = false;
|
|
20
|
+
for (const attribute of attributes) {
|
|
21
|
+
const at = attribute.indexOf('=');
|
|
22
|
+
const key = (at === -1 ? attribute : attribute.slice(0, at)).trim().toLowerCase();
|
|
23
|
+
const raw = at === -1 ? '' : attribute.slice(at + 1).trim();
|
|
24
|
+
if (key === 'path' && raw.startsWith('/'))
|
|
25
|
+
cookiePath = raw;
|
|
26
|
+
if (key === 'secure')
|
|
27
|
+
secure = true;
|
|
28
|
+
if (key === 'max-age') {
|
|
29
|
+
const seconds = Number(raw);
|
|
30
|
+
if (Number.isFinite(seconds))
|
|
31
|
+
expiresAt = seconds <= 0 ? 0 : Date.now() + seconds * 1000;
|
|
32
|
+
}
|
|
33
|
+
if (key === 'expires' && expiresAt === Number.POSITIVE_INFINITY) {
|
|
34
|
+
const parsed = Date.parse(raw);
|
|
35
|
+
if (Number.isFinite(parsed))
|
|
36
|
+
expiresAt = parsed;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return { name, value, path: cookiePath, expiresAt, secure };
|
|
40
|
+
}
|
|
41
|
+
/** Store every non-expired cookie from one response and drop the ones it cleared. */
|
|
42
|
+
export function storeCookies(jar, setCookie) {
|
|
43
|
+
if (setCookie === undefined)
|
|
44
|
+
return;
|
|
45
|
+
for (const line of Array.isArray(setCookie) ? setCookie : [setCookie]) {
|
|
46
|
+
const entry = parseSetCookie(line);
|
|
47
|
+
if (entry === null)
|
|
48
|
+
continue;
|
|
49
|
+
// A `Secure` cookie is refused too: the tunnel is plain HTTP to 127.0.0.1, so replaying it would downgrade a
|
|
50
|
+
// flag the remote asked for.
|
|
51
|
+
if (entry.value === '' || entry.expiresAt <= Date.now() || entry.secure) {
|
|
52
|
+
jar.delete(entry.name);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!jar.has(entry.name) && jar.size >= MAX_JAR_COOKIES)
|
|
56
|
+
continue;
|
|
57
|
+
jar.set(entry.name, { name: entry.name, value: entry.value, path: entry.path, expiresAt: entry.expiresAt });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** Cookies whose path covers the upstream path, as one `Cookie` header value. */
|
|
61
|
+
export function cookieHeader(jar, path) {
|
|
62
|
+
const now = Date.now();
|
|
63
|
+
const parts = [];
|
|
64
|
+
for (const [name, entry] of jar) {
|
|
65
|
+
if (entry.expiresAt <= now) {
|
|
66
|
+
jar.delete(name);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const base = entry.path.endsWith('/') ? entry.path.slice(0, -1) : entry.path;
|
|
70
|
+
if (entry.path === '/' || path === entry.path || path.startsWith(`${base}/`)) {
|
|
71
|
+
parts.push(`${name}=${entry.value}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return parts.join('; ');
|
|
75
|
+
}
|
|
76
|
+
/** Create the per-host jar book. `authorityOf` is injected instead of imported: `remoteAuthority` lives with header
|
|
77
|
+
* rewriting, which already imports `cookieHeader` here, so reaching back would make two leaves import each other. */
|
|
78
|
+
export function createJarBook(authorityOf) {
|
|
79
|
+
const jars = new Map();
|
|
80
|
+
return {
|
|
81
|
+
// A jar is bound to the authority it was filled from: after a restart or a re-attach the remote comes back on a
|
|
82
|
+
// new random port, and cookies issued by the old instance must not be sent to the new one.
|
|
83
|
+
jarFor(hostId, target) {
|
|
84
|
+
const authority = authorityOf(target);
|
|
85
|
+
const entry = jars.get(hostId);
|
|
86
|
+
if (entry !== undefined && entry.authority === authority)
|
|
87
|
+
return entry.jar;
|
|
88
|
+
const fresh = { authority, jar: new Map() };
|
|
89
|
+
jars.set(hostId, fresh);
|
|
90
|
+
return fresh.jar;
|
|
91
|
+
},
|
|
92
|
+
clear(hostId) {
|
|
93
|
+
if (hostId === undefined)
|
|
94
|
+
jars.clear();
|
|
95
|
+
else
|
|
96
|
+
jars.delete(hostId);
|
|
97
|
+
},
|
|
98
|
+
get(hostId) {
|
|
99
|
+
return jars.get(hostId)?.jar;
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/** Header rewriting for the same-origin proxy: an allowlist out, a blocklist back, and `Host`/`Origin` rewritten to the
|
|
2
|
+
* remote's own loopback authority, so its authority-bound cookie and same-origin fence keep working while the browser's
|
|
3
|
+
* local credentials and this hop's traffic-shaping headers stay here. */
|
|
4
|
+
import { REMOTE_VIEW_PREFIX } from '../constants.js';
|
|
5
|
+
import { cookieHeader } from './cookies.js';
|
|
6
|
+
/** One set of lowercase header names, written space-separated so a list stays visible at a glance. */
|
|
7
|
+
const headerSet = (names) => new Set(names.split(' '));
|
|
8
|
+
/** Headers that describe one hop and must not be copied to the other connection. */
|
|
9
|
+
const HOP_BY_HOP = headerSet('connection keep-alive proxy-authenticate proxy-authorization te trailer transfer-encoding upgrade');
|
|
10
|
+
const FORWARDED_REQUEST_HEADERS = headerSet('accept accept-encoding accept-language cache-control content-length content-type range user-agent x-requested-with');
|
|
11
|
+
/** Conditional-request headers: `if-match`, `if-none-match`, `if-modified-since`, `if-range`, … */
|
|
12
|
+
const FORWARDED_REQUEST_PREFIX = 'if-';
|
|
13
|
+
/** The fields a WebSocket handshake needs, forwarded only on an upgrade. */
|
|
14
|
+
const UPGRADE_REQUEST_HEADERS = headerSet('connection upgrade sec-websocket-key sec-websocket-version sec-websocket-protocol sec-websocket-extensions');
|
|
15
|
+
// The request side is an allowlist on purpose: a blocklist forwarded the browser's local credentials (`authorization`,
|
|
16
|
+
// `cookie`, `x-dsh-*`) and this hop's `forwarded`/`sec-fetch-*` headers to a host the remote controls. The response
|
|
17
|
+
// side blocks what would let a remote reshape this origin (`clear-site-data`, `access-control-*`).
|
|
18
|
+
const BLOCKED_RESPONSE_HEADERS = headerSet('clear-site-data refresh content-location report-to nel permissions-policy alt-svc');
|
|
19
|
+
/** Every `access-control-*` response header belongs to the remote's origin, not this one. */
|
|
20
|
+
const BLOCKED_RESPONSE_PREFIX = 'access-control-';
|
|
21
|
+
export function forwardableRequestHeader(name, preserveUpgrade = false) {
|
|
22
|
+
if (FORWARDED_REQUEST_HEADERS.has(name))
|
|
23
|
+
return true;
|
|
24
|
+
if (name.startsWith(FORWARDED_REQUEST_PREFIX))
|
|
25
|
+
return true;
|
|
26
|
+
return preserveUpgrade === true && UPGRADE_REQUEST_HEADERS.has(name);
|
|
27
|
+
}
|
|
28
|
+
export function forwardableResponseHeader(name) {
|
|
29
|
+
if (BLOCKED_RESPONSE_HEADERS.has(name))
|
|
30
|
+
return false;
|
|
31
|
+
return !name.startsWith(BLOCKED_RESPONSE_PREFIX);
|
|
32
|
+
}
|
|
33
|
+
/** Absolute origin of the remote's own listener, as the remote sees itself through the tunnel. */
|
|
34
|
+
export function remoteOrigin(target) {
|
|
35
|
+
const port = Number(target.remotePort);
|
|
36
|
+
return `http://127.0.0.1:${Number.isInteger(port) && port > 0 ? port : target.localPort}`;
|
|
37
|
+
}
|
|
38
|
+
/** The remote's own `host:port`, as its `Host` header and its cookies are bound to it. */
|
|
39
|
+
export function remoteAuthority(target) {
|
|
40
|
+
return remoteOrigin(target).slice('http://'.length);
|
|
41
|
+
}
|
|
42
|
+
/** Rewrite an absolute URL from the local origin to the remote's origin, keeping its path. */
|
|
43
|
+
function rewriteSameOrigin(value, localOrigin, target) {
|
|
44
|
+
const local = (typeof localOrigin === 'string' ? localOrigin : '').replace(/\/$/, '');
|
|
45
|
+
const text = String(value);
|
|
46
|
+
if (local !== '' && (text === local || text.startsWith(`${local}/`))) {
|
|
47
|
+
return remoteOrigin(target) + text.slice(local.length);
|
|
48
|
+
}
|
|
49
|
+
return text;
|
|
50
|
+
}
|
|
51
|
+
/** Request headers for the upstream: allowlisted content headers, rewritten `Host`/`Origin`/`Referer`, this host's
|
|
52
|
+
* cookies — nothing else. */
|
|
53
|
+
export function upstreamHeaders(rawHeaders, input) {
|
|
54
|
+
const out = {};
|
|
55
|
+
const preserveUpgrade = input.preserveUpgrade === true;
|
|
56
|
+
for (let at = 0; at < rawHeaders.length; at += 2) {
|
|
57
|
+
const name = String(rawHeaders[at]).toLowerCase();
|
|
58
|
+
const value = rawHeaders[at + 1];
|
|
59
|
+
if (name === 'host' || name === 'cookie')
|
|
60
|
+
continue;
|
|
61
|
+
if (name === 'origin') {
|
|
62
|
+
out.origin = remoteOrigin(input.target);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (name === 'referer') {
|
|
66
|
+
out.referer = rewriteSameOrigin(value, input.localOrigin, input.target);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (!forwardableRequestHeader(name, preserveUpgrade))
|
|
70
|
+
continue;
|
|
71
|
+
out[name] = out[name] === undefined ? value : [].concat(out[name], value);
|
|
72
|
+
}
|
|
73
|
+
out.host = remoteAuthority(input.target);
|
|
74
|
+
const cookies = cookieHeader(input.jar, input.path);
|
|
75
|
+
if (cookies !== '')
|
|
76
|
+
out.cookie = cookies;
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
/** Drop only the `frame-ancestors` CSP directive — the proxy frames that one page, so a hardened remote stays usable;
|
|
80
|
+
* every other directive goes out as sent. */
|
|
81
|
+
export function withoutFrameAncestors(value) {
|
|
82
|
+
return String(value)
|
|
83
|
+
.split(';')
|
|
84
|
+
.filter((directive) => !/^\s*frame-ancestors\b/i.test(directive))
|
|
85
|
+
.map((directive) => directive.trim())
|
|
86
|
+
.filter((directive) => directive !== '')
|
|
87
|
+
.join('; ');
|
|
88
|
+
}
|
|
89
|
+
/** Rewrite one upstream `Location` for the browser: one naming the remote's loopback listener folds back under the view
|
|
90
|
+
* prefix (a form post or token exchange stays in-frame); any other absolute target — host, scheme, `//evil.example`,
|
|
91
|
+
* another loopback port — is refused (`null` drops it), since this frame must never leave the seat the user opened. */
|
|
92
|
+
export function safeLocation(value, input = {}) {
|
|
93
|
+
const text = String(value ?? '')
|
|
94
|
+
.replace(/[\r\n]/g, '')
|
|
95
|
+
.trim();
|
|
96
|
+
if (text === '')
|
|
97
|
+
return null;
|
|
98
|
+
if (input.hostId && input.remoteOrigin) {
|
|
99
|
+
if (text === input.remoteOrigin)
|
|
100
|
+
return `${REMOTE_VIEW_PREFIX}${input.hostId}/`;
|
|
101
|
+
if (text.startsWith(`${input.remoteOrigin}/`)) {
|
|
102
|
+
return `${REMOTE_VIEW_PREFIX}${input.hostId}${text.slice(input.remoteOrigin.length)}`;
|
|
103
|
+
}
|
|
104
|
+
if (text.startsWith(`${input.remoteOrigin}?`) || text.startsWith(`${input.remoteOrigin}#`)) {
|
|
105
|
+
return `${REMOTE_VIEW_PREFIX}${input.hostId}/${text.slice(input.remoteOrigin.length)}`;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// Any scheme (`https:`, `javascript:`, `data:`…) is an absolute target.
|
|
109
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(text))
|
|
110
|
+
return null;
|
|
111
|
+
// A backslash is a slash for special schemes (`/\evil.example` resolves to http://evil.example/): off-origin.
|
|
112
|
+
if (text.includes('\\'))
|
|
113
|
+
return null;
|
|
114
|
+
// `//host/…`: a browser reads it as protocol-relative, i.e. off-origin.
|
|
115
|
+
if (text.startsWith('//'))
|
|
116
|
+
return null;
|
|
117
|
+
return text;
|
|
118
|
+
}
|
|
119
|
+
/** Response headers for the browser: drop hop-by-hop fields, this connection's framing, the remote's cookies (to the
|
|
120
|
+
* jar), inherited frame denials and browser-policy headers; `Location` is rewritten as `safeLocation` describes. */
|
|
121
|
+
export function responseHeaders(rawHeaders, input = {}) {
|
|
122
|
+
const out = [];
|
|
123
|
+
const preserveUpgrade = input.preserveUpgrade === true;
|
|
124
|
+
for (let at = 0; at < rawHeaders.length; at += 2) {
|
|
125
|
+
const name = String(rawHeaders[at]).toLowerCase();
|
|
126
|
+
// `Connection`/`Upgrade` are hop-by-hop, except in the response to a WebSocket handshake: dropping them there
|
|
127
|
+
// would turn a valid 101 into a protocol error.
|
|
128
|
+
if (HOP_BY_HOP.has(name) && !(preserveUpgrade && (name === 'connection' || name === 'upgrade')))
|
|
129
|
+
continue;
|
|
130
|
+
if (name === 'set-cookie' || name === 'x-frame-options')
|
|
131
|
+
continue;
|
|
132
|
+
if (!forwardableResponseHeader(name))
|
|
133
|
+
continue;
|
|
134
|
+
if (name === 'content-security-policy') {
|
|
135
|
+
out.push(rawHeaders[at], withoutFrameAncestors(String(rawHeaders[at + 1])));
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (name === 'location') {
|
|
139
|
+
const location = safeLocation(rawHeaders[at + 1], input);
|
|
140
|
+
if (location !== null)
|
|
141
|
+
out.push(rawHeaders[at], location);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
out.push(rawHeaders[at], rawHeaders[at + 1]);
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
/** Rewrite one raw upstream response head (status line + headers, without the final blank line). The upgrade path would
|
|
149
|
+
* otherwise forward a 101 byte-for-byte, `Set-Cookie` and browser policy included; frames are never touched. */
|
|
150
|
+
export function filterResponseHead(headText, input = {}) {
|
|
151
|
+
const lines = String(headText ?? '').split('\r\n');
|
|
152
|
+
const statusLine = lines.shift() ?? '';
|
|
153
|
+
if (!/^HTTP\/1\.[01] \d{3}(?: .*)?$/.test(statusLine))
|
|
154
|
+
return '';
|
|
155
|
+
const raw = [];
|
|
156
|
+
for (const line of lines) {
|
|
157
|
+
const colon = line.indexOf(':');
|
|
158
|
+
if (colon <= 0)
|
|
159
|
+
continue;
|
|
160
|
+
raw.push(line.slice(0, colon).trim(), line.slice(colon + 1).trim());
|
|
161
|
+
}
|
|
162
|
+
const filtered = responseHeaders(raw, { ...input, preserveUpgrade: true });
|
|
163
|
+
let out = `${statusLine}\r\n`;
|
|
164
|
+
for (let at = 0; at < filtered.length; at += 2)
|
|
165
|
+
out += `${filtered[at]}: ${filtered[at + 1]}\r\n`;
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/** The HTTP half of the same-origin proxy: admission, the local same-origin fence, view-path resolution, the upstream
|
|
2
|
+
* forward with its 30 s deadline, and the seven plain-text refusals. */
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import { trustedRequest } from '../request-trust.js';
|
|
5
|
+
import { storeCookies } from './cookies.js';
|
|
6
|
+
import { remoteOrigin, responseHeaders, upstreamHeaders } from './headers.js';
|
|
7
|
+
import { parseViewPath } from './routes.js';
|
|
8
|
+
/** One status line and a short body: every refusal this proxy answers with. */
|
|
9
|
+
function plain(res, status, text) {
|
|
10
|
+
const body = String(text);
|
|
11
|
+
try {
|
|
12
|
+
res.writeHead(status, {
|
|
13
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
14
|
+
'cache-control': 'no-store',
|
|
15
|
+
'content-length': Buffer.byteLength(body),
|
|
16
|
+
});
|
|
17
|
+
res.end(body);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
// swallow-ok: the client may already have closed the response
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** The one gate both halves run before anything is proxied: teardown, DSH's own admission (first, because the proxy reaches a connected host's remote session), the local origin and then the same-origin fence. No refusal says whether a seat exists. */
|
|
24
|
+
export function admitSeat(rt, req) {
|
|
25
|
+
if (rt.disposed())
|
|
26
|
+
return { ok: false, status: 503, text: 'proxy disposed', admission: false };
|
|
27
|
+
const rejection = rt.admit(req);
|
|
28
|
+
if (rejection !== undefined) {
|
|
29
|
+
return { ok: false, status: rejection, text: 'request rejected by DSH admission', admission: true };
|
|
30
|
+
}
|
|
31
|
+
const origin = rt.localOrigin();
|
|
32
|
+
if (origin === null)
|
|
33
|
+
return { ok: false, status: 503, text: 'local origin is not ready', admission: false };
|
|
34
|
+
if (!trustedRequest(req, origin)) {
|
|
35
|
+
return { ok: false, status: 403, text: 'cross-site request rejected', admission: false };
|
|
36
|
+
}
|
|
37
|
+
return { ok: true, origin };
|
|
38
|
+
}
|
|
39
|
+
/** Create the HTTP handler of one proxy activation. Every request under the view prefix is stripped of the prefix and
|
|
40
|
+
* forwarded to that host's loopback tunnel; a host that is not currently connected is a 404, and DSH's own admission
|
|
41
|
+
* plus the local same-origin fence decide whether the caller may use the seat at all. */
|
|
42
|
+
export function createHttpHandler(rt) {
|
|
43
|
+
return function handle(req, res) {
|
|
44
|
+
const seat = admitSeat(rt, req);
|
|
45
|
+
if (seat.ok === false) {
|
|
46
|
+
plain(res, seat.status, seat.text);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
let pathname;
|
|
50
|
+
let search;
|
|
51
|
+
try {
|
|
52
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
53
|
+
pathname = url.pathname;
|
|
54
|
+
search = url.search;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
plain(res, 400, 'bad request path');
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const parsed = parseViewPath(pathname);
|
|
61
|
+
if (parsed === null) {
|
|
62
|
+
plain(res, 404, 'unknown remote view');
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const target = rt.targetOf(parsed.hostId);
|
|
66
|
+
if (target === null) {
|
|
67
|
+
plain(res, 404, 'host is not connected');
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const jar = rt.jarFor(parsed.hostId, target);
|
|
71
|
+
const upstreamPath = parsed.path + search;
|
|
72
|
+
const headers = upstreamHeaders(req.rawHeaders, {
|
|
73
|
+
target,
|
|
74
|
+
localOrigin: seat.origin.origin,
|
|
75
|
+
path: parsed.path,
|
|
76
|
+
jar,
|
|
77
|
+
});
|
|
78
|
+
let answered = false;
|
|
79
|
+
let failed = false;
|
|
80
|
+
// The remote is reached over a tunnel; a listener that accepts and never answers used to hang the local request
|
|
81
|
+
// forever. The deadline covers the wait for response headers only — once the response started, an idle stream
|
|
82
|
+
// (SSE, a large asset) is legitimate.
|
|
83
|
+
const upstream = http.request({
|
|
84
|
+
host: '127.0.0.1',
|
|
85
|
+
port: target.localPort,
|
|
86
|
+
path: upstreamPath,
|
|
87
|
+
method: req.method,
|
|
88
|
+
headers,
|
|
89
|
+
timeout: rt.upstreamTimeoutMs,
|
|
90
|
+
}, (response) => {
|
|
91
|
+
answered = true;
|
|
92
|
+
upstream.setTimeout(0);
|
|
93
|
+
storeCookies(jar, response.headers['set-cookie']);
|
|
94
|
+
try {
|
|
95
|
+
res.writeHead(response.statusCode ?? 502, responseHeaders(response.rawHeaders, {
|
|
96
|
+
hostId: parsed.hostId,
|
|
97
|
+
remoteOrigin: remoteOrigin(target),
|
|
98
|
+
}));
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
response.destroy();
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
// A browser that leaves the page mid-load must not keep the tunneled response alive.
|
|
105
|
+
res.once('close', () => response.destroy());
|
|
106
|
+
response.pipe(res);
|
|
107
|
+
});
|
|
108
|
+
/** One failed upstream: report it once and answer 502 (or nothing, when the response has already started). Nothing
|
|
109
|
+
* from the failure reaches the log line: the emitter is request-driven, so CodeQL treats its error as
|
|
110
|
+
* user-controlled (log injection). The loopback port names the host to an operator; the browser sees the 502. */
|
|
111
|
+
const upstreamFailed = () => {
|
|
112
|
+
if (failed)
|
|
113
|
+
return;
|
|
114
|
+
failed = true;
|
|
115
|
+
rt.logger.debug?.(`[dsh-remote-go] remote proxy upstream 127.0.0.1:${target.localPort} failed`);
|
|
116
|
+
plain(res, 502, 'remote UI is unreachable');
|
|
117
|
+
rt.reportUpstreamFailure(parsed.hostId);
|
|
118
|
+
};
|
|
119
|
+
upstream.on('timeout', () => {
|
|
120
|
+
if (answered)
|
|
121
|
+
return;
|
|
122
|
+
answered = true;
|
|
123
|
+
upstream.destroy();
|
|
124
|
+
upstreamFailed();
|
|
125
|
+
});
|
|
126
|
+
upstream.on('error', () => {
|
|
127
|
+
// A failure after the response started is still worth reporting (the Host confirms it with probes); `plain`
|
|
128
|
+
// is a no-op once the headers are out.
|
|
129
|
+
upstreamFailed();
|
|
130
|
+
});
|
|
131
|
+
req.once('aborted', () => upstream.destroy());
|
|
132
|
+
req.pipe(upstream);
|
|
133
|
+
};
|
|
134
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { REMOTE_VIEW_PREFIX } from '../constants.js';
|
|
2
|
+
import { createJarBook, cookieHeader } from './cookies.js';
|
|
3
|
+
import { remoteAuthority } from './headers.js';
|
|
4
|
+
import { createHttpHandler } from './http.js';
|
|
5
|
+
import { UPSTREAM_TIMEOUT_MS } from './limits.js';
|
|
6
|
+
import { HOST_ID_PATTERN, upgradePath } from './routes.js';
|
|
7
|
+
import { createUpgradeHandler } from './upgrade.js';
|
|
8
|
+
/** Create the proxy. `resolveHost` is the single pivot: the loopback target for one connected host, or null — nothing
|
|
9
|
+
* else in this module knows how a tunnel was made. */
|
|
10
|
+
export function createRemoteProxy(options) {
|
|
11
|
+
const logger = options.logger ?? console;
|
|
12
|
+
const webServer = options.webServer;
|
|
13
|
+
const getOrigin = options.getOrigin;
|
|
14
|
+
const resolveHost = options.resolveHost;
|
|
15
|
+
// Annotated because the default must answer like the real gate: a kernel may provide no Connection service at all,
|
|
16
|
+
// and a missing gate admits the request.
|
|
17
|
+
const admit = typeof options.admit === 'function' ? options.admit : () => undefined;
|
|
18
|
+
const onUpstreamError = options.onUpstreamError;
|
|
19
|
+
const upstreamTimeoutMs = Number.isSafeInteger(options.upstreamTimeoutMs) && options.upstreamTimeoutMs > 0
|
|
20
|
+
? options.upstreamTimeoutMs
|
|
21
|
+
: UPSTREAM_TIMEOUT_MS;
|
|
22
|
+
const jars = createJarBook(remoteAuthority);
|
|
23
|
+
const upgrades = new Map();
|
|
24
|
+
const sockets = new Set();
|
|
25
|
+
let disposed = false;
|
|
26
|
+
function localOrigin() {
|
|
27
|
+
try {
|
|
28
|
+
const origin = getOrigin();
|
|
29
|
+
return typeof origin === 'string' && origin !== '' ? new URL(origin) : null;
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function targetOf(hostId) {
|
|
36
|
+
try {
|
|
37
|
+
const target = resolveHost(hostId);
|
|
38
|
+
return target && Number.isInteger(Number(target.localPort)) && Number(target.localPort) > 0 ? target : null;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** The two handlers see exactly these operations, never this closure. */
|
|
45
|
+
const runtime = {
|
|
46
|
+
disposed: () => disposed,
|
|
47
|
+
logger,
|
|
48
|
+
admit,
|
|
49
|
+
localOrigin,
|
|
50
|
+
targetOf,
|
|
51
|
+
jarFor: (hostId, target) => jars.jarFor(hostId, target),
|
|
52
|
+
// Report one failed upstream without letting the reporter break the proxy: it only feeds the liveness
|
|
53
|
+
// confirmation, so a throwing reporter must never fail the request.
|
|
54
|
+
reportUpstreamFailure(hostId) {
|
|
55
|
+
try {
|
|
56
|
+
onUpstreamError?.(hostId);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// swallow-ok: reporting only feeds the liveness confirmation
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
upstreamTimeoutMs,
|
|
63
|
+
};
|
|
64
|
+
const handle = createHttpHandler(runtime);
|
|
65
|
+
const handleUpgrade = createUpgradeHandler(runtime, {
|
|
66
|
+
add: (socket) => void sockets.add(socket),
|
|
67
|
+
delete: (socket) => void sockets.delete(socket),
|
|
68
|
+
});
|
|
69
|
+
/** Keep one upgrade route per configured host, called on init and on every state change: a host that disappears
|
|
70
|
+
* loses its route and its cookies. */
|
|
71
|
+
function sync(hostIds) {
|
|
72
|
+
if (disposed)
|
|
73
|
+
return;
|
|
74
|
+
const wanted = new Set((Array.isArray(hostIds) ? hostIds : []).filter((id) => HOST_ID_PATTERN.test(String(id))));
|
|
75
|
+
for (const [hostId, dispose] of upgrades) {
|
|
76
|
+
if (wanted.has(hostId))
|
|
77
|
+
continue;
|
|
78
|
+
dispose();
|
|
79
|
+
upgrades.delete(hostId);
|
|
80
|
+
jars.clear(hostId);
|
|
81
|
+
}
|
|
82
|
+
for (const hostId of wanted) {
|
|
83
|
+
if (upgrades.has(hostId))
|
|
84
|
+
continue;
|
|
85
|
+
try {
|
|
86
|
+
upgrades.set(hostId, webServer.registerUpgrade({
|
|
87
|
+
path: upgradePath(hostId),
|
|
88
|
+
handler: (req, socket, head) => handleUpgrade(hostId, req, socket, head),
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
logger.warn?.(`[dsh-remote-go] could not register the stream route for ${hostId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
prefix: REMOTE_VIEW_PREFIX,
|
|
98
|
+
// The web server matches `pathname === prefix || pathname.startsWith(prefix + '/')`, so the trailing slash must go.
|
|
99
|
+
routePath: REMOTE_VIEW_PREFIX.replace(/\/$/, ''),
|
|
100
|
+
handle,
|
|
101
|
+
handleUpgrade,
|
|
102
|
+
sync,
|
|
103
|
+
/** One host's current cookie header, for diagnostics and tests. */
|
|
104
|
+
cookies(hostId) {
|
|
105
|
+
const jar = jars.get(hostId);
|
|
106
|
+
return jar === undefined ? '' : cookieHeader(jar, '/');
|
|
107
|
+
},
|
|
108
|
+
dispose() {
|
|
109
|
+
if (disposed)
|
|
110
|
+
return;
|
|
111
|
+
disposed = true;
|
|
112
|
+
for (const dispose of upgrades.values())
|
|
113
|
+
dispose();
|
|
114
|
+
upgrades.clear();
|
|
115
|
+
jars.clear();
|
|
116
|
+
for (const socket of sockets)
|
|
117
|
+
socket.destroy();
|
|
118
|
+
sockets.clear();
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** The two ceilings one upstream connection is held to: how long the remote may take to answer, and how large a
|
|
2
|
+
* handshake response head may grow before it can no longer be a WebSocket upgrade. */
|
|
3
|
+
/** How long the remote may take to accept a connection and answer. */
|
|
4
|
+
export const UPSTREAM_TIMEOUT_MS = 30_000;
|
|
5
|
+
/** A handshake response head larger than this cannot be a WebSocket upgrade; it is dropped. */
|
|
6
|
+
export const MAX_UPSTREAM_HEAD_BYTES = 64 * 1024;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** The URL shapes of the same-origin proxy: which view path names which host, and the exact upgrade pathname one host's
|
|
2
|
+
* stream arrives on. */
|
|
3
|
+
import { REMOTE_VIEW_PREFIX } from '../constants.js';
|
|
4
|
+
/** The remote web UI's own stream route — the only upgrade path a DSH web serves. */
|
|
5
|
+
const REMOTE_STREAM_PATH = '/api/remote.mux';
|
|
6
|
+
/** One host id, as the view prefix and the run registry spell it. */
|
|
7
|
+
export const HOST_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
8
|
+
/** Split `/dsh-remote-go/remote/<hostId>/<rest>` into its host and the upstream path. Returns null for anything that is
|
|
9
|
+
* not one well-formed view path, encoded slashes included. */
|
|
10
|
+
export function parseViewPath(pathname) {
|
|
11
|
+
if (typeof pathname !== 'string' || !pathname.startsWith(REMOTE_VIEW_PREFIX))
|
|
12
|
+
return null;
|
|
13
|
+
const rest = pathname.slice(REMOTE_VIEW_PREFIX.length);
|
|
14
|
+
// The seat is always `<prefix><hostId>/`: the bare host id is not a page.
|
|
15
|
+
const slash = rest.indexOf('/');
|
|
16
|
+
if (slash === -1)
|
|
17
|
+
return null;
|
|
18
|
+
let hostId;
|
|
19
|
+
try {
|
|
20
|
+
hostId = decodeURIComponent(rest.slice(0, slash));
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
if (!HOST_ID_PATTERN.test(hostId))
|
|
26
|
+
return null;
|
|
27
|
+
return { hostId, path: rest.slice(slash) };
|
|
28
|
+
}
|
|
29
|
+
/** Exact pathname the remote's stream upgrade arrives on. */
|
|
30
|
+
export function upgradePath(hostId) {
|
|
31
|
+
return `${REMOTE_VIEW_PREFIX}${hostId}${REMOTE_STREAM_PATH}`;
|
|
32
|
+
}
|