dsh-remote-go 0.2.0 → 0.3.0
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} +7710 -8182
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/{src → dist/src}/constants.js +30 -56
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -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/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,123 @@
|
|
|
1
|
+
/** Validation and naming for absolute remote POSIX paths. */
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { errors } from './errors.js';
|
|
4
|
+
/** Longest accepted path, matching the remote contract of ordinary POSIX tools. */
|
|
5
|
+
const MAX_PATH_CHARS = 4096;
|
|
6
|
+
/**
|
|
7
|
+
* Validate and normalize a remote file path.
|
|
8
|
+
* The input comes from a client request, so anything that is not a usable absolute POSIX
|
|
9
|
+
* path is refused with a coded error instead of reaching a remote command.
|
|
10
|
+
*/
|
|
11
|
+
export function normalizeRemoteFilePath(value) {
|
|
12
|
+
if (typeof value !== 'string') {
|
|
13
|
+
throw errors.invalidInput('path', {
|
|
14
|
+
zh: '远端文件路径必须是字符串。',
|
|
15
|
+
en: 'The remote file path must be a string.',
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
const text = value;
|
|
19
|
+
if (text === '') {
|
|
20
|
+
throw errors.invalidInput('path', {
|
|
21
|
+
zh: '远端文件路径不能为空。',
|
|
22
|
+
en: 'The remote file path must not be empty.',
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
if (text.length > MAX_PATH_CHARS) {
|
|
26
|
+
throw errors.invalidInput('path', {
|
|
27
|
+
zh: '远端文件路径过长。',
|
|
28
|
+
en: 'The remote file path is too long.',
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
if (text.includes('\0') || text.includes('\r') || text.includes('\n')) {
|
|
32
|
+
throw errors.invalidInput('path', {
|
|
33
|
+
zh: '远端文件路径包含不可用的控制字符。',
|
|
34
|
+
en: 'The remote file path contains unsupported control characters.',
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
if (!text.startsWith('/')) {
|
|
38
|
+
throw errors.invalidInput('path', {
|
|
39
|
+
zh: '远端文件路径必须是绝对路径。',
|
|
40
|
+
en: 'The remote file path must be absolute.',
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
const normalized = path.posix.normalize(text);
|
|
44
|
+
if (!normalized.startsWith('/')) {
|
|
45
|
+
throw errors.invalidInput('path', {
|
|
46
|
+
zh: '远端文件路径必须是绝对路径。',
|
|
47
|
+
en: 'The remote file path must be absolute.',
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
return normalized;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The suggested download name for a remote path: the last path segment, or a safe generic name.
|
|
54
|
+
*/
|
|
55
|
+
export function remoteFileName(remotePath) {
|
|
56
|
+
const name = path.posix.basename(remotePath);
|
|
57
|
+
return name === '' || name === '/' || name === '.' || name === '..' ? 'download' : name;
|
|
58
|
+
}
|
|
59
|
+
/** One local filename segment; Windows-safe so the same code works on every Desktop. */
|
|
60
|
+
export function safeLocalSegment(value) {
|
|
61
|
+
let text = String(value ?? '')
|
|
62
|
+
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_')
|
|
63
|
+
.replace(/[. ]+$/, '');
|
|
64
|
+
if (text === '' || text === '.' || text === '..')
|
|
65
|
+
text = '_';
|
|
66
|
+
if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(text))
|
|
67
|
+
text = '_' + text;
|
|
68
|
+
return text;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Windows treats these names as its own metadata or as shell entries: writing them into
|
|
72
|
+
* a download either corrupts a folder view (`desktop.ini`, `thumbs.db`) or leaves a file
|
|
73
|
+
* that a double click executes instead of showing (`.lnk`, `.url`). A remote host never
|
|
74
|
+
* gets to plant one in a local download.
|
|
75
|
+
*/
|
|
76
|
+
const IGNORED_LOCAL_NAMES = new Set(['desktop.ini', 'thumbs.db', 'ehthumbs.db', '.ds_store']);
|
|
77
|
+
const IGNORED_LOCAL_SUFFIXES = ['.lnk', '.url'];
|
|
78
|
+
/**
|
|
79
|
+
* Whether a remote name must be left out of a local folder download.
|
|
80
|
+
*/
|
|
81
|
+
export function isIgnoredLocalName(value) {
|
|
82
|
+
const name = String(value ?? '')
|
|
83
|
+
.trim()
|
|
84
|
+
.toLowerCase();
|
|
85
|
+
if (name === '')
|
|
86
|
+
return false;
|
|
87
|
+
if (IGNORED_LOCAL_NAMES.has(name))
|
|
88
|
+
return true;
|
|
89
|
+
return IGNORED_LOCAL_SUFFIXES.some((suffix) => name.endsWith(suffix));
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Pick a local path that no earlier member of the same download already claimed.
|
|
93
|
+
*
|
|
94
|
+
* A case-insensitive filesystem (the Windows/macOS defaults) maps `Report.md` and
|
|
95
|
+
* `report.md` to one file: keeping both names would silently drop one of the two remote
|
|
96
|
+
* files. The later one is renamed `report (2).md` instead, so the file count on disk
|
|
97
|
+
* matches the inventory.
|
|
98
|
+
*/
|
|
99
|
+
export function uniqueLocalPath(desired, taken, options = {}) {
|
|
100
|
+
const key = (value) => localPathKey(value, options);
|
|
101
|
+
if (!taken.has(key(desired)))
|
|
102
|
+
return desired;
|
|
103
|
+
const directory = path.dirname(desired);
|
|
104
|
+
const extension = path.extname(desired);
|
|
105
|
+
const base = path.basename(desired, extension);
|
|
106
|
+
for (let index = 2; index < 1000; index += 1) {
|
|
107
|
+
const candidate = path.join(directory, `${base} (${index})${extension}`);
|
|
108
|
+
if (!taken.has(key(candidate)))
|
|
109
|
+
return candidate;
|
|
110
|
+
}
|
|
111
|
+
throw errors.remoteFileUnavailable({
|
|
112
|
+
zh: '远端有太多文件映射到同一个本地文件名,无法安全保存。',
|
|
113
|
+
en: 'Too many remote files map to the same local file name to save them safely.',
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The collision key of a local path: separator-normalized, and lowercased when the local
|
|
118
|
+
* filesystem ignores case.
|
|
119
|
+
*/
|
|
120
|
+
export function localPathKey(value, options = {}) {
|
|
121
|
+
const text = String(value ?? '').replace(/\\/g, '/');
|
|
122
|
+
return options.caseInsensitive === true ? text.toLowerCase() : text;
|
|
123
|
+
}
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote process and reachability primitives: find, stop and probe DSH processes on the remote, plus the one HTTP round-trip that proves the remote UI answers.
|
|
3
|
+
*/
|
|
4
|
+
import http from 'node:http';
|
|
5
|
+
import { TUNNEL_PROBE_TIMEOUT_MS } from './constants.js';
|
|
6
|
+
import { isPid, messageOf } from './util.js';
|
|
7
|
+
/** A listener answering 200, 302 or 401 is up: 401 without the launch cookie still proves it serves. */
|
|
8
|
+
export function isUiUp(status) {
|
|
9
|
+
return status === 200 || status === 302 || status === 401;
|
|
10
|
+
}
|
|
11
|
+
export function buildForeignDshCommand(ignorePids = []) {
|
|
12
|
+
const ignore = (Array.isArray(ignorePids) ? ignorePids : [])
|
|
13
|
+
.map((pid) => Number(pid))
|
|
14
|
+
.filter((pid) => isPid(pid))
|
|
15
|
+
.join(' ');
|
|
16
|
+
return `set -u
|
|
17
|
+
IGNORE=" ${ignore} "
|
|
18
|
+
PS_OUT=$(ps -eww -o pid=,comm=,args= 2>/dev/null || ps -eo pid=,comm=,args= 2>/dev/null || true)
|
|
19
|
+
printf '%s\\n' "$PS_OUT" | while IFS= read -r LINE; do
|
|
20
|
+
[ -z "$LINE" ] && continue
|
|
21
|
+
set -- $LINE
|
|
22
|
+
PID=$1
|
|
23
|
+
COMM=$2
|
|
24
|
+
shift 2
|
|
25
|
+
ARGS="$*"
|
|
26
|
+
[ -z "$PID" ] && continue
|
|
27
|
+
case "$IGNORE" in *" $PID "*) continue ;; esac
|
|
28
|
+
case "$COMM" in node|dsh|npm|npx) ;; *) continue ;; esac
|
|
29
|
+
case "$ARGS" in
|
|
30
|
+
*"@deepseek-ai/dsh"*|*"/bin/dsh "*|*" dsh "*) ;;
|
|
31
|
+
*) continue ;;
|
|
32
|
+
esac
|
|
33
|
+
case "$ARGS" in
|
|
34
|
+
*"ps -eww"*|*"PS_OUT"*|*"IGNORE"*) continue ;;
|
|
35
|
+
esac
|
|
36
|
+
ENV_HOME=$(tr '\\0' '\\n' < "/proc/$PID/environ" 2>/dev/null | sed -n 's/^DSH_HOME=//p' | tail -n 1)
|
|
37
|
+
if [ -n "\${ENV_HOME:-}" ] && [ "$ENV_HOME" != "$HOME/.dsh" ]; then continue; fi
|
|
38
|
+
printf '%s\\t%s\\n' "$PID" "$ARGS"
|
|
39
|
+
done`;
|
|
40
|
+
}
|
|
41
|
+
export function parseForeignDshOutput(stdout) {
|
|
42
|
+
const processes = [];
|
|
43
|
+
for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
|
|
44
|
+
const tab = rawLine.indexOf('\t');
|
|
45
|
+
if (tab <= 0)
|
|
46
|
+
continue;
|
|
47
|
+
const pid = Number(rawLine.slice(0, tab).trim());
|
|
48
|
+
const command = rawLine.slice(tab + 1).trim();
|
|
49
|
+
if (!isPid(pid) || command === '')
|
|
50
|
+
continue;
|
|
51
|
+
processes.push({ pid, command });
|
|
52
|
+
}
|
|
53
|
+
return processes;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Find DSH processes on the remote that this plugin did not start.
|
|
57
|
+
*
|
|
58
|
+
* Never throws: a failed scan is reported as `{ ok: false }`, and the caller
|
|
59
|
+
* proceeds without a conflict prompt (a broken scan must not block connecting).
|
|
60
|
+
*/
|
|
61
|
+
export async function findForeignDshProcesses(ssh, options = {}) {
|
|
62
|
+
try {
|
|
63
|
+
const result = await ssh.exec(buildForeignDshCommand(options.ignorePids ?? []), {
|
|
64
|
+
timeoutMs: options.timeoutMs ?? 20_000,
|
|
65
|
+
maxBytes: 200_000,
|
|
66
|
+
});
|
|
67
|
+
if (result.code !== 0) {
|
|
68
|
+
return { ok: false, processes: [], reason: 'exec-failed', technical: String(result.stderr ?? '').slice(0, 500) };
|
|
69
|
+
}
|
|
70
|
+
return { ok: true, processes: parseForeignDshOutput(result.stdout) };
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
// swallow-ok: a scan failure is surfaced as ok:false and the caller proceeds without a prompt
|
|
74
|
+
return {
|
|
75
|
+
ok: false,
|
|
76
|
+
processes: [],
|
|
77
|
+
reason: 'exec-failed',
|
|
78
|
+
technical: messageOf(error),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export async function stopForeignDshProcesses(ssh, processes, options = {}) {
|
|
83
|
+
const pids = [
|
|
84
|
+
...new Set((Array.isArray(processes) ? processes : []).map((process) => Number(process?.pid)).filter((pid) => isPid(pid))),
|
|
85
|
+
];
|
|
86
|
+
if (pids.length === 0)
|
|
87
|
+
return { ok: true, alive: [], output: '' };
|
|
88
|
+
const script = `set -u
|
|
89
|
+
PIDS="${pids.join(' ')}"
|
|
90
|
+
for PID in $PIDS; do kill -TERM "$PID" 2>/dev/null || true; done
|
|
91
|
+
i=0
|
|
92
|
+
while [ "$i" -lt 20 ]; do
|
|
93
|
+
ALIVE=0
|
|
94
|
+
for PID in $PIDS; do
|
|
95
|
+
if kill -0 "$PID" 2>/dev/null; then ALIVE=1; fi
|
|
96
|
+
done
|
|
97
|
+
if [ "$ALIVE" -eq 0 ]; then break; fi
|
|
98
|
+
i=$((i+1))
|
|
99
|
+
sleep 0.5
|
|
100
|
+
done
|
|
101
|
+
for PID in $PIDS; do
|
|
102
|
+
if kill -0 "$PID" 2>/dev/null; then kill -KILL "$PID" 2>/dev/null || true; fi
|
|
103
|
+
done
|
|
104
|
+
sleep 0.2
|
|
105
|
+
for PID in $PIDS; do
|
|
106
|
+
if kill -0 "$PID" 2>/dev/null; then echo "ALIVE:$PID"; fi
|
|
107
|
+
done
|
|
108
|
+
echo "STOPPED"
|
|
109
|
+
`;
|
|
110
|
+
try {
|
|
111
|
+
const result = await ssh.exec(script, { timeoutMs: options.timeoutMs ?? 30_000 });
|
|
112
|
+
const output = String(result.stdout ?? '');
|
|
113
|
+
const alive = [...output.matchAll(/ALIVE:(\d+)/g)].map((match) => Number(match[1]));
|
|
114
|
+
return { ok: result.code === 0 && alive.length === 0, alive, output };
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
// swallow-ok: a stop failure is returned to the caller with the original message
|
|
118
|
+
return { ok: false, alive: pids, output: messageOf(error) };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* TCP ports a pid is listening on, read from its own `/proc` network tables and
|
|
123
|
+
* matched against the socket inodes it holds. Used after a remote restart: the
|
|
124
|
+
* process may be the same pid with a new random port, or a new pid entirely.
|
|
125
|
+
* @param ssh - SSH transport.
|
|
126
|
+
* @param pid - remote process id.
|
|
127
|
+
* @returns listening ports, ascending and unique.
|
|
128
|
+
*/
|
|
129
|
+
export async function remoteListenPorts(ssh, pid) {
|
|
130
|
+
if (!isPid(pid))
|
|
131
|
+
return [];
|
|
132
|
+
const script = `set -u
|
|
133
|
+
PID=${pid}
|
|
134
|
+
[ -d "/proc/$PID" ] || exit 0
|
|
135
|
+
ls -l "/proc/$PID/fd" 2>/dev/null | sed -n 's/.*socket:\\[\\([0-9][0-9]*\\)\\].*/INODE:\\1/p' | sort -u
|
|
136
|
+
for NET in "/proc/$PID/net/tcp" "/proc/$PID/net/tcp6"; do
|
|
137
|
+
[ -r "$NET" ] || continue
|
|
138
|
+
awk 'NR > 1 && $4 == "0A" { print "LISTEN:" $2 ":" $10 }' "$NET" 2>/dev/null
|
|
139
|
+
done
|
|
140
|
+
`;
|
|
141
|
+
try {
|
|
142
|
+
const result = await ssh.exec(script, { timeoutMs: 15_000 });
|
|
143
|
+
return parseListenPorts(result.stdout);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
// swallow-ok: an unreadable /proc directory yields no candidate ports
|
|
147
|
+
return [];
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** Decode the `INODE:` / `LISTEN:<addr-hex>:<port-hex>:<inode>` lines of {@link remoteListenPorts}. */
|
|
151
|
+
export function parseListenPorts(stdout) {
|
|
152
|
+
const inodes = new Set();
|
|
153
|
+
const ports = [];
|
|
154
|
+
for (const line of String(stdout ?? '').split(/\r?\n/)) {
|
|
155
|
+
const inode = /^INODE:(\d+)$/.exec(line);
|
|
156
|
+
if (inode) {
|
|
157
|
+
inodes.add(inode[1]);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
const listen = /^LISTEN:[0-9A-Fa-f]+:([0-9A-Fa-f]{1,4}):(\d+)$/.exec(line);
|
|
161
|
+
if (!listen)
|
|
162
|
+
continue;
|
|
163
|
+
const port = Number.parseInt(listen[1], 16);
|
|
164
|
+
if (isPid(port) && port <= 65535)
|
|
165
|
+
ports.push({ port, inode: listen[2] });
|
|
166
|
+
}
|
|
167
|
+
return [...new Set(ports.filter((entry) => inodes.has(entry.inode)).map((entry) => entry.port))].sort((left, right) => left - right);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* The pid behind one listening loopback port, found by matching the port's socket
|
|
171
|
+
* inode against every `/proc/<pid>/fd`. Needed when the remote restarted into a new
|
|
172
|
+
* pid that the run registry does not know yet.
|
|
173
|
+
* @param ssh - SSH transport.
|
|
174
|
+
* @param port - TCP port on the remote's loopback.
|
|
175
|
+
* @returns the owning pid, or null when it cannot be read.
|
|
176
|
+
*/
|
|
177
|
+
export async function remotePortOwnerPid(ssh, port) {
|
|
178
|
+
if (!isPid(port) || port > 65535)
|
|
179
|
+
return null;
|
|
180
|
+
const script = `set -u
|
|
181
|
+
PORT_HEX=$(printf '%04X' ${port})
|
|
182
|
+
INODE=$(awk -v p=":$PORT_HEX" '$2 ~ p"$" && $4 == "0A" { print $10; exit }' /proc/net/tcp 2>/dev/null)
|
|
183
|
+
[ -n "\${INODE:-}" ] || exit 0
|
|
184
|
+
for D in /proc/[0-9]*; do
|
|
185
|
+
if ls -l "$D/fd" 2>/dev/null | grep -q "socket:\\[\${INODE}\\]"; then
|
|
186
|
+
echo "PID:\${D#/proc/}"
|
|
187
|
+
exit 0
|
|
188
|
+
fi
|
|
189
|
+
done
|
|
190
|
+
`;
|
|
191
|
+
try {
|
|
192
|
+
const result = await ssh.exec(script, { timeoutMs: 20_000 });
|
|
193
|
+
const match = /^PID:(\d+)$/m.exec(String(result.stdout ?? ''));
|
|
194
|
+
const pid = match ? Number(match[1]) : 0;
|
|
195
|
+
return isPid(pid) ? pid : null;
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
// swallow-ok: an unreadable /proc scan means the pid is unknown, the caller falls back
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* The identity of one remote process, read from `/proc` before the plugin ever signals it.
|
|
204
|
+
* The kernel start time is stable across `exec` (so an in-place DSH restart keeps it) and
|
|
205
|
+
* changes when a pid is reused by another process - which is exactly what a kill decision
|
|
206
|
+
* must rule out. The command line and `DSH_HOME` prove the process is the DSH the plugin
|
|
207
|
+
* thinks it is.
|
|
208
|
+
*
|
|
209
|
+
* @param ssh - SSH transport.
|
|
210
|
+
* @param pid - remote process id.
|
|
211
|
+
*/
|
|
212
|
+
export async function remoteProcessIdentity(ssh, pid) {
|
|
213
|
+
if (!isPid(pid))
|
|
214
|
+
return { ok: false, reason: 'invalid-pid' };
|
|
215
|
+
const script = `set -u
|
|
216
|
+
PID=${pid}
|
|
217
|
+
[ -d "/proc/$PID" ] || { echo "MISSING"; exit 0; }
|
|
218
|
+
RAW=$(cat "/proc/$PID/stat" 2>/dev/null || true)
|
|
219
|
+
[ -n "$RAW" ] || { echo "NO-STAT"; exit 0; }
|
|
220
|
+
REST=$(printf '%s' "$RAW" | sed 's/^.*) //')
|
|
221
|
+
set -- $REST
|
|
222
|
+
printf 'START:%s\\n' "\${20}"
|
|
223
|
+
CMD=$(tr '\\0' ' ' < "/proc/$PID/cmdline" 2>/dev/null || true)
|
|
224
|
+
printf 'CMD:%s\\n' "$CMD"
|
|
225
|
+
HOME_LINE=$(tr '\\0' '\\n' < "/proc/$PID/environ" 2>/dev/null | sed -n 's/^DSH_HOME=//p' | tail -n 1)
|
|
226
|
+
printf 'DSH_HOME:%s\\n' "\${HOME_LINE:-}"
|
|
227
|
+
`;
|
|
228
|
+
try {
|
|
229
|
+
const result = await ssh.exec(script, { timeoutMs: 10_000, maxBytes: 32_000 });
|
|
230
|
+
return parseProcessIdentity(result.stdout);
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
// swallow-ok: an unreadable /proc means the pid cannot be proven, and callers fail closed
|
|
234
|
+
return { ok: false, reason: 'unreadable' };
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
/** Decode the `START:` / `CMD:` / `DSH_HOME:` lines of {@link remoteProcessIdentity}. */
|
|
238
|
+
export function parseProcessIdentity(stdout) {
|
|
239
|
+
const text = String(stdout ?? '');
|
|
240
|
+
// The markers below are matched anywhere in the output, deliberately: a command line that
|
|
241
|
+
// happens to contain MISSING/NO-STAT must not be mistaken for a readable identity (fail closed).
|
|
242
|
+
if (text.includes('MISSING'))
|
|
243
|
+
return { ok: false, reason: 'missing' };
|
|
244
|
+
if (text.includes('NO-STAT'))
|
|
245
|
+
return { ok: false, reason: 'unreadable' };
|
|
246
|
+
const start = /^START:(\d+)$/m.exec(text);
|
|
247
|
+
const command = /^CMD:(.*)$/m.exec(text);
|
|
248
|
+
if (!start || !command)
|
|
249
|
+
return { ok: false, reason: 'unreadable' };
|
|
250
|
+
const home = /^DSH_HOME:(.*)$/m.exec(text);
|
|
251
|
+
return {
|
|
252
|
+
ok: true,
|
|
253
|
+
startTime: start[1],
|
|
254
|
+
command: command[1].trim(),
|
|
255
|
+
dshHome: home === null ? '' : home[1].trim(),
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
export async function remoteHttpStatus(ssh, port) {
|
|
259
|
+
if (!isPid(port))
|
|
260
|
+
return null;
|
|
261
|
+
const script = `URL="http://127.0.0.1:${port}/"
|
|
262
|
+
if command -v curl >/dev/null 2>&1; then
|
|
263
|
+
curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$URL" 2>/dev/null || true
|
|
264
|
+
elif command -v wget >/dev/null 2>&1; then
|
|
265
|
+
wget -S -O /dev/null --max-time 5 "$URL" 2>&1 | sed -n 's/.*HTTP\\/[0-9.]* \\([0-9][0-9][0-9]\\).*/\\1/p' | head -n 1
|
|
266
|
+
fi
|
|
267
|
+
`;
|
|
268
|
+
try {
|
|
269
|
+
const result = await ssh.exec(script, { timeoutMs: 15_000 });
|
|
270
|
+
const code = Number(String(result.stdout ?? '').trim());
|
|
271
|
+
return Number.isInteger(code) && code > 0 ? code : null;
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
export async function waitForRemoteUi(ssh, port, options = {}) {
|
|
278
|
+
const attempts = options.attempts ?? 20;
|
|
279
|
+
const intervalMs = options.intervalMs ?? 500;
|
|
280
|
+
let last = null;
|
|
281
|
+
for (let i = 0; i < attempts; i += 1) {
|
|
282
|
+
last = await remoteHttpStatus(ssh, port);
|
|
283
|
+
if (isUiUp(last))
|
|
284
|
+
return { ok: true, status: last };
|
|
285
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
286
|
+
}
|
|
287
|
+
return { ok: false, status: last };
|
|
288
|
+
}
|
|
289
|
+
export async function exchangeTokenOverTunnel(localPort, token, options = {}) {
|
|
290
|
+
const timeoutMs = options.timeoutMs ?? TUNNEL_PROBE_TIMEOUT_MS;
|
|
291
|
+
const basePath = options.path ?? '/';
|
|
292
|
+
const tokenPath = `/?token=${encodeURIComponent(token)}`;
|
|
293
|
+
const first = await httpRequest({
|
|
294
|
+
port: localPort,
|
|
295
|
+
path: basePath === '/' ? tokenPath : `${basePath}?token=${encodeURIComponent(token)}`,
|
|
296
|
+
timeoutMs,
|
|
297
|
+
});
|
|
298
|
+
const setCookies = first.headers['set-cookie'] ?? [];
|
|
299
|
+
const cookieHeader = setCookies.map((cookie) => String(cookie).split(';')[0]).join('; ');
|
|
300
|
+
const location = first.headers.location ?? null;
|
|
301
|
+
const second = await httpRequest({
|
|
302
|
+
port: localPort,
|
|
303
|
+
path: location && location.startsWith('/') ? location : '/',
|
|
304
|
+
timeoutMs,
|
|
305
|
+
headers: cookieHeader ? { cookie: cookieHeader } : {},
|
|
306
|
+
});
|
|
307
|
+
const titleMatch = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(second.body);
|
|
308
|
+
return {
|
|
309
|
+
ok: second.status === 200 && second.body.length > 0,
|
|
310
|
+
firstStatus: first.status,
|
|
311
|
+
status: second.status,
|
|
312
|
+
title: titleMatch ? titleMatch[1].trim().slice(0, 200) : null,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
function httpRequest(options) {
|
|
316
|
+
return new Promise((resolve, reject) => {
|
|
317
|
+
const request = http.request({
|
|
318
|
+
host: '127.0.0.1',
|
|
319
|
+
port: options.port,
|
|
320
|
+
path: options.path,
|
|
321
|
+
method: 'GET',
|
|
322
|
+
headers: { 'user-agent': 'dsh-remote-go', ...options.headers },
|
|
323
|
+
timeout: options.timeoutMs,
|
|
324
|
+
}, (response) => {
|
|
325
|
+
const chunks = [];
|
|
326
|
+
response.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
|
|
327
|
+
response.on('end', () => {
|
|
328
|
+
resolve({
|
|
329
|
+
status: response.statusCode ?? 0,
|
|
330
|
+
headers: response.headers,
|
|
331
|
+
body: Buffer.concat(chunks).toString('utf8'),
|
|
332
|
+
});
|
|
333
|
+
});
|
|
334
|
+
});
|
|
335
|
+
request.on('timeout', () => request.destroy(new Error('local tunnel probe timed out')));
|
|
336
|
+
request.on('error', reject);
|
|
337
|
+
request.end();
|
|
338
|
+
});
|
|
339
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `run/web.json` record: the marker a launch writes, the tolerant parser and the atomic
|
|
3
|
+
* writer. Every field is untrusted — the parser hands back `unknown` values and each consumer
|
|
4
|
+
* narrows the one it reads — and the write goes through a temp file + rename, so a concurrent
|
|
5
|
+
* reader never sees a half-written record (M4). Reading and dropping the record live here too:
|
|
6
|
+
* the file is one fact, so it has one owner.
|
|
7
|
+
*/
|
|
8
|
+
import { DEFAULT_REMOTE_PROFILE } from '../constants.js';
|
|
9
|
+
import { errors } from '../errors.js';
|
|
10
|
+
import { isPid, messageOf, nowIso, shellQuote } from '../util.js';
|
|
11
|
+
import { normalizeVersion } from '../version.js';
|
|
12
|
+
/**
|
|
13
|
+
* Version tag written into the run registry. Bumping it invalidates adoption of
|
|
14
|
+
* instances started by an older launch path (they may lack the browser-carrier
|
|
15
|
+
* overlay, which would leave the in-window page stuck at "failed to load plugins").
|
|
16
|
+
*/
|
|
17
|
+
export const LAUNCH_MARKER = 'browser-carrier-v1';
|
|
18
|
+
/**
|
|
19
|
+
* Read `run/web.json`. The record is written atomically (temp + rename), but a record from an
|
|
20
|
+
* older launch path or a truncated file still names the process: parse what is there instead
|
|
21
|
+
* of reporting "no record" and losing the only pid (M4).
|
|
22
|
+
* @param text - the raw file content.
|
|
23
|
+
* @returns the parsed record, or null when it names no pid.
|
|
24
|
+
*/
|
|
25
|
+
export function parseRunRegistry(text) {
|
|
26
|
+
const raw = String(text ?? '').trim();
|
|
27
|
+
if (raw === '')
|
|
28
|
+
return null;
|
|
29
|
+
try {
|
|
30
|
+
const parsed = JSON.parse(raw);
|
|
31
|
+
// `isPlainObject` is the guard that makes the untrusted document a record of unknowns;
|
|
32
|
+
// every consumer still narrows the individual field it reads.
|
|
33
|
+
return isPlainObjectValue(parsed) ? parsed : null;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
// swallow-ok: fall through to the field-by-field recovery below
|
|
37
|
+
}
|
|
38
|
+
const field = (name) => new RegExp(`"${name}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(raw)?.[1] ?? null;
|
|
39
|
+
// A number must be terminated by the next field or the record end: `{"pid":42` is a
|
|
40
|
+
// truncated record, not a pid of 42 (review: no prefix matches).
|
|
41
|
+
const number = (name) => Number(new RegExp(`"${name}"\\s*:\\s*(\\d+)\\s*[,}]`).exec(raw)?.[1] ?? 0);
|
|
42
|
+
const pid = number('pid');
|
|
43
|
+
if (!isPid(pid))
|
|
44
|
+
return null;
|
|
45
|
+
const port = number('port');
|
|
46
|
+
return {
|
|
47
|
+
pid,
|
|
48
|
+
port: isPid(port) ? port : 0,
|
|
49
|
+
startedAt: field('startedAt'),
|
|
50
|
+
profile: field('profile'),
|
|
51
|
+
version: field('version'),
|
|
52
|
+
dshHome: field('dshHome'),
|
|
53
|
+
launch: field('launch'),
|
|
54
|
+
origin: field('origin'),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** A JSON object (an array included): the shape `parseRunRegistry` accepts without inspection. */
|
|
58
|
+
export function isPlainObjectValue(value) {
|
|
59
|
+
return value !== null && typeof value === 'object';
|
|
60
|
+
}
|
|
61
|
+
export async function readRunRegistry(ssh, layout) {
|
|
62
|
+
try {
|
|
63
|
+
const result = await ssh.exec(`cat ${shellQuote(layout.runFile)} 2>/dev/null || true`, { timeoutMs: 10_000 });
|
|
64
|
+
if (result.code !== 0 || result.stdout.trim() === '')
|
|
65
|
+
return null;
|
|
66
|
+
return parseRunRegistry(result.stdout);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The pid/port record the plugin writes to `run/web.json` (the same shape the
|
|
74
|
+
* launch script writes). Kept pure so a re-attach can be tested without SSH.
|
|
75
|
+
* @param input - pid, port, profile, dshHome, version, startedAt.
|
|
76
|
+
* @returns the registry record.
|
|
77
|
+
*/
|
|
78
|
+
export function buildRunRegistryRecord(input = {}) {
|
|
79
|
+
const pid = Number(input.pid ?? 0);
|
|
80
|
+
const port = Number(input.port ?? 0);
|
|
81
|
+
if (!isPid(pid))
|
|
82
|
+
throw errors.invalidInput('pid', { zh: 'pid 不合法。', en: 'The pid is invalid.' });
|
|
83
|
+
if (!isPid(port) || port > 65535)
|
|
84
|
+
throw errors.invalidInput('port', { zh: '端口不合法。', en: 'The port is invalid.' });
|
|
85
|
+
const dshHome = String(input.dshHome ?? '').trim();
|
|
86
|
+
if (dshHome === '') {
|
|
87
|
+
throw errors.invalidInput('dshHome', { zh: '远端 DSH_HOME 未知。', en: 'The remote DSH_HOME is unknown.' });
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
pid,
|
|
91
|
+
port,
|
|
92
|
+
startedAt: typeof input.startedAt === 'string' && input.startedAt !== '' ? input.startedAt : nowIso(),
|
|
93
|
+
profile: typeof input.profile === 'string' && input.profile !== '' ? input.profile : DEFAULT_REMOTE_PROFILE,
|
|
94
|
+
version: normalizeVersion(input.version ?? ''),
|
|
95
|
+
dshHome,
|
|
96
|
+
launch: LAUNCH_MARKER,
|
|
97
|
+
// `launch`: this plugin started the process; `reattach`: the plugin only took it over.
|
|
98
|
+
// The next connection reads this so a re-attached process never gains kill rights.
|
|
99
|
+
origin: input.origin === 'reattach' ? 'reattach' : 'launch',
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Drop `run/web.json` without signalling anything: used when the bound process is already
|
|
104
|
+
* gone (a stop) or the record is known stale. Never kills a pid.
|
|
105
|
+
* @returns whether the removal was acknowledged.
|
|
106
|
+
*/
|
|
107
|
+
export async function clearRunRegistry(ssh, layout) {
|
|
108
|
+
try {
|
|
109
|
+
const result = await ssh.exec(`rm -f ${shellQuote(layout.runFile)}`, { timeoutMs: 10_000 });
|
|
110
|
+
return { ok: result.code === 0, output: String(result.stdout ?? '').trim() };
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
// swallow-ok: a failed removal is returned as ok:false and the caller logs it; the next
|
|
114
|
+
// connect still re-checks the registry, and a dead pid is never adopted
|
|
115
|
+
return { ok: false, output: messageOf(error) };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Rewrite `run/web.json` after a re-attach: the remote restarted on a new port
|
|
120
|
+
* (and possibly a new pid) without going through the launch script, so the stale
|
|
121
|
+
* record would mislead the next connect's adopt step.
|
|
122
|
+
* @param record - validated record from {@link buildRunRegistryRecord}.
|
|
123
|
+
* @returns whether the write was acknowledged.
|
|
124
|
+
*/
|
|
125
|
+
export async function writeRunRegistry(ssh, layout, record) {
|
|
126
|
+
const payload = JSON.stringify(record);
|
|
127
|
+
// Temp file + rename: a concurrent reader (`cat run/web.json`) sees the old record or the
|
|
128
|
+
// new one, never a truncated line that makes the adopt step misread the pid (M4).
|
|
129
|
+
const script = `set -eu
|
|
130
|
+
umask 077
|
|
131
|
+
mkdir -p ${shellQuote(layout.runDir)}
|
|
132
|
+
RUN=${shellQuote(layout.runFile)}
|
|
133
|
+
TMP="$RUN.tmp.$$"
|
|
134
|
+
printf '%s\\n' ${shellQuote(payload)} > "$TMP"
|
|
135
|
+
mv -f "$TMP" "$RUN"
|
|
136
|
+
echo "REGISTRY-WRITTEN"
|
|
137
|
+
`;
|
|
138
|
+
try {
|
|
139
|
+
const result = await ssh.exec(script, { timeoutMs: 15_000, maxBytes: 8_000 });
|
|
140
|
+
return { ok: result.code === 0 && result.stdout.includes('REGISTRY-WRITTEN'), output: result.stdout.trim() };
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
// A registry write failure is reported to the caller, which logs it and carries on:
|
|
144
|
+
// the live tunnel is what matters, the next connect re-adopts from the log line.
|
|
145
|
+
return { ok: false, output: messageOf(error) };
|
|
146
|
+
}
|
|
147
|
+
}
|