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
@@ -0,0 +1,477 @@
1
+ /**
2
+ * Getting servers in from wherever they already are.
3
+ *
4
+ * ## Why this is a list of readers and not one importer
5
+ *
6
+ * Nobody starts here. They have a `~/.ssh/config` with forty hosts, or a
7
+ * FileZilla site manager, or a spreadsheet a colleague sent them. Asking them to
8
+ * retype it is asking them not to bother, and every one of those sources is a
9
+ * different shape.
10
+ *
11
+ * So each format is a small reader that answers two questions — does this look
12
+ * like mine, and what servers are in it — and everything after that is shared:
13
+ * one normalisation, one validation, one merge. Adding a format is forty lines
14
+ * and cannot break the others.
15
+ *
16
+ * ## What is deliberately not read
17
+ *
18
+ * **Passwords.** FileZilla stores them base64-encoded, PuTTY does not store them
19
+ * at all, Transmit keeps them in the keychain. Importing a credential silently
20
+ * from another application's store is not a favour: it copies a secret the
21
+ * person has forgotten they have, into a second place they now have to think
22
+ * about. Hosts, users, ports and key paths come across; a password is asked for
23
+ * once, by them, when they first connect.
24
+ */
25
+ import fs from 'fs';
26
+ import os from 'os';
27
+ import path from 'path';
28
+ import { execFileSync } from 'child_process';
29
+ import { readSheet } from './xlsx.js';
30
+ import { logger } from './logger.js';
31
+
32
+ /**
33
+ * @typedef {object} ImportedServer
34
+ * @property {string} name
35
+ * @property {string} host
36
+ * @property {string} [user]
37
+ * @property {number} [port]
38
+ * @property {string} [keyPath]
39
+ * @property {string} [defaultDir]
40
+ * @property {string} [description]
41
+ * @property {string} [group]
42
+ * @property {string} [platform]
43
+ * @property {string} [proxyJump]
44
+ */
45
+
46
+ /** The columns a spreadsheet or CSV may use, and what each becomes. */
47
+ const COLUMNS = {
48
+ name: 'name', nom: 'name', label: 'name', alias: 'name', session: 'name',
49
+ host: 'host', hostname: 'host', address: 'host', adresse: 'host', ip: 'host', server: 'host',
50
+ user: 'user', username: 'user', utilisateur: 'user', login: 'user',
51
+ port: 'port',
52
+ key: 'keyPath', keypath: 'keyPath', identityfile: 'keyPath', 'key path': 'keyPath', cle: 'keyPath',
53
+ dir: 'defaultDir', directory: 'defaultDir', defaultdir: 'defaultDir',
54
+ 'default dir': 'defaultDir', 'default directory': 'defaultDir', dossier: 'defaultDir',
55
+ description: 'description', comment: 'description', notes: 'description',
56
+ group: 'group', groupe: 'group', category: 'group', tag: 'group', folder: 'group',
57
+ platform: 'platform', os: 'platform',
58
+ proxyjump: 'proxyJump', 'proxy jump': 'proxyJump', bastion: 'proxyJump', jump: 'proxyJump',
59
+ };
60
+
61
+ /** A server name the rest of the system will accept: lowercase, letters, digits, underscore. */
62
+ function slug(raw, fallback = 'server') {
63
+ const cleaned = String(raw || '').trim().toLowerCase()
64
+ .replace(/[^a-z0-9_]+/g, '_').replace(/^_+|_+$/g, '');
65
+ return cleaned || fallback;
66
+ }
67
+
68
+ /**
69
+ * One row from any source, checked and tidied.
70
+ *
71
+ * @param {Record<string, any>} raw
72
+ * @param {string[]} warnings - Appended to, so the caller can report what was dropped
73
+ * @returns {ImportedServer|null} null when there is nothing usable
74
+ */
75
+ function normalise(raw, warnings) {
76
+ // A leading # means a comment, as it does in every other config format. The
77
+ // template uses it for the notes at the bottom; without this they read as
78
+ // three servers that forgot their hostname.
79
+ const label = String(raw.name || '').trim();
80
+ if (label.startsWith('#')) return null;
81
+
82
+ const host = String(raw.host || '').trim();
83
+ if (!host) {
84
+ if (label) warnings.push(`"${label}" has no host — skipped`);
85
+ return null;
86
+ }
87
+ // A `user@host` in the host column is a common way to write it.
88
+ let user = raw.user ? String(raw.user).trim() : undefined;
89
+ let bare = host;
90
+ const at = host.lastIndexOf('@');
91
+ if (at > 0) { bare = host.slice(at + 1); user = user || host.slice(0, at); }
92
+
93
+ // And so is `host:port`, as long as it is not an IPv6 literal.
94
+ let port = raw.port ? parseInt(String(raw.port), 10) : undefined;
95
+ const colon = bare.lastIndexOf(':');
96
+ if (colon > 0 && !bare.includes('[') && bare.indexOf(':') === colon) {
97
+ const maybe = parseInt(bare.slice(colon + 1), 10);
98
+ if (Number.isInteger(maybe) && maybe > 0 && maybe < 65536) {
99
+ port = port || maybe;
100
+ bare = bare.slice(0, colon);
101
+ }
102
+ }
103
+ if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) {
104
+ warnings.push(`"${raw.name || bare}" has port "${raw.port}" — ignored, using 22`);
105
+ port = undefined;
106
+ }
107
+
108
+ /** @type {ImportedServer} */
109
+ const server = { name: slug(raw.name || bare), host: bare };
110
+ if (user) server.user = user;
111
+ if (port && port !== 22) server.port = port;
112
+ for (const field of ['keyPath', 'defaultDir', 'description', 'group', 'proxyJump']) {
113
+ const value = raw[field] ? String(raw[field]).trim() : '';
114
+ if (value) server[field] = value;
115
+ }
116
+ if (server.keyPath) server.keyPath = server.keyPath.replace(/^~(?=\/)/, os.homedir());
117
+ const platform = String(raw.platform || '').trim().toLowerCase();
118
+ if (platform === 'windows') server.platform = 'windows';
119
+ if (server.group) server.group = server.group.trim().toLowerCase();
120
+ return server;
121
+ }
122
+
123
+ /** Rows of cells (from CSV or a spreadsheet) into servers, using the header row. */
124
+ function fromTable(rows, warnings) {
125
+ const header = (rows[0] || []).map(cell => String(cell).trim().toLowerCase());
126
+ const mapping = header.map(cell => COLUMNS[cell] ?? null);
127
+ if (!mapping.includes('host')) {
128
+ throw new Error(
129
+ `No "host" column. Found: ${header.filter(Boolean).join(', ') || '(nothing)'}. `
130
+ + 'The template from `ssh-manager import --template` has the columns this expects.');
131
+ }
132
+ const unknown = header.filter((cell, i) => cell && mapping[i] === null);
133
+ if (unknown.length) warnings.push(`Columns ignored: ${unknown.join(', ')}`);
134
+
135
+ return rows.slice(1)
136
+ .filter(row => row.some(cell => String(cell).trim()))
137
+ .map(row => {
138
+ /** @type {Record<string, any>} */
139
+ const raw = {};
140
+ mapping.forEach((field, i) => { if (field) raw[field] = row[i]; });
141
+ return normalise(raw, warnings);
142
+ })
143
+ .filter(Boolean);
144
+ }
145
+
146
+ /** A CSV line splitter that understands quotes, because hosts have commas in comments. */
147
+ function splitCsv(text) {
148
+ const separator = (text.split('\n')[0].match(/;/g) || []).length
149
+ > (text.split('\n')[0].match(/,/g) || []).length ? ';' : ',';
150
+ /** @type {string[][]} */
151
+ const rows = [];
152
+ let row = [];
153
+ let cell = '';
154
+ let quoted = false;
155
+ for (let i = 0; i < text.length; i++) {
156
+ const ch = text[i];
157
+ if (quoted) {
158
+ if (ch === '"' && text[i + 1] === '"') { cell += '"'; i++; }
159
+ else if (ch === '"') quoted = false;
160
+ else cell += ch;
161
+ } else if (ch === '"') quoted = true;
162
+ else if (ch === separator) { row.push(cell); cell = ''; }
163
+ else if (ch === '\n') { row.push(cell); rows.push(row); row = []; cell = ''; }
164
+ else if (ch !== '\r') cell += ch;
165
+ }
166
+ if (cell || row.length) { row.push(cell); rows.push(row); }
167
+ return rows;
168
+ }
169
+
170
+ /* ------------------------------------------------------------------ readers */
171
+
172
+ /** @type {{id: string, label: string, detect: (name: string, text: string) => boolean, parse: (text: string, file: string, warnings: string[]) => ImportedServer[]}[]} */
173
+ export const READERS = [
174
+ {
175
+ id: 'ssh-config',
176
+ label: 'OpenSSH config (~/.ssh/config)',
177
+ detect: (name, text) => /(^|\/)config$/.test(name) || /^\s*Host\s+\S/mi.test(text),
178
+ parse(text, file, warnings) {
179
+ /** @type {ImportedServer[]} */
180
+ const servers = [];
181
+ /** @type {Record<string, any>|null} */
182
+ let current = null;
183
+ const flush = () => {
184
+ if (!current) return;
185
+ const server = normalise(current, warnings);
186
+ if (server) servers.push(server);
187
+ current = null;
188
+ };
189
+ for (const line of text.split('\n')) {
190
+ const trimmed = line.trim();
191
+ if (!trimmed || trimmed.startsWith('#')) continue;
192
+ const [keyword, ...rest] = trimmed.split(/[\s=]+/);
193
+ const value = rest.join(' ').trim();
194
+ switch (keyword.toLowerCase()) {
195
+ case 'host': {
196
+ flush();
197
+ // `Host a b c` defines aliases for one machine, and `Host *` is
198
+ // defaults for everything — neither is a server to import.
199
+ const names = value.split(/\s+/).filter(n => !n.includes('*') && !n.includes('?'));
200
+ if (names.length) current = { name: names[0], host: names[0] };
201
+ break;
202
+ }
203
+ case 'include':
204
+ warnings.push(`\`Include ${value}\` was not followed — import those files separately`);
205
+ break;
206
+ case 'hostname': if (current) current.host = value; break;
207
+ case 'user': if (current) current.user = value; break;
208
+ case 'port': if (current) current.port = value; break;
209
+ case 'identityfile': if (current && !current.keyPath) current.keyPath = value; break;
210
+ case 'proxyjump': if (current) current.proxyJump = value.split(',')[0].replace(/^.*@/, ''); break;
211
+ default: break;
212
+ }
213
+ }
214
+ flush();
215
+ return servers;
216
+ },
217
+ },
218
+ {
219
+ id: 'xlsx',
220
+ label: 'Spreadsheet (.xlsx)',
221
+ detect: name => name.toLowerCase().endsWith('.xlsx'),
222
+ parse: (_text, file, warnings) => fromTable(readSheet(fs.readFileSync(file)), warnings),
223
+ },
224
+ {
225
+ id: 'filezilla',
226
+ label: 'FileZilla (sitemanager.xml)',
227
+ detect: (name, text) => /sitemanager\.xml$/i.test(name) || text.includes('<FileZilla3'),
228
+ parse(text, file, warnings) {
229
+ const value = (block, tag) =>
230
+ new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`).exec(block)?.[1]?.trim() || '';
231
+ /** @type {ImportedServer[]} */
232
+ const servers = [];
233
+ for (const match of text.matchAll(/<Server[\s>]([\s\S]*?)<\/Server>/g)) {
234
+ const block = match[1];
235
+ // FileZilla protocol 1 is SFTP. FTP entries are not SSH servers and
236
+ // importing them would produce hosts that can never connect.
237
+ if (value(block, 'Protocol') !== '1') {
238
+ const skipped = value(block, 'Name') || value(block, 'Host');
239
+ warnings.push(`"${skipped}" is not SFTP — skipped`);
240
+ continue;
241
+ }
242
+ const server = normalise({
243
+ name: value(block, 'Name') || value(block, 'Host'),
244
+ host: value(block, 'Host'),
245
+ user: value(block, 'User'),
246
+ port: value(block, 'Port'),
247
+ keyPath: value(block, 'Keyfile'),
248
+ defaultDir: value(block, 'RemoteDir').replace(/^\d+\s+\d+\s+/, '') || '',
249
+ description: value(block, 'Comments'),
250
+ }, warnings);
251
+ if (server) servers.push(server);
252
+ }
253
+ return servers;
254
+ },
255
+ },
256
+ {
257
+ id: 'putty',
258
+ label: 'PuTTY (exported .reg)',
259
+ detect: (name, text) => text.includes('SimonTatham\\PuTTY\\Sessions'),
260
+ parse(text, file, warnings) {
261
+ /** @type {ImportedServer[]} */
262
+ const servers = [];
263
+ for (const section of text.split(/^\[/m).slice(1)) {
264
+ const header = section.split(']')[0];
265
+ if (!header.includes('PuTTY\\Sessions\\')) continue;
266
+ const raw = header.split('Sessions\\').pop();
267
+ // Session names are percent-encoded in the registry path.
268
+ const name = decodeURIComponent(raw.replace(/%(?![0-9a-fA-F]{2})/g, '%25'));
269
+ const str = key => new RegExp(`"${key}"="([^"]*)"`).exec(section)?.[1];
270
+ const dword = key => {
271
+ const hex = new RegExp(`"${key}"=dword:([0-9a-fA-F]+)`).exec(section)?.[1];
272
+ return hex ? parseInt(hex, 16) : undefined;
273
+ };
274
+ if ((str('Protocol') || 'ssh').toLowerCase() !== 'ssh') {
275
+ warnings.push(`"${name}" is not an SSH session — skipped`);
276
+ continue;
277
+ }
278
+ const server = normalise({
279
+ name,
280
+ host: str('HostName'),
281
+ user: str('UserName'),
282
+ port: dword('PortNumber'),
283
+ // A .ppk is PuTTY's own key format; ssh2 cannot read it. Say so
284
+ // rather than storing a path that will fail at connection time.
285
+ keyPath: /\.ppk$/i.test(str('PublicKeyFile') || '') ? '' : str('PublicKeyFile'),
286
+ }, warnings);
287
+ if (server) {
288
+ if (/\.ppk$/i.test(str('PublicKeyFile') || '')) {
289
+ warnings.push(`"${name}" uses a .ppk key — convert it with \`puttygen key.ppk -O private-openssh -o key\``);
290
+ }
291
+ servers.push(server);
292
+ }
293
+ }
294
+ return servers;
295
+ },
296
+ },
297
+ {
298
+ id: 'termius',
299
+ label: 'Termius (JSON export)',
300
+ detect: (name, text) => /^\s*[[{]/.test(text) && /"(address|hosts)"/.test(text),
301
+ parse(text, file, warnings) {
302
+ const data = JSON.parse(text);
303
+ const list = Array.isArray(data) ? data : data.hosts || data.servers || [];
304
+ /** @type {Map<string, string>} */
305
+ const groups = new Map();
306
+ for (const group of data.groups || []) groups.set(String(group.id), group.label || group.name);
307
+ return list.map(entry => normalise({
308
+ name: entry.label || entry.name || entry.address,
309
+ host: entry.address || entry.host || entry.hostname,
310
+ user: entry.username || entry.user || entry.ssh?.username,
311
+ port: entry.port || entry.ssh?.port,
312
+ group: groups.get(String(entry.group ?? entry.group_id)) || entry.group_label,
313
+ description: entry.description || entry.tags?.join(', '),
314
+ }, warnings)).filter(Boolean);
315
+ },
316
+ },
317
+ {
318
+ id: 'mobaxterm',
319
+ label: 'MobaXterm (.mxtsessions)',
320
+ detect: name => name.toLowerCase().endsWith('.mxtsessions'),
321
+ parse(text, file, warnings) {
322
+ /** @type {ImportedServer[]} */
323
+ const servers = [];
324
+ // The folder a bookmark lives in is `SubRep=`, not the section header —
325
+ // the header is `[Bookmarks_1]`, an index, which is not a name anyone
326
+ // chose or would recognise as their group.
327
+ let folder = '';
328
+ for (const line of text.split('\n')) {
329
+ const trimmed = line.trim();
330
+ if (!trimmed) continue;
331
+ if (trimmed.startsWith('[')) { folder = ''; continue; }
332
+ const at = trimmed.indexOf('=');
333
+ if (at < 0) continue;
334
+ const name = trimmed.slice(0, at);
335
+ const body = trimmed.slice(at + 1);
336
+ if (name === 'SubRep') { folder = body.split('\\').pop(); continue; }
337
+ if (name === 'ImgNum') continue;
338
+ // `#<type>#<n>%host%port%user%…`; type 109 is SSH.
339
+ const typed = /^#(\d+)#\d+%(.*)$/.exec(body);
340
+ if (!typed) continue;
341
+ if (typed[1] !== '109') { warnings.push(`"${name}" is not an SSH session — skipped`); continue; }
342
+ const parts = typed[2].split('%');
343
+ const server = normalise({
344
+ name, host: parts[0], port: parts[1], user: parts[2],
345
+ group: folder,
346
+ }, warnings);
347
+ if (server) servers.push(server);
348
+ }
349
+ return servers;
350
+ },
351
+ },
352
+ {
353
+ id: 'csv',
354
+ label: 'CSV',
355
+ // Deliberately last, and deliberately grudging. This is the only reader
356
+ // that guesses from content alone, and it used to claim a Termius export:
357
+ // the JSON's first line contains "address" and commas, which was enough.
358
+ detect: (name, text) => name.toLowerCase().endsWith('.csv')
359
+ || (!/^\s*[[{<]/.test(text)
360
+ && /^[^\n]*\b(host|hostname|address)\b[^\n]*[,;]/i.test(text)),
361
+ parse: (text, file, warnings) => fromTable(splitCsv(text), warnings),
362
+ },
363
+ ];
364
+
365
+ /* ------------------------------------------------------------- entry points */
366
+
367
+ /** Where each application keeps its list, when it keeps one somewhere findable. */
368
+ export const WELL_KNOWN = {
369
+ 'ssh-config': () => [path.join(os.homedir(), '.ssh', 'config')],
370
+ filezilla: () => [
371
+ path.join(os.homedir(), '.config', 'filezilla', 'sitemanager.xml'),
372
+ path.join(os.homedir(), 'Library', 'Application Support', 'FileZilla', 'sitemanager.xml'),
373
+ path.join(os.homedir(), 'AppData', 'Roaming', 'FileZilla', 'sitemanager.xml'),
374
+ ],
375
+ };
376
+
377
+ /**
378
+ * Transmit keeps one binary plist per favourite, so it is a directory rather
379
+ * than a file and cannot be a normal reader.
380
+ *
381
+ * Read through `plutil`, which is on every Mac and is the only supported way to
382
+ * decode a binary plist. Transmit is macOS-only, so there is no other platform
383
+ * to care about.
384
+ *
385
+ * @param {string[]} warnings
386
+ * @returns {ImportedServer[]}
387
+ */
388
+ export function readTransmit(warnings) {
389
+ const dir = path.join(os.homedir(), 'Library', 'Application Support', 'Transmit', 'Metadata');
390
+ if (process.platform !== 'darwin' || !fs.existsSync(dir)) return [];
391
+ /** @type {ImportedServer[]} */
392
+ const servers = [];
393
+ for (const file of fs.readdirSync(dir).filter(f => f.endsWith('.favoriteMetadata'))) {
394
+ try {
395
+ const json = execFileSync('plutil', ['-convert', 'json', '-o', '-', path.join(dir, file)],
396
+ { encoding: 'utf8', timeout: 5000 });
397
+ const entry = JSON.parse(json);
398
+ const protocol = String(entry.com_panic_transmit_protocol || '').toUpperCase();
399
+ // Transmit does FTP and WebDAV too; only SFTP is an SSH server.
400
+ if (protocol && !protocol.includes('SFTP')) {
401
+ warnings.push(`"${entry.com_panic_transmit_nickname || file}" is ${protocol} — skipped`);
402
+ continue;
403
+ }
404
+ const server = normalise({
405
+ name: entry.com_panic_transmit_nickname,
406
+ host: entry.com_panic_transmit_server,
407
+ user: entry.com_panic_transmit_username,
408
+ port: entry.com_panic_transmit_port,
409
+ }, warnings);
410
+ if (server) servers.push(server);
411
+ } catch (error) {
412
+ warnings.push(`Could not read ${file}: ${error.message}`);
413
+ }
414
+ }
415
+ return servers;
416
+ }
417
+
418
+ /**
419
+ * Read a file, whatever it turns out to be.
420
+ *
421
+ * @param {string} file - Path to the export
422
+ * @param {string} [forceId] - Skip detection and use this reader
423
+ * @returns {{servers: ImportedServer[], source: string, warnings: string[]}}
424
+ */
425
+ export function importFile(file, forceId) {
426
+ if (!fs.existsSync(file)) throw new Error(`No such file: ${file}`);
427
+ const name = path.basename(file);
428
+ // A spreadsheet is a zip; reading it as text would be nonsense, so only read
429
+ // enough to sniff with and let the reader open the file itself if it needs to.
430
+ const isBinary = /\.xlsx$/i.test(name);
431
+ const text = isBinary ? '' : fs.readFileSync(file, 'utf8');
432
+
433
+ const reader = forceId
434
+ ? READERS.find(r => r.id === forceId)
435
+ : READERS.find(r => r.detect(name, text));
436
+ if (!reader) {
437
+ throw new Error(
438
+ `Cannot tell what ${name} is. Name the format with --format <id>, one of: `
439
+ + READERS.map(r => r.id).join(', '));
440
+ }
441
+
442
+ /** @type {string[]} */
443
+ const warnings = [];
444
+ const servers = reader.parse(text, file, warnings);
445
+ logger.info('Servers read for import', { source: reader.id, count: servers.length });
446
+ return { servers, source: reader.label, warnings };
447
+ }
448
+
449
+ /**
450
+ * Merge imported servers over what is already configured.
451
+ *
452
+ * Existing entries are never silently overwritten: a name that already exists
453
+ * comes back as a conflict for the caller to decide about. Import is additive
454
+ * or it is a footgun.
455
+ *
456
+ * @param {ImportedServer[]} incoming
457
+ * @param {string[]} existing - Names already configured
458
+ * @returns {{fresh: ImportedServer[], conflicts: ImportedServer[]}}
459
+ */
460
+ export function plan(incoming, existing) {
461
+ const known = new Set(existing.map(name => name.toLowerCase()));
462
+ const seen = new Set();
463
+ /** @type {ImportedServer[]} */
464
+ const fresh = [];
465
+ /** @type {ImportedServer[]} */
466
+ const conflicts = [];
467
+ for (const server of incoming) {
468
+ // Two rows can slug to the same name; the second gets a suffix rather than
469
+ // silently replacing the first.
470
+ let name = server.name;
471
+ for (let n = 2; seen.has(name); n++) name = `${server.name}_${n}`;
472
+ seen.add(name);
473
+ const resolved = { ...server, name };
474
+ (known.has(name) ? conflicts : fresh).push(resolved);
475
+ }
476
+ return { fresh, conflicts };
477
+ }
@@ -48,7 +48,14 @@ export function shellPath(value) {
48
48
  * @returns {number} A non-negative integer
49
49
  */
50
50
  export function safeInteger(value, fallback) {
51
- const n = Number(value);
51
+ let n;
52
+ try {
53
+ n = Number(value);
54
+ } catch {
55
+ return fallback; // an object that cannot become a number at all (found by the property test)
56
+ }
52
57
  if (!Number.isFinite(n)) return fallback;
53
- return Math.max(0, Math.trunc(n));
58
+ // Capped: above 2^53 a number is no longer exact, and from 1e21 up it prints
59
+ // as "1e+21", which no command reads as a count (found by the property test).
60
+ return Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.trunc(n)));
54
61
  }
@@ -0,0 +1,155 @@
1
+ import SSHManager from './ssh-manager.js';
2
+ import { resolveServerName } from './server-aliases.js';
3
+
4
+ // Create a socket from a proxy command (e.g., "ncat --proxy 127.0.0.1:1080 --proxy-type socks5 %h %p")
5
+ // The command is executed through the system shell, matching OpenSSH ProxyCommand semantics,
6
+ // so quoted arguments and shell metacharacters work as users expect.
7
+ async function createProxyCommandSocket(proxyCommand, host, port) {
8
+ const { spawn } = await import('child_process');
9
+ const { Duplex } = await import('stream');
10
+
11
+ const cmd = proxyCommand.replace(/%h/g, host).replace(/%p/g, port.toString());
12
+
13
+ return new Promise((resolve, reject) => {
14
+ const child = spawn(cmd, {
15
+ shell: true,
16
+ stdio: ['pipe', 'pipe', 'pipe']
17
+ });
18
+
19
+ // Cast: Node accepts a {readable, writable} pair here, but the bundled
20
+ // types only model the stream/iterable overloads.
21
+ const socket = Duplex.from(/** @type {any} */ ({
22
+ readable: child.stdout,
23
+ writable: child.stdin,
24
+ allowHalfOpen: false
25
+ }));
26
+
27
+ // Forward proxy stderr to the MCP server's stderr for debugging
28
+ child.stderr.on('data', (chunk) => {
29
+ process.stderr.write(`[proxy-command] ${chunk}`);
30
+ });
31
+
32
+ let settled = false;
33
+ const settle = (fn, arg) => {
34
+ if (settled) return;
35
+ settled = true;
36
+ fn(arg);
37
+ };
38
+
39
+ socket.on('close', () => {
40
+ if (!child.killed) child.kill();
41
+ });
42
+
43
+ child.on('error', (err) => settle(reject, err));
44
+ child.on('spawn', () => settle(resolve, socket));
45
+ child.on('exit', (code, signal) => {
46
+ // Only surface unexpected exits — a kill() after a successful connection is normal.
47
+ if (!settled && code !== 0) {
48
+ settle(reject, new Error(`Proxy command exited with code ${code}${signal ? ` (${signal})` : ''}`));
49
+ } else if (settled && code !== 0 && !signal && !socket.destroyed) {
50
+ socket.destroy(new Error(`Proxy command exited with code ${code}`));
51
+ }
52
+ });
53
+ });
54
+ }
55
+
56
+ /** Validate the complete chain before opening any network connection. */
57
+ function validateProxyChain(name, servers) {
58
+ const seen = new Set();
59
+ let current = name;
60
+ while (current) {
61
+ if (seen.has(current)) throw new Error(`Circular proxy jump detected: ${[...seen, current].join(' -> ')}`);
62
+ seen.add(current);
63
+ const config = servers[current];
64
+ if (!config) throw new Error(`Proxy jump server "${current}" not found`);
65
+ if (!config.proxyJump) break;
66
+ const next = resolveServerName(config.proxyJump, servers);
67
+ if (!next) throw new Error(`Proxy jump server "${config.proxyJump}" not found`);
68
+ current = next;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Shared transport setup for the pooled MCP engine and standalone UI clients.
74
+ * The caller owns ssh; resolveJump supplies either a pooled or an owned client.
75
+ * @param {SSHManager} ssh
76
+ * @param {Record<string, any>} servers
77
+ * @param {{ readyTimeout?: number, resolveJump: (name: string) => Promise<SSHManager> }} options
78
+ * @returns {Promise<string|null>} Canonical jump name, if one was used
79
+ */
80
+ export async function connectSSH(ssh, servers, { readyTimeout, resolveJump }) {
81
+ const config = ssh.config;
82
+ const options = readyTimeout === undefined ? {} : { readyTimeout };
83
+ if (config.proxyJump) {
84
+ validateProxyChain(config.name, servers);
85
+ const jumpName = resolveServerName(config.proxyJump, servers);
86
+ const jump = await resolveJump(jumpName);
87
+ const stream = await jump.forwardOut('127.0.0.1', 0, config.host, config.port || 22);
88
+ try { await ssh.connect({ ...options, sock: stream }); }
89
+ catch (error) { stream.destroy(); throw error; }
90
+ ssh.jumpConnection = jump;
91
+ return jumpName;
92
+ }
93
+ if (config.proxyCommand) {
94
+ const socket = await createProxyCommandSocket(config.proxyCommand, config.host, config.port || 22);
95
+ try { await ssh.connect({ ...options, sock: socket }); }
96
+ catch (error) { socket.destroy(); throw error; }
97
+ } else {
98
+ await ssh.connect(options);
99
+ }
100
+ return null;
101
+ }
102
+
103
+ /**
104
+ * The configuration a connection is opened with, for the person or the agent
105
+ * opening it.
106
+ *
107
+ * A person is never announced as an agent. The AI_AGENT label exists so that
108
+ * a server's logs can tell the two apart, and a human click in the control
109
+ * plane tagged as an agent would be exactly the confusion it is meant to end.
110
+ * Everything else is the server's own configuration, untouched.
111
+ *
112
+ * @param {string} canonical - Resolved server name
113
+ * @param {Record<string, any>} servers - Loaded configuration
114
+ * @param {'agent'|'human'} [actor] - Who is driving this connection
115
+ * @returns {Record<string, any>}
116
+ */
117
+ export function connectionConfig(canonical, servers, actor) {
118
+ const config = { ...servers[canonical], name: canonical };
119
+ if (actor === 'human') config.announceAgent = false;
120
+ return config;
121
+ }
122
+
123
+ /**
124
+ * Open an independent connection and own its entire jump chain. Disposing the
125
+ * returned client releases every transport, including partial setup on error.
126
+ * @param {string} name
127
+ * @param {Record<string, any>} servers
128
+ * @param {{ readyTimeout?: number, actor?: 'agent'|'human' }} [options] - `actor: 'human'` for
129
+ * anything a person started from the control plane
130
+ * @returns {Promise<SSHManager>}
131
+ */
132
+ export async function connectServer(name, servers, options = {}) {
133
+ const { actor, ...connectOptions } = options;
134
+ const canonical = resolveServerName(name, servers);
135
+ if (!canonical) throw new Error(`Server "${name}" not found`);
136
+ validateProxyChain(canonical, servers);
137
+ const ssh = new SSHManager(connectionConfig(canonical, servers, actor));
138
+ const owned = [];
139
+ const dispose = ssh.dispose.bind(ssh);
140
+ ssh.dispose = () => {
141
+ try { dispose(); }
142
+ finally { for (const jump of owned.splice(0)) jump.dispose(); }
143
+ };
144
+ try {
145
+ await connectSSH(ssh, servers, { ...connectOptions, resolveJump: async jumpName => {
146
+ const jump = await connectServer(jumpName, servers, options);
147
+ owned.push(jump);
148
+ return jump;
149
+ } });
150
+ return ssh;
151
+ } catch (error) {
152
+ ssh.dispose();
153
+ throw error;
154
+ }
155
+ }