dsh-remote-go 0.3.0 → 0.3.2

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 (86) hide show
  1. package/README.md +1 -0
  2. package/dist/client.js +1348 -2095
  3. package/dist/src/admission.js +3 -28
  4. package/dist/src/api.js +37 -99
  5. package/dist/src/atomic-json.js +32 -66
  6. package/dist/src/bootstrap.js +17 -27
  7. package/dist/src/connect/attach.js +3 -25
  8. package/dist/src/connect/bootstrap.js +2 -8
  9. package/dist/src/connect/failures.js +3 -18
  10. package/dist/src/connect/guards.js +13 -8
  11. package/dist/src/connect/launch.js +11 -21
  12. package/dist/src/connect/links.js +11 -27
  13. package/dist/src/connect/ownership.js +33 -114
  14. package/dist/src/connect/pipeline.js +62 -159
  15. package/dist/src/connect/reattach.js +26 -44
  16. package/dist/src/connect/registry.js +0 -1
  17. package/dist/src/connect/repair.js +8 -37
  18. package/dist/src/connect/restart.js +36 -97
  19. package/dist/src/connect/stop.js +16 -50
  20. package/dist/src/connect/transport.js +10 -18
  21. package/dist/src/connect/verify.js +3 -12
  22. package/dist/src/connect/watchdog.js +6 -38
  23. package/dist/src/connect-log.js +16 -41
  24. package/dist/src/connect-progress.js +13 -45
  25. package/dist/src/constants.js +18 -43
  26. package/dist/src/context.js +13 -32
  27. package/dist/src/diagnostics.js +56 -25
  28. package/dist/src/download-jobs.js +11 -20
  29. package/dist/src/errors.js +175 -190
  30. package/dist/src/events.js +20 -84
  31. package/dist/src/host-lifecycle.js +69 -177
  32. package/dist/src/host-registry.js +27 -78
  33. package/dist/src/host-runtime.js +0 -9
  34. package/dist/src/host-view.js +6 -29
  35. package/dist/src/index.js +15 -35
  36. package/dist/src/kernel-adapter.js +34 -80
  37. package/dist/src/key-files.js +10 -23
  38. package/dist/src/known-hosts.js +13 -34
  39. package/dist/src/layout.js +3 -20
  40. package/dist/src/local-download.js +94 -163
  41. package/dist/src/local-ssh.js +12 -19
  42. package/dist/src/local-version.js +35 -49
  43. package/dist/src/node/download.js +1 -4
  44. package/dist/src/node-runtime.js +19 -38
  45. package/dist/src/probe.js +6 -7
  46. package/dist/src/prompts.js +56 -128
  47. package/dist/src/proxy/cookies.js +26 -60
  48. package/dist/src/proxy/headers.js +30 -125
  49. package/dist/src/proxy/http.js +33 -41
  50. package/dist/src/proxy/index.js +20 -34
  51. package/dist/src/proxy/limits.js +4 -6
  52. package/dist/src/proxy/routes.js +10 -17
  53. package/dist/src/proxy/upgrade.js +27 -42
  54. package/dist/src/redact.js +14 -33
  55. package/dist/src/remote-files.js +9 -21
  56. package/dist/src/remote-path.js +21 -62
  57. package/dist/src/remote-proc.js +35 -103
  58. package/dist/src/remote-web/registry.js +10 -50
  59. package/dist/src/remote-web/resolve.js +23 -104
  60. package/dist/src/remote-web/start.js +27 -64
  61. package/dist/src/remote-web/stop.js +6 -25
  62. package/dist/src/request-trust.js +15 -32
  63. package/dist/src/runtime/dispatch.js +33 -143
  64. package/dist/src/runtime/effects.js +7 -17
  65. package/dist/src/runtime/events.js +1 -1
  66. package/dist/src/runtime/fsm.js +11 -61
  67. package/dist/src/runtime/rules.js +121 -199
  68. package/dist/src/secrets.js +15 -38
  69. package/dist/src/service.js +22 -128
  70. package/dist/src/settings.js +41 -42
  71. package/dist/src/ssh-config.js +22 -41
  72. package/dist/src/ssh-failures.js +23 -74
  73. package/dist/src/ssh-sftp.js +47 -86
  74. package/dist/src/ssh.js +99 -179
  75. package/dist/src/store.js +31 -48
  76. package/dist/src/tool-shared.js +17 -52
  77. package/dist/src/tools-exec-policy.js +33 -79
  78. package/dist/src/tools-exec.js +87 -151
  79. package/dist/src/tools-report.js +100 -167
  80. package/dist/src/tools.js +59 -133
  81. package/dist/src/tunnel.js +9 -27
  82. package/dist/src/util.js +19 -56
  83. package/dist/src/version.js +6 -12
  84. package/dist/src/watchdog-bus.js +0 -8
  85. package/dist/src/watchdog.js +7 -47
  86. package/package.json +3 -3
