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.
Files changed (135) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7144 -8367
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +21 -0
  5. package/dist/src/api.js +380 -0
  6. package/dist/src/atomic-json.js +201 -0
  7. package/dist/src/bootstrap.js +96 -0
  8. package/dist/src/connect/attach.js +21 -0
  9. package/dist/src/connect/bootstrap.js +8 -0
  10. package/dist/src/connect/failures.js +29 -0
  11. package/dist/src/connect/guards.js +36 -0
  12. package/dist/src/connect/launch.js +70 -0
  13. package/dist/src/connect/links.js +54 -0
  14. package/dist/src/connect/ownership.js +139 -0
  15. package/dist/src/connect/pipeline.js +376 -0
  16. package/dist/src/connect/reattach.js +191 -0
  17. package/dist/src/connect/registry.js +10 -0
  18. package/dist/src/connect/repair.js +97 -0
  19. package/dist/src/connect/restart.js +255 -0
  20. package/dist/src/connect/stop.js +164 -0
  21. package/dist/src/connect/transport.js +101 -0
  22. package/dist/src/connect/verify.js +30 -0
  23. package/dist/src/connect/watchdog.js +44 -0
  24. package/dist/src/connect-log.js +137 -0
  25. package/dist/src/connect-progress.js +110 -0
  26. package/dist/src/constants.js +29 -0
  27. package/dist/src/context.js +96 -0
  28. package/dist/src/diagnostics.js +133 -0
  29. package/dist/src/download-jobs.js +221 -0
  30. package/dist/src/errors.js +228 -0
  31. package/dist/src/events.js +326 -0
  32. package/dist/src/host-lifecycle.js +368 -0
  33. package/dist/src/host-registry.js +181 -0
  34. package/dist/src/host-runtime.js +77 -0
  35. package/dist/src/host-view.js +52 -0
  36. package/dist/src/index.js +196 -0
  37. package/dist/src/kernel-adapter.js +388 -0
  38. package/dist/src/key-files.js +39 -0
  39. package/dist/src/known-hosts.js +104 -0
  40. package/dist/src/layout.js +26 -0
  41. package/dist/src/local-download.js +311 -0
  42. package/dist/src/local-ssh.js +23 -0
  43. package/dist/src/local-version.js +87 -0
  44. package/dist/src/node/download.js +157 -0
  45. package/dist/src/node-runtime.js +327 -0
  46. package/dist/src/probe.js +95 -0
  47. package/dist/src/prompts.js +198 -0
  48. package/dist/src/proxy/cookies.js +102 -0
  49. package/dist/src/proxy/headers.js +167 -0
  50. package/dist/src/proxy/http.js +134 -0
  51. package/dist/src/proxy/index.js +121 -0
  52. package/dist/src/proxy/limits.js +6 -0
  53. package/dist/src/proxy/routes.js +32 -0
  54. package/dist/src/proxy/upgrade.js +160 -0
  55. package/dist/src/redact.js +85 -0
  56. package/dist/src/remote-files.js +60 -0
  57. package/dist/src/remote-path.js +82 -0
  58. package/dist/src/remote-proc.js +271 -0
  59. package/dist/src/remote-web/registry.js +107 -0
  60. package/dist/src/remote-web/resolve.js +229 -0
  61. package/dist/src/remote-web/start.js +190 -0
  62. package/dist/src/remote-web/stop.js +74 -0
  63. package/dist/src/request-trust.js +70 -0
  64. package/dist/src/runtime/dispatch.js +200 -0
  65. package/dist/src/runtime/effects.js +81 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +70 -0
  68. package/dist/src/runtime/rules.js +480 -0
  69. package/dist/src/secrets.js +119 -0
  70. package/dist/src/service.js +300 -0
  71. package/dist/src/settings.js +143 -0
  72. package/dist/src/ssh-config.js +257 -0
  73. package/dist/src/ssh-failures.js +71 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +258 -0
  76. package/dist/src/ssh.js +395 -0
  77. package/dist/src/store.js +174 -0
  78. package/dist/src/tool-shared.js +146 -0
  79. package/dist/src/tools-exec-policy.js +121 -0
  80. package/dist/src/tools-exec.js +307 -0
  81. package/dist/src/tools-report.js +357 -0
  82. package/dist/src/tools.js +337 -0
  83. package/dist/src/tunnel.js +111 -0
  84. package/dist/src/util.js +112 -0
  85. package/dist/src/version.js +108 -0
  86. package/dist/src/watchdog-bus.js +21 -0
  87. package/dist/src/watchdog.js +116 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +1 -1
  90. package/locale/zh.json +1 -1
  91. package/package.json +37 -19
  92. package/src/admission.js +0 -43
  93. package/src/api.js +0 -536
  94. package/src/atomic-json.js +0 -225
  95. package/src/bootstrap.js +0 -113
  96. package/src/connect-log.js +0 -176
  97. package/src/connect-pipeline.js +0 -1900
  98. package/src/connect-progress.js +0 -155
  99. package/src/constants.js +0 -93
  100. package/src/diagnostics.js +0 -160
  101. package/src/download-jobs.js +0 -234
  102. package/src/errors.js +0 -412
  103. package/src/host-lifecycle.js +0 -604
  104. package/src/host-registry.js +0 -217
  105. package/src/host-runtime.js +0 -127
  106. package/src/host-view.js +0 -75
  107. package/src/index.js +0 -206
  108. package/src/key-files.js +0 -54
  109. package/src/known-hosts.js +0 -133
  110. package/src/layout.js +0 -53
  111. package/src/local-download.js +0 -381
  112. package/src/local-ssh.js +0 -27
  113. package/src/local-version.js +0 -88
  114. package/src/node-runtime.js +0 -521
  115. package/src/probe.js +0 -101
  116. package/src/prompts.js +0 -229
  117. package/src/redact.js +0 -68
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -137
  120. package/src/remote-proc.js +0 -343
  121. package/src/remote-proxy.js +0 -815
  122. package/src/remote-web.js +0 -751
  123. package/src/request-trust.js +0 -89
  124. package/src/secrets.js +0 -109
  125. package/src/service.js +0 -459
  126. package/src/settings.js +0 -163
  127. package/src/ssh-config.js +0 -271
  128. package/src/ssh.js +0 -731
  129. package/src/store.js +0 -193
  130. package/src/tools.js +0 -386
  131. package/src/tunnel.js +0 -132
  132. package/src/util.js +0 -153
  133. package/src/version.js +0 -103
  134. package/src/webapp.js +0 -43
  135. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -0,0 +1,160 @@
