mcp-ssh-manager 3.8.7 → 4.0.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 (104) hide show
  1. package/.eslintignore +5 -0
  2. package/.gitattributes +5 -0
  3. package/CHANGELOG.md +371 -6
  4. package/CLAUDE.md +6 -0
  5. package/CODE_OF_CONDUCT.md +18 -0
  6. package/CONTRIBUTING.md +30 -0
  7. package/Formula/ssh-manager.rb +60 -0
  8. package/README.md +484 -964
  9. package/ROADMAP-V4.md +451 -0
  10. package/brand/README.md +43 -0
  11. package/brand/icon.svg +32 -0
  12. package/brand/mark.svg +18 -0
  13. package/brand/wordmark.svg +30 -0
  14. package/cli/app.js +230 -0
  15. package/cli/control.js +116 -0
  16. package/cli/lib/colors.sh +15 -0
  17. package/cli/lib/menu.sh +145 -96
  18. package/cli/portability.js +186 -0
  19. package/cli/ssh-manager +197 -91
  20. package/cli/ssh-manager.js +14 -0
  21. package/cli/style.js +17 -0
  22. package/cli/vault.js +411 -0
  23. package/desktop/ControlPlaneApp.swift +219 -0
  24. package/desktop/build.sh +58 -0
  25. package/desktop/electron/after-pack.cjs +39 -0
  26. package/desktop/electron/electron-builder.yml +148 -0
  27. package/desktop/electron/finalize-artifacts.mjs +83 -0
  28. package/desktop/electron/main.js +815 -0
  29. package/desktop/electron/package-lock.json +3656 -0
  30. package/desktop/electron/package.json +30 -0
  31. package/desktop/electron/prepare-engine.mjs +84 -0
  32. package/desktop/electron/resources/entitlements.mac.plist +22 -0
  33. package/desktop/electron/resources/icon.png +0 -0
  34. package/desktop/electron/resources/trayTemplate.png +0 -0
  35. package/desktop/electron/resources/trayTemplate@2x.png +0 -0
  36. package/desktop/electron/smoke-test.mjs +184 -0
  37. package/dist/ui/app.css +1 -0
  38. package/dist/ui/app.js +501 -0
  39. package/dist/ui/assets/Forum-Regular.woff2 +0 -0
  40. package/dist/ui/assets/JetBrainsMono-Bold.woff2 +0 -0
  41. package/dist/ui/assets/JetBrainsMono-Regular.woff2 +0 -0
  42. package/dist/ui/assets/Karla-Variable.woff2 +0 -0
  43. package/dist/ui/index.html +16 -0
  44. package/docs/DISTRIBUTION.md +136 -0
  45. package/docs/FINAL-TEST-V4.md +209 -0
  46. package/docs/MIGRATION.md +334 -0
  47. package/docs/TESTING-V4.md +119 -0
  48. package/docs/superpowers/specs/2026-10-08-desktop-from-npm-and-cli-design.md +187 -0
  49. package/docs/videos/control-plane.mp4 +0 -0
  50. package/package.json +61 -30
  51. package/scripts/build-interface.mjs +73 -0
  52. package/scripts/capture-screenshots.mjs +191 -0
  53. package/scripts/demo-env.mjs +461 -0
  54. package/scripts/frame-screenshots.py +176 -0
  55. package/scripts/macbook-mockup.py +296 -0
  56. package/scripts/make-tray-icon.py +61 -0
  57. package/scripts/preview-candidate.mjs +291 -0
  58. package/scripts/publish-desktop.mjs +46 -0
  59. package/scripts/record-demo.mjs +229 -0
  60. package/scripts/release-version.mjs +32 -0
  61. package/scripts/render-cli-menu.py +157 -0
  62. package/scripts/requirements-dev.in +12 -0
  63. package/scripts/requirements-dev.txt +424 -0
  64. package/scripts/run-ui-regression.mjs +48 -0
  65. package/scripts/setup-hooks.sh +7 -13
  66. package/scripts/smoke-desktop.mjs +80 -0
  67. package/scripts/test-drag-and-drop.mjs +114 -0
  68. package/scripts/test-first-run.mjs +5 -0
  69. package/scripts/test-import-ui.mjs +5 -0
  70. package/scripts/test-preferences-persist.mjs +5 -0
  71. package/scripts/test-upgrade-from-published.mjs +226 -0
  72. package/scripts/verify-mac-build.sh +153 -0
  73. package/scripts/verify-windows-build.ps1 +15 -0
  74. package/server.json +3 -3
  75. package/skills/README.md +42 -0
  76. package/skills/ssh-incident/SKILL.md +55 -0
  77. package/skills/ssh-operations/SKILL.md +62 -0
  78. package/skills/ssh-restricted/SKILL.md +57 -0
  79. package/src/agent-clients.js +482 -0
  80. package/src/approval.js +291 -0
  81. package/src/audit.js +11 -1
  82. package/src/command-log.js +162 -0
  83. package/src/config-loader.js +119 -4
  84. package/src/config-paths.js +101 -0
  85. package/src/control-plane.js +2730 -0
  86. package/src/desktop-install.js +747 -0
  87. package/src/index.js +179 -213
  88. package/src/live-stream.js +261 -0
  89. package/src/saved-commands.js +150 -0
  90. package/src/secret-store.js +573 -0
  91. package/src/server-aliases.js +8 -7
  92. package/src/server-config-manager.js +33 -7
  93. package/src/server-export.js +106 -0
  94. package/src/server-groups.js +82 -21
  95. package/src/server-import.js +477 -0
  96. package/src/shell-quote.js +9 -2
  97. package/src/ssh-connection.js +155 -0
  98. package/src/ssh-manager.js +186 -13
  99. package/src/tunnel-manager.js +79 -0
  100. package/src/vault-recovery.js +206 -0
  101. package/src/xlsx.js +322 -0
  102. package/docs/images/social-preview.png +0 -0
  103. package/docs/images/social-preview@2x.png +0 -0
  104. package/docs/images/ssh-manager-cli-menu.png +0 -0