@@ -1,22 +1,13 @@
1
- /**
2
- * Diagnostics redaction: tokens, passwords and private keys never leave the machine in a diagnostic package.
3
- */
1
+ /** Diagnostics redaction: tokens, passwords and private keys never leave the machine in a diagnostic package. */
4
2
  const SECRET_QUERY_KEYS = ['token', 'access_token', 'api_key', 'apikey', 'key', 'secret', 'password', 'passwd', 'auth'];
5
3
  const SECRET_HEADER_RE = /\b(authorization|cookie|set-cookie|x-api-key|proxy-authorization)\s*:\s*[^\r\n]+/gi;
6
4
  /** Custom authentication headers (`x-auth-token`, `x-dsh-session-key`, …) are secrets too. */
7
5
  const SECRET_CUSTOM_HEADER_RE = /\b(x-[a-z0-9-]*(?:token|key|secret|auth)[a-z0-9-]*)\s*:\s*[^\r\n]+/gi;
8
6
  const BEARER_RE = /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/g;
9
7
  const TOKEN_QUERY_RE = new RegExp(`([?&](?:${SECRET_QUERY_KEYS.join('|')})=)[^&#\\s"']+`, 'gi');
10
- /**
11
- * A bare `token=…` outside a query string (log lines, `#fragment`, key=value dumps). The
12
- * value never contains `<`/`>` so an already-redacted `<redacted>` is left alone.
13
- */
14
- /**
15
- * A bare `key=value` pair (log lines, `#fragment`, dumps). The anchor is "not alphanumeric" rather
16
- * than `\b`, so a prefixed env name such as `MYSQL_PWD=…` is caught too (`_` is a word character,
17
- * which made `\b` miss it). The value never contains `<`/`>` so an already-redacted `<redacted>` is
18
- * left alone.
19
- */
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. */
20
11
  const BARE_TOKEN_KEYS = [
21
12
  'token',
22
13
  'access_token',
@@ -31,20 +22,14 @@ const BARE_TOKEN_KEYS = [
31
22
  'key',
32
23
  ];
33
24
  const BARE_TOKEN_RE = new RegExp(`(^|[^A-Za-z0-9])((?:${BARE_TOKEN_KEYS.join('|')})\\s*=\\s*)[^\\s&;,'"<>]+`, 'gi');
34
- /**
35
- * A secret passed as a command-line flag (`--token abc`, `--api-key x`, `--password y`). No `\b`
36
- * anchor: `-` is a non-word character, so a boundary never holds right before `--token`. The
37
- * separate `PASSWORD_FLAG_RE` below covers the historic spellings; this one catches the token-ish
38
- * flags that a launch command line carries, which `ps` output made worth redacting.
39
- */
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. */
40
28
  const SECRET_FLAG_RE = /(?:--?)(?:token|api-key|apikey|auth-token|access-token|password|passphrase)[=\s]+(?!<redacted>)\S+/gi;
41
29
  const PRIVATE_KEY_RE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g;
42
- /**
43
- * `--password X`, `password=X` and the short `-p X` form. The short form is also ssh's
44
- * port flag (`ssh -p 2222`), so a bare number is left alone: a port is not a secret and
45
- * mangling it would make the technical detail unreadable. The value may also be glued to the
46
- * flag (`mysql -pHunter2`), which is why the whitespace after `-p` is optional.
47
- */
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`). */
48
33
  const PASSWORD_FLAG_RE = /(--password[=\s]+|password[=:]\s*|-p\s*(?!\d+\b))(\S+)/gi;
49
34
  const DSH_TOKEN_LINE_RE = /(dsh web:\s*\S*?\?token=)[A-Za-z0-9._~+/=-]+/g;
50
35
  export function redactText(text, options = {}) {
@@ -52,9 +37,8 @@ export function redactText(text, options = {}) {
52
37
  return text;
53
38
  let out = text;
54
39
  out = out.replace(PRIVATE_KEY_RE, '-----BEGIN PRIVATE KEY-----<redacted>-----END PRIVATE KEY-----');
55
- // A capture that was cut before the footer (`safeText` bounds every field before it redacts) leaves
56
- // a header with no END; the complete-block rule above cannot match it, so the body is dropped
57
- // explicitly. The placeholder from the rule above already carries an END and is left alone.
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.
58
42
  const strayBegin = out.lastIndexOf('-----BEGIN ');
59
43
  if (strayBegin >= 0 && strayBegin > out.lastIndexOf('-----END ')) {
60
44
  out = `${out.slice(0, strayBegin)}-----BEGIN PRIVATE KEY-----<redacted>`;
@@ -68,8 +52,7 @@ export function redactText(text, options = {}) {
68
52
  out = out.replace(BARE_TOKEN_RE, '$1$2<redacted>');
69
53
  out = out.replace(PASSWORD_FLAG_RE, '$1<redacted>');
70
54
  if (!options.keepPaths) {
71
- // Home directories of the remote account are not secrets, but avoid leaking
72
- // arbitrary local user names into exported diagnostics.
55
+ // Remote home directories are not secrets, but arbitrary local user names should not leak.
73
56
  out = out.replace(/(\/home\/)[^/\s]+/g, '$1<user>');
74
57
  out = out.replace(/(\/Users\/)[^/\s]+/g, '$1<user>');
75
58
  out = out.replace(/\b(C:\\Users\\)[^\\\s]+/gi, '$1<user>');
@@ -89,9 +72,7 @@ function redactValue(key, value) {
89
72
  return redactObject(value);
90
73
  return value;
91
74
  }
92
- /**
93
- * Deep-redact a JSON-compatible value.
94
- */
75
+ /** Deep-redact a JSON-compatible value. */
95
76
  export function redactObject(value) {
96
77
  if (Array.isArray(value))
97
78
  return value.map((item) => redactValue('', item));
@@ -1,16 +1,9 @@
1
- /**
2
- * Remote download entry: validate an absolute Linux path, inspect it, then hand it
3
- * to the local writer. Both files and folders stream directly to disk; no bytes are
4
- * buffered in the Host and no ZIP is created.
5
- */
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.
6
3
  import { errors, isRemoteGoError } from './errors.js';
7
4
  import { requireDestination, saveHostFile, saveHostFolder } from './local-download.js';
8
5
  import { normalizeRemoteFilePath } from './remote-path.js';
9
- /**
10
- * Save one file or one folder for a download job.
11
- * @param runtime - the connected host runtime.
12
- * @param rawPath - the requested absolute remote path.
13
- */
6
+ /** Save one file or one folder for a download job. */
14
7
  export async function readHostDownload(runtime, rawPath, options = {}) {
15
8
  if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
16
9
  throw errors.remoteFileUnavailable({
@@ -23,10 +16,9 @@ export async function readHostDownload(runtime, rawPath, options = {}) {
23
16
  if (typeof ssh.inspectRemotePath !== 'function') {
24
17
  throw errors.internal('the SSH transport does not support path inspection');
25
18
  }
26
- let destination;
27
19
  try {
28
20
  const info = await ssh.inspectRemotePath(remotePath);
29
- destination = await requireDestination(options.destination, { home: options.home });
21
+ const destination = await requireDestination(options.destination, { home: options.home });
30
22
  if (info.isFile)
31
23
  return await saveHostFile(runtime, remotePath, destination, options);
32
24
  if (info.isDirectory)
@@ -42,18 +34,14 @@ export async function readHostDownload(runtime, rawPath, options = {}) {
42
34
  throw toRemoteFileError(error);
43
35
  }
44
36
  }
45
- /**
46
- * Classify an SFTP failure without leaking transport internals to the client.
47
- * @param error - the transport error.
48
- * @returns a client-safe error.
49
- */
37
+ /** Classify an SFTP failure without leaking transport internals to the client. */
50
38
  export function toRemoteFileError(error) {
51
- // `isRemoteGoError` only declares a boolean (it lives in the P1a set); the `as` restates
52
- // the narrowing its `instanceof` proves at runtime.
39
+ // `isRemoteGoError` only declares a boolean; the `as` restates the narrowing its `instanceof`
40
+ // proves at runtime.
53
41
  if (isRemoteGoError(error))
54
42
  return error;
55
- // A transport error is `unknown`: the `as` restates the two fields an SFTP error carries
56
- // (`code` 2/3 for ENOENT/EACCES) and the `??` fallbacks keep a thrown string working.
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.
57
45
  const code = Number(error?.code);
58
46
  const message = String(error?.message ?? error ?? '');
59
47
  if (code === 2 || /no such file|not found/i.test(message)) {
@@ -3,55 +3,29 @@ import path from 'node:path';
3
3
  import { errors } from './errors.js';
4
4
  /** Longest accepted path, matching the remote contract of ordinary POSIX tools. */
5
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
- */
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. */
11
10
  export function normalizeRemoteFilePath(value) {
12
11
  if (typeof value !== 'string') {
13
- throw errors.invalidInput('path', {
14
- zh: '远端文件路径必须是字符串。',
15
- en: 'The remote file path must be a string.',
16
- });
12
+ throw invalidPath('远端文件路径必须是字符串。', 'The remote file path must be a string.');
17
13
  }
18
14
  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
- }
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.');
31
19
  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
- });
20
+ throw invalidPath('远端文件路径包含不可用的控制字符。', 'The remote file path contains unsupported control characters.');
42
21
  }
43
22
  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
- });
23
+ if (!normalized.startsWith('/') || !text.startsWith('/')) {
24
+ throw invalidPath('远端文件路径必须是绝对路径。', 'The remote file path must be absolute.');
49
25
  }
50
26
  return normalized;
51
27
  }
52
- /**
53
- * The suggested download name for a remote path: the last path segment, or a safe generic name.
54
- */
28
+ /** The suggested download name for a remote path: the last path segment, or a safe generic name. */
55
29
  export function remoteFileName(remotePath) {
56
30
  const name = path.posix.basename(remotePath);
57
31
  return name === '' || name === '/' || name === '.' || name === '..' ? 'download' : name;
@@ -67,35 +41,23 @@ export function safeLocalSegment(value) {
67
41
  text = '_' + text;
68
42
  return text;
69
43
  }
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
- */
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. */
76
47
  const IGNORED_LOCAL_NAMES = new Set(['desktop.ini', 'thumbs.db', 'ehthumbs.db', '.ds_store']);
77
48
  const IGNORED_LOCAL_SUFFIXES = ['.lnk', '.url'];
78
- /**
79
- * Whether a remote name must be left out of a local folder download.
80
- */
49
+ /** Whether a remote name must be left out of a local folder download. */
81
50
  export function isIgnoredLocalName(value) {
82
51
  const name = String(value ?? '')
83
52
  .trim()
84
53
  .toLowerCase();
85
- if (name === '')
86
- return false;
87
54
  if (IGNORED_LOCAL_NAMES.has(name))
88
55
  return true;
89
56
  return IGNORED_LOCAL_SUFFIXES.some((suffix) => name.endsWith(suffix));
90
57
  }
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
- */
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. */
99
61
  export function uniqueLocalPath(desired, taken, options = {}) {
100
62
  const key = (value) => localPathKey(value, options);
101
63
  if (!taken.has(key(desired)))
@@ -113,10 +75,7 @@ export function uniqueLocalPath(desired, taken, options = {}) {
113
75
  en: 'Too many remote files map to the same local file name to save them safely.',
114
76
  });
115
77
  }
116
- /**
117
- * The collision key of a local path: separator-normalized, and lowercased when the local
118
- * filesystem ignores case.
119
- */
78
+ /** The collision key of a local path: separator-normalized, and lowercased when the local filesystem ignores case. */
120
79
  export function localPathKey(value, options = {}) {
121
80
  const text = String(value ?? '').replace(/\\/g, '/');
122
81
  return options.caseInsensitive === true ? text.toLowerCase() : text;
@@ -1,6 +1,4 @@
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
- */
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. */
4
2
  import http from 'node:http';
5
3
  import { TUNNEL_PROBE_TIMEOUT_MS } from './constants.js';
6
4
  import { isPid, messageOf } from './util.js';
@@ -19,20 +17,13 @@ PS_OUT=$(ps -eww -o pid=,comm=,args= 2>/dev/null || ps -eo pid=,comm=,args= 2>/d
19
17
  printf '%s\\n' "$PS_OUT" | while IFS= read -r LINE; do
20
18
  [ -z "$LINE" ] && continue
21
19
  set -- $LINE
22
- PID=$1
23
- COMM=$2
24
- shift 2
25
- ARGS="$*"
20
+ PID=$1 COMM=$2
21
+ shift 2; ARGS="$*"
26
22
  [ -z "$PID" ] && continue
27
23
  case "$IGNORE" in *" $PID "*) continue ;; esac
28
24
  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
25
+ case "$ARGS" in *"@deepseek-ai/dsh"*|*"/bin/dsh "*|*" dsh "*) ;; *) continue ;; esac
26
+ case "$ARGS" in *"ps -eww"*|*"PS_OUT"*|*"IGNORE"*) continue ;; esac
36
27
  ENV_HOME=$(tr '\\0' '\\n' < "/proc/$PID/environ" 2>/dev/null | sed -n 's/^DSH_HOME=//p' | tail -n 1)
37
28
  if [ -n "\${ENV_HOME:-}" ] && [ "$ENV_HOME" != "$HOME/.dsh" ]; then continue; fi
38
29
  printf '%s\\t%s\\n' "$PID" "$ARGS"
@@ -52,31 +43,26 @@ export function parseForeignDshOutput(stdout) {
52
43
  }
53
44
  return processes;
54
45
  }
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
- */
46
+ /** Find DSH processes on the remote that this plugin did not start; never throws, because a broken scan must not block connecting. */
61
47
  export async function findForeignDshProcesses(ssh, options = {}) {
48
+ const failed = (technical) => ({
49
+ ok: false,
50
+ processes: [],
51
+ reason: 'exec-failed',
52
+ technical,
53
+ });
62
54
  try {
63
55
  const result = await ssh.exec(buildForeignDshCommand(options.ignorePids ?? []), {
64
56
  timeoutMs: options.timeoutMs ?? 20_000,
65
57
  maxBytes: 200_000,
66
58
  });
67
- if (result.code !== 0) {
68
- return { ok: false, processes: [], reason: 'exec-failed', technical: String(result.stderr ?? '').slice(0, 500) };
69
- }
59
+ if (result.code !== 0)
60
+ return failed(String(result.stderr ?? '').slice(0, 500));
70
61
  return { ok: true, processes: parseForeignDshOutput(result.stdout) };
71
62
  }
72
63
  catch (error) {
73
64
  // 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
- };
65
+ return failed(messageOf(error));
80
66
  }
81
67
  }
82
68
  export async function stopForeignDshProcesses(ssh, processes, options = {}) {
@@ -90,21 +76,13 @@ PIDS="${pids.join(' ')}"
90
76
  for PID in $PIDS; do kill -TERM "$PID" 2>/dev/null || true; done
91
77
  i=0
92
78
  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
79
+ ALIVE=0; for PID in $PIDS; do if kill -0 "$PID" 2>/dev/null; then ALIVE=1; fi; done
97
80
  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
81
+ i=$((i+1)); sleep 0.5
103
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
104
84
  sleep 0.2
105
- for PID in $PIDS; do
106
- if kill -0 "$PID" 2>/dev/null; then echo "ALIVE:$PID"; fi
107
- done
85
+ for PID in $PIDS; do if kill -0 "$PID" 2>/dev/null; then echo "ALIVE:$PID"; fi; done
108
86
  echo "STOPPED"
109
87
  `;
110
88
  try {
@@ -118,14 +96,7 @@ echo "STOPPED"
118
96
  return { ok: false, alive: pids, output: messageOf(error) };
119
97
  }
120
98
  }
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
- */
99
+ /** TCP ports a pid is listening on, read from its own `/proc` network tables and matched against the socket inodes it holds. */
129
100
  export async function remoteListenPorts(ssh, pid) {
130
101
  if (!isPid(pid))
131
102
  return [];
@@ -133,10 +104,7 @@ export async function remoteListenPorts(ssh, pid) {
133
104
  PID=${pid}
134
105
  [ -d "/proc/$PID" ] || exit 0
135
106
  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
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
140
108
  `;
141
109
  try {
142
110
  const result = await ssh.exec(script, { timeoutMs: 15_000 });
@@ -147,7 +115,6 @@ done
147
115
  return [];
148
116
  }
149
117
  }
150
- /** Decode the `INODE:` / `LISTEN:<addr-hex>:<port-hex>:<inode>` lines of {@link remoteListenPorts}. */
151
118
  export function parseListenPorts(stdout) {
152
119
  const inodes = new Set();
153
120
  const ports = [];
@@ -166,14 +133,7 @@ export function parseListenPorts(stdout) {
166
133
  }
167
134
  return [...new Set(ports.filter((entry) => inodes.has(entry.inode)).map((entry) => entry.port))].sort((left, right) => left - right);
168
135
  }
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
- */
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. */
177
137
  export async function remotePortOwnerPid(ssh, port) {
178
138
  if (!isPid(port) || port > 65535)
179
139
  return null;
@@ -182,10 +142,7 @@ PORT_HEX=$(printf '%04X' ${port})
182
142
  INODE=$(awk -v p=":$PORT_HEX" '$2 ~ p"$" && $4 == "0A" { print $10; exit }' /proc/net/tcp 2>/dev/null)
183
143
  [ -n "\${INODE:-}" ] || exit 0
184
144
  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
145
+ if ls -l "$D/fd" 2>/dev/null | grep -q "socket:\\[\${INODE}\\]"; then echo "PID:\${D#/proc/}"; exit 0; fi
189
146
  done
190
147
  `;
191
148
  try {
@@ -199,29 +156,17 @@ done
199
156
  return null;
200
157
  }
201
158
  }
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
- */
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. */
212
160
  export async function remoteProcessIdentity(ssh, pid) {
213
161
  if (!isPid(pid))
214
162
  return { ok: false, reason: 'invalid-pid' };
215
163
  const script = `set -u
216
164
  PID=${pid}
217
165
  [ -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
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
222
168
  printf 'START:%s\\n' "\${20}"
223
- CMD=$(tr '\\0' ' ' < "/proc/$PID/cmdline" 2>/dev/null || true)
224
- printf 'CMD:%s\\n' "$CMD"
169
+ CMD=$(tr '\\0' ' ' < "/proc/$PID/cmdline" 2>/dev/null || true); printf 'CMD:%s\\n' "$CMD"
225
170
  HOME_LINE=$(tr '\\0' '\\n' < "/proc/$PID/environ" 2>/dev/null | sed -n 's/^DSH_HOME=//p' | tail -n 1)
226
171
  printf 'DSH_HOME:%s\\n' "\${HOME_LINE:-}"
227
172
  `;
@@ -234,11 +179,9 @@ printf 'DSH_HOME:%s\\n' "\${HOME_LINE:-}"
234
179
  return { ok: false, reason: 'unreadable' };
235
180
  }
236
181
  }
