dsh-remote-go 0.3.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 (85) hide show
  1. package/dist/client.js +1344 -2095
  2. package/dist/src/admission.js +3 -28
  3. package/dist/src/api.js +37 -99
  4. package/dist/src/atomic-json.js +32 -66
  5. package/dist/src/bootstrap.js +17 -27
  6. package/dist/src/connect/attach.js +3 -25
  7. package/dist/src/connect/bootstrap.js +2 -8
  8. package/dist/src/connect/failures.js +3 -18
  9. package/dist/src/connect/guards.js +13 -8
  10. package/dist/src/connect/launch.js +11 -21
  11. package/dist/src/connect/links.js +11 -27
  12. package/dist/src/connect/ownership.js +33 -114
  13. package/dist/src/connect/pipeline.js +61 -158
  14. package/dist/src/connect/reattach.js +20 -44
  15. package/dist/src/connect/registry.js +0 -1
  16. package/dist/src/connect/repair.js +8 -37
  17. package/dist/src/connect/restart.js +36 -97
  18. package/dist/src/connect/stop.js +16 -50
  19. package/dist/src/connect/transport.js +10 -18
  20. package/dist/src/connect/verify.js +3 -12
  21. package/dist/src/connect/watchdog.js +6 -38
  22. package/dist/src/connect-log.js +16 -41
  23. package/dist/src/connect-progress.js +13 -45
  24. package/dist/src/constants.js +2 -40
  25. package/dist/src/context.js +10 -31
  26. package/dist/src/diagnostics.js +56 -25
  27. package/dist/src/download-jobs.js +11 -20
  28. package/dist/src/errors.js +175 -190
  29. package/dist/src/events.js +20 -84
  30. package/dist/src/host-lifecycle.js +39 -175
  31. package/dist/src/host-registry.js +27 -78
  32. package/dist/src/host-runtime.js +0 -9
  33. package/dist/src/host-view.js +6 -29
  34. package/dist/src/index.js +15 -35
  35. package/dist/src/kernel-adapter.js +34 -80
  36. package/dist/src/key-files.js +10 -23
  37. package/dist/src/known-hosts.js +13 -34
  38. package/dist/src/layout.js +3 -20
  39. package/dist/src/local-download.js +94 -163
  40. package/dist/src/local-ssh.js +12 -19
  41. package/dist/src/local-version.js +35 -49
  42. package/dist/src/node/download.js +1 -4
  43. package/dist/src/node-runtime.js +19 -38
  44. package/dist/src/probe.js +6 -7
  45. package/dist/src/prompts.js +56 -128
  46. package/dist/src/proxy/cookies.js +26 -60
  47. package/dist/src/proxy/headers.js +30 -125
  48. package/dist/src/proxy/http.js +33 -41
  49. package/dist/src/proxy/index.js +20 -34
  50. package/dist/src/proxy/limits.js +4 -6
  51. package/dist/src/proxy/routes.js +10 -17
  52. package/dist/src/proxy/upgrade.js +27 -42
  53. package/dist/src/redact.js +14 -33
  54. package/dist/src/remote-files.js +9 -21
  55. package/dist/src/remote-path.js +21 -62
  56. package/dist/src/remote-proc.js +35 -103
  57. package/dist/src/remote-web/registry.js +10 -50
  58. package/dist/src/remote-web/resolve.js +23 -104
  59. package/dist/src/remote-web/start.js +27 -64
  60. package/dist/src/remote-web/stop.js +6 -25
  61. package/dist/src/request-trust.js +15 -32
  62. package/dist/src/runtime/dispatch.js +33 -143
  63. package/dist/src/runtime/effects.js +7 -17
  64. package/dist/src/runtime/events.js +1 -1
  65. package/dist/src/runtime/fsm.js +11 -61
  66. package/dist/src/runtime/rules.js +113 -198
  67. package/dist/src/secrets.js +15 -38
  68. package/dist/src/service.js +22 -128
  69. package/dist/src/settings.js +41 -42
  70. package/dist/src/ssh-config.js +22 -41
  71. package/dist/src/ssh-failures.js +23 -74
  72. package/dist/src/ssh-sftp.js +47 -86
  73. package/dist/src/ssh.js +95 -177
  74. package/dist/src/store.js +31 -48
  75. package/dist/src/tool-shared.js +17 -52
  76. package/dist/src/tools-exec-policy.js +33 -79
  77. package/dist/src/tools-exec.js +87 -151
  78. package/dist/src/tools-report.js +100 -167
  79. package/dist/src/tools.js +59 -133
  80. package/dist/src/tunnel.js +9 -27
  81. package/dist/src/util.js +19 -56
  82. package/dist/src/version.js +6 -12
  83. package/dist/src/watchdog-bus.js +0 -8
  84. package/dist/src/watchdog.js +7 -47
  85. package/package.json +1 -1