@@ -1,9 +1,9 @@
1
1
  import { Client } from 'ssh2';
2
2
  import fs from 'fs';
3
- import os from 'os';
4
3
  import { trustedHostKeyAlgorithms, verifyHostKey } from './ssh-key-manager.js';
5
4
  import { logger } from './logger.js';
6
5
  import { shellPath } from './shell-quote.js';
6
+ import { expandHomePath } from './config-paths.js';
7
7
 
8
8
  // Validate liveness-probe output across shells (bash, cmd.exe, PowerShell).
9
9
  // Normalize CRLF, stray quotes/backslashes and case before matching so quoted
@@ -21,6 +21,50 @@ export function isPingAlive(stdout) {
21
21
  return normalized.includes('ping');
22
22
  }
23
23
 
24
+ // The name this tool announces to hosts it drives, following the AI_AGENT
25
+ // over SSH convention: https://github.com/mthamil107/whotyped/blob/main/docs/spec/ai-agent-over-ssh.md
26
+ // Deliberately unprefixed, unlike the SSH_SERVER_* / MCP_SSH_* settings: a
27
+ // server-side consumer should not have to know which client sent it.
28
+ const AGENT_NAME = 'mcp-ssh-manager';
29
+
30
+ /**
31
+ * Whether connections to this server announce that an AI agent is driving.
32
+ *
33
+ * Off unless asked for. Upgrading must not change what reaches a server, and
34
+ * the request goes to every host whatever its `AcceptEnv` — sshd only declines
35
+ * to *store* it — so a host the operator does not control would learn that an
36
+ * agent is on the other end and could shape its output for one. The operators
37
+ * who benefit are those who configured their servers to record it, and they
38
+ * are also the ones in a position to flip one switch.
39
+ *
40
+ * A per-server value wins in both directions, so one untrusted host can stay
41
+ * silent under a global switch. Otherwise `SSH_MANAGER_ANNOUNCE_AGENT` decides.
42
+ *
43
+ * @param {{announceAgent?: boolean}} [config] - Server configuration
44
+ * @returns {boolean}
45
+ */
46
+ function announcesAgent(config) {
47
+ if (config?.announceAgent === true) return true;
48
+ if (config?.announceAgent === false) return false;
49
+ const global = process.env.SSH_MANAGER_ANNOUNCE_AGENT;
50
+ return typeof global === 'string' && ['true', '1', 'yes', 'on'].includes(global.trim().toLowerCase());
51
+ }
52
+
53
+ /**
54
+ * The same announcement for `ssh_sync`, which drives rsync through the system
55
+ * `ssh` rather than ssh2. `SendEnv` rather than `SetEnv`: it has been in
56
+ * OpenSSH since 3.9, where `SetEnv` needs 7.8, and a user who opted in on an
57
+ * older client should get a missing label, not a broken sync.
58
+ *
59
+ * @param {{announceAgent?: boolean}} [config] - Server configuration
60
+ * @returns {{sshOptions: string[], env: Record<string, string>}}
61
+ */
62
+ export function rsyncAgentAnnouncement(config) {
63
+ return announcesAgent(config)
64
+ ? { sshOptions: ['-o SendEnv=AI_AGENT'], env: { AI_AGENT: AGENT_NAME } }
65
+ : { sshOptions: [], env: {} };
66
+ }
67
+
24
68
  class SSHManager {
25
69
  constructor(config) {
26
70
  this.config = config;
@@ -43,7 +87,7 @@ class SSHManager {
43
87
 
44
88
  this.client.on('error', (err) => {
45
89
  this.connected = false;
46
- reject(err);
90
+ reject(this.describeAuthFailure(err));
47
91
  });
48
92
 
49
93
  this.client.on('end', () => {
@@ -55,7 +99,10 @@ class SSHManager {
55
99
  host: this.config.host,
56
100
  port: this.config.port || 22,
57
101
  username: this.config.user,
58
- readyTimeout: 60000, // Increased from 20000 to 60000 for slow connections
102
+ // 60s suits an agent's command, which is worth waiting for. A health
103
+ // dashboard is not: it must answer in seconds, so callers can shorten
104
+ // this per connection.
105
+ readyTimeout: options.readyTimeout ?? 60000,
59
106
  keepaliveInterval: 10000,
60
107
  algorithms: {
61
108
  kex: [
@@ -111,7 +158,6 @@ class SSHManager {
111
158
  // Verify the key ssh2 received on this connection, never a second
112
159
  // ssh-keyscan connection. First contact remains noninteractive TOFU;
113
160
  // a changed known key is refused before credentials are sent.
114
- // Up to 3.8.5 this callback accepted every key (GHSA-cwg3-pfmm-w8rm).
115
161
  if (this.hostKeyVerification) {
116
162
  const trusted = trustedHostKeyAlgorithms(this.config.host, this.config.port || 22);
117
163
  if (trusted.length) connConfig.algorithms.serverHostKey = trusted;
@@ -140,7 +186,7 @@ class SSHManager {
140
186
  // Add authentication (support both keyPath and keypath for compatibility)
141
187
  const keyPath = this.config.keyPath || this.config.keypath;
142
188
  if (keyPath) {
143
- const resolvedKeyPath = keyPath.replace('~', os.homedir());
189
+ const resolvedKeyPath = expandHomePath(keyPath);
144
190
  connConfig.privateKey = fs.readFileSync(resolvedKeyPath);
145
191
  // OpenSSH user certificate (<key>-cert.pub): sent to the server as the
146
192
  // identity while privateKey signs. Read on every connect, so a renewed
@@ -148,7 +194,7 @@ class SSHManager {
148
194
  // Requires an ssh2 release with certificate support (mscdex/ssh2#1495);
149
195
  // older ssh2 ignores the unknown option and authenticates with the key.
150
196
  if (this.config.certPath) {
151
- connConfig.publicKey = fs.readFileSync(this.config.certPath.replace('~', os.homedir()));
197
+ connConfig.publicKey = fs.readFileSync(expandHomePath(this.config.certPath));
152
198
  }
153
199
  if (this.config.passphrase) {
154
200
  connConfig.passphrase = this.config.passphrase;
@@ -157,6 +203,8 @@ class SSHManager {
157
203
  connConfig.password = this.config.password;
158
204
  }
159
205
 
206
+ connConfig.authHandler = this.trackedAuthHandler(connConfig);
207
+
160
208
  // Use provided stream for proxy jump connections
161
209
  if (options.sock) {
162
210
  connConfig.sock = options.sock;
@@ -166,13 +214,104 @@ class SSHManager {
166
214
  });
167
215
  }
168
216
 
217
+ /**
218
+ * ssh2's own order (none, password, publickey, agent), with two additions:
219
+ * a method the server said it does not accept is not sent, and every
220
+ * attempt is recorded so a failure can say what was refused.
221
+ *
222
+ * The order is unchanged on purpose: a server whose password changed but
223
+ * that accepts a key from the agent still connects, as it did in 3.8.5.
224
+ * What changes is the error. A refused password followed by every agent key
225
+ * used to end as the server's "Too many authentication failures", and the
226
+ * refused password never reached the user (issue #88).
227
+ * @param {Record<string, any>} connConfig
228
+ */
229
+ trackedAuthHandler(connConfig) {
230
+ const queue = ['none'];
231
+ if (connConfig.password !== undefined) queue.push('password');
232
+ if (connConfig.privateKey !== undefined) queue.push('publickey');
233
+ if (connConfig.agent !== undefined) queue.push('agent');
234
+ /** @type {{tried: string[], skipped: string[], offered: string[]|null}} */
235
+ const auth = { tried: [], skipped: [], offered: null };
236
+ this.auth = auth;
237
+ return (methodsLeft) => {
238
+ if (Array.isArray(methodsLeft)) auth.offered = methodsLeft;
239
+ while (queue.length) {
240
+ const method = queue.shift();
241
+ const accepted = method === 'none' || !auth.offered
242
+ || auth.offered.includes(method === 'agent' ? 'publickey' : method);
243
+ if (accepted) {
244
+ auth.tried.push(method);
245
+ return method;
246
+ }
247
+ auth.skipped.push(method);
248
+ }
249
+ return false;
250
+ };
251
+ }
252
+
253
+ /**
254
+ * The connection error, with what authentication tried when that is what
255
+ * failed. The server's own words are kept at the end.
256
+ * @param {Error & {level?: string}} err
257
+ * @returns {Error}
258
+ */
259
+ describeAuthFailure(err) {
260
+ const auth = this.auth;
261
+ const authFailed = err?.level === 'client-authentication'
262
+ || /authentication|too many/i.test(err?.message || '');
263
+ if (!auth || !authFailed) return err;
264
+
265
+ const offered = auth.offered?.length ? auth.offered.join(', ') : null;
266
+ const facts = [];
267
+ const outcome = method => {
268
+ if (auth.tried.includes(method)) return 'refused';
269
+ if (auth.skipped.includes(method)) return 'not offered';
270
+ return null;
271
+ };
272
+ const password = outcome('password');
273
+ if (password === 'refused') facts.push('the password was refused');
274
+ if (password === 'not offered') facts.push(`the server does not accept passwords${offered ? ` (it offers: ${offered})` : ''}`);
275
+ const key = outcome('publickey');
276
+ if (key === 'refused') facts.push('the configured key was refused');
277
+ if (key === 'not offered') facts.push(`the server does not accept keys${offered ? ` (it offers: ${offered})` : ''}`);
278
+ if (auth.tried.includes('agent')) {
279
+ facts.push(/too many/i.test(err.message)
280
+ ? 'the server then closed the connection while ssh-agent keys were being tried'
281
+ : 'no ssh-agent key was accepted');
282
+ }
283
+ if (!facts.length) return err;
284
+
285
+ const target = `${this.config.user || this.config.username}@${this.config.host}:${this.config.port || 22}`;
286
+ const described = new Error(`Authentication failed for ${target}: ${facts.join('; ')} (${err.message})`);
287
+ Object.assign(described, { level: err.level, cause: err });
288
+ return described;
289
+ }
290
+
291
+ /**
292
+ * Channel options announcing this tool to the host, or an empty object when
293
+ * this server does not announce — see `announcesAgent()`.
294
+ *
295
+ * Every channel needs its own copy: `env` is a per-channel request in
296
+ * RFC 4254 §6.4, not a connection-level setting, so a site that forgets to
297
+ * call this announces nothing while its siblings do.
298
+ *
299
+ * Returns `{}` rather than undefined when opted out, because ssh2's
300
+ * `exec(cmd, opts, cb)` reads `opts.allowHalfOpen` without guarding
301
+ * (lib/client.js), so an undefined options object throws at the call.
302
+ *
303
+ * @returns {{env?: {AI_AGENT: string}}}
304
+ */
305
+ channelEnv() {
306
+ return announcesAgent(this.config) ? { env: { AI_AGENT: AGENT_NAME } } : {};
307
+ }
308
+
169
309
  async execCommand(command, options = {}) {
170
310
  if (!this.connected) {
171
311
  throw new Error('Not connected to SSH server');
172
312
  }
173
313
 
174
- const { timeout = 30000, cwd, rawCommand = false, stdin = null } = options;
175
- // Quoted: a working directory is data, never shell code (GHSA-37fv-fcpc-j236).
314
+ const { timeout = 30000, cwd, rawCommand = false, stdin = null, onStdout, onStderr } = options;
176
315
  const fullCommand = (cwd && !rawCommand) ? `cd -- ${shellPath(cwd)} && ${command}` : command;
177
316
 
178
317
  return new Promise((resolve, reject) => {
@@ -212,7 +351,7 @@ class SSHManager {
212
351
  }, timeout);
213
352
  }
214
353
 
215
- this.client.exec(fullCommand, (err, streamObj) => {
354
+ this.client.exec(fullCommand, this.channelEnv(), (err, streamObj) => {
216
355
  if (err) {
217
356
  completed = true;
218
357
  if (timeoutId) clearTimeout(timeoutId);
@@ -257,11 +396,21 @@ class SSHManager {
257
396
  });
258
397
 
259
398
  stream.on('data', (data) => {
260
- stdout += data.toString();
399
+ const text = data.toString();
400
+ stdout += text;
401
+ // Emitted as it arrives, so a watcher sees output during a long
402
+ // command rather than all at once when it finishes.
403
+ if (onStdout) {
404
+ try { onStdout(text); } catch { /* a watcher must never break a command */ }
405
+ }
261
406
  });
262
407
 
263
408
  stream.stderr.on('data', (data) => {
264
- stderr += data.toString();
409
+ const text = data.toString();
410
+ stderr += text;
411
+ if (onStderr) {
412
+ try { onStderr(text); } catch { /* same */ }
413
+ }
265
414
  });
266
415
 
267
416
  stream.on('error', (err) => {
@@ -284,7 +433,7 @@ class SSHManager {
284
433
  const fullCommand = cwd ? `cd -- ${shellPath(cwd)} && ${command}` : command;
285
434
 
286
435
  return new Promise((resolve, reject) => {
287
- this.client.exec(fullCommand, (err, stream) => {
436
+ this.client.exec(fullCommand, this.channelEnv(), (err, stream) => {
288
437
  if (err) {
289
438
  reject(err);
290
439
  return;
@@ -320,13 +469,28 @@ class SSHManager {
320
469
  });
321
470
  }
322
471
 
472
+ /**
473
+ * Open an interactive shell.
474
+ *
475
+ * `options` stays the pty/window options and is passed as ssh2's first
476
+ * argument; the agent announcement goes in the *second*. This is not
477
+ * cosmetic: ssh2's `shell(wndopts, opts, cb)` reassigns `opts = wndopts`
478
+ * and drops `wndopts` when the first object carries `env`, so folding the
479
+ * announcement into `options` would silently discard `term`, `cols`, `rows`
480
+ * and `modes` and fall back to ssh2's pty defaults. `modes: { ECHO: 0 }`
481
+ * is load-bearing for the session marker protocol, and losing it would not
482
+ * fail any test — it would just make interactive sessions misbehave.
483
+ *
484
+ * @param {object} [options] pty/window options (term, cols, rows, modes)
485
+ * @returns {Promise<import('ssh2').ClientChannel>}
486
+ */
323
487
  async requestShell(options = {}) {
324
488
  if (!this.connected) {
325
489
  throw new Error('Not connected to SSH server');
326
490
  }
327
491
 
328
492
  return new Promise((resolve, reject) => {
329
- this.client.shell(options, (err, stream) => {
493
+ this.client.shell(options, this.channelEnv(), (err, stream) => {
330
494
  if (err) {
331
495
  reject(err);
332
496
  return;
@@ -336,6 +500,15 @@ class SSHManager {
336
500
  });
337
501
  }
338
502
 
503
+ /**
504
+ * SFTP deliberately does not announce the agent. ssh2 supports
505
+ * `sftp(env, cb)`, but unlike exec and shell — which call `reqEnv` with no
506
+ * callback, so `want_reply` is 0 and an unaccepted name cannot fail — the
507
+ * sftp path passes a callback and fails the whole session when the server
508
+ * refuses the request. Most sshd configs ship `AcceptEnv LANG LC_*` only,
509
+ * so announcing here would break uploads and downloads on the majority of
510
+ * hosts to gain a label on one channel type. Not worth it.
511
+ */
339
512
  async getSFTP() {
340
513
  if (this.sftp) return this.sftp;
341
514
 
@@ -6,6 +6,9 @@
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import net from 'net';
8
8
  import { logger } from './logger.js';
9
+ import fs from 'fs';
10
+ import os from 'os';
11
+ import path from 'path';
9
12
 
10
13
  // Map to store active tunnels
11
14
  const tunnels = new Map();
@@ -422,6 +425,7 @@ class SSHTunnel {
422
425
  }
423
426
 
424
427
  tunnels.delete(this.id);
428
+ publishTunnelState();
425
429
  }
426
430
 
427
431
  /**
@@ -488,6 +492,7 @@ export async function createTunnel(serverName, ssh, config) {
488
492
 
489
493
  try {
490
494
  await tunnel.start();
495
+ publishTunnelState();
491
496
 
492
497
  logger.info('SSH tunnel created', {
493
498
  id: tunnelId,
@@ -498,6 +503,7 @@ export async function createTunnel(serverName, ssh, config) {
498
503
  return tunnel;
499
504
  } catch (error) {
500
505
  tunnels.delete(tunnelId);
506
+ publishTunnelState();
501
507
  throw error;
502
508
  }
503
509
  }
@@ -505,6 +511,79 @@ export async function createTunnel(serverName, ssh, config) {
505
511
  /**
506
512
  * List all active tunnels
507
513
  */
514
+ /**
515
+ * Where the open-tunnel state is published for other processes to read.
516
+ * @returns {string} Absolute path
517
+ */
518
+ export function tunnelStatePath() {
519
+ const home = process.env.SSH_MANAGER_HOME || path.join(os.homedir(), '.ssh-manager');
520
+ return path.join(home, 'tunnels.json');
521
+ }
522
+
523
+ /**
524
+ * Publish the open tunnels to a file so another process — the control plane —
525
+ * can see them.
526
+ *
527
+ * Tunnels live in a Map inside whichever process opened them, which is fine
528
+ * until something else wants to display them. The file carries this process's
529
+ * pid, because a stale file left by a crashed engine would otherwise show
530
+ * tunnels that no longer exist: a reader checks the pid is alive before
531
+ * believing the contents.
532
+ *
533
+ * Failures are swallowed. Publishing state is a convenience; it must never take
534
+ * down a tunnel that is working.
535
+ */
536
+ function publishTunnelState() {
537
+ const statePath = tunnelStatePath();
538
+ try {
539
+ const open = [];
540
+ for (const [, tunnel] of tunnels.entries()) {
541
+ if (tunnel.state !== TUNNEL_STATES.CLOSED) open.push(tunnel.getInfo());
542
+ }
543
+
544
+ if (open.length === 0) {
545
+ // No tunnels, no file: an empty file and a missing one mean the same
546
+ // thing, and removing it stops a dead pid lingering on disk.
547
+ try { fs.unlinkSync(statePath); } catch { /* already gone */ }
548
+ return;
549
+ }
550
+
551
+ fs.mkdirSync(path.dirname(statePath), { recursive: true, mode: 0o700 });
552
+ fs.writeFileSync(
553
+ statePath,
554
+ `${JSON.stringify({ pid: process.pid, updatedAt: new Date().toISOString(), tunnels: open }, null, 2)}\n`,
555
+ { mode: 0o600 }
556
+ );
557
+ } catch (error) {
558
+ logger.debug('Could not publish tunnel state', { error: error.message });
559
+ }
560
+ }
561
+
562
+ /**
563
+ * Read tunnels published by the engine process.
564
+ *
565
+ * Returns an empty list when the file is missing, unreadable, or written by a
566
+ * process that is no longer running — a stale list is worse than none, because
567
+ * it would show tunnels an operator believes are open.
568
+ *
569
+ * @param {string} [statePath] - File to read
570
+ * @returns {{tunnels: any[], pid: number|null, stale: boolean}}
571
+ */
572
+ export function readPublishedTunnels(statePath = tunnelStatePath()) {
573
+ try {
574
+ const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
575
+ // Signal 0 tests for existence without touching the process.
576
+ try {
577
+ process.kill(state.pid, 0);
578
+ } catch {
579
+ return { tunnels: [], pid: state.pid ?? null, stale: true };
580
+ }
581
+ return { tunnels: state.tunnels || [], pid: state.pid, stale: false };
582
+ } catch {
583
+ return { tunnels: [], pid: null, stale: false };
584
+ }
585
+ }
586
+
508
587
  export function listTunnels(serverName = null) {
509
588
  const activeTunnels = [];
510
589
 
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Recovery files: one encrypted copy of the vault that does not depend on this
3
+ * machine's keychain.
4
+ *
5
+ * ## Why this exists
6
+ *
7
+ * The vault's master key lives in the OS keychain, which is the right place for
8
+ * it — but it is tied to one machine and one user account. Reinstall the OS,
9
+ * move to a new laptop, or let a Linux keyring get wiped, and the vault is a
10
+ * file of ciphertext nobody can read. The credentials themselves are usually
11
+ * recoverable from elsewhere (a password manager, a colleague, the server's own
12
+ * `authorized_keys`), but "usually" is doing a lot of work in that sentence at
13
+ * the moment you need it.
14
+ *
15
+ * ## Why a passphrase and not a printed key
16
+ *
17
+ * The obvious alternative is what a wallet does: generate a recovery key, print
18
+ * it, tell the user to keep the paper. That works when what is being protected
19
+ * is one secret you re-enter once. It does not work here: what is protected is
20
+ * thirty servers with hosts, ports, users, key paths and modes, and nobody
21
+ * retypes that from a sheet of paper. So the recovery unit is a **file** —
22
+ * something a password manager can hold as an attachment, or a private repo can
23
+ * carry — encrypted under a passphrase the operator chooses and can remember.
24
+ *
25
+ * ## What it is not
26
+ *
27
+ * Not a backup of the key. Handing someone the master key in a file next to the
28
+ * vault would defeat the keychain entirely. The recovery file is encrypted from
29
+ * the plaintext, under a **different** key derived from the passphrase, so
30
+ * possessing it without the passphrase is worth nothing.
31
+ */
32
+ import crypto from 'crypto';
33
+ import fs from 'fs';
34
+ import path from 'path';
35
+ import { SECRET_FIELDS } from './secret-store.js';
36
+
37
+ const ALGORITHM = 'aes-256-gcm';
38
+ const KEY_BYTES = 32;
39
+ const IV_BYTES = 12;
40
+ const SALT_BYTES = 16;
41
+
42
+ /**
43
+ * scrypt cost. N=2^17 takes roughly a quarter-second on a modern laptop, which
44
+ * is imperceptible when you type a passphrase once and expensive enough that
45
+ * guessing at scale is not free. maxmem has to be raised to match: Node's
46
+ * default refuses this N.
47
+ */
48
+ const SCRYPT = { N: 131072, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
49
+
50
+ /** The format marker, so a future change can be told apart rather than guessed at. */
51
+ const FORMAT = 'ssh-manager-recovery-v1';
52
+
53
+ /**
54
+ * Derive the file key from a passphrase.
55
+ * @param {string} passphrase - What the operator typed
56
+ * @param {Buffer} salt - Per-file salt
57
+ * @returns {Buffer} 32-byte key
58
+ */
59
+ function deriveKey(passphrase, salt) {
60
+ return crypto.scryptSync(passphrase.normalize('NFKC'), salt, KEY_BYTES, SCRYPT);
61
+ }
62
+
63
+ /**
64
+ * Write a recovery file.
65
+ *
66
+ * @param {Record<string, any>} servers - Decrypted server configs, as the vault hands them out
67
+ * @param {string} passphrase - Chosen by the operator
68
+ * @param {string} outputPath - Where to write
69
+ * @returns {{ path: string, servers: number, secrets: number }}
70
+ */
71
+ export function writeRecoveryFile(servers, passphrase, outputPath) {
72
+ const content = serializeRecovery(servers, passphrase);
73
+ const file = JSON.parse(content);
74
+ fs.mkdirSync(path.dirname(path.resolve(outputPath)), { recursive: true });
75
+ const temporary = `${outputPath}.${crypto.randomUUID()}.tmp`;
76
+ try {
77
+ fs.writeFileSync(temporary, content, { mode: 0o600, flag: 'wx' });
78
+ fs.renameSync(temporary, outputPath);
79
+ } finally {
80
+ fs.rmSync(temporary, { force: true });
81
+ }
82
+ return { path: path.resolve(outputPath), servers: file.contains.servers, secrets: file.contains.secrets };
83
+ }
84
+
85
+ /** Build the same encrypted file for CLI disk writes and browser downloads.
86
+ * @param {Record<string, any>} servers
87
+ * @param {string} passphrase
88
+ * @returns {string}
89
+ */
90
+ export function serializeRecovery(servers, passphrase) {
91
+ if (!passphrase || passphrase.length < 8) {
92
+ throw new Error('The passphrase must be at least 8 characters — this is the only thing protecting the file.');
93
+ }
94
+
95
+ const salt = crypto.randomBytes(SALT_BYTES);
96
+ const iv = crypto.randomBytes(IV_BYTES);
97
+ const key = deriveKey(passphrase, salt);
98
+
99
+ const plaintext = Buffer.from(JSON.stringify({ servers }), 'utf8');
100
+ const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
101
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
102
+
103
+ /** @param {any} value @returns {number} */
104
+ const countSecrets = value => {
105
+ if (Array.isArray(value)) return value.reduce((sum, item) => sum + countSecrets(item), 0);
106
+ if (!value || typeof value !== 'object') return 0;
107
+ return Object.entries(value).reduce((sum, [field, item]) =>
108
+ sum + (SECRET_FIELDS.includes(field) ? (item ? 1 : 0) : countSecrets(item)), 0);
109
+ };
110
+ const secrets = Object.values(servers).reduce((sum, server) => sum + countSecrets(server), 0);
111
+
112
+ const file = {
113
+ format: FORMAT,
114
+ createdAt: new Date().toISOString(),
115
+ // Stated in the file so whoever finds it in five years knows what it takes
116
+ // to open it, without needing this source.
117
+ kdf: { name: 'scrypt', ...SCRYPT, salt: salt.toString('base64') },
118
+ cipher: ALGORITHM,
119
+ iv: iv.toString('base64'),
120
+ tag: cipher.getAuthTag().toString('base64'),
121
+ data: ciphertext.toString('base64'),
122
+ // Deliberately outside the ciphertext: enough to identify a file without
123
+ // opening it, never enough to be worth stealing.
124
+ contains: { servers: Object.keys(servers).length, secrets },
125
+ };
126
+
127
+ return `${JSON.stringify(file, null, 2)}\n`;
128
+ }
129
+
130
+ /**
131
+ * Read a recovery file back.
132
+ *
133
+ * @param {string} inputPath - The file
134
+ * @param {string} passphrase - The one used to write it
135
+ * @returns {Record<string, any>} The servers, in the clear
136
+ */
137
+ export function readRecoveryFile(inputPath, passphrase) {
138
+ let content;
139
+ try {
140
+ content = fs.readFileSync(inputPath, 'utf8');
141
+ } catch (error) {
142
+ throw new Error(`Cannot read ${inputPath}: ${error.message}`);
143
+ }
144
+ return decryptRecoveryContent(content, passphrase);
145
+ }
146
+
147
+ /** @param {string} content @param {string} passphrase @returns {Record<string, any>} */
148
+ export function decryptRecoveryContent(content, passphrase) {
149
+ const file = JSON.parse(content);
150
+ if (file.format !== FORMAT) {
151
+ throw new Error(`Not a recovery file (found format "${file.format ?? 'none'}").`);
152
+ }
153
+
154
+ const kdf = file.kdf ?? {};
155
+ // Unauthenticated file metadata must not request unbounded memory or CPU
156
+ // from the desktop process before the GCM tag can be checked.
157
+ if (kdf.name !== 'scrypt' || !Number.isInteger(kdf.N) || kdf.N < 2 || kdf.N > SCRYPT.N
158
+ || (kdf.N & (kdf.N - 1)) !== 0 || !Number.isInteger(kdf.r) || kdf.r < 1 || kdf.r > SCRYPT.r
159
+ || !Number.isInteger(kdf.p) || kdf.p < 1 || kdf.p > SCRYPT.p) {
160
+ throw new Error('Unsupported recovery key derivation parameters');
161
+ }
162
+ // Read the parameters from the file rather than assuming today's constants:
163
+ // a file written by an older version must still open.
164
+ const key = crypto.scryptSync(
165
+ passphrase.normalize('NFKC'),
166
+ Buffer.from(kdf.salt, 'base64'),
167
+ KEY_BYTES,
168
+ { N: kdf.N, r: kdf.r, p: kdf.p, maxmem: SCRYPT.maxmem }
169
+ );
170
+
171
+ const decipher = crypto.createDecipheriv(ALGORITHM, key, Buffer.from(file.iv, 'base64'));
172
+ decipher.setAuthTag(Buffer.from(file.tag, 'base64'));
173
+ try {
174
+ const plaintext = Buffer.concat([
175
+ decipher.update(Buffer.from(file.data, 'base64')),
176
+ decipher.final(),
177
+ ]);
178
+ const servers = JSON.parse(plaintext.toString('utf8')).servers;
179
+ if (!servers || typeof servers !== 'object' || Array.isArray(servers)
180
+ || Object.values(servers).some(config => !config || typeof config !== 'object' || Array.isArray(config))) {
181
+ throw new Error('Invalid recovery server data');
182
+ }
183
+ return servers;
184
+ } catch {
185
+ // GCM cannot tell a wrong passphrase from a corrupted file, and guessing
186
+ // which would only mislead.
187
+ throw new Error('Wrong passphrase, or the file has been altered.');
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Describe a recovery file without opening it — what it holds and when it was
193
+ * made, so an operator can tell two of them apart before typing anything.
194
+ *
195
+ * @param {string} inputPath - The file
196
+ * @returns {{ createdAt: string, servers: number, secrets: number }}
197
+ */
198
+ export function describeRecoveryFile(inputPath) {
199
+ const file = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
200
+ if (file.format !== FORMAT) throw new Error(`${inputPath} is not a recovery file.`);
201
+ return {
202
+ createdAt: file.createdAt,
203
+ servers: file.contains?.servers ?? 0,
204
+ secrets: file.contains?.secrets ?? 0,
205
+ };
206
+ }