237
- /** Decode the `START:` / `CMD:` / `DSH_HOME:` lines of {@link remoteProcessIdentity}. */
238
182
  export function parseProcessIdentity(stdout) {
239
183
  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).
184
+ // Matched anywhere in the output deliberately: a command line containing MISSING/NO-STAT must not read as an identity.
242
185
  if (text.includes('MISSING'))
243
186
  return { ok: false, reason: 'missing' };
244
187
  if (text.includes('NO-STAT'))
@@ -248,22 +191,14 @@ export function parseProcessIdentity(stdout) {
248
191
  if (!start || !command)
249
192
  return { ok: false, reason: 'unreadable' };
250
193
  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
- };
194
+ return { ok: true, startTime: start[1], command: command[1].trim(), dshHome: home === null ? '' : home[1].trim() };
257
195
  }
258
196
  export async function remoteHttpStatus(ssh, port) {
259
197
  if (!isPid(port))
260
198
  return null;
261
199
  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
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
267
202
  `;
268
203
  try {
269
204
  const result = await ssh.exec(script, { timeoutMs: 15_000 });
@@ -290,17 +225,14 @@ export async function exchangeTokenOverTunnel(localPort, token, options = {}) {
290
225
  const timeoutMs = options.timeoutMs ?? TUNNEL_PROBE_TIMEOUT_MS;
291
226
  const basePath = options.path ?? '/';
292
227
  const tokenPath = `/?token=${encodeURIComponent(token)}`;
293
- const first = await httpRequest({
294
- port: localPort,
295
- path: basePath === '/' ? tokenPath : `${basePath}?token=${encodeURIComponent(token)}`,
296
- timeoutMs,
297
- });
228
+ const path = basePath === '/' ? tokenPath : `${basePath}?token=${encodeURIComponent(token)}`;
229
+ const first = await httpRequest({ port: localPort, path, timeoutMs });
298
230
  const setCookies = first.headers['set-cookie'] ?? [];
299
231
  const cookieHeader = setCookies.map((cookie) => String(cookie).split(';')[0]).join('; ');
300
- const location = first.headers.location ?? null;
232
+ const back = first.headers.location?.startsWith('/') ? first.headers.location : '/';
301
233
  const second = await httpRequest({
302
234
  port: localPort,
303
- path: location && location.startsWith('/') ? location : '/',
235
+ path: back,
304
236
  timeoutMs,
305
237
  headers: cookieHeader ? { cookie: cookieHeader } : {},
306
238
  });
@@ -1,43 +1,22 @@
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
- */
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. */
8
3
  import { DEFAULT_REMOTE_PROFILE } from '../constants.js';
9
4
  import { errors } from '../errors.js';
10
5
  import { isPid, messageOf, nowIso, shellQuote } from '../util.js';
11
6
  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
7
  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
8
  export function parseRunRegistry(text) {
26
9
  const raw = String(text ?? '').trim();
27
10
  if (raw === '')
28
11
  return null;
29
12
  try {
30
13
  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
14
  return isPlainObjectValue(parsed) ? parsed : null;
34
15
  }
35
16
  catch {
36
17
  // swallow-ok: fall through to the field-by-field recovery below
37
18
  }
38
19
  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
20
  const number = (name) => Number(new RegExp(`"${name}"\\s*:\\s*(\\d+)\\s*[,}]`).exec(raw)?.[1] ?? 0);
42
21
  const pid = number('pid');
43
22
  if (!isPid(pid))
@@ -54,7 +33,6 @@ export function parseRunRegistry(text) {
54
33
  origin: field('origin'),
55
34
  };
56
35
  }
57
- /** A JSON object (an array included): the shape `parseRunRegistry` accepts without inspection. */
58
36
  export function isPlainObjectValue(value) {
59
37
  return value !== null && typeof value === 'object';
60
38
  }
@@ -69,12 +47,12 @@ export async function readRunRegistry(ssh, layout) {
69
47
  return null;
70
48
  }
71
49
  }
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
- */
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
+ }
78
56
  export function buildRunRegistryRecord(input = {}) {
79
57
  const pid = Number(input.pid ?? 0);
80
58
  const port = Number(input.port ?? 0);
@@ -94,38 +72,22 @@ export function buildRunRegistryRecord(input = {}) {
94
72
  version: normalizeVersion(input.version ?? ''),
95
73
  dshHome,
96
74
  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
75
  origin: input.origin === 'reattach' ? 'reattach' : 'launch',
100
76
  };
101
77
  }
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
78
  export async function clearRunRegistry(ssh, layout) {
108
79
  try {
109
80
  const result = await ssh.exec(`rm -f ${shellQuote(layout.runFile)}`, { timeoutMs: 10_000 });
110
81
  return { ok: result.code === 0, output: String(result.stdout ?? '').trim() };
111
82
  }
112
83
  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
84
+ // swallow-ok: returned as ok:false and logged by the caller; the next connect re-checks the
115
85
  return { ok: false, output: messageOf(error) };
116
86
  }
117
87
  }
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
88
  export async function writeRunRegistry(ssh, layout, record) {
126
89
  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).
90
+ // Temp file + rename: a concurrent reader sees the old record or the new one, never a truncated line.
129
91
  const script = `set -eu
130
92
  umask 077
131
93
  mkdir -p ${shellQuote(layout.runDir)}
@@ -140,8 +102,6 @@ echo "REGISTRY-WRITTEN"
140
102
  return { ok: result.code === 0 && result.stdout.includes('REGISTRY-WRITTEN'), output: result.stdout.trim() };
141
103
  }
142
104
  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
105
  return { ok: false, output: messageOf(error) };
146
106
  }
147
107
  }