@@ -1,6 +1,4 @@
1
- /**
2
- * The client-facing view of one host (docs/api.md HostView).
3
- */
1
+ /** The client-facing view of one host (docs/api.md HostView). */
4
2
  import { versionParity } from './version.js';
5
3
  import { connectLogTail, connectLogVisible } from './connect-log.js';
6
4
  export function hostView(runtime, ctx, options = {}) {
@@ -9,23 +7,13 @@ export function hostView(runtime, ctx, options = {}) {
9
7
  id: runtime.id,
10
8
  name: entry.name,
11
9
  address: entry.address,
10
+ // Presentation only: the editor must never parse this form back (a bare IPv6 such as
11
+ // `fe80::1` used to yield port 1 and silently replace the default port with 22).
12
12
  addressMasked: maskAddress(entry),
13
- /**
14
- * The plain connection fields. The masked address is presentation only: the editor must not
15
- * parse it back (a bare IPv6 like `fe80::1` used to yield port 1, and the default port was
16
- * silently replaced by 22). Never a secret.
17
- */
18
13
  username: entry.username ?? null,
19
14
  port: entry.port ?? 22,
20
- /** Never the secret itself; lets the Client ask for a one-time password. */
21
15
  authType: entry.auth?.type ?? 'key',
22
- /** The configured key file path (not a secret); lets the edit form prefill it. */
23
16
  authKeyPath: entry.auth?.type === 'key' && typeof entry.auth.keyPath === 'string' ? entry.auth.keyPath : null,
24
- /**
25
- * Whether a remembered password exists in the credential store (never the value). The
26
- * runtime mirror is restored from the store on load, so this stays true across a DSH
27
- * restart while a one-time password used for this connection alone stays false.
28
- */
29
17
  passwordSaved: entry.auth?.type === 'password' ? runtime.passwordSaved === true : false,
30
18
  passwordStorageAvailable: ctx.passwordStorageAvailable,
31
19
  jumpHost: entry.jumpHost ?? null,
@@ -39,10 +27,7 @@ export function hostView(runtime, ctx, options = {}) {
39
27
  logs: options.logs === false ? [] : connectLogVisible(runtime.status) ? connectLogTail(runtime) : [],
40
28
  logAttempt: typeof runtime.connectCount === 'number' ? runtime.connectCount : 0,
41
29
  logSeq: typeof runtime.logSeq === 'number' ? runtime.logSeq : 0,
42
- remote: {
43
- ...runtime.remote,
44
- version: runtime.remote.version ?? null,
45
- },
30
+ remote: { ...runtime.remote, version: runtime.remote.version ?? null },
46
31
  keepAlive: entry.keepAlive,
47
32
  idleMinutes: entry.idleMinutes,
48
33
  autoReconnect: entry.autoReconnect,
@@ -52,19 +37,11 @@ export function hostView(runtime, ctx, options = {}) {
52
37
  updatedAt: entry.updatedAt,
53
38
  targetVersion: ctx.targetVersion,
54
39
  versionParity: versionParity(ctx.targetVersion, runtime.remote.version ?? null),
55
- /**
56
- * True when `hosts.json` was unreadable on load: this list is the recovered fallback, and a
57
- * copy of the damaged file is kept next to it (`hosts.json.corrupt-<timestamp>`). Contract
58
- * field only — the Client renders it as a warning (docs/api.md HostView).
59
- */
60
40
  storeCorrupt: ctx.storeCorrupt === true,
61
41
  };
62
42
  }
63
- /**
64
- * The display form of the endpoint: `user@host`, `user@host:2222`, and bracketed IPv6
65
- * (`user@[fe80::1]`, `user@[fe80::1]:2222`). The port is omitted only for SSH's default 22, which
66
- * is why the Client reads `port`/`username` instead of parsing this string.
67
- */
43
+ /** The display form of the endpoint (`user@host`, `user@host:2222`, bracketed IPv6); the port is omitted only for SSH's
44
+ * default 22, which is why the Client reads `port`/`username` instead of parsing this string. */
68
45
  export function maskAddress(entry) {
69
46
  const port = entry.port && entry.port !== 22 ? `:${entry.port}` : '';
70
47
  const user = entry.username ? `${entry.username}@` : '';
package/dist/src/index.js CHANGED
@@ -1,7 +1,5 @@
1
- /**
2
- * dsh-remote-go — Host half: registers the local HTTP API and the browser half's same-origin remote proxy,
3
- * and owns the SSH / bootstrap / tunnel lifecycle; it never copies remote data.
4
- */
1
+ /** dsh-remote-go — Host half: registers the local HTTP API and the browser half's same-origin remote proxy, and owns
2
+ * the SSH / bootstrap / tunnel lifecycle; it never copies remote data. */
5
3
  import { API_PREFIX, PLUGIN_ID, REMOTE_VIEW_PREFIX } from './constants.js';
6
4
  import { statSync } from 'node:fs';
7
5
  import { createAdmission } from './admission.js';
@@ -19,13 +17,12 @@ export const inject = ['webServer'];
19
17
  export const optional = ['connection', 'credentials'];
20
18
  export function apply(ctx, config = {}) {
21
19
  const logger = createLogger();
22
- // The kernel's own metadata (loader fiber, client-module registry) is read through one adapter,
23
- // so `/diagnostics/self` and every future kernel probe share the same three-state answers.
20
+ // The kernel's own metadata (loader fiber, client-module registry) is read through one adapter, so
21
+ // `/diagnostics/self` and every future kernel probe share the same three-state answers.
24
22
  const kernel = createKernelAdapter(ctx);
25
23
  const home = config.home ? String(config.home) : resolveDshHome(process.env);
26
24
  const stateDir = resolveStateDir(home);
27
25
  const store = new HostStore({ dir: stateDir, logger });
28
- // Saved SSH passwords live in DSH's credential store, never in hosts.json.
29
26
  const secrets = createSecretStore({ ctx, logger });
30
27
  const service = new RemoteGoService({
31
28
  store,
@@ -43,9 +40,8 @@ export function apply(ctx, config = {}) {
43
40
  return null;
44
41
  }
45
42
  };
46
- // DSH's own admission for every route this plugin serves: the kernel's Host/Origin fence plus
47
- // browser-session authentication. `connection` is optional, so the gate hands the request to the
48
- // plugin's own fence when the service is absent (see admission.js).
43
+ // DSH's own admission for every route this plugin serves; `connection` is optional, so the gate
44
+ // hands the request to the plugin's own fence when the service is absent (see admission.ts).
49
45
  const admit = createAdmission(ctx, logger);
50
46
  const api = createApi({
51
47
  service,
@@ -60,14 +56,13 @@ export function apply(ctx, config = {}) {
60
56
  storeCorrupt: store.hostsCorrupt,
61
57
  }),
62
58
  });
63
- // The browser half's remote window lives on the local origin (the desktop half uses a guest
64
- // instead), so the same-origin proxy is the only thing that needs to know how to reach a tunnel.
59
+ // The browser half's remote window lives on the local origin, so the same-origin proxy is the only
60
+ // thing that needs to know how to reach a tunnel.
65
61
  const proxy = createRemoteProxy({
66
62
  webServer: ctx.webServer,
67
63
  getOrigin,
68
64
  admit,
69
65
  resolveHost: (id) => service.webViewTarget(id),
70
- // A failed upstream is a suspicion, not a restart: the service confirms it with probes.
71
66
  onUpstreamError: (id) => service.noteUpstreamFailure(id),
72
67
  logger,
73
68
  });
@@ -84,8 +79,6 @@ export function apply(ctx, config = {}) {
84
79
  path: proxy.routePath,
85
80
  handler: (req, res) => proxy.handle(req, res),
86
81
  });
87
- // The model-facing host list lives on the Host half only: a local LLM session reads the same
88
- // snapshot the switcher renders, and the remote DSH never loads this package.
89
82
  const disposeTools = registerHostTools(ctx, {
90
83
  service,
91
84
  logger,
@@ -102,11 +95,9 @@ export function apply(ctx, config = {}) {
102
95
  const detected = await detectLocalVersion({ ctx, logger });
103
96
  if (detected.version)
104
97
  service.setLocalVersion(detected.version, detected.source);
105
- // The managed Node version is the lower bound of DSH's own `engines.node`;
106
- // reading it here keeps the plugin in step with the running DSH build.
98
+ // The managed Node version is the lower bound of DSH's own `engines.node`, read here to stay
99
+ // in step with the running DSH build.
107
100
  const engine = await detectLocalEnginesNode({ ctx });
108
- // `setLocalEnginesNode` has always taken one parameter; the source is not persisted there
109
- // (only `setLocalVersion` reports where its value came from).
110
101
  if (engine.range)
111
102
  service.setLocalEnginesNode(engine.range);
112
103
  if (!detected.version)
@@ -136,20 +127,14 @@ export function apply(ctx, config = {}) {
136
127
  }, 'dsh-remote-go: http api + service');
137
128
  return service;
138
129
  }
139
- /**
140
- * The `/diagnostics/self` body: the installation facts plus the kernel probe table.
141
- *
142
- * Every kernel read goes through `kernel-adapter.ts`, whose three states map onto this document the
143
- * same way everywhere: `ok` fills the historical field, `absent`/`changed` leave it `null` (exactly
144
- * what a missing service used to do) and `kernel.probes` says which of the two it was.
145
- */
130
+ /** The `/diagnostics/self` body: every kernel read goes through `kernel-adapter.ts`, whose three states map the same
131
+ * way everywhere (`ok` fills the field, `absent`/`changed` leave it `null` and `probes` says which). */
146
132
  function describeSelf(kernel, info) {
147
133
  const out = {
148
134
  home: info.home,
149
135
  stateDir: info.stateDir,
150
136
  hostVersion: info.localVersion,
151
137
  engineNodeRange: info.engineNodeRange ?? null,
152
- // True when hosts.json was unreadable and the list beside it is the recovered fallback.
153
138
  storeCorrupt: info.storeCorrupt === true,
154
139
  entry: null,
155
140
  client: null,
@@ -192,16 +177,11 @@ function describeSelf(kernel, info) {
192
177
  }
193
178
  function createLogger() {
194
179
  const tag = '[dsh-remote-go]';
180
+ // The sink is resolved per call, not captured: an embedding shell may replace `console.*` after
181
+ // `apply()`, and a captured function would keep writing to the old one.
195
182
  const write = (level, args) => {
196
- const sink = level === 'debug'
197
- ? console.debug
198
- : level === 'error'
199
- ? console.error
200
- : level === 'warn'
201
- ? console.warn
202
- : console.info;
203
183
  try {
204
- sink?.call(console, tag, ...args);
184
+ console[level]?.call(console, tag, ...args);
205
185
  }
206
186
  catch {
207
187
  // swallow-ok: logging must never throw into the host
@@ -1,25 +1,8 @@
1
- /**
2
- * The kernel introspection adapter (review #7; design-contract §3): the one module that reads
3
- * DSH's own shapes — the loader fiber, the client-module registry, and the two optional services
4
- * this plugin borrows (`connection` for request admission, `credentials` for saved SSH passwords).
5
- *
6
- * Why an adapter instead of four local `try/catch` blocks: these are somebody else's internals, and
7
- * the plugin has to tell two very different failures apart. A kernel that never provided a service
8
- * must keep working exactly as it did (the local fence, the replicated key grammar, the
9
- * `package.json` version scan), while a kernel that still provides the service but moved a field
10
- * must never be mistaken for that older one. Hence three states, decided in one fixed order:
11
- *
12
- * take the candidate → empty means `absent` → non-empty but the wrong shape means `changed`
13
- * → right shape but the call throws *also* means `changed`
14
- *
15
- * Callers may fall back on `absent`; they must degrade safely on `changed`. The security-relevant
16
- * one is the admission gate: a check that cannot decide answers `500` (invariant B9), never
17
- * "admitted". The same reading of `changed` is what keeps a moved credential grammar from being
18
- * read as "no credentials" (a silent fallback) or as "everything is fine".
19
- */
1
+ /** The kernel introspection adapter reads DSH's own shapes (loader fiber, client modules, `connection`, `credentials`)
2
+ * as `ok`/`absent`/`changed`: callers fall back on `absent` and degrade safely on `changed` — never "admitted". */
20
3
  import { PLUGIN_ID } from './constants.js';
21
4
  import { isPlainObject, messageOf } from './util.js';
22
- /** The contract version of the probe table (design-contract §3.5); additive changes bump it. */
5
+ /** The contract version of the probe table; additive changes bump it. */
23
6
  export const KERNEL_PROBE_VERSION = '2.12';
24
7
  /** The `dsh-credentials` segment grammar (`KEY_SEGMENT_PATTERN` in that package). */
25
8
  const KEY_SEGMENT = /^[a-z][a-z0-9-]*$/;
@@ -59,22 +42,21 @@ function propagate(failed) {
59
42
  reason: failed.reason,
60
43
  };
61
44
  }
62
- /**
63
- * Bind one untyped service member to its owner.
64
- *
65
- * The kernel's services are classes; a method detached from its instance loses `this`, so every
66
- * call goes through `Reflect.apply` on the resolved owner instead of an assertion on the member.
67
- * @param member - the member the shape check already proved callable.
68
- * @param owner - the service object it was read from.
69
- * @returns a callable that forwards every argument unchanged.
70
- */
45
+ /** Bind one untyped service member to its owner: a detached class method loses `this`, so calls go through
46
+ * `Reflect.apply` instead of an assertion on the member. */
71
47
  function bindMember(member, owner) {
72
48
  return (...args) => Reflect.apply(member, owner, args);
73
49
  }
74
- /**
75
- * Read one revision tag (a string or a number in DSH's own history) without guessing.
76
- * @returns the value, `null` when the field is absent, or `undefined` when it is the wrong type.
77
- */
50
+ /** One member of an untyped service, narrowed to a callable bound to its owner, or why it is not one. */
51
+ function callableOf(owner, name, label) {
52
+ const member = owner[name];
53
+ if (member === undefined)
54
+ return absent(`${label} has no ${name}()`);
55
+ if (typeof member !== 'function')
56
+ return changed(`${label}.${name} is ${describeType(member)}`);
57
+ return ok(bindMember(member, owner), `${label}.${name} is callable`);
58
+ }
59
+ /** Read one revision tag (a string or a number in DSH's own history) without guessing. */
78
60
  function readRev(value) {
79
61
  if (value === undefined || value === null)
80
62
  return null;
@@ -82,13 +64,8 @@ function readRev(value) {
82
64
  return value;
83
65
  return undefined;
84
66
  }
85
- /**
86
- * `ctx.get(name)` without trusting either the context or the lookup.
87
- *
88
- * A context that is not an object, has no `get`, or throws is *absence*: the adapter could not see
89
- * the service, which is exactly what an older composition looks like. It is never `changed`,
90
- * because "I could not read it" says nothing about the shape behind it (design-contract §3.4, T-f).
91
- */
67
+ /** `ctx.get(name)` trusting neither side: a non-object context, a missing `get` or a throw is *absence*, never
68
+ * `changed` — "could not read it" says nothing about the shape behind it. */
92
69
  function lookupService(ctx, name) {
93
70
  if (!isPlainObject(ctx))
94
71
  return absent('the plugin context is not an object');
@@ -125,22 +102,13 @@ function line(probe) {
125
102
  return { state: 'changed', detail: `probe threw: ${messageOf(error)}` };
126
103
  }
127
104
  }
128
- /**
129
- * Build the adapter for one kernel context.
130
- *
131
- * `ctx` is `unknown` on purpose: it comes from the loader and every member below is narrowed by a
132
- * shape check before use, so a kernel that renames or drops a member is reported instead of
133
- * crashing the Host process at call time. Probes are cheap and stateless, so a caller may keep one
134
- * adapter or build one per call; `probeReport()` is the only method that runs all of them.
135
- * @param ctx - the plugin context the loader handed to `apply`.
136
- * @returns the adapter.
137
- */
105
+ /** Build the adapter for one kernel context: `ctx` is `unknown` on purpose (it comes from the loader and every member
106
+ * is shape-checked first, so a renamed member is reported, not a crash). `probeReport()` runs every probe at once. */
138
107
  export function createKernelAdapter(ctx) {
139
108
  /** The `clientModules` service: `ctx.get` first, then the property `ctx.clientModules` (its fallback). */
140
109
  function clientModules() {
141
110
  const looked = lookupService(ctx, 'clientModules');
142
- // A throwing lookup is not retried through the property: the historical code read the property
143
- // only when `get` returned nothing, and a throw says the same "cannot see it" (T-f).
111
+ // A throwing lookup is not retried through the property: the old code read it only when `get` returned nothing.
144
112
  if (looked.reason === 'lookup-failed')
145
113
  return propagate(looked);
146
114
  if (looked.state === 'ok' && looked.value !== null) {
@@ -155,27 +123,19 @@ export function createKernelAdapter(ctx) {
155
123
  return changed(`clientModules is ${describeType(direct)}`);
156
124
  return absent('clientModules is not injected');
157
125
  }
158
- /**
159
- * The published graph object, or why it could not be read.
160
- *
161
- * Validation stops at the object boundary on purpose: the release version, the revision tag and
162
- * the entry list are read by different consumers (the version probe needs only the release, the
163
- * diagnostics row needs the entries), so each probe narrows the fields *it* reads instead of
164
- * failing the others. A kernel that grows a field must not switch off a probe that never read it.
165
- */
126
+ /** The published graph object, or why it could not be read. Validation stops at the object boundary: each probe
127
+ * narrows only the fields *it* reads, so a kernel that grows a field cannot switch a probe off. */
166
128
  function readGraph() {
167
129
  const service = clientModules();
168
130
  if (service.state !== 'ok' || service.value === null)
169
131
  return propagate(service);
170
132
  const owner = service.value;
171
- const graphMember = owner.graph;
172
- if (graphMember === undefined)
173
- return absent('clientModules has no graph()');
174
- if (typeof graphMember !== 'function')
175
- return changed(`clientModules.graph is ${describeType(graphMember)}`);
133
+ const graph = callableOf(owner, 'graph', 'clientModules');
134
+ if (graph.state !== 'ok' || graph.value === null)
135
+ return propagate(graph);
176
136
  let raw;
177
137
  try {
178
- raw = bindMember(graphMember, owner)();
138
+ raw = graph.value();
179
139
  }
180
140
  catch (error) {
181
141
  return changed(`clientModules.graph() threw: ${messageOf(error)}`, 'call-failed');
@@ -193,13 +153,10 @@ export function createKernelAdapter(ctx) {
193
153
  return propagate(looked);
194
154
  if (!isPlainObject(looked.value))
195
155
  return changed(`connection is ${describeType(looked.value)}`);
196
- const owner = looked.value;
197
- const member = owner.requestRejection;
198
- if (member === undefined)
199
- return absent('connection has no requestRejection()');
200
- if (typeof member !== 'function')
201
- return changed(`connection.requestRejection is ${describeType(member)}`);
202
- return ok(bindMember(member, owner), 'connection admission is callable');
156
+ const member = callableOf(looked.value, 'requestRejection', 'connection');
157
+ if (member.state !== 'ok' || member.value === null)
158
+ return propagate(member);
159
+ return ok(member.value, 'connection admission is callable');
203
160
  }
204
161
  const adapter = {
205
162
  fiberEntry() {
@@ -306,15 +263,12 @@ export function createKernelAdapter(ctx) {
306
263
  const service = clientModules();
307
264
  if (service.state !== 'ok' || service.value === null)
308
265
  return propagate(service);
309
- const owner = service.value;
310
- const member = owner.clientPath;
311
- if (member === undefined)
312
- return absent('clientModules has no clientPath()');
313
- if (typeof member !== 'function')
314
- return changed(`clientModules.clientPath is ${describeType(member)}`);
266
+ const member = callableOf(service.value, 'clientPath', 'clientModules');
267
+ if (member.state !== 'ok' || member.value === null)
268
+ return propagate(member);
315
269
  let raw;
316
270
  try {
317
- raw = bindMember(member, owner)(id);
271
+ raw = member.value(id);
318
272
  }
319
273
  catch (error) {
320
274
  return changed(`clientModules.clientPath() threw: ${messageOf(error)}`, 'call-failed');
@@ -1,6 +1,5 @@
1
- /**
2
- * Read-only directory browsing for the key-file picker; a path that resolves outside the user home directory (through `..` or a symlink) is refused.
3
- */
1
+ /** Read-only directory browsing for the key-file picker; a path that resolves outside the user home directory (through
2
+ * `..` or a symlink) is refused. */
4
3
  import { promises as fs } from 'node:fs';
5
4
  import path from 'node:path';
6
5
  import { expandHome } from './util.js';
@@ -10,28 +9,21 @@ export const OUTSIDE_HOME = 'EOUTSIDEHOME';
10
9
  export async function listKeyFiles(options) {
11
10
  const home = path.resolve(options.home);
12
11
  const impl = options.fsImpl ?? fs;
13
- // Canonical base: the home directory spelled the way the filesystem reports it.
14
- // Every path below derives from this one spelling, so the returned `path` and
15
- // `parent` can never disagree — Windows hands out an 8.3 short path
16
- // (`C:\Users\RUNNER~1\…`) for a directory that realpath reports in long form.
12
+ // Canonical base: the home directory as the filesystem reports it, so `path` and `parent` cannot disagree — Windows
13
+ // hands out an 8.3 short path (`C:\Users\RUNNER~1\…`) for a directory realpath reports in long form.
17
14
  const realHome = await impl.realpath(home).catch(() => home);
18
- const requested = expandHome(options.dir, realHome);
19
- const target = path.resolve(requested || path.join(realHome, '.ssh'));
20
- // Resolve first, then judge: a symlinked directory may lead outside home. A path
21
- // that does not exist keeps its requested spelling, which the check still judges.
15
+ const target = path.resolve(expandHome(options.dir, realHome) || path.join(realHome, '.ssh'));
16
+ // Resolve first, then judge: a symlinked directory may lead outside home; a missing path keeps its spelling.
22
17
  const realTarget = await impl.realpath(target).catch(() => target);
23
18
  if (realTarget !== realHome && !realTarget.startsWith(realHome + path.sep)) {
24
- const error = new Error('key-file path must stay inside the home directory');
25
- error.code = OUTSIDE_HOME;
26
- throw error;
19
+ throw Object.assign(new Error('key-file path must stay inside the home directory'), { code: OUTSIDE_HOME });
27
20
  }
28
21
  const dirents = await impl.readdir(realTarget, { withFileTypes: true });
29
22
  const entries = [];
30
23
  for (const dirent of dirents) {
31
24
  const full = path.join(realTarget, dirent.name);
32
25
  const isDirectory = dirent.isDirectory();
33
- // Only regular files and directories are selectable; a socket or device node
34
- // in a home directory is never a private key.
26
+ // Only regular files and directories are selectable; a socket or device node is never a private key.
35
27
  if (!isDirectory && !dirent.isFile())
36
28
  continue;
37
29
  entries.push({ name: dirent.name, path: full, isDirectory });
@@ -42,11 +34,6 @@ export async function listKeyFiles(options) {
42
34
  return left.name.localeCompare(right.name);
43
35
  });
44
36
  const shown = entries.slice(0, MAX_ENTRIES);
45
- const parent = realTarget === realHome ? null : path.dirname(realTarget);
46
- return {
47
- path: realTarget,
48
- parent: parent ?? realHome,
49
- entries: shown,
50
- truncated: entries.length > shown.length,
51
- };
37
+ const parent = realTarget === realHome ? realHome : path.dirname(realTarget);
38
+ return { path: realTarget, parent, entries: shown, truncated: entries.length > shown.length };
52
39
  }
@@ -1,14 +1,12 @@
1
- /**
2
- * Read-only `~/.ssh/known_hosts` parsing and OpenSSH SHA256 fingerprints; hashed entries are counted, never guessed at.
3
- */
1
+ /** Read-only `~/.ssh/known_hosts` parsing and OpenSSH SHA256 fingerprints; hashed entries are counted, never guessed
2
+ * at. */
4
3
  import { createHash } from 'node:crypto';
5
4
  export function fingerprintFromBase64(keyBase64) {
6
- const digest = createHash('sha256').update(Buffer.from(keyBase64, 'base64')).digest('base64');
7
- return `SHA256:${digest.replace(/=+$/g, '')}`;
5
+ return fingerprintFromBlob(Buffer.from(keyBase64, 'base64'));
8
6
  }
7
+ /** OpenSSH's `SHA256:<base64, no padding>` form for one already-decoded key blob. */
9
8
  export function fingerprintFromBlob(keyBlob) {
10
- const digest = createHash('sha256').update(keyBlob).digest('base64');
11
- return `SHA256:${digest.replace(/=+$/g, '')}`;
9
+ return `SHA256:${createHash('sha256').update(keyBlob).digest('base64').replace(/=+$/g, '')}`;
12
10
  }
13
11
  export function parseKnownHosts(text) {
14
12
  const entries = [];
@@ -58,13 +56,9 @@ export function parseKnownHosts(text) {
58
56
  }
59
57
  return { entries, hashedCount, malformed, revoked, certAuthority };
60
58
  }
61
- /**
62
- * OpenSSH `known_hosts` host-field matching: `*` matches any run of characters, `?` exactly
63
- * one, everything else is literal and the comparison ignores case.
64
- *
65
- * Implemented without a regular expression on purpose: a host field is data, and building a
66
- * `RegExp` from it invites injection and backtracking on remote-controlled text.
67
- */
59
+ /** OpenSSH `known_hosts` host-field matching: `*` matches any run of characters, `?` exactly one, everything else is
60
+ * literal and case is ignored. No regular expression on purpose: a host field is data, and building a `RegExp` from it
61
+ * invites injection and backtracking on remote-controlled text. */
68
62
  function wildcardMatch(pattern, value) {
69
63
  const wanted = String(pattern).toLowerCase();
70
64
  const text = String(value).toLowerCase();
@@ -95,31 +89,16 @@ function wildcardMatch(pattern, value) {
95
89
  patternAt += 1;
96
90
  return patternAt === wanted.length;
97
91
  }
98
- /**
99
- * Whether one `known_hosts` host field covers `host` on `port`.
100
- *
101
- * OpenSSH writes a plain `host` field only for port 22 and `[host]:port` for every other
102
- * port, and it matches the same way: a plain entry never vouches for a service on 2222.
103
- */
92
+ /** Whether one `known_hosts` host field covers `host` on `port`: OpenSSH writes a plain field only for port 22 and
93
+ * `[host]:port` for every other port, so a plain entry never vouches for a service on 2222. */
104
94
  export function knownHostFieldMatches(pattern, host, port) {
105
95
  const targetPort = Number(port) || 22;
106
- const target = targetPort === 22 ? String(host) : `[${host}]:${targetPort}`;
107
- return wildcardMatch(pattern, target);
96
+ return wildcardMatch(pattern, targetPort === 22 ? String(host) : `[${host}]:${targetPort}`);
108
97
  }
109
98
  export function findKnownHostEntries(parsed, host, port) {
110
99
  return parsed.entries.filter((entry) => entry.hosts.some((pattern) => knownHostFieldMatches(pattern, host, port)));
111
100
  }
112
101
  export function summarizeKnownHosts(parsed) {
113
- const hosts = new Set();
114
- for (const entry of parsed.entries) {
115
- for (const host of entry.hosts) {
116
- if (!host.startsWith('|1|'))
117
- hosts.add(host);
118
- }
119
- }
120
- return {
121
- entries: parsed.entries.length,
122
- hashed: parsed.hashedCount,
123
- hosts: [...hosts].sort().slice(0, 200),
124
- };
102
+ const hosts = parsed.entries.flatMap((entry) => entry.hosts).filter((host) => !host.startsWith('|1|'));
103
+ return { entries: parsed.entries.length, hashed: parsed.hashedCount, hosts: [...new Set(hosts)].sort().slice(0, 200) };
125
104
  }
@@ -1,16 +1,7 @@
1
- /**
2
- * Remote directory layout: everything the plugin writes lives under `$DSH_HOME/remote-go`, so a host only gets `~/.dsh` plus that one subdirectory.
3
- */
1
+ /** Remote directory layout: everything the plugin writes lives under `$DSH_HOME/remote-go`, so a host gets only
2
+ * `~/.dsh` plus that one subdirectory. */
4
3
  import { REMOTE_DSH_DIR, REMOTE_STATE_DIR } from './constants.js';
5
4
  import { errors } from './errors.js';
6
- /**
7
- * Build the remote layout for a known home directory.
8
- *
9
- * The home has to be a real absolute path: an unexpanded `~` is not expanded by a
10
- * non-interactive shell, so a layout built without it would silently address a literal
11
- * `~` directory (`kill -0` a `~`-path pid is a no-op that still exits 0). Refusing here
12
- * keeps every caller honest instead of pretending such a command worked.
13
- */
14
5
  export function remoteLayout(home) {
15
6
  const base = typeof home === 'string' ? home.trim().replace(/\/+$/, '') : '';
16
7
  if (!base.startsWith('/')) {
@@ -20,10 +11,7 @@ export function remoteLayout(home) {
20
11
  const root = `${dshHome}/${REMOTE_STATE_DIR}`;
21
12
  return {
22
13
  root,
23
- // Kept for callers that resolve the remote DSH home separately from the
24
- // plugin's own state directory.
25
14
  stateHome: dshHome,
26
- // The remote DSH runs with its real home, so its data is the user's own.
27
15
  dshHome,
28
16
  nodeDir: `${root}/node`,
29
17
  downloadDir: `${root}/downloads`,
@@ -33,11 +21,6 @@ export function remoteLayout(home) {
33
21
  runFile: `${root}/run/web.json`,
34
22
  };
35
23
  }
36
- /**
37
- * The layout a host runtime describes: the facts its live connection probed, or the home
38
- * it remembered before those facts were cleared (keep-alive / idle policy).
39
- */
40
24
  export function layoutForRuntime(runtime) {
41
- const home = runtime?.facts?.home ?? runtime?.remoteHome ?? null;
42
- return remoteLayout(home);
25
+ return remoteLayout(runtime?.facts?.home ?? runtime?.remoteHome ?? null);
43
26
  }