1
+ /** The WebSocket half of the same-origin proxy: the one WebSocket route a remote DSH owns (`/api/remote.mux`) gets an
2
+ * exact upgrade route per connected host, because the local web server matches upgrades by exact pathname. The
3
+ * handshake is admitted and fenced like an HTTP request, the upstream head is filtered before the browser sees it (a
4
+ * 101 used to be forwarded byte-for-byte, handing the remote's `Set-Cookie` to the local origin), and both directions
5
+ * then stream untouched. */
6
+ import http from 'node:http';
7
+ import net from 'node:net';
8
+ import { filterResponseHead, remoteOrigin, upstreamHeaders } from './headers.js';
9
+ import { admitSeat } from './http.js';
10
+ import { MAX_UPSTREAM_HEAD_BYTES } from './limits.js';
11
+ import { parseViewPath } from './routes.js';
12
+ /** Create the upgrade handler of one proxy activation. An upgrade owns its socket, so every refusal here either answers
13
+ * the handshake with a status and closes it (an admission rejection) or destroys it; nothing falls back to an HTTP
14
+ * response. */
15
+ export function createUpgradeHandler(rt, track) {
16
+ /** One exact upgrade route per host: the only WebSocket a DSH web serves is its stream mux. */
17
+ return function handleUpgrade(hostId, req, socket, head) {
18
+ const seat = admitSeat(rt, req);
19
+ if (seat.ok === false) {
20
+ if (seat.admission === false) {
21
+ socket.destroy();
22
+ return;
23
+ }
24
+ // An upgrade owns its socket: answer the handshake with the status, then close it.
25
+ socket.on('error', () => { });
26
+ socket.end(`HTTP/1.1 ${seat.status} ${http.STATUS_CODES[seat.status] ?? 'Rejected'}\r\n` +
27
+ 'connection: close\r\ncontent-length: 0\r\n\r\n');
28
+ return;
29
+ }
30
+ const target = rt.targetOf(hostId);
31
+ if (target === null) {
32
+ socket.destroy();
33
+ return;
34
+ }
35
+ // A malformed request target (absolute-form, broken escape) must not throw out of the upgrade handler: the HTTP
36
+ // path already degrades to a 400, this one just drops the socket.
37
+ let parsed = null;
38
+ try {
39
+ parsed = parseViewPath(new URL(req.url ?? '/', 'http://127.0.0.1').pathname);
40
+ }
41
+ catch {
42
+ parsed = null;
43
+ }
44
+ if (parsed === null) {
45
+ socket.destroy();
46
+ return;
47
+ }
48
+ const headers = upstreamHeaders(req.rawHeaders, {
49
+ target,
50
+ localOrigin: seat.origin.origin,
51
+ path: parsed.path,
52
+ jar: rt.jarFor(hostId, target),
53
+ preserveUpgrade: true,
54
+ });
55
+ let raw = `${req.method} ${parsed.path} HTTP/1.1\r\n`;
56
+ for (const [name, value] of Object.entries(headers)) {
57
+ for (const item of Array.isArray(value) ? value : [value])
58
+ raw += `${name}: ${item}\r\n`;
59
+ }
60
+ raw += '\r\n';
61
+ const upstream = net.connect({ port: target.localPort, host: '127.0.0.1', timeout: rt.upstreamTimeoutMs });
62
+ let settled = false;
63
+ // An upgrade owns its socket, so the deadline covers the handshake only: an upstream that accepts and never
64
+ // answers would otherwise leave both sockets dangling forever.
65
+ const handshakeTimer = setTimeout(() => failUpgrade(), rt.upstreamTimeoutMs);
66
+ handshakeTimer.unref?.();
67
+ function failUpgrade() {
68
+ clearTimeout(handshakeTimer);
69
+ if (settled)
70
+ return;
71
+ settled = true;
72
+ upstream.destroy();
73
+ socket.destroy();
74
+ rt.reportUpstreamFailure(hostId);
75
+ }
76
+ track.add(socket);
77
+ // The upstream's response head is filtered before the browser sees it: a 101 used to be forwarded byte-for-byte,
78
+ // which also handed the remote's `Set-Cookie` and policy headers to the local origin. Only the head is parsed;
79
+ // everything after it streams untouched.
80
+ let upstreamHead = Buffer.alloc(0);
81
+ let headForwarded = false;
82
+ const writeToClient = (chunk) => {
83
+ if (!socket.write(chunk))
84
+ upstream.pause();
85
+ };
86
+ const forwardUpstreamData = (chunk) => {
87
+ if (settled)
88
+ return;
89
+ clearTimeout(handshakeTimer);
90
+ upstream.setTimeout(0);
91
+ if (headForwarded) {
92
+ writeToClient(chunk);
93
+ return;
94
+ }
95
+ upstreamHead = upstreamHead.length === 0 ? Buffer.from(chunk) : Buffer.concat([upstreamHead, chunk]);
96
+ if (upstreamHead.length > MAX_UPSTREAM_HEAD_BYTES) {
97
+ // Nothing legitimate answers a handshake with a head this large.
98
+ failUpgrade();
99
+ return;
100
+ }
101
+ const end = upstreamHead.indexOf('\r\n\r\n');
102
+ if (end === -1)
103
+ return;
104
+ const filtered = filterResponseHead(upstreamHead.subarray(0, end).toString('latin1'), {
105
+ hostId,
106
+ remoteOrigin: remoteOrigin(target),
107
+ });
108
+ if (filtered === '') {
109
+ failUpgrade();
110
+ return;
111
+ }
112
+ headForwarded = true;
113
+ writeToClient(`${filtered}\r\n`);
114
+ const rest = upstreamHead.subarray(end + 4);
115
+ upstreamHead = Buffer.alloc(0);
116
+ if (rest.length > 0)
117
+ writeToClient(rest);
118
+ };
119
+ upstream.on('data', forwardUpstreamData);
120
+ socket.on('drain', () => upstream.resume());
121
+ upstream.on('timeout', () => failUpgrade());
122
+ upstream.on('error', () => failUpgrade());
123
+ /** The remote ended the stream. `upstream.pipe(socket)` used to forward that EOF implicitly; the head is parsed
124
+ * here, so the end of the upstream must still close the browser side or the page would hold a dead socket forever.
125
+ */
126
+ const endClient = () => {
127
+ if (settled)
128
+ return;
129
+ settled = true;
130
+ clearTimeout(handshakeTimer);
131
+ try {
132
+ socket.end();
133
+ }
134
+ catch {
135
+ // swallow-ok: the client socket may already be closed
136
+ }
137
+ };
138
+ upstream.on('end', endClient);
139
+ upstream.on('close', endClient);
140
+ socket.once('close', () => {
141
+ settled = true;
142
+ clearTimeout(handshakeTimer);
143
+ track.delete(socket);
144
+ upstream.destroy();
145
+ });
146
+ socket.on('error', () => {
147
+ settled = true;
148
+ clearTimeout(handshakeTimer);
149
+ upstream.destroy();
150
+ });
151
+ upstream.once('connect', () => {
152
+ if (settled)
153
+ return;
154
+ upstream.write(raw);
155
+ if (head && head.length > 0)
156
+ upstream.write(head);
157
+ socket.pipe(upstream);
158
+ });
159
+ };
160
+ }
@@ -0,0 +1,85 @@
1
+ /** Diagnostics redaction: tokens, passwords and private keys never leave the machine in a diagnostic package. */
2
+ const SECRET_QUERY_KEYS = ['token', 'access_token', 'api_key', 'apikey', 'key', 'secret', 'password', 'passwd', 'auth'];
3
+ const SECRET_HEADER_RE = /\b(authorization|cookie|set-cookie|x-api-key|proxy-authorization)\s*:\s*[^\r\n]+/gi;
4
+ /** Custom authentication headers (`x-auth-token`, `x-dsh-session-key`, …) are secrets too. */
5
+ const SECRET_CUSTOM_HEADER_RE = /\b(x-[a-z0-9-]*(?:token|key|secret|auth)[a-z0-9-]*)\s*:\s*[^\r\n]+/gi;
6
+ const BEARER_RE = /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/g;
7
+ const TOKEN_QUERY_RE = new RegExp(`([?&](?:${SECRET_QUERY_KEYS.join('|')})=)[^&#\\s"']+`, 'gi');
8
+ /** A bare `key=value` pair (log lines, `#fragment`, dumps). The anchor is "not alphanumeric" rather than `\b`, so
9
+ * `MYSQL_PWD=…` is caught too (`_` is a word character, which made `\b` miss it); and the value never contains `<`/`>`,
10
+ * so an already-redacted `<redacted>` is left alone. */
11
+ const BARE_TOKEN_KEYS = [
12
+ 'token',
13
+ 'access_token',
14
+ 'api_key',
15
+ 'apikey',
16
+ 'secret',
17
+ 'password',
18
+ 'passwd',
19
+ 'pwd',
20
+ 'auth',
21
+ 'credential',
22
+ 'key',
23
+ ];
24
+ const BARE_TOKEN_RE = new RegExp(`(^|[^A-Za-z0-9])((?:${BARE_TOKEN_KEYS.join('|')})\\s*=\\s*)[^\\s&;,'"<>]+`, 'gi');
25
+ /** A secret passed as a command-line flag (`--token abc`, `--api-key x`). No `\b` anchor: `-` is a non-word character,
26
+ * so a boundary never holds right before `--token`. The separate `PASSWORD_FLAG_RE` covers the historic spellings; this
27
+ * one catches the token-ish flags a launch command line carries in `ps` output. */
28
+ const SECRET_FLAG_RE = /(?:--?)(?:token|api-key|apikey|auth-token|access-token|password|passphrase)[=\s]+(?!<redacted>)\S+/gi;
29
+ const PRIVATE_KEY_RE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g;
30
+ /** `--password X`, `password=X` and the short `-p X` form. That short form is also ssh's port flag (`ssh -p 2222`), so
31
+ * a bare number is left alone — a port is not a secret and mangling it would make the technical detail unreadable. The
32
+ * whitespace after `-p` is optional because the value may be glued to the flag (`mysql -pHunter2`). */
33
+ const PASSWORD_FLAG_RE = /(--password[=\s]+|password[=:]\s*|-p\s*(?!\d+\b))(\S+)/gi;
34
+ const DSH_TOKEN_LINE_RE = /(dsh web:\s*\S*?\?token=)[A-Za-z0-9._~+/=-]+/g;
35
+ export function redactText(text, options = {}) {
36
+ if (typeof text !== 'string' || text === '')
37
+ return text;
38
+ let out = text;
39
+ out = out.replace(PRIVATE_KEY_RE, '-----BEGIN PRIVATE KEY-----<redacted>-----END PRIVATE KEY-----');
40
+ // A capture cut before the footer (`safeText` bounds every field before it redacts) leaves a
41
+ // header with no END, which the complete-block rule above cannot match: drop the body explicitly.
42
+ const strayBegin = out.lastIndexOf('-----BEGIN ');
43
+ if (strayBegin >= 0 && strayBegin > out.lastIndexOf('-----END ')) {
44
+ out = `${out.slice(0, strayBegin)}-----BEGIN PRIVATE KEY-----<redacted>`;
45
+ }
46
+ out = out.replace(SECRET_HEADER_RE, (match) => `${match.split(':')[0]}: <redacted>`);
47
+ out = out.replace(SECRET_CUSTOM_HEADER_RE, (match) => `${match.split(':')[0]}: <redacted>`);
48
+ out = out.replace(BEARER_RE, (_match, scheme) => `${scheme} <redacted>`);
49
+ out = out.replace(TOKEN_QUERY_RE, '$1<redacted>');
50
+ out = out.replace(DSH_TOKEN_LINE_RE, '$1<redacted>');
51
+ out = out.replace(SECRET_FLAG_RE, (match) => `${match.replace(/\S+$/, '')}<redacted>`);
52
+ out = out.replace(BARE_TOKEN_RE, '$1$2<redacted>');
53
+ out = out.replace(PASSWORD_FLAG_RE, '$1<redacted>');
54
+ if (!options.keepPaths) {
55
+ // Remote home directories are not secrets, but arbitrary local user names should not leak.
56
+ out = out.replace(/(\/home\/)[^/\s]+/g, '$1<user>');
57
+ out = out.replace(/(\/Users\/)[^/\s]+/g, '$1<user>');
58
+ out = out.replace(/\b(C:\\Users\\)[^\\\s]+/gi, '$1<user>');
59
+ }
60
+ return out;
61
+ }
62
+ function redactValue(key, value) {
63
+ const lowered = String(key).toLowerCase();
64
+ if (typeof value === 'string') {
65
+ if (/(password|token|secret|passphrase|authorization|apikey|api_key|privatekey|cookie)/.test(lowered))
66
+ return '<redacted>';
67
+ return redactText(value);
68
+ }
69
+ if (Array.isArray(value))
70
+ return value.map((item) => redactValue(key, item));
71
+ if (value && typeof value === 'object')
72
+ return redactObject(value);
73
+ return value;
74
+ }
75
+ /** Deep-redact a JSON-compatible value. */
76
+ export function redactObject(value) {
77
+ if (Array.isArray(value))
78
+ return value.map((item) => redactValue('', item));
79
+ if (!value || typeof value !== 'object')
80
+ return value;
81
+ const out = {};
82
+ for (const [key, item] of Object.entries(value))
83
+ out[key] = redactValue(key, item);
84
+ return out;
85
+ }
@@ -0,0 +1,60 @@
1
+ // Remote download entry: validate an absolute Linux path, inspect it, then hand it to the local
2
+ // writer; files and folders stream straight to disk, so nothing is buffered and no ZIP is created.
3
+ import { errors, isRemoteGoError } from './errors.js';
4
+ import { requireDestination, saveHostFile, saveHostFolder } from './local-download.js';
5
+ import { normalizeRemoteFilePath } from './remote-path.js';
6
+ /** Save one file or one folder for a download job. */
7
+ export async function readHostDownload(runtime, rawPath, options = {}) {
8
+ if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
9
+ throw errors.remoteFileUnavailable({
10
+ zh: '这台主机还没有连接,无法读取远端内容。',
11
+ en: 'This host is not connected, so the remote content cannot be read.',
12
+ });
13
+ }
14
+ const remotePath = normalizeRemoteFilePath(rawPath);
15
+ const ssh = runtime.ssh;
16
+ if (typeof ssh.inspectRemotePath !== 'function') {
17
+ throw errors.internal('the SSH transport does not support path inspection');
18
+ }
19
+ try {
20
+ const info = await ssh.inspectRemotePath(remotePath);
21
+ const destination = await requireDestination(options.destination, { home: options.home });
22
+ if (info.isFile)
23
+ return await saveHostFile(runtime, remotePath, destination, options);
24
+ if (info.isDirectory)
25
+ return await saveHostFolder(runtime, remotePath, destination, options);
26
+ throw errors.remoteFileUnavailable({
27
+ zh: '这个远端路径既不是普通文件,也不是文件夹。',
28
+ en: 'This remote path is neither a regular file nor a folder.',
29
+ });
30
+ }
31
+ catch (error) {
32
+ if (isRemoteGoError(error))
33
+ throw error;
34
+ throw toRemoteFileError(error);
35
+ }
36
+ }
37
+ /** Classify an SFTP failure without leaking transport internals to the client. */
38
+ export function toRemoteFileError(error) {
39
+ // `isRemoteGoError` only declares a boolean; the `as` restates the narrowing its `instanceof`
40
+ // proves at runtime.
41
+ if (isRemoteGoError(error))
42
+ return error;
43
+ // A transport error is `unknown`: the `as` restates the two fields an SFTP error carries (`code`
44
+ // 2/3 for ENOENT/EACCES) and the `??` fallbacks keep a thrown string working.
45
+ const code = Number(error?.code);
46
+ const message = String(error?.message ?? error ?? '');
47
+ if (code === 2 || /no such file|not found/i.test(message)) {
48
+ return errors.remoteFileUnavailable({
49
+ zh: '远端文件不存在或已经被移动。',
50
+ en: 'The remote file no longer exists or was moved.',
51
+ });
52
+ }
53
+ if (code === 3 || /permission denied|access denied/i.test(message)) {
54
+ return errors.remoteFileUnavailable({
55
+ zh: '当前 SSH 用户没有读取这个远端路径的权限。',
56
+ en: 'The SSH user is not allowed to read this remote path.',
57
+ });
58
+ }
59
+ return errors.remoteFileUnavailable(undefined, { technical: message.slice(0, 300) });
60
+ }
@@ -0,0 +1,82 @@
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
+ /** The one "this remote path is unusable" refusal; every rule below reports it with the same code. */
7
+ const invalidPath = (zh, en) => errors.invalidInput('path', { zh, en });
8
+ /** Validate and normalize a remote file path. The input comes from a client request, so anything that is not a usable
9
+ * absolute POSIX path is refused with a coded error instead of reaching a remote command. */
10
+ export function normalizeRemoteFilePath(value) {
11
+ if (typeof value !== 'string') {
12
+ throw invalidPath('远端文件路径必须是字符串。', 'The remote file path must be a string.');
13
+ }
14
+ const text = value;
15
+ if (text === '')
16
+ throw invalidPath('远端文件路径不能为空。', 'The remote file path must not be empty.');
17
+ if (text.length > MAX_PATH_CHARS)
18
+ throw invalidPath('远端文件路径过长。', 'The remote file path is too long.');
19
+ if (text.includes('\0') || text.includes('\r') || text.includes('\n')) {
20
+ throw invalidPath('远端文件路径包含不可用的控制字符。', 'The remote file path contains unsupported control characters.');
21
+ }
22
+ const normalized = path.posix.normalize(text);
23
+ if (!normalized.startsWith('/') || !text.startsWith('/')) {
24
+ throw invalidPath('远端文件路径必须是绝对路径。', 'The remote file path must be absolute.');
25
+ }
26
+ return normalized;
27
+ }
28
+ /** The suggested download name for a remote path: the last path segment, or a safe generic name. */
29
+ export function remoteFileName(remotePath) {
30
+ const name = path.posix.basename(remotePath);
31
+ return name === '' || name === '/' || name === '.' || name === '..' ? 'download' : name;
32
+ }
33
+ /** One local filename segment; Windows-safe so the same code works on every Desktop. */
34
+ export function safeLocalSegment(value) {
35
+ let text = String(value ?? '')
36
+ .replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_')
37
+ .replace(/[. ]+$/, '');
38
+ if (text === '' || text === '.' || text === '..')
39
+ text = '_';
40
+ if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(text))
41
+ text = '_' + text;
42
+ return text;
43
+ }
44
+ /** Windows treats these names as its own metadata or as shell entries: writing one into a download either corrupts a
45
+ * folder view (`desktop.ini`, `thumbs.db`) or leaves a file a double click executes instead of shows (`.lnk`, `.url`).
46
+ * A remote host never gets to plant one in a local download. */
47
+ const IGNORED_LOCAL_NAMES = new Set(['desktop.ini', 'thumbs.db', 'ehthumbs.db', '.ds_store']);
48
+ const IGNORED_LOCAL_SUFFIXES = ['.lnk', '.url'];
49
+ /** Whether a remote name must be left out of a local folder download. */
50
+ export function isIgnoredLocalName(value) {
51
+ const name = String(value ?? '')
52
+ .trim()
53
+ .toLowerCase();
54
+ if (IGNORED_LOCAL_NAMES.has(name))
55
+ return true;
56
+ return IGNORED_LOCAL_SUFFIXES.some((suffix) => name.endsWith(suffix));
57
+ }
58
+ /** Pick a local path that no earlier member of the same download already claimed. A case-insensitive filesystem (the
59
+ * Windows/macOS default) maps `Report.md` and `report.md` to one file, so keeping both names would silently drop one
60
+ * remote file: the later one becomes `report (2).md` instead. */
61
+ export function uniqueLocalPath(desired, taken, options = {}) {
62
+ const key = (value) => localPathKey(value, options);
63
+ if (!taken.has(key(desired)))
64
+ return desired;
65
+ const directory = path.dirname(desired);
66
+ const extension = path.extname(desired);
67
+ const base = path.basename(desired, extension);
68
+ for (let index = 2; index < 1000; index += 1) {
69
+ const candidate = path.join(directory, `${base} (${index})${extension}`);
70
+ if (!taken.has(key(candidate)))
71
+ return candidate;
72
+ }
73
+ throw errors.remoteFileUnavailable({
74
+ zh: '远端有太多文件映射到同一个本地文件名,无法安全保存。',
75
+ en: 'Too many remote files map to the same local file name to save them safely.',
76
+ });
77
+ }
78
+ /** The collision key of a local path: separator-normalized, and lowercased when the local filesystem ignores case. */
79
+ export function localPathKey(value, options = {}) {
80
+ const text = String(value ?? '').replace(/\\/g, '/');
81
+ return options.caseInsensitive === true ? text.toLowerCase() : text;
82
+ }
@@ -0,0 +1,271 @@
1
+ /** 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. */
2
+ import http from 'node:http';
3
+ import { TUNNEL_PROBE_TIMEOUT_MS } from './constants.js';
4
+ import { isPid, messageOf } from './util.js';
5
+ /** A listener answering 200, 302 or 401 is up: 401 without the launch cookie still proves it serves. */
6
+ export function isUiUp(status) {
7
+ return status === 200 || status === 302 || status === 401;
8
+ }
9
+ export function buildForeignDshCommand(ignorePids = []) {
10
+ const ignore = (Array.isArray(ignorePids) ? ignorePids : [])
11
+ .map((pid) => Number(pid))
12
+ .filter((pid) => isPid(pid))
13
+ .join(' ');
14
+ return `set -u
15
+ IGNORE=" ${ignore} "
16
+ PS_OUT=$(ps -eww -o pid=,comm=,args= 2>/dev/null || ps -eo pid=,comm=,args= 2>/dev/null || true)
17
+ printf '%s\\n' "$PS_OUT" | while IFS= read -r LINE; do
18
+ [ -z "$LINE" ] && continue
19
+ set -- $LINE
20
+ PID=$1 COMM=$2
21
+ shift 2; ARGS="$*"
22
+ [ -z "$PID" ] && continue
23
+ case "$IGNORE" in *" $PID "*) continue ;; esac
24
+ case "$COMM" in node|dsh|npm|npx) ;; *) continue ;; esac
25
+ case "$ARGS" in *"@deepseek-ai/dsh"*|*"/bin/dsh "*|*" dsh "*) ;; *) continue ;; esac
26
+ case "$ARGS" in *"ps -eww"*|*"PS_OUT"*|*"IGNORE"*) continue ;; esac
27
+ ENV_HOME=$(tr '\\0' '\\n' < "/proc/$PID/environ" 2>/dev/null | sed -n 's/^DSH_HOME=//p' | tail -n 1)
28
+ if [ -n "\${ENV_HOME:-}" ] && [ "$ENV_HOME" != "$HOME/.dsh" ]; then continue; fi
29
+ printf '%s\\t%s\\n' "$PID" "$ARGS"
30
+ done`;
31
+ }
32
+ export function parseForeignDshOutput(stdout) {
33
+ const processes = [];
34
+ for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
35
+ const tab = rawLine.indexOf('\t');
36
+ if (tab <= 0)
37
+ continue;
38
+ const pid = Number(rawLine.slice(0, tab).trim());
39
+ const command = rawLine.slice(tab + 1).trim();
40
+ if (!isPid(pid) || command === '')
41
+ continue;
42
+ processes.push({ pid, command });
43
+ }
44
+ return processes;
45
+ }
46
+ /** Find DSH processes on the remote that this plugin did not start; never throws, because a broken scan must not block connecting. */
47
+ export async function findForeignDshProcesses(ssh, options = {}) {
48
+ const failed = (technical) => ({
49
+ ok: false,
50
+ processes: [],
51
+ reason: 'exec-failed',
52
+ technical,
53
+ });
54
+ try {
55
+ const result = await ssh.exec(buildForeignDshCommand(options.ignorePids ?? []), {
56
+ timeoutMs: options.timeoutMs ?? 20_000,
57
+ maxBytes: 200_000,
58
+ });
59
+ if (result.code !== 0)
60
+ return failed(String(result.stderr ?? '').slice(0, 500));
61
+ return { ok: true, processes: parseForeignDshOutput(result.stdout) };
62
+ }
63
+ catch (error) {
64
+ // swallow-ok: a scan failure is surfaced as ok:false and the caller proceeds without a prompt
65
+ return failed(messageOf(error));
66
+ }
67
+ }
68
+ export async function stopForeignDshProcesses(ssh, processes, options = {}) {
69
+ const pids = [
70
+ ...new Set((Array.isArray(processes) ? processes : []).map((process) => Number(process?.pid)).filter((pid) => isPid(pid))),
71
+ ];
72
+ if (pids.length === 0)
73
+ return { ok: true, alive: [], output: '' };
74
+ const script = `set -u
75
+ PIDS="${pids.join(' ')}"
76
+ for PID in $PIDS; do kill -TERM "$PID" 2>/dev/null || true; done
77
+ i=0
78
+ while [ "$i" -lt 20 ]; do
79
+ ALIVE=0; for PID in $PIDS; do if kill -0 "$PID" 2>/dev/null; then ALIVE=1; fi; done
80
+ if [ "$ALIVE" -eq 0 ]; then break; fi
81
+ i=$((i+1)); sleep 0.5
82
+ done
83
+ for PID in $PIDS; do if kill -0 "$PID" 2>/dev/null; then kill -KILL "$PID" 2>/dev/null || true; fi; done
84
+ sleep 0.2
85
+ for PID in $PIDS; do if kill -0 "$PID" 2>/dev/null; then echo "ALIVE:$PID"; fi; done
86
+ echo "STOPPED"
87
+ `;
88
+ try {
89
+ const result = await ssh.exec(script, { timeoutMs: options.timeoutMs ?? 30_000 });
90
+ const output = String(result.stdout ?? '');
91
+ const alive = [...output.matchAll(/ALIVE:(\d+)/g)].map((match) => Number(match[1]));
92
+ return { ok: result.code === 0 && alive.length === 0, alive, output };
93
+ }
94
+ catch (error) {
95
+ // swallow-ok: a stop failure is returned to the caller with the original message
96
+ return { ok: false, alive: pids, output: messageOf(error) };
97
+ }
98
+ }
99
+ /** TCP ports a pid is listening on, read from its own `/proc` network tables and matched against the socket inodes it holds. */
100
+ export async function remoteListenPorts(ssh, pid) {
101
+ if (!isPid(pid))
102
+ return [];
103
+ const script = `set -u
104
+ PID=${pid}
105
+ [ -d "/proc/$PID" ] || exit 0
106
+ ls -l "/proc/$PID/fd" 2>/dev/null | sed -n 's/.*socket:\\[\\([0-9][0-9]*\\)\\].*/INODE:\\1/p' | sort -u
107
+ for NET in "/proc/$PID/net/tcp" "/proc/$PID/net/tcp6"; do [ -r "$NET" ] && awk 'NR > 1 && $4 == "0A" { print "LISTEN:" $2 ":" $10 }' "$NET" 2>/dev/null; done
108
+ `;
109
+ try {
110
+ const result = await ssh.exec(script, { timeoutMs: 15_000 });
111
+ return parseListenPorts(result.stdout);
112
+ }
113
+ catch {
114
+ // swallow-ok: an unreadable /proc directory yields no candidate ports
115
+ return [];
116
+ }
117
+ }
118
+ export function parseListenPorts(stdout) {
119
+ const inodes = new Set();
120
+ const ports = [];
121
+ for (const line of String(stdout ?? '').split(/\r?\n/)) {
122
+ const inode = /^INODE:(\d+)$/.exec(line);
123
+ if (inode) {
124
+ inodes.add(inode[1]);
125
+ continue;
126
+ }
127
+ const listen = /^LISTEN:[0-9A-Fa-f]+:([0-9A-Fa-f]{1,4}):(\d+)$/.exec(line);
128
+ if (!listen)
129
+ continue;
130
+ const port = Number.parseInt(listen[1], 16);
131
+ if (isPid(port) && port <= 65535)
132
+ ports.push({ port, inode: listen[2] });
133
+ }
134
+ return [...new Set(ports.filter((entry) => inodes.has(entry.inode)).map((entry) => entry.port))].sort((left, right) => left - right);
135
+ }
136
+ /** The pid behind one listening loopback port, found by matching the port's socket inode against every `/proc/<pid>/fd`; needed when the remote restarted into a pid the run registry does not know yet. */
137
+ export async function remotePortOwnerPid(ssh, port) {
138
+ if (!isPid(port) || port > 65535)
139
+ return null;
140
+ const script = `set -u
141
+ PORT_HEX=$(printf '%04X' ${port})
142
+ INODE=$(awk -v p=":$PORT_HEX" '$2 ~ p"$" && $4 == "0A" { print $10; exit }' /proc/net/tcp 2>/dev/null)
143
+ [ -n "\${INODE:-}" ] || exit 0
144
+ for D in /proc/[0-9]*; do
145
+ if ls -l "$D/fd" 2>/dev/null | grep -q "socket:\\[\${INODE}\\]"; then echo "PID:\${D#/proc/}"; exit 0; fi
146
+ done
147
+ `;
148
+ try {
149
+ const result = await ssh.exec(script, { timeoutMs: 20_000 });
150
+ const match = /^PID:(\d+)$/m.exec(String(result.stdout ?? ''));
151
+ const pid = match ? Number(match[1]) : 0;
152
+ return isPid(pid) ? pid : null;
153
+ }
154
+ catch {
155
+ // swallow-ok: an unreadable /proc scan means the pid is unknown, the caller falls back
156
+ return null;
157
+ }
158
+ }
159
+ /** The identity of one remote process, read from `/proc` before the plugin ever signals it: the kernel start time is stable across `exec` (so an in-place DSH restart keeps it) and changes when a pid is reused, which is exactly what a kill decision must rule out. */
160
+ export async function remoteProcessIdentity(ssh, pid) {
161
+ if (!isPid(pid))
162
+ return { ok: false, reason: 'invalid-pid' };
163
+ const script = `set -u
164
+ PID=${pid}
165
+ [ -d "/proc/$PID" ] || { echo "MISSING"; exit 0; }
166
+ RAW=$(cat "/proc/$PID/stat" 2>/dev/null || true); [ -n "$RAW" ] || { echo "NO-STAT"; exit 0; }
167
+ REST=$(printf '%s' "$RAW" | sed 's/^.*) //'); set -- $REST
168
+ printf 'START:%s\\n' "\${20}"
169
+ CMD=$(tr '\\0' ' ' < "/proc/$PID/cmdline" 2>/dev/null || true); printf 'CMD:%s\\n' "$CMD"
170
+ HOME_LINE=$(tr '\\0' '\\n' < "/proc/$PID/environ" 2>/dev/null | sed -n 's/^DSH_HOME=//p' | tail -n 1)
171
+ printf 'DSH_HOME:%s\\n' "\${HOME_LINE:-}"
172
+ `;
173
+ try {
174
+ const result = await ssh.exec(script, { timeoutMs: 10_000, maxBytes: 32_000 });
175
+ return parseProcessIdentity(result.stdout);
176
+ }
177
+ catch {
178
+ // swallow-ok: an unreadable /proc means the pid cannot be proven, and callers fail closed
179
+ return { ok: false, reason: 'unreadable' };
180
+ }
181
+ }
182
+ export function parseProcessIdentity(stdout) {
183
+ const text = String(stdout ?? '');
184
+ // Matched anywhere in the output deliberately: a command line containing MISSING/NO-STAT must not read as an identity.
185
+ if (text.includes('MISSING'))
186
+ return { ok: false, reason: 'missing' };
187
+ if (text.includes('NO-STAT'))
188
+ return { ok: false, reason: 'unreadable' };
189
+ const start = /^START:(\d+)$/m.exec(text);
190
+ const command = /^CMD:(.*)$/m.exec(text);
191
+ if (!start || !command)
192
+ return { ok: false, reason: 'unreadable' };
193
+ const home = /^DSH_HOME:(.*)$/m.exec(text);
194
+ return { ok: true, startTime: start[1], command: command[1].trim(), dshHome: home === null ? '' : home[1].trim() };
195
+ }
196
+ export async function remoteHttpStatus(ssh, port) {
197
+ if (!isPid(port))
198
+ return null;
199
+ const script = `URL="http://127.0.0.1:${port}/"
200
+ if command -v curl >/dev/null 2>&1; then curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$URL" 2>/dev/null || true
201
+ elif command -v wget >/dev/null 2>&1; then 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; fi
202
+ `;
203
+ try {
204
+ const result = await ssh.exec(script, { timeoutMs: 15_000 });
205
+ const code = Number(String(result.stdout ?? '').trim());
206
+ return Number.isInteger(code) && code > 0 ? code : null;
207
+ }
208
+ catch {
209
+ return null;
210
+ }
211
+ }
212
+ export async function waitForRemoteUi(ssh, port, options = {}) {
213
+ const attempts = options.attempts ?? 20;
214
+ const intervalMs = options.intervalMs ?? 500;
215
+ let last = null;
216
+ for (let i = 0; i < attempts; i += 1) {
217
+ last = await remoteHttpStatus(ssh, port);
218
+ if (isUiUp(last))
219
+ return { ok: true, status: last };
220
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
221
+ }
222
+ return { ok: false, status: last };
223
+ }
224
+ export async function exchangeTokenOverTunnel(localPort, token, options = {}) {
225
+ const timeoutMs = options.timeoutMs ?? TUNNEL_PROBE_TIMEOUT_MS;
226
+ const basePath = options.path ?? '/';
227
+ const tokenPath = `/?token=${encodeURIComponent(token)}`;
228
+ const path = basePath === '/' ? tokenPath : `${basePath}?token=${encodeURIComponent(token)}`;
229
+ const first = await httpRequest({ port: localPort, path, timeoutMs });
230
+ const setCookies = first.headers['set-cookie'] ?? [];
231
+ const cookieHeader = setCookies.map((cookie) => String(cookie).split(';')[0]).join('; ');
232
+ const back = first.headers.location?.startsWith('/') ? first.headers.location : '/';
233
+ const second = await httpRequest({
234
+ port: localPort,
235
+ path: back,
236
+ timeoutMs,
237
+ headers: cookieHeader ? { cookie: cookieHeader } : {},
238
+ });
239
+ const titleMatch = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(second.body);
240
+ return {
241
+ ok: second.status === 200 && second.body.length > 0,
242
+ firstStatus: first.status,
243
+ status: second.status,
244
+ title: titleMatch ? titleMatch[1].trim().slice(0, 200) : null,
245
+ };
246
+ }
247
+ function httpRequest(options) {
248
+ return new Promise((resolve, reject) => {
249
+ const request = http.request({
250
+ host: '127.0.0.1',
251
+ port: options.port,
252
+ path: options.path,
253
+ method: 'GET',
254
+ headers: { 'user-agent': 'dsh-remote-go', ...options.headers },
255
+ timeout: options.timeoutMs,
256
+ }, (response) => {
257
+ const chunks = [];
258
+ response.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
259
+ response.on('end', () => {
260
+ resolve({
261
+ status: response.statusCode ?? 0,
262
+ headers: response.headers,
263
+ body: Buffer.concat(chunks).toString('utf8'),
264
+ });
265
+ });
266
+ });
267
+ request.on('timeout', () => request.destroy(new Error('local tunnel probe timed out')));
268
+ request.on('error', reject);
269
+ request.end();
270
+ });
271
+ }