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,107 @@
|
|
|
1
|
+
/** The `run/web.json` record: the launch marker, the tolerant parser and the atomic writer. Every field is
|
|
2
|
+
* untrusted and each consumer narrows the one it reads. */
|
|
3
|
+
import { DEFAULT_REMOTE_PROFILE } from '../constants.js';
|
|
4
|
+
import { errors } from '../errors.js';
|
|
5
|
+
import { isPid, messageOf, nowIso, shellQuote } from '../util.js';
|
|
6
|
+
import { normalizeVersion } from '../version.js';
|
|
7
|
+
export const LAUNCH_MARKER = 'browser-carrier-v1';
|
|
8
|
+
export function parseRunRegistry(text) {
|
|
9
|
+
const raw = String(text ?? '').trim();
|
|
10
|
+
if (raw === '')
|
|
11
|
+
return null;
|
|
12
|
+
try {
|
|
13
|
+
const parsed = JSON.parse(raw);
|
|
14
|
+
return isPlainObjectValue(parsed) ? parsed : null;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// swallow-ok: fall through to the field-by-field recovery below
|
|
18
|
+
}
|
|
19
|
+
const field = (name) => new RegExp(`"${name}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(raw)?.[1] ?? null;
|
|
20
|
+
const number = (name) => Number(new RegExp(`"${name}"\\s*:\\s*(\\d+)\\s*[,}]`).exec(raw)?.[1] ?? 0);
|
|
21
|
+
const pid = number('pid');
|
|
22
|
+
if (!isPid(pid))
|
|
23
|
+
return null;
|
|
24
|
+
const port = number('port');
|
|
25
|
+
return {
|
|
26
|
+
pid,
|
|
27
|
+
port: isPid(port) ? port : 0,
|
|
28
|
+
startedAt: field('startedAt'),
|
|
29
|
+
profile: field('profile'),
|
|
30
|
+
version: field('version'),
|
|
31
|
+
dshHome: field('dshHome'),
|
|
32
|
+
launch: field('launch'),
|
|
33
|
+
origin: field('origin'),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
export function isPlainObjectValue(value) {
|
|
37
|
+
return value !== null && typeof value === 'object';
|
|
38
|
+
}
|
|
39
|
+
export async function readRunRegistry(ssh, layout) {
|
|
40
|
+
try {
|
|
41
|
+
const result = await ssh.exec(`cat ${shellQuote(layout.runFile)} 2>/dev/null || true`, { timeoutMs: 10_000 });
|
|
42
|
+
if (result.code !== 0 || result.stdout.trim() === '')
|
|
43
|
+
return null;
|
|
44
|
+
return parseRunRegistry(result.stdout);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** True when one `run/web.json` record names the instance of this layout/profile at `pid`: the one ownership rule the stop and restart proof, the launch pipeline and the re-attach/adopt probe all re-check. */
|
|
51
|
+
export function registryNamesInstance(record, layout, profile, pid) {
|
|
52
|
+
if (record === null || record.dshHome !== layout.dshHome || record.profile !== profile)
|
|
53
|
+
return false;
|
|
54
|
+
return isPid(pid) && Number(record.pid) === pid;
|
|
55
|
+
}
|
|
56
|
+
export function buildRunRegistryRecord(input = {}) {
|
|
57
|
+
const pid = Number(input.pid ?? 0);
|
|
58
|
+
const port = Number(input.port ?? 0);
|
|
59
|
+
if (!isPid(pid))
|
|
60
|
+
throw errors.invalidInput('pid', { zh: 'pid 不合法。', en: 'The pid is invalid.' });
|
|
61
|
+
if (!isPid(port) || port > 65535)
|
|
62
|
+
throw errors.invalidInput('port', { zh: '端口不合法。', en: 'The port is invalid.' });
|
|
63
|
+
const dshHome = String(input.dshHome ?? '').trim();
|
|
64
|
+
if (dshHome === '') {
|
|
65
|
+
throw errors.invalidInput('dshHome', { zh: '远端 DSH_HOME 未知。', en: 'The remote DSH_HOME is unknown.' });
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
pid,
|
|
69
|
+
port,
|
|
70
|
+
startedAt: typeof input.startedAt === 'string' && input.startedAt !== '' ? input.startedAt : nowIso(),
|
|
71
|
+
profile: typeof input.profile === 'string' && input.profile !== '' ? input.profile : DEFAULT_REMOTE_PROFILE,
|
|
72
|
+
version: normalizeVersion(input.version ?? ''),
|
|
73
|
+
dshHome,
|
|
74
|
+
launch: LAUNCH_MARKER,
|
|
75
|
+
origin: input.origin === 'reattach' ? 'reattach' : 'launch',
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
export async function clearRunRegistry(ssh, layout) {
|
|
79
|
+
try {
|
|
80
|
+
const result = await ssh.exec(`rm -f ${shellQuote(layout.runFile)}`, { timeoutMs: 10_000 });
|
|
81
|
+
return { ok: result.code === 0, output: String(result.stdout ?? '').trim() };
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
// swallow-ok: returned as ok:false and logged by the caller; the next connect re-checks the
|
|
85
|
+
return { ok: false, output: messageOf(error) };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export async function writeRunRegistry(ssh, layout, record) {
|
|
89
|
+
const payload = JSON.stringify(record);
|
|
90
|
+
// Temp file + rename: a concurrent reader sees the old record or the new one, never a truncated line.
|
|
91
|
+
const script = `set -eu
|
|
92
|
+
umask 077
|
|
93
|
+
mkdir -p ${shellQuote(layout.runDir)}
|
|
94
|
+
RUN=${shellQuote(layout.runFile)}
|
|
95
|
+
TMP="$RUN.tmp.$$"
|
|
96
|
+
printf '%s\\n' ${shellQuote(payload)} > "$TMP"
|
|
97
|
+
mv -f "$TMP" "$RUN"
|
|
98
|
+
echo "REGISTRY-WRITTEN"
|
|
99
|
+
`;
|
|
100
|
+
try {
|
|
101
|
+
const result = await ssh.exec(script, { timeoutMs: 15_000, maxBytes: 8_000 });
|
|
102
|
+
return { ok: result.code === 0 && result.stdout.includes('REGISTRY-WRITTEN'), output: result.stdout.trim() };
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
return { ok: false, output: messageOf(error) };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/** Probing the remote DSH web: the `dsh web:` readiness line, pid liveness, adoption, the real version a process
|
|
2
|
+
* runs, and the re-attach probe that refuses a candidate it cannot prove. */
|
|
3
|
+
import { DEFAULT_REMOTE_PROFILE } from '../constants.js';
|
|
4
|
+
import { findForeignDshProcesses, isUiUp, remoteHttpStatus, remoteListenPorts, remotePortOwnerPid, remoteProcessIdentity, } from '../remote-proc.js';
|
|
5
|
+
import { isLoopbackHost, isPid, shellQuote } from '../util.js';
|
|
6
|
+
import { normalizeVersion } from '../version.js';
|
|
7
|
+
import { LAUNCH_MARKER, isPlainObjectValue, readRunRegistry, registryNamesInstance } from './registry.js';
|
|
8
|
+
const WEB_LINE_RE = /dsh web:\s*(https?:\/\/[^\s]+)/;
|
|
9
|
+
export function parseWebLine(text) {
|
|
10
|
+
const match = WEB_LINE_RE.exec(String(text ?? ''));
|
|
11
|
+
if (!match)
|
|
12
|
+
return null;
|
|
13
|
+
const rawUrl = match[1];
|
|
14
|
+
let url;
|
|
15
|
+
try {
|
|
16
|
+
url = new URL(rawUrl);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
const host = url.hostname.replace(/^\[|\]$/g, '');
|
|
22
|
+
const port = url.port ? Number(url.port) : url.protocol === 'https:' ? 443 : 80;
|
|
23
|
+
const token = url.searchParams.get('token') ?? '';
|
|
24
|
+
if (!isPid(port))
|
|
25
|
+
return null;
|
|
26
|
+
return { url: rawUrl, host, port, token, rawLine: match[0] };
|
|
27
|
+
}
|
|
28
|
+
export async function readWebLineFromLog(ssh, layout) {
|
|
29
|
+
try {
|
|
30
|
+
const result = await ssh.exec(`grep 'dsh web:' ${shellQuote(layout.logFile)} 2>/dev/null | tail -n 1 || true`, {
|
|
31
|
+
timeoutMs: 15_000,
|
|
32
|
+
});
|
|
33
|
+
if (result.code !== 0 || !result.stdout.trim())
|
|
34
|
+
return null;
|
|
35
|
+
return parseWebLine(result.stdout);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export async function remotePidAlive(ssh, pid) {
|
|
42
|
+
if (!isPid(pid))
|
|
43
|
+
return false;
|
|
44
|
+
try {
|
|
45
|
+
const result = await ssh.exec(`kill -0 ${pid} 2>/dev/null && echo alive || true`, { timeoutMs: 10_000 });
|
|
46
|
+
return result.stdout.includes('alive');
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export async function adoptRemoteWeb(ssh, layout, options = {}) {
|
|
53
|
+
const profile = options.profile ?? DEFAULT_REMOTE_PROFILE;
|
|
54
|
+
const registry = await readRunRegistry(ssh, layout);
|
|
55
|
+
// Instances from a launch path without the browser-carrier overlay could serve a stuck page: not adoptable.
|
|
56
|
+
if (registry?.launch !== LAUNCH_MARKER)
|
|
57
|
+
return null;
|
|
58
|
+
const pid = Number(registry?.pid ?? 0);
|
|
59
|
+
if (!registryNamesInstance(registry, layout, profile, pid))
|
|
60
|
+
return null;
|
|
61
|
+
if (!(await remotePidAlive(ssh, pid)))
|
|
62
|
+
return null;
|
|
63
|
+
const line = await readWebLineFromLog(ssh, layout);
|
|
64
|
+
if (!line || line.token === '')
|
|
65
|
+
return null;
|
|
66
|
+
// An adopted instance is reached through the loopback tunnel only, exactly like a fresh launch.
|
|
67
|
+
if (!isLoopbackHost(line.host))
|
|
68
|
+
return null;
|
|
69
|
+
if (!isUiUp(await remoteHttpStatus(ssh, line.port)))
|
|
70
|
+
return null;
|
|
71
|
+
const version = typeof registry?.version === 'string' && registry.version !== '' ? normalizeVersion(registry.version) : null;
|
|
72
|
+
return {
|
|
73
|
+
pid,
|
|
74
|
+
port: line.port,
|
|
75
|
+
token: line.token,
|
|
76
|
+
url: line.url,
|
|
77
|
+
version,
|
|
78
|
+
profile,
|
|
79
|
+
dshHome: layout.dshHome,
|
|
80
|
+
adopted: true,
|
|
81
|
+
origin: registry.origin === 'reattach' ? 'reattach' : 'launch',
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
export function commandMatchesProfile(command, profile) {
|
|
85
|
+
const wanted = String(profile ?? '');
|
|
86
|
+
if (wanted === '')
|
|
87
|
+
return false;
|
|
88
|
+
const escaped = wanted.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
89
|
+
return new RegExp(`--profile[=\\s]+${escaped}(?:\\s|$)`).test(String(command ?? ''));
|
|
90
|
+
}
|
|
91
|
+
export function versionFromCommand(command) {
|
|
92
|
+
const match = /@deepseek-ai\/dsh@([^\s'"]+)/.exec(String(command ?? ''));
|
|
93
|
+
return match ? normalizeVersion(match[1]) : null;
|
|
94
|
+
}
|
|
95
|
+
export function dshPackageDirFromCommand(command) {
|
|
96
|
+
const text = String(command ?? '');
|
|
97
|
+
const marker = '/node_modules/@deepseek-ai/dsh';
|
|
98
|
+
let at = text.indexOf(marker);
|
|
99
|
+
while (at !== -1) {
|
|
100
|
+
if (/^(?:\/lib\/bin\.js|[\s'"]|$)/.test(text.slice(at + marker.length))) {
|
|
101
|
+
let start = at;
|
|
102
|
+
while (start > 0 && !/[\s'"]/.test(text[start - 1]))
|
|
103
|
+
start -= 1;
|
|
104
|
+
const dir = text.slice(start, at + marker.length);
|
|
105
|
+
return dir.startsWith('/') && !dir.split('/').includes('..') ? dir : null;
|
|
106
|
+
}
|
|
107
|
+
at = text.indexOf(marker, at + marker.length);
|
|
108
|
+
}
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
export async function remoteDshVersion(ssh, command) {
|
|
112
|
+
const pinned = versionFromCommand(command);
|
|
113
|
+
if (pinned)
|
|
114
|
+
return pinned;
|
|
115
|
+
const dir = dshPackageDirFromCommand(command);
|
|
116
|
+
if (dir === null || typeof ssh.readRemoteFile !== 'function')
|
|
117
|
+
return null;
|
|
118
|
+
try {
|
|
119
|
+
const file = await ssh.readRemoteFile(`${dir}/package.json`, { maxBytes: 64 * 1024 });
|
|
120
|
+
const text = Buffer.isBuffer(file?.data) ? file.data.toString('utf8') : String(file?.data ?? '');
|
|
121
|
+
const parsed = JSON.parse(text);
|
|
122
|
+
const version = isPlainObjectValue(parsed) && typeof parsed.version === 'string' ? normalizeVersion(parsed.version) : '';
|
|
123
|
+
return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version) ? version : null;
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
// swallow-ok: an unreadable package.json only means the version stays unknown (never assumed)
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
export async function resolveRemoteWeb(ssh, layout, options = {}) {
|
|
131
|
+
const profile = options.profile ?? DEFAULT_REMOTE_PROFILE;
|
|
132
|
+
const registry = await readRunRegistry(ssh, layout);
|
|
133
|
+
const line = await readWebLineFromLog(ssh, layout);
|
|
134
|
+
const registryPid = Number(registry?.pid ?? 0);
|
|
135
|
+
const registryVersion = typeof registry?.version === 'string' && registry.version !== '' ? normalizeVersion(registry.version) : null;
|
|
136
|
+
const alive = registryNamesInstance(registry, layout, profile, registryPid) &&
|
|
137
|
+
registry?.launch === LAUNCH_MARKER &&
|
|
138
|
+
(await remotePidAlive(ssh, registryPid));
|
|
139
|
+
let listeners = null;
|
|
140
|
+
const listenersOf = async (pid) => {
|
|
141
|
+
if (listeners === null)
|
|
142
|
+
listeners = await remoteListenPorts(ssh, pid);
|
|
143
|
+
return listeners;
|
|
144
|
+
};
|
|
145
|
+
let tokenlessPort = 0;
|
|
146
|
+
let firstFailure = null;
|
|
147
|
+
const take = async (pid, port, source) => {
|
|
148
|
+
const identity = await remoteProcessIdentity(ssh, pid);
|
|
149
|
+
if (identity.ok !== true)
|
|
150
|
+
return { ok: false, reason: `identity-${identity.reason}` };
|
|
151
|
+
if (!commandMatchesProfile(identity.command, profile))
|
|
152
|
+
return { ok: false, reason: 'profile-mismatch' };
|
|
153
|
+
if (identity.dshHome === '' || identity.dshHome !== layout.dshHome)
|
|
154
|
+
return { ok: false, reason: 'dsh-home-mismatch' };
|
|
155
|
+
const token = line !== null && line.port === port ? line.token : '';
|
|
156
|
+
// A candidate that answers HTTP but has no token is not usable: a real DSH answers `/?token=` with 401.
|
|
157
|
+
if (token === '') {
|
|
158
|
+
tokenlessPort = port;
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
const proven = await remoteDshVersion(ssh, identity.command);
|
|
162
|
+
return {
|
|
163
|
+
ok: true,
|
|
164
|
+
pid,
|
|
165
|
+
port,
|
|
166
|
+
token,
|
|
167
|
+
url: line.url,
|
|
168
|
+
version: proven ?? (pid === registryPid ? registryVersion : null),
|
|
169
|
+
profile,
|
|
170
|
+
dshHome: identity.dshHome,
|
|
171
|
+
source,
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
const rememberFailure = (candidate) => {
|
|
175
|
+
if (candidate !== null && candidate.ok !== true && firstFailure === null)
|
|
176
|
+
firstFailure = candidate;
|
|
177
|
+
};
|
|
178
|
+
if (alive) {
|
|
179
|
+
const candidates = [...(await listenersOf(registryPid))];
|
|
180
|
+
if (isPid(Number(registry?.port ?? 0)))
|
|
181
|
+
candidates.push(Number(registry.port));
|
|
182
|
+
for (const port of [...new Set(candidates.filter((value) => isPid(value) && value <= 65535))]) {
|
|
183
|
+
if (!isUiUp(await remoteHttpStatus(ssh, port)))
|
|
184
|
+
continue;
|
|
185
|
+
const owner = await remotePortOwnerPid(ssh, port);
|
|
186
|
+
if (!isPid(owner) || owner !== registryPid)
|
|
187
|
+
continue;
|
|
188
|
+
const candidate = await take(registryPid, port, 'registry');
|
|
189
|
+
if (candidate?.ok === true)
|
|
190
|
+
return candidate;
|
|
191
|
+
rememberFailure(candidate);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (line !== null && isPid(line.port) && isUiUp(await remoteHttpStatus(ssh, line.port))) {
|
|
195
|
+
let pid = 0;
|
|
196
|
+
if (alive && (await listenersOf(registryPid)).includes(line.port))
|
|
197
|
+
pid = registryPid;
|
|
198
|
+
if (!isPid(pid))
|
|
199
|
+
pid = await remotePortOwnerPid(ssh, line.port);
|
|
200
|
+
if (isPid(pid)) {
|
|
201
|
+
const candidate = await take(pid, line.port, 'log');
|
|
202
|
+
if (candidate?.ok === true)
|
|
203
|
+
return candidate;
|
|
204
|
+
rememberFailure(candidate);
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
firstFailure = { ok: false, reason: 'pid-unknown' };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const scanned = await findForeignDshProcesses(ssh, { ignorePids: alive ? [registryPid] : [] });
|
|
211
|
+
if (scanned.ok === true) {
|
|
212
|
+
for (const process of scanned.processes) {
|
|
213
|
+
if (!commandMatchesProfile(process.command, profile))
|
|
214
|
+
continue;
|
|
215
|
+
for (const port of await remoteListenPorts(ssh, process.pid)) {
|
|
216
|
+
if (!isUiUp(await remoteHttpStatus(ssh, port)))
|
|
217
|
+
continue;
|
|
218
|
+
const identity = await remoteProcessIdentity(ssh, process.pid);
|
|
219
|
+
if (identity.ok === true && identity.dshHome === layout.dshHome)
|
|
220
|
+
return { ok: false, reason: 'no-token' };
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (firstFailure !== null)
|
|
225
|
+
return firstFailure;
|
|
226
|
+
if (tokenlessPort !== 0)
|
|
227
|
+
return { ok: false, reason: 'no-token' };
|
|
228
|
+
return { ok: false, reason: alive ? 'no-listener' : 'no-running-web' };
|
|
229
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { DEFAULT_REMOTE_PROFILE, REMOTE_START_TIMEOUT_MS } from '../constants.js';
|
|
2
|
+
import { errors } from '../errors.js';
|
|
3
|
+
import { remoteLayout } from '../layout.js';
|
|
4
|
+
import { headTail, isLoopbackHost, isPid, messageOf, shellQuote } from '../util.js';
|
|
5
|
+
import { normalizeVersion } from '../version.js';
|
|
6
|
+
import { LAUNCH_MARKER } from './registry.js';
|
|
7
|
+
import { parseWebLine, remotePidAlive } from './resolve.js';
|
|
8
|
+
import { stopRemoteWeb } from './stop.js';
|
|
9
|
+
export const BROWSER_CARRIER_PATCH_FILE = 'browser-carrier.patch.yml';
|
|
10
|
+
const BROWSER_CARRIER_PATCH = `# Written by dsh-remote-go. The remote window is a browser client, so the
|
|
11
|
+
# Remote-Event carrier (api-remotes) must stay enabled even when a profile
|
|
12
|
+
# bundle disables it for a native-UI companion.
|
|
13
|
+
- id: api-remotes
|
|
14
|
+
disabled: false`;
|
|
15
|
+
export function buildStartCommand(plan, layout, options = {}) {
|
|
16
|
+
const profile = options.profile ?? plan.profile ?? DEFAULT_REMOTE_PROFILE;
|
|
17
|
+
const patch = options.patchPath ? `--patch ${shellQuote(options.patchPath)} ` : '';
|
|
18
|
+
const args = `${patch}--profile ${shellQuote(profile)} --no-open --port 0`;
|
|
19
|
+
const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
|
|
20
|
+
return `env DSH_HOME=${shellQuote(layout.dshHome)} ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} ${args}`;
|
|
21
|
+
}
|
|
22
|
+
export function buildBrowserCarrierProbe(plan, layout, profile) {
|
|
23
|
+
const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
|
|
24
|
+
const dumpFile = shellQuote(`${layout.root}/profile-dump.yml`);
|
|
25
|
+
const patchFile = shellQuote(`${layout.root}/${BROWSER_CARRIER_PATCH_FILE}`);
|
|
26
|
+
return `set -u
|
|
27
|
+
umask 077
|
|
28
|
+
mkdir -p ${shellQuote(layout.root)}
|
|
29
|
+
DUMP=${dumpFile}
|
|
30
|
+
if ! env DSH_HOME=${shellQuote(layout.dshHome)} ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --profile ${shellQuote(profile)} --dump-config > "$DUMP" 2>/dev/null; then
|
|
31
|
+
echo "DUMP-FAILED"
|
|
32
|
+
rm -f "$DUMP"
|
|
33
|
+
exit 0
|
|
34
|
+
fi
|
|
35
|
+
if grep -A6 'id: api-remotes' "$DUMP" | grep -q 'disabled: true'; then
|
|
36
|
+
cat > ${patchFile} <<'DSH_REMOTE_GO_PATCH'
|
|
37
|
+
${BROWSER_CARRIER_PATCH}
|
|
38
|
+
DSH_REMOTE_GO_PATCH
|
|
39
|
+
echo "PATCH"
|
|
40
|
+
else
|
|
41
|
+
echo "CLEAR"
|
|
42
|
+
fi
|
|
43
|
+
rm -f "$DUMP"`;
|
|
44
|
+
}
|
|
45
|
+
export async function ensureBrowserCarrier(ssh, options) {
|
|
46
|
+
try {
|
|
47
|
+
const result = await ssh.exec(buildBrowserCarrierProbe(options.plan, options.layout, options.profile), {
|
|
48
|
+
timeoutMs: 60_000,
|
|
49
|
+
maxBytes: 64_000,
|
|
50
|
+
});
|
|
51
|
+
if (result.code === 0 && result.stdout.includes('PATCH')) {
|
|
52
|
+
options.onLine?.('browser carrier: the profile disables api-remotes; re-enabling it for this launch');
|
|
53
|
+
return { status: 'patched', patchPath: `${options.layout.root}/${BROWSER_CARRIER_PATCH_FILE}` };
|
|
54
|
+
}
|
|
55
|
+
if (result.code === 0 && result.stdout.includes('CLEAR')) {
|
|
56
|
+
options.onLine?.('browser carrier: api-remotes is enabled by the profile');
|
|
57
|
+
return { status: 'clear', patchPath: null };
|
|
58
|
+
}
|
|
59
|
+
options.onLine?.(`browser carrier: profile probe failed (${headTail(result.stdout + result.stderr, 300)})`);
|
|
60
|
+
return { status: 'unknown', patchPath: null };
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
// swallow-ok: launching without the overlay keeps the start error (missing profile, npx failure)
|
|
64
|
+
options.onLine?.(`browser carrier: probe failed (${messageOf(error)})`);
|
|
65
|
+
return { status: 'unknown', patchPath: null };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function buildStartScript(startCommand, layout, options = {}) {
|
|
69
|
+
const waitSeconds = options.waitSeconds ?? Math.ceil(REMOTE_START_TIMEOUT_MS / 1000);
|
|
70
|
+
const version = normalizeVersion(options.version ?? '');
|
|
71
|
+
const profile = options.profile ?? DEFAULT_REMOTE_PROFILE;
|
|
72
|
+
const logFile = shellQuote(layout.logFile);
|
|
73
|
+
const runFile = shellQuote(layout.runFile);
|
|
74
|
+
// `umask 077` keeps the log (which carries the launch URL with its token) private; the run registry is written to
|
|
75
|
+
// a temp file and renamed, so a reader never sees a half-written record.
|
|
76
|
+
const startedAtPlaceholder = '$(date -u +%Y-%m-%dT%H:%M:%SZ)';
|
|
77
|
+
return `set -eu
|
|
78
|
+
umask 077
|
|
79
|
+
mkdir -p ${shellQuote(layout.logsDir)} ${shellQuote(layout.runDir)} ${shellQuote(layout.stateHome)}
|
|
80
|
+
LOG=${logFile}
|
|
81
|
+
: > "$LOG"
|
|
82
|
+
chmod 600 "$LOG" 2>/dev/null || true
|
|
83
|
+
cd "$HOME"
|
|
84
|
+
setsid nohup bash -lc ${shellQuote(startCommand)} >> "$LOG" 2>&1 < /dev/null &
|
|
85
|
+
PID=$!
|
|
86
|
+
echo "PID:$PID"
|
|
87
|
+
i=0
|
|
88
|
+
while [ "$i" -lt ${waitSeconds} ]; do
|
|
89
|
+
if grep -q 'dsh web:' "$LOG" 2>/dev/null; then break; fi
|
|
90
|
+
if ! kill -0 "$PID" 2>/dev/null; then
|
|
91
|
+
echo "EXITED:$PID"
|
|
92
|
+
echo "---LOG---"
|
|
93
|
+
tail -n 60 "$LOG" 2>/dev/null || true
|
|
94
|
+
exit 3
|
|
95
|
+
fi
|
|
96
|
+
i=$((i+1))
|
|
97
|
+
sleep 1
|
|
98
|
+
done
|
|
99
|
+
LINE=$(grep -m1 'dsh web:' "$LOG" 2>/dev/null || true)
|
|
100
|
+
if [ -z "$LINE" ]; then
|
|
101
|
+
echo "TIMEOUT"
|
|
102
|
+
echo "---LOG---"
|
|
103
|
+
tail -n 60 "$LOG" 2>/dev/null || true
|
|
104
|
+
exit 4
|
|
105
|
+
fi
|
|
106
|
+
echo "LINE:$LINE"
|
|
107
|
+
PORT=$(printf '%s' "$LINE" | sed -n 's#.*127\\.0\\.0\\.1:\\([0-9][0-9]*\\)/.*#\\1#p')
|
|
108
|
+
if [ -z "$PORT" ]; then PORT=$(printf '%s' "$LINE" | sed -n 's#.*:\\([0-9][0-9]*\\)/.*#\\1#p'); fi
|
|
109
|
+
RUN=${runFile}
|
|
110
|
+
TMP="$RUN.tmp.$$"
|
|
111
|
+
printf '{"pid":%s,"port":%s,"startedAt":"%s","profile":%s,"version":%s,"dshHome":%s,"launch":"${LAUNCH_MARKER}"}\\n' "$PID" "\${PORT:-0}" "${startedAtPlaceholder}" ${shellQuote(JSON.stringify(profile))} ${shellQuote(JSON.stringify(version))} ${shellQuote(JSON.stringify(layout.dshHome))} > "$TMP"
|
|
112
|
+
mv -f "$TMP" "$RUN"
|
|
113
|
+
echo "DONE:$PID:$PORT"
|
|
114
|
+
`;
|
|
115
|
+
}
|
|
116
|
+
export function parseLaunchedPid(text) {
|
|
117
|
+
const combined = String(text ?? '');
|
|
118
|
+
const done = /DONE:(\d+):(\d+)/.exec(combined);
|
|
119
|
+
if (done)
|
|
120
|
+
return { pid: Number(done[1]), port: Number(done[2]) };
|
|
121
|
+
const started = /(?:^|\n)PID:(\d+)\s*(?:\n|$)/.exec(combined);
|
|
122
|
+
return started ? { pid: Number(started[1]), port: 0 } : { pid: 0, port: 0 };
|
|
123
|
+
}
|
|
124
|
+
export async function startRemoteWeb(ssh, options) {
|
|
125
|
+
const layout = options.layout ?? remoteLayout(options.home);
|
|
126
|
+
const profile = options.profile ?? options.plan.profile ?? DEFAULT_REMOTE_PROFILE;
|
|
127
|
+
const carrier = await ensureBrowserCarrier(ssh, { plan: options.plan, layout, profile, onLine: options.onLine });
|
|
128
|
+
const startCommand = buildStartCommand(options.plan, layout, { profile, patchPath: carrier.patchPath });
|
|
129
|
+
const script = buildStartScript(startCommand, layout, {
|
|
130
|
+
waitSeconds: Math.ceil((options.timeoutMs ?? REMOTE_START_TIMEOUT_MS) / 1000),
|
|
131
|
+
version: options.plan.start.targetVersion,
|
|
132
|
+
profile,
|
|
133
|
+
});
|
|
134
|
+
const lines = [];
|
|
135
|
+
const result = await ssh.exec(script, {
|
|
136
|
+
timeoutMs: (options.timeoutMs ?? REMOTE_START_TIMEOUT_MS) + 30_000,
|
|
137
|
+
maxBytes: 200_000,
|
|
138
|
+
onStdout: (chunk) => {
|
|
139
|
+
for (const line of chunk.split(/\r?\n/)) {
|
|
140
|
+
if (line === '')
|
|
141
|
+
continue;
|
|
142
|
+
lines.push(line);
|
|
143
|
+
options.onLine?.(line);
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
});
|
|
147
|
+
// The launch script prints its pid before it waits, so a failure can still stop what it started.
|
|
148
|
+
const combined = `${result.stdout}\n${result.stderr}`;
|
|
149
|
+
const launched = parseLaunchedPid(combined);
|
|
150
|
+
const failed = async (error) => {
|
|
151
|
+
if (isPid(launched.pid)) {
|
|
152
|
+
let alive = false;
|
|
153
|
+
try {
|
|
154
|
+
alive = await remotePidAlive(ssh, launched.pid);
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
// swallow-ok: an unreadable liveness check means "cannot prove it is ours", so no signal
|
|
158
|
+
}
|
|
159
|
+
if (alive) {
|
|
160
|
+
const stopped = await stopRemoteWeb(ssh, layout, { pid: launched.pid });
|
|
161
|
+
const outcome = stopped.ok === true ? 'it was stopped' : 'it could not be stopped';
|
|
162
|
+
options.onLine?.(`start failed after pid ${launched.pid} was launched; ${outcome}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return error;
|
|
166
|
+
};
|
|
167
|
+
if (result.code !== 0)
|
|
168
|
+
throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)));
|
|
169
|
+
const parsed = parseWebLine(combined);
|
|
170
|
+
if (!parsed)
|
|
171
|
+
throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)));
|
|
172
|
+
if (!isLoopbackHost(parsed.host)) {
|
|
173
|
+
throw await failed(errors.remoteUiUnreachable({
|
|
174
|
+
zh: `远端 DSH 宣布的地址不是回环地址(${parsed.host}),无法安全地经 SSH 隧道访问。`,
|
|
175
|
+
en: `The remote DSH advertised a non-loopback host (${parsed.host}); it cannot be reached safely through the SSH tunnel.`,
|
|
176
|
+
}));
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
pid: launched.pid,
|
|
180
|
+
port: parsed.port,
|
|
181
|
+
token: parsed.token,
|
|
182
|
+
url: parsed.url,
|
|
183
|
+
logPath: layout.logFile,
|
|
184
|
+
startedAt: new Date().toISOString(),
|
|
185
|
+
rawLine: parsed.rawLine,
|
|
186
|
+
profile,
|
|
187
|
+
dshHome: layout.dshHome,
|
|
188
|
+
browserCarrier: carrier.status,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { remotePortOwnerPid } from '../remote-proc.js';
|
|
2
|
+
import { isPid, messageOf, shellQuote } from '../util.js';
|
|
3
|
+
import { readRunRegistry } from './registry.js';
|
|
4
|
+
import { readWebLineFromLog } from './resolve.js';
|
|
5
|
+
export async function stopRemoteWeb(ssh, layout, options = {}) {
|
|
6
|
+
let pid = Number(options.pid ?? 0);
|
|
7
|
+
if (!isPid(pid))
|
|
8
|
+
pid = Number((await readRunRegistry(ssh, layout))?.pid ?? 0);
|
|
9
|
+
if (!isPid(pid)) {
|
|
10
|
+
const line = await readWebLineFromLog(ssh, layout);
|
|
11
|
+
const owner = line && isPid(line.port) ? Number(await remotePortOwnerPid(ssh, line.port)) : 0;
|
|
12
|
+
pid = isPid(owner) ? owner : 0;
|
|
13
|
+
}
|
|
14
|
+
const script = `set -u
|
|
15
|
+
umask 077
|
|
16
|
+
RUN=${shellQuote(layout.runFile)}
|
|
17
|
+
PID=${isPid(pid) ? pid : 0}
|
|
18
|
+
if [ "$PID" -eq 0 ] && [ -f "$RUN" ]; then
|
|
19
|
+
PID=$(sed -n 's/.*"pid":\\([0-9][0-9]*\\).*/\\1/p' "$RUN" | head -n 1)
|
|
20
|
+
fi
|
|
21
|
+
PID="\${PID:-0}"
|
|
22
|
+
if [ "$PID" -eq 0 ]; then
|
|
23
|
+
echo "NO-TARGET"
|
|
24
|
+
exit 5
|
|
25
|
+
fi
|
|
26
|
+
drop_own_record() {
|
|
27
|
+
if [ ! -f "$RUN" ]; then return 0; fi
|
|
28
|
+
REC_PID=$(sed -n 's/.*"pid":\\([0-9][0-9]*\\).*/\\1/p' "$RUN" 2>/dev/null | head -n 1)
|
|
29
|
+
if [ "\${REC_PID:-}" = "$PID" ]; then rm -f "$RUN"; fi
|
|
30
|
+
}
|
|
31
|
+
if ! kill -0 "$PID" 2>/dev/null; then
|
|
32
|
+
echo "GONE:$PID"
|
|
33
|
+
drop_own_record
|
|
34
|
+
exit 0
|
|
35
|
+
fi
|
|
36
|
+
kill -TERM "-$PID" 2>/dev/null || kill -TERM "$PID" 2>/dev/null || true
|
|
37
|
+
n=0
|
|
38
|
+
while [ "$n" -lt 20 ]; do
|
|
39
|
+
kill -0 "$PID" 2>/dev/null || break
|
|
40
|
+
n=$((n+1))
|
|
41
|
+
sleep 0.5
|
|
42
|
+
done
|
|
43
|
+
if kill -0 "$PID" 2>/dev/null; then
|
|
44
|
+
kill -KILL "-$PID" 2>/dev/null || kill -KILL "$PID" 2>/dev/null || true
|
|
45
|
+
n=0
|
|
46
|
+
while [ "$n" -lt 10 ]; do
|
|
47
|
+
kill -0 "$PID" 2>/dev/null || break
|
|
48
|
+
n=$((n+1))
|
|
49
|
+
sleep 0.5
|
|
50
|
+
done
|
|
51
|
+
fi
|
|
52
|
+
if kill -0 "$PID" 2>/dev/null; then
|
|
53
|
+
echo "ALIVE:$PID"
|
|
54
|
+
exit 6
|
|
55
|
+
fi
|
|
56
|
+
drop_own_record
|
|
57
|
+
echo "STOPPED:$PID"
|
|
58
|
+
`;
|
|
59
|
+
try {
|
|
60
|
+
const result = await ssh.exec(script, { timeoutMs: 40_000 });
|
|
61
|
+
const output = result.stdout.trim();
|
|
62
|
+
if (output.includes('NO-TARGET'))
|
|
63
|
+
return { ok: false, reason: 'no-target', output };
|
|
64
|
+
if (output.includes('ALIVE:'))
|
|
65
|
+
return { ok: false, reason: 'alive', output };
|
|
66
|
+
if (result.code !== 0)
|
|
67
|
+
return { ok: false, reason: 'not-confirmed', output };
|
|
68
|
+
return { ok: true, output };
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
// swallow-ok: a throw here is a transport failure, reported as an unconfirmed stop so the caller
|
|
72
|
+
return { ok: false, reason: 'error', output: messageOf(error) };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** The browser-trust fence shared by the local HTTP API and the same-origin remote proxy: did this request arrive from
|
|
2
|
+
* the origin it names? Two confused-deputy paths reach a loopback web server — DNS rebinding and a cross-site page —
|
|
3
|
+
* and a browser labels neither reliably, so `Host` (the one header rebinding cannot forge) is checked on every request,
|
|
4
|
+
* and `Origin`/`sec-fetch-site` must agree when attached. */
|
|
5
|
+
const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
|
|
6
|
+
/** The port a URL actually names, counting an omitted default port. */
|
|
7
|
+
function effectivePort(url) {
|
|
8
|
+
if (url.port !== '')
|
|
9
|
+
return url.port;
|
|
10
|
+
return url.protocol === 'https:' ? '443' : '80';
|
|
11
|
+
}
|
|
12
|
+
// Hostname/port match for a `Host` header (no scheme); loopback spellings are interchangeable
|
|
13
|
+
// because a browser may dial either one.
|
|
14
|
+
export function sameServerHost(value, origin) {
|
|
15
|
+
if (typeof value !== 'string' || value === '')
|
|
16
|
+
return false;
|
|
17
|
+
let candidate;
|
|
18
|
+
try {
|
|
19
|
+
candidate = new URL(`${origin.protocol}//${value}`);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
// WHATWG parsing rewrites anything that is not a bare authority: `user@host` drops its userinfo, a backslash becomes
|
|
25
|
+
// a path separator, `#`/`?` start the fragment/query, a trailing dot and a zero-padded port are normalized away. A
|
|
26
|
+
// browser fills `Host` from the serialized URL, so a rewritten value is not an authority this server answers to —
|
|
27
|
+
// comparing the rewritten hostname would let `attacker.example@127.0.0.1:port` pass as loopback.
|
|
28
|
+
if (candidate.host !== value.toLowerCase())
|
|
29
|
+
return false;
|
|
30
|
+
if (effectivePort(candidate) !== effectivePort(origin))
|
|
31
|
+
return false;
|
|
32
|
+
if (candidate.hostname === origin.hostname)
|
|
33
|
+
return true;
|
|
34
|
+
return LOOPBACK_HOSTNAMES.has(origin.hostname) && LOOPBACK_HOSTNAMES.has(candidate.hostname);
|
|
35
|
+
}
|
|
36
|
+
// Full same-origin match for an `Origin` header (scheme included). The authority is compared verbatim
|
|
37
|
+
// as well as through `sameServerHost`, for the rewrite reason above: otherwise
|
|
38
|
+
// `http://attacker.example@127.0.0.1:port` would pass as loopback.
|
|
39
|
+
export function sameServerOrigin(value, origin) {
|
|
40
|
+
if (typeof value !== 'string' || value === '')
|
|
41
|
+
return false;
|
|
42
|
+
// One trailing slash is tolerated (`Origin: http://host/` is not what a browser sends, but a
|
|
43
|
+
// hand-written caller may); no regex on this string, it is attacker-controlled.
|
|
44
|
+
const text = value.endsWith('/') ? value.slice(0, -1) : value;
|
|
45
|
+
let candidate;
|
|
46
|
+
try {
|
|
47
|
+
candidate = new URL(text);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
// Drop the scheme without a regex: `scheme://rest` is the only shape left after URL parsing.
|
|
53
|
+
const schemeEnd = text.indexOf('://');
|
|
54
|
+
const authority = schemeEnd === -1 ? '' : text.slice(schemeEnd + 3);
|
|
55
|
+
if (authority.toLowerCase() !== candidate.host)
|
|
56
|
+
return false;
|
|
57
|
+
return candidate.protocol === origin.protocol && sameServerHost(candidate.host, origin);
|
|
58
|
+
}
|
|
59
|
+
// The fence applied to a browser navigation and its subresources: the request must name this server,
|
|
60
|
+
// and any browser-announced relationship must be same-origin.
|
|
61
|
+
export function trustedRequest(req, origin) {
|
|
62
|
+
if (!sameServerHost(req.headers.host, origin))
|
|
63
|
+
return false;
|
|
64
|
+
const originHeader = req.headers.origin;
|
|
65
|
+
if (typeof originHeader === 'string' && originHeader !== '' && !sameServerOrigin(originHeader, origin))
|
|
66
|
+
return false;
|
|
67
|
+
if (req.headers['sec-fetch-site'] === 'cross-site')
|
|
68
|
+
return false;
|
|
69
|
+
return true;
|
|
70
|
+
}
|