@aide-family/dsh-remote 0.0.0-stage → 0.6.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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +793 -2
  3. package/bin/dsh-remote-terminal +82 -0
  4. package/cordis.patch.yml +3 -0
  5. package/docs/TERMINAL_ACTIONS.md +39 -0
  6. package/docs/assets/host-audit.png +0 -0
  7. package/docs/assets/host-manager.png +0 -0
  8. package/docs/assets/live-terminal.png +0 -0
  9. package/docs/assets/remote-ops.png +0 -0
  10. package/docs/assets/remote-terminal.png +0 -0
  11. package/docs/icon.svg +11 -0
  12. package/lib/api-helpers.js +325 -0
  13. package/lib/api.js +715 -0
  14. package/lib/approval.js +238 -0
  15. package/lib/audit.js +224 -0
  16. package/lib/client.js +4919 -0
  17. package/lib/config.js +762 -0
  18. package/lib/connection-profile.js +65 -0
  19. package/lib/host-registry.js +703 -0
  20. package/lib/host-store.js +139 -0
  21. package/lib/hosts.js +442 -0
  22. package/lib/index.js +419 -0
  23. package/lib/live-stream.js +121 -0
  24. package/lib/live.js +245 -0
  25. package/lib/policy/argv.js +77 -0
  26. package/lib/policy/command-guard.js +404 -0
  27. package/lib/policy/docker.js +140 -0
  28. package/lib/policy/index.js +21 -0
  29. package/lib/policy/inspection.js +111 -0
  30. package/lib/policy/kubectl.js +128 -0
  31. package/lib/policy/shell-command.js +525 -0
  32. package/lib/policy/shell-wrappers.js +143 -0
  33. package/lib/policy/ssh.js +53 -0
  34. package/lib/policy/sudo.js +38 -0
  35. package/lib/policy/systemctl.js +22 -0
  36. package/lib/policy/types.js +12 -0
  37. package/lib/prompt.js +29 -0
  38. package/lib/render.js +442 -0
  39. package/lib/runtime-deps.js +50 -0
  40. package/lib/ssh/auth.js +256 -0
  41. package/lib/ssh/connection.js +504 -0
  42. package/lib/ssh/errors.js +209 -0
  43. package/lib/ssh/exec.js +394 -0
  44. package/lib/ssh/known-hosts.js +313 -0
  45. package/lib/ssh/pty.js +472 -0
  46. package/lib/ssh/sftp.js +589 -0
  47. package/lib/ssh/transport.js +801 -0
  48. package/lib/ssh-config.js +395 -0
  49. package/lib/terminal/bridge.cjs +305 -0
  50. package/lib/terminal/connection-login.js +188 -0
  51. package/lib/terminal/manager.js +656 -0
  52. package/lib/terminal/node-launcher.js +211 -0
  53. package/lib/terminal/pty-session.js +673 -0
  54. package/lib/terminal/relay-socket.js +605 -0
  55. package/lib/terminal/relay.js +905 -0
  56. package/lib/terminal/scrollback.js +588 -0
  57. package/lib/terminal/tools.js +532 -0
  58. package/lib/tools.js +751 -0
  59. package/package.json +90 -4
package/lib/config.js ADDED
@@ -0,0 +1,762 @@
1
+ /**
2
+ * dsh-remote configuration: Schemastery schema + programmatic normalization.
3
+ *
4
+ * `Config` is the schema the DSH loader validates the plugin config with (it
5
+ * also drives the settings UI). `normalizeConfig(raw)` is the plain-JS
6
+ * counterpart used by `lib/index.js` and unit tests: it fills the same defaults
7
+ * and performs the semantic checks a schema cannot express well (unique host
8
+ * names, environment-variable *names* instead of secrets, numeric ranges).
9
+ *
10
+ * This module is pure: no filesystem, environment, or network access. Host
11
+ * discovery (`~/.ssh/config` reading) lives in `lib/ssh-config.js`/`lib/hosts.js`.
12
+ */
13
+
14
+ import { normalizeConnectionProfile } from "./connection-profile.js";
15
+ import { importRuntimePeer } from "./runtime-deps.js";
16
+ const { default: Schema } = await importRuntimePeer("@deepseek-ai/schemastery");
17
+
18
+ /** `~/.ssh/config` default location (expanded by the host loader). */
19
+ export const DEFAULT_SSH_CONFIG_PATH = "~/.ssh/config";
20
+
21
+ /** Approval policies: auto (approve mutating actions), always, never. */
22
+ export const APPROVAL_POLICIES = Object.freeze(["auto", "always", "never"]);
23
+
24
+ /** Known-host verification modes. */
25
+ export const KNOWN_HOSTS_POLICIES = Object.freeze(["tofu", "strict", "insecure"]);
26
+
27
+ /** What `policy: auto` does with commands the static classifier cannot prove read-only. */
28
+ export const UNPROVEN_COMMAND_POLICIES = Object.freeze(["allow", "ask"]);
29
+
30
+ /**
31
+ * Environment variables are referenced by NAME; this is the accepted shape.
32
+ * A config value that does not match (a number, a real password, an empty
33
+ * string) is rejected so a secret can never be pasted into the config file.
34
+ */
35
+ const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/u;
36
+
37
+ /** Defaults from `docs/ARCHITECTURE.md` ("Hosts contract", config fields). */
38
+ const DEFAULTS = Object.freeze({
39
+ hosts: Object.freeze([]),
40
+ includeSshConfig: true,
41
+ sshConfigPath: DEFAULT_SSH_CONFIG_PATH,
42
+ hostRegistryPath: "",
43
+ policy: "auto",
44
+ readonlyHosts: Object.freeze([]),
45
+ allowHosts: Object.freeze([]),
46
+ denyCommandPatterns: Object.freeze([]),
47
+ connectTimeoutMs: 20_000,
48
+ execTimeoutMs: 120_000,
49
+ maxOutputBytes: 200_000,
50
+ maxReadBytes: 800_000,
51
+ maxTransferBytes: 52_428_800,
52
+ knownHostsPolicy: "tofu",
53
+ allowLocalOutsideWorkspace: false,
54
+ promptGuidance: true,
55
+ terminalEnabled: true,
56
+ userTerminal: true,
57
+ userTerminalTtlMs: 1_800_000,
58
+ userTerminalReconnectAttempts: 5,
59
+ userTerminalScrollbackBytes: 400_000,
60
+ managementApi: true,
61
+ unprovenCommands: "allow",
62
+ liveTerminal: true,
63
+ autoOpenLiveTerminal: true,
64
+ devLiveEvents: false,
65
+ terminalRows: 40,
66
+ terminalCols: 120,
67
+ terminalIdleSilenceMs: 800,
68
+ terminalTimeoutMs: 30_000,
69
+ terminalStartupTimeoutMs: 15_000,
70
+ terminalScrollbackLines: 2_000,
71
+ terminalScrollbackBytes: 2_000_000,
72
+ terminalMaxReadBytes: 262_144,
73
+ });
74
+
75
+ /**
76
+ * One entry of `config.hosts`: connection coordinates plus *references* to
77
+ * credentials (environment-variable names), never the credentials themselves.
78
+ *
79
+ * @typedef {object} ConfiguredHost
80
+ * @property {string} name Unique lookup name the model uses (no whitespace).
81
+ * @property {string} [host] Hostname or IP address; optional for a shortcut.
82
+ * @property {string} [viaHost] Existing direct host lookup name for a terminal-only shortcut.
83
+ * @property {string} [loginCommand] Legacy sww command (migrated by normalization).
84
+ * @property {object[]} [actions] Ordered user-defined terminal actions after entrance login.
85
+ * @property {number} [port] SSH port, 1-65535 (default 22).
86
+ * @property {string} [username] Login user.
87
+ * @property {string} [identityFile] Private key path; `~` is allowed.
88
+ * @property {string} [passwordEnv] Environment-variable NAME holding the password.
89
+ * @property {string} [passphraseEnv] Environment-variable NAME holding the key passphrase.
90
+ * @property {string[]} [proxyJump] ProxyJump chain, `[user@]host[:port]` entries.
91
+ * @property {string[]} [tags] Freeform tags surfaced by `remote_hosts`.
92
+ * @property {string} [description] Human description surfaced by `remote_hosts`.
93
+ */
94
+
95
+ const ActionKeys = ["Enter", "Tab", "Escape", "Ctrl-C", "Ctrl-D", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Backspace"];
96
+ const ActionCommon = {
97
+ label: Schema.string().max(80).description("Optional short display label; no secrets."),
98
+ timeoutMs: Schema.natural().min(100).max(120_000).description("Completion timeout in milliseconds (default 30000)."),
99
+ };
100
+ const ActionExpect = Schema.string().min(1).max(2048).description("Literal output that confirms completion, never a regular expression.");
101
+ const ActionText = Schema.string().min(1).max(4096).description("Printable command/text only; never embed credentials.");
102
+ const ConnectionActionSchema = Schema.union([
103
+ Schema.object({ ...ActionCommon, type: Schema.const("command").required(), value: ActionText.required(), expect: ActionExpect,
104
+ expectCluster: Schema.string().description("Legacy completion: root prompt on this safe cluster name; exclusive with expect.") }),
105
+ Schema.object({ ...ActionCommon, type: Schema.const("text").required(), value: ActionText.required(), expect: ActionExpect }),
106
+ Schema.object({ ...ActionCommon, type: Schema.const("key").required(), value: Schema.union(ActionKeys.map((value) => Schema.const(value))).required(), expect: ActionExpect }),
107
+ Schema.object({ ...ActionCommon, type: Schema.const("wait").required(), value: ActionExpect.required() }),
108
+ Schema.object({ label: ActionCommon.label, type: Schema.const("delay").required(), durationMs: Schema.natural().max(120_000).required() }),
109
+ ]);
110
+
111
+ const ConfiguredHostFields = {
112
+ name: Schema.string()
113
+ .required()
114
+ .description("Unique lookup name the model uses (no whitespace)."),
115
+ host: Schema.string()
116
+ .description("Hostname or IP address; optional for a viaHost login shortcut."),
117
+ viaHost: Schema.string().description("Existing host lookup name used by a terminal-only shortcut."),
118
+ loginCommand: Schema.string().description("Legacy sww shortcut; migrated to actions when actions is absent."),
119
+ // Schemastery arrays default to []; keep absence distinct from an invalid empty flow.
120
+ actions: Schema.array(ConnectionActionSchema).min(1).max(32).default(undefined).description("Ordered terminal actions after entrance SSH login; stop on failure or cancellation. No embedded secrets."),
121
+ port: Schema.natural()
122
+ .min(1)
123
+ .max(65_535)
124
+ .default(22)
125
+ .description("SSH port (1-65535, default 22)."),
126
+ username: Schema.string().description("Login user."),
127
+ identityFile: Schema.string().description("Private key path; `~` is allowed."),
128
+ passwordEnv: Schema.string()
129
+ .pattern(ENV_NAME_RE)
130
+ .description("Environment variable NAME holding the password (never the value)."),
131
+ passphraseEnv: Schema.string()
132
+ .pattern(ENV_NAME_RE)
133
+ .description("Environment variable NAME holding the key passphrase (never the value)."),
134
+ proxyJump: Schema.array(Schema.string()).description(
135
+ "ProxyJump chain entries, `[user@]host[:port]`.",
136
+ ),
137
+ tags: Schema.array(Schema.string()).description("Freeform tags shown by `remote_hosts`."),
138
+ description: Schema.string().description("Human description shown by `remote_hosts`."),
139
+ };
140
+ const ConfiguredHostSchema = Schema.union([
141
+ Schema.object({ ...ConfiguredHostFields, host: Schema.string().required() }),
142
+ Schema.object({ ...ConfiguredHostFields, viaHost: Schema.string().required(), actions: Schema.array(ConnectionActionSchema).min(1).max(32).required() }),
143
+ Schema.object({ ...ConfiguredHostFields, viaHost: Schema.string().required(), loginCommand: Schema.string().required() }),
144
+ ]);
145
+
146
+ /**
147
+ * Plugin configuration schema. Empty config is valid: every field has a
148
+ * default, so `apply(ctx)` works with no config block at all.
149
+ */
150
+ export const Config = Schema.object({
151
+ hosts: Schema.array(ConfiguredHostSchema).default([]).description(
152
+ "Configured hosts (in addition to ~/.ssh/config). Config entries win on name collisions.",
153
+ ),
154
+ includeSshConfig: Schema.boolean()
155
+ .default(DEFAULTS.includeSshConfig)
156
+ .description("Discover hosts from the OpenSSH client config."),
157
+ sshConfigPath: Schema.string()
158
+ .default(DEFAULTS.sshConfigPath)
159
+ .description("OpenSSH client config path; `~` is allowed."),
160
+ hostRegistryPath: Schema.string()
161
+ .default(DEFAULTS.hostRegistryPath)
162
+ .description("Managed-host registry file; empty means `$DSH_HOME/remote/hosts.json`."),
163
+ policy: Schema.union(APPROVAL_POLICIES.map((value) => Schema.const(value)))
164
+ .default(DEFAULTS.policy)
165
+ .description("Approval policy: auto asks for mutating actions, always asks for everything, never denies mutating actions."),
166
+ readonlyHosts: Schema.array(Schema.string())
167
+ .default([])
168
+ .description("Host-name globs (* and ?) whose mutating actions are always denied."),
169
+ allowHosts: Schema.array(Schema.string())
170
+ .default([])
171
+ .description("Host-name globs (* and ?) that may be used; empty means every host."),
172
+ denyCommandPatterns: Schema.array(Schema.string())
173
+ .default([])
174
+ .description("RegExp sources; a matching remote command is denied outright."),
175
+ connectTimeoutMs: Schema.natural()
176
+ .min(1)
177
+ .default(DEFAULTS.connectTimeoutMs)
178
+ .description("TCP/banner connect timeout in milliseconds."),
179
+ execTimeoutMs: Schema.natural()
180
+ .min(1)
181
+ .default(DEFAULTS.execTimeoutMs)
182
+ .description("Default remote command timeout in milliseconds."),
183
+ maxOutputBytes: Schema.natural()
184
+ .min(1)
185
+ .default(DEFAULTS.maxOutputBytes)
186
+ .description("Per-stream cap for remote command output (tail kept)."),
187
+ maxReadBytes: Schema.natural()
188
+ .min(1)
189
+ .default(DEFAULTS.maxReadBytes)
190
+ .description("Cap for one `remote_read` file read."),
191
+ maxTransferBytes: Schema.natural()
192
+ .min(1)
193
+ .default(DEFAULTS.maxTransferBytes)
194
+ .description("Cap for one upload/download."),
195
+ knownHostsPolicy: Schema.union(KNOWN_HOSTS_POLICIES.map((value) => Schema.const(value)))
196
+ .default(DEFAULTS.knownHostsPolicy)
197
+ .description("Host-key verification: tofu, strict, or insecure."),
198
+ allowLocalOutsideWorkspace: Schema.boolean()
199
+ .default(DEFAULTS.allowLocalOutsideWorkspace)
200
+ .description("Allow `remote_transfer` local paths outside the session workspace."),
201
+ promptGuidance: Schema.boolean()
202
+ .default(DEFAULTS.promptGuidance)
203
+ .description("Contribute the dsh-remote system-prompt section."),
204
+ terminalEnabled: Schema.boolean()
205
+ .default(DEFAULTS.terminalEnabled)
206
+ .description("Register the persistent remote-shell tools (remote_shell_*)."),
207
+ userTerminal: Schema.boolean()
208
+ .default(DEFAULTS.userTerminal)
209
+ .description(
210
+ "Serve the user-driven interactive SSH terminal: the relay socket, the terminal.* management API and the browser panel.",
211
+ ),
212
+ userTerminalTtlMs: Schema.natural()
213
+ .min(0)
214
+ .default(DEFAULTS.userTerminalTtlMs)
215
+ .description(
216
+ "Idle time (ms) after the last terminal bridge detaches before the SSH session is closed; 0 keeps it open.",
217
+ ),
218
+ userTerminalReconnectAttempts: Schema.natural()
219
+ .min(1)
220
+ .default(DEFAULTS.userTerminalReconnectAttempts)
221
+ .description("Automatic SSH reconnect attempts after a drop in the user terminal."),
222
+ userTerminalScrollbackBytes: Schema.natural()
223
+ .min(1)
224
+ .default(DEFAULTS.userTerminalScrollbackBytes)
225
+ .description("Replay buffer (bytes) retained for a reattached user terminal."),
226
+ managementApi: Schema.boolean()
227
+ .default(DEFAULTS.managementApi)
228
+ .description("Serve the browser management API (/dsh-remote/api) when a web server is mounted."),
229
+ unprovenCommands: Schema.union(UNPROVEN_COMMAND_POLICIES.map((value) => Schema.const(value)))
230
+ .default(DEFAULTS.unprovenCommands)
231
+ .description(
232
+ 'Under policy "auto", how to treat commands the classifier cannot prove read-only: "allow" runs them without approval (only provably mutating commands ask), "ask" requires approval.',
233
+ ),
234
+ liveTerminal: Schema.boolean()
235
+ .default(DEFAULTS.liveTerminal)
236
+ .description("Serve the live command stream (/dsh-remote/live) and register the right-sidebar terminal."),
237
+ autoOpenLiveTerminal: Schema.boolean()
238
+ .default(DEFAULTS.autoOpenLiveTerminal)
239
+ .description("Open the right-sidebar terminal automatically when a remote command starts."),
240
+ devLiveEvents: Schema.boolean()
241
+ .default(DEFAULTS.devLiveEvents)
242
+ .description("Expose the dev-only live-event injector on the management API (testing; keep off in production)."),
243
+ terminalRows: Schema.natural()
244
+ .min(1)
245
+ .default(DEFAULTS.terminalRows)
246
+ .description("PTY rows requested for remote shell sessions."),
247
+ terminalCols: Schema.natural()
248
+ .min(1)
249
+ .default(DEFAULTS.terminalCols)
250
+ .description("PTY columns requested for remote shell sessions."),
251
+ terminalIdleSilenceMs: Schema.natural()
252
+ .min(50)
253
+ .default(DEFAULTS.terminalIdleSilenceMs)
254
+ .description("Output silence (ms) that settles a remote-shell send as inferred-idle."),
255
+ terminalTimeoutMs: Schema.natural()
256
+ .min(1)
257
+ .default(DEFAULTS.terminalTimeoutMs)
258
+ .description("Absolute bound (ms) on one remote-shell send wait."),
259
+ terminalStartupTimeoutMs: Schema.natural()
260
+ .min(1)
261
+ .default(DEFAULTS.terminalStartupTimeoutMs)
262
+ .description("Bound (ms) on remote-shell startup before the session publishes."),
263
+ terminalScrollbackLines: Schema.natural()
264
+ .min(1)
265
+ .default(DEFAULTS.terminalScrollbackLines)
266
+ .description("Retained remote-shell scrollback lines."),
267
+ terminalScrollbackBytes: Schema.natural()
268
+ .min(1)
269
+ .default(DEFAULTS.terminalScrollbackBytes)
270
+ .description("Retained remote-shell scrollback byte cap."),
271
+ terminalMaxReadBytes: Schema.natural()
272
+ .min(64)
273
+ .default(DEFAULTS.terminalMaxReadBytes)
274
+ .description("Byte cap for one remote_shell_read/remote_shell_send result."),
275
+ });
276
+
277
+ /**
278
+ * Validate and normalize a raw plugin config into a defaults-filled plain
279
+ * object. Safe to call with `undefined` (or with an already-normalized object:
280
+ * it is idempotent). Never performs I/O.
281
+ *
282
+ * @param {unknown} [raw]
283
+ * @returns {{
284
+ * hosts: ConfiguredHost[],
285
+ * includeSshConfig: boolean,
286
+ * sshConfigPath: string,
287
+ * hostRegistryPath: string,
288
+ * policy: "auto" | "always" | "never",
289
+ * readonlyHosts: string[],
290
+ * allowHosts: string[],
291
+ * denyCommandPatterns: string[],
292
+ * connectTimeoutMs: number,
293
+ * execTimeoutMs: number,
294
+ * maxOutputBytes: number,
295
+ * maxReadBytes: number,
296
+ * maxTransferBytes: number,
297
+ * knownHostsPolicy: "tofu" | "strict" | "insecure",
298
+ * allowLocalOutsideWorkspace: boolean,
299
+ * promptGuidance: boolean,
300
+ * terminalEnabled: boolean,
301
+ * userTerminal: boolean,
302
+ * userTerminalTtlMs: number,
303
+ * userTerminalReconnectAttempts: number,
304
+ * userTerminalScrollbackBytes: number,
305
+ * managementApi: boolean,
306
+ * unprovenCommands: "allow" | "ask",
307
+ * liveTerminal: boolean,
308
+ * autoOpenLiveTerminal: boolean,
309
+ * devLiveEvents: boolean,
310
+ * terminalRows: number,
311
+ * terminalCols: number,
312
+ * terminalIdleSilenceMs: number,
313
+ * terminalTimeoutMs: number,
314
+ * terminalStartupTimeoutMs: number,
315
+ * terminalScrollbackLines: number,
316
+ * terminalScrollbackBytes: number,
317
+ * terminalMaxReadBytes: number,
318
+ * }}
319
+ */
320
+ export function normalizeConfig(raw) {
321
+ const source = readObject(raw);
322
+
323
+ return {
324
+ hosts: normalizeHosts(source),
325
+ includeSshConfig: booleanField(source, "includeSshConfig", DEFAULTS.includeSshConfig),
326
+ sshConfigPath: pathField(source, "sshConfigPath", DEFAULTS.sshConfigPath),
327
+ hostRegistryPath: registryPathField(source, "hostRegistryPath", DEFAULTS.hostRegistryPath),
328
+ policy: enumField(source, "policy", DEFAULTS.policy, APPROVAL_POLICIES),
329
+ readonlyHosts: stringListField(source, "readonlyHosts"),
330
+ allowHosts: stringListField(source, "allowHosts"),
331
+ denyCommandPatterns: stringListField(source, "denyCommandPatterns"),
332
+ connectTimeoutMs: positiveIntegerField(source, "connectTimeoutMs", DEFAULTS.connectTimeoutMs),
333
+ execTimeoutMs: positiveIntegerField(source, "execTimeoutMs", DEFAULTS.execTimeoutMs),
334
+ maxOutputBytes: positiveIntegerField(source, "maxOutputBytes", DEFAULTS.maxOutputBytes),
335
+ maxReadBytes: positiveIntegerField(source, "maxReadBytes", DEFAULTS.maxReadBytes),
336
+ maxTransferBytes: positiveIntegerField(source, "maxTransferBytes", DEFAULTS.maxTransferBytes),
337
+ knownHostsPolicy: enumField(
338
+ source,
339
+ "knownHostsPolicy",
340
+ DEFAULTS.knownHostsPolicy,
341
+ KNOWN_HOSTS_POLICIES,
342
+ ),
343
+ allowLocalOutsideWorkspace: booleanField(
344
+ source,
345
+ "allowLocalOutsideWorkspace",
346
+ DEFAULTS.allowLocalOutsideWorkspace,
347
+ ),
348
+ promptGuidance: booleanField(source, "promptGuidance", DEFAULTS.promptGuidance),
349
+ terminalEnabled: booleanField(source, "terminalEnabled", DEFAULTS.terminalEnabled),
350
+ userTerminal: booleanField(source, "userTerminal", DEFAULTS.userTerminal),
351
+ userTerminalTtlMs: nonNegativeIntegerField(
352
+ source,
353
+ "userTerminalTtlMs",
354
+ DEFAULTS.userTerminalTtlMs,
355
+ ),
356
+ userTerminalReconnectAttempts: positiveIntegerField(
357
+ source,
358
+ "userTerminalReconnectAttempts",
359
+ DEFAULTS.userTerminalReconnectAttempts,
360
+ ),
361
+ userTerminalScrollbackBytes: positiveIntegerField(
362
+ source,
363
+ "userTerminalScrollbackBytes",
364
+ DEFAULTS.userTerminalScrollbackBytes,
365
+ ),
366
+ managementApi: booleanField(source, "managementApi", DEFAULTS.managementApi),
367
+ unprovenCommands: enumField(
368
+ source,
369
+ "unprovenCommands",
370
+ DEFAULTS.unprovenCommands,
371
+ UNPROVEN_COMMAND_POLICIES,
372
+ ),
373
+ liveTerminal: booleanField(source, "liveTerminal", DEFAULTS.liveTerminal),
374
+ autoOpenLiveTerminal: booleanField(
375
+ source,
376
+ "autoOpenLiveTerminal",
377
+ DEFAULTS.autoOpenLiveTerminal,
378
+ ),
379
+ devLiveEvents: booleanField(source, "devLiveEvents", DEFAULTS.devLiveEvents),
380
+ terminalRows: positiveIntegerField(source, "terminalRows", DEFAULTS.terminalRows),
381
+ terminalCols: positiveIntegerField(source, "terminalCols", DEFAULTS.terminalCols),
382
+ terminalIdleSilenceMs: positiveIntegerField(
383
+ source,
384
+ "terminalIdleSilenceMs",
385
+ DEFAULTS.terminalIdleSilenceMs,
386
+ ),
387
+ terminalTimeoutMs: positiveIntegerField(
388
+ source,
389
+ "terminalTimeoutMs",
390
+ DEFAULTS.terminalTimeoutMs,
391
+ ),
392
+ terminalStartupTimeoutMs: positiveIntegerField(
393
+ source,
394
+ "terminalStartupTimeoutMs",
395
+ DEFAULTS.terminalStartupTimeoutMs,
396
+ ),
397
+ terminalScrollbackLines: positiveIntegerField(
398
+ source,
399
+ "terminalScrollbackLines",
400
+ DEFAULTS.terminalScrollbackLines,
401
+ ),
402
+ terminalScrollbackBytes: positiveIntegerField(
403
+ source,
404
+ "terminalScrollbackBytes",
405
+ DEFAULTS.terminalScrollbackBytes,
406
+ ),
407
+ terminalMaxReadBytes: positiveIntegerField(
408
+ source,
409
+ "terminalMaxReadBytes",
410
+ DEFAULTS.terminalMaxReadBytes,
411
+ ),
412
+ };
413
+ }
414
+
415
+ /**
416
+ * Normalize one configured host, rejecting malformed entries with an error that
417
+ * names the offending host (or at least its index).
418
+ *
419
+ * @param {unknown} entry
420
+ * @param {number} index
421
+ * @returns {ConfiguredHost}
422
+ */
423
+ function normalizeHostEntry(entry, index) {
424
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
425
+ throw configError(`hosts[${index}] must be an object`);
426
+ }
427
+
428
+ const name = requiredString(entry, "name", `hosts[${index}]`);
429
+ if (/\s/u.test(name)) {
430
+ throw configError(`host ${quote(name)}: name must not contain whitespace`);
431
+ }
432
+ const label = `host ${quote(name)}`;
433
+
434
+ let profile;
435
+ try {
436
+ profile = normalizeConnectionProfile(entry);
437
+ } catch (error) {
438
+ throw configError(`${label}: ${error.message}`);
439
+ }
440
+ const host = profile.viaHost ? optionalString(entry, "host", label) : requiredString(entry, "host", label);
441
+ if (host !== undefined && /\s/u.test(host)) {
442
+ throw configError(`${label}: host must not contain whitespace`);
443
+ }
444
+
445
+ const portValue = entry.port;
446
+ const port = portValue === undefined || portValue === null ? 22 : portValue;
447
+ if (
448
+ typeof port !== "number" ||
449
+ !Number.isSafeInteger(port) ||
450
+ port < 1 ||
451
+ port > 65_535
452
+ ) {
453
+ throw configError(
454
+ `${label}: port must be an integer between 1 and 65535 (got ${formatValue(portValue)})`,
455
+ );
456
+ }
457
+
458
+ const normalized = {
459
+ ...profile,
460
+ name,
461
+ host,
462
+ port,
463
+ username: optionalString(entry, "username", label),
464
+ identityFile: optionalString(entry, "identityFile", label),
465
+ passwordEnv: envNameField(entry, "passwordEnv", label),
466
+ passphraseEnv: envNameField(entry, "passphraseEnv", label),
467
+ proxyJump: proxyJumpField(entry, label),
468
+ tags: tagsField(entry, label),
469
+ description: optionalString(entry, "description", label),
470
+ };
471
+
472
+ return compact(normalized);
473
+ }
474
+
475
+ /**
476
+ * @param {Record<string, unknown>} source
477
+ * @returns {ConfiguredHost[]}
478
+ */
479
+ function normalizeHosts(source) {
480
+ const value = source.hosts;
481
+ if (value === undefined || value === null) return [];
482
+ if (!Array.isArray(value)) {
483
+ throw configError("hosts must be an array of host objects");
484
+ }
485
+
486
+ const seen = new Map();
487
+ const hosts = [];
488
+ for (let index = 0; index < value.length; index += 1) {
489
+ const host = normalizeHostEntry(value[index], index);
490
+ const key = host.name.toLowerCase();
491
+ const previous = seen.get(key);
492
+ if (previous !== undefined) {
493
+ throw configError(
494
+ `duplicate host name ${quote(host.name)} in hosts[${index}] (already defined by hosts[${previous}]); host names must be unique`,
495
+ );
496
+ }
497
+ seen.set(key, index);
498
+ hosts.push(host);
499
+ }
500
+ return hosts;
501
+ }
502
+
503
+ /** @param {unknown} raw @returns {Record<string, unknown>} */
504
+ function readObject(raw) {
505
+ if (raw === undefined || raw === null) return {};
506
+ if (typeof raw !== "object" || Array.isArray(raw)) {
507
+ throw configError(`config must be an object (got ${formatValue(raw)})`);
508
+ }
509
+ return /** @type {Record<string, unknown>} */ (raw);
510
+ }
511
+
512
+ /**
513
+ * @param {Record<string, unknown>} source
514
+ * @param {string} key
515
+ * @param {string} label
516
+ * @returns {string}
517
+ */
518
+ function requiredString(source, key, label) {
519
+ const value = source[key];
520
+ if (typeof value !== "string" || value.trim() === "") {
521
+ throw configError(`${label}: ${key} must be a non-empty string (got ${formatValue(value)})`);
522
+ }
523
+ return value.trim();
524
+ }
525
+
526
+ /**
527
+ * @param {Record<string, unknown>} source
528
+ * @param {string} key
529
+ * @param {string} label
530
+ * @returns {string | undefined}
531
+ */
532
+ function optionalString(source, key, label) {
533
+ const value = source[key];
534
+ if (value === undefined || value === null) return undefined;
535
+ if (typeof value !== "string" || value.trim() === "") {
536
+ throw configError(`${label}: ${key} must be a non-empty string (got ${formatValue(value)})`);
537
+ }
538
+ return value.trim();
539
+ }
540
+
541
+ /**
542
+ * `passwordEnv`/`passphraseEnv` hold environment-variable NAMES. Reject values
543
+ * that cannot be a variable name (numbers, booleans, empty strings, or an
544
+ * actual pasted secret with spaces) so secrets never live in the config file.
545
+ *
546
+ * @param {Record<string, unknown>} source
547
+ * @param {"passwordEnv" | "passphraseEnv"} key
548
+ * @param {string} label
549
+ * @returns {string | undefined}
550
+ */
551
+ function envNameField(source, key, label) {
552
+ const value = source[key];
553
+ if (value === undefined || value === null) return undefined;
554
+ if (typeof value !== "string" || !ENV_NAME_RE.test(value.trim())) {
555
+ throw configError(
556
+ `${label}: ${key} must be the NAME of an environment variable ` +
557
+ `(e.g. "PROD_PASSWORD", matching ${ENV_NAME_RE.source}) — never the secret value itself ` +
558
+ `(got ${formatValue(value)})`,
559
+ );
560
+ }
561
+ return value.trim();
562
+ }
563
+
564
+ /**
565
+ * @param {Record<string, unknown>} source
566
+ * @param {string} label
567
+ * @returns {string[] | undefined}
568
+ */
569
+ function proxyJumpField(source, label) {
570
+ const value = source.proxyJump;
571
+ if (value === undefined || value === null) return undefined;
572
+ if (!Array.isArray(value)) {
573
+ throw configError(
574
+ `${label}: proxyJump must be an array of "[user@]host[:port]" strings (got ${formatValue(value)})`,
575
+ );
576
+ }
577
+ return value.map((hop, index) => {
578
+ if (typeof hop !== "string" || hop.trim() === "") {
579
+ throw configError(
580
+ `${label}: proxyJump[${index}] must be a non-empty string (got ${formatValue(hop)})`,
581
+ );
582
+ }
583
+ return hop.trim();
584
+ });
585
+ }
586
+
587
+ /**
588
+ * @param {Record<string, unknown>} source
589
+ * @param {string} label
590
+ * @returns {string[] | undefined}
591
+ */
592
+ function tagsField(source, label) {
593
+ const value = source.tags;
594
+ if (value === undefined || value === null) return undefined;
595
+ if (!Array.isArray(value)) {
596
+ throw configError(`${label}: tags must be an array of strings (got ${formatValue(value)})`);
597
+ }
598
+ return value.map((tag, index) => {
599
+ if (typeof tag !== "string" || tag.trim() === "") {
600
+ throw configError(`${label}: tags[${index}] must be a non-empty string`);
601
+ }
602
+ return tag.trim();
603
+ });
604
+ }
605
+
606
+ /**
607
+ * @param {Record<string, unknown>} source
608
+ * @param {string} key
609
+ * @param {boolean} fallback
610
+ * @param {readonly string[]} allowed
611
+ * @returns {string}
612
+ */
613
+ function enumField(source, key, fallback, allowed) {
614
+ const value = source[key];
615
+ if (value === undefined || value === null) return fallback;
616
+ if (typeof value !== "string" || !allowed.includes(value)) {
617
+ throw configError(`${key} must be one of ${allowed.map((item) => quote(item)).join(", ")} (got ${formatValue(value)})`);
618
+ }
619
+ return value;
620
+ }
621
+
622
+ /**
623
+ * @param {Record<string, unknown>} source
624
+ * @param {string} key
625
+ * @param {boolean} fallback
626
+ * @returns {boolean}
627
+ */
628
+ function booleanField(source, key, fallback) {
629
+ const value = source[key];
630
+ if (value === undefined || value === null) return fallback;
631
+ if (typeof value !== "boolean") {
632
+ throw configError(`${key} must be a boolean (got ${formatValue(value)})`);
633
+ }
634
+ return value;
635
+ }
636
+
637
+ /**
638
+ * @param {Record<string, unknown>} source
639
+ * @param {string} key
640
+ * @param {number} fallback
641
+ * @returns {number}
642
+ */
643
+ function positiveIntegerField(source, key, fallback) {
644
+ const value = source[key];
645
+ if (value === undefined || value === null) return fallback;
646
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) {
647
+ throw configError(`${key} must be a positive integer (got ${formatValue(value)})`);
648
+ }
649
+ return value;
650
+ }
651
+
652
+ /**
653
+ * Zero-or-more integer (0 has a documented meaning for some timeouts: it
654
+ * disables the corresponding idle/expiry behavior).
655
+ *
656
+ * @param {Record<string, unknown>} source
657
+ * @param {string} key
658
+ * @param {number} fallback
659
+ * @returns {number}
660
+ */
661
+ function nonNegativeIntegerField(source, key, fallback) {
662
+ const value = source[key];
663
+ if (value === undefined || value === null) return fallback;
664
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
665
+ throw configError(`${key} must be a non-negative integer (got ${formatValue(value)})`);
666
+ }
667
+ return value;
668
+ }
669
+
670
+ /**
671
+ * A list of glob patterns / RegExp sources / freeform strings. Entries are
672
+ * trimmed and must be non-empty strings; globs are otherwise unrestricted
673
+ * because the host matcher treats every non-`*`/`?` character literally.
674
+ *
675
+ * @param {Record<string, unknown>} source
676
+ * @param {string} key
677
+ * @returns {string[]}
678
+ */
679
+ function stringListField(source, key) {
680
+ const value = source[key];
681
+ if (value === undefined || value === null) return [];
682
+ if (!Array.isArray(value)) {
683
+ throw configError(`${key} must be an array of strings (got ${formatValue(value)})`);
684
+ }
685
+ return value.map((entry, index) => {
686
+ if (typeof entry !== "string" || entry.trim() === "") {
687
+ throw configError(`${key}[${index}] must be a non-empty string (got ${formatValue(entry)})`);
688
+ }
689
+ return entry.trim();
690
+ });
691
+ }
692
+
693
+ /**
694
+ * @param {Record<string, unknown>} source
695
+ * @param {string} key
696
+ * @param {string} fallback
697
+ * @returns {string}
698
+ */
699
+ function pathField(source, key, fallback) {
700
+ const value = source[key];
701
+ if (value === undefined || value === null) return fallback;
702
+ if (typeof value !== "string" || value.trim() === "") {
703
+ throw configError(`${key} must be a non-empty path string (got ${formatValue(value)})`);
704
+ }
705
+ return value.trim();
706
+ }
707
+
708
+ /**
709
+ * A filesystem path. An empty string is preserved (for fields where the empty
710
+ * string has a documented meaning such as "use the default location").
711
+ *
712
+ * @param {Record<string, unknown>} source
713
+ * @param {string} key
714
+ * @param {string} fallback
715
+ * @returns {string}
716
+ */
717
+ function registryPathField(source, key, fallback) {
718
+ const value = source[key];
719
+ if (value === undefined || value === null) return fallback;
720
+ if (typeof value !== "string") {
721
+ throw configError(`${key} must be a path string (got ${formatValue(value)})`);
722
+ }
723
+ return value.trim();
724
+ }
725
+
726
+ /**
727
+ * Drop undefined properties so normalized objects compare cleanly and never
728
+ * carry `key: undefined` placeholders.
729
+ *
730
+ * @template {Record<string, unknown>} T
731
+ * @param {T} value
732
+ * @returns {T}
733
+ */
734
+ function compact(value) {
735
+ for (const key of Object.keys(value)) {
736
+ if (value[key] === undefined) delete value[key];
737
+ }
738
+ return value;
739
+ }
740
+
741
+ /** @param {string} message @returns {Error} */
742
+ function configError(message) {
743
+ return new Error(`dsh-remote: ${message}`);
744
+ }
745
+
746
+ /** @param {string} value @returns {string} */
747
+ function quote(value) {
748
+ return JSON.stringify(value);
749
+ }
750
+
751
+ /** @param {unknown} value @returns {string} */
752
+ function formatValue(value) {
753
+ if (value === undefined) return "undefined";
754
+ if (value === null) return "null";
755
+ if (typeof value === "string") return quote(value);
756
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
757
+ return String(value);
758
+ }
759
+ if (Array.isArray(value)) return "array";
760
+ return typeof value;
761
+ }
762
+