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,747 @@
1
+ // Getting the desktop application from the npm engine.
2
+ //
3
+ // Someone who installed mcp-ssh-manager from npm has the engine, the CLI and
4
+ // the browser control plane. The desktop application is the same control plane
5
+ // in a window, with a menu bar item and native notifications. This module is
6
+ // the one path from the first to the second, used by `ssh-manager app` and by
7
+ // the control plane's "Install the app" button.
8
+ //
9
+ // ## What gets installed, and why it can be trusted
10
+ //
11
+ // The engine installs the application of **its own version**: release tag
12
+ // `v<package.json version>`, never "the latest". A beta engine installs its
13
+ // beta, and 4.0.0 never pulls 4.1.0 in behind the user's back.
14
+ //
15
+ // The release publishes `release-manifest-<platform>.json` beside the
16
+ // installers, listing every file with its size and SHA-256. The release
17
+ // workflow refuses to publish an artifact that differs from it, so it is the
18
+ // reference. Nothing is installed unless all of this holds:
19
+ //
20
+ // 1. the downloaded bytes have the manifest's size and SHA-256, computed
21
+ // while downloading into a private temporary directory;
22
+ // 2. on macOS, the unpacked application passes `codesign --verify --deep
23
+ // --strict`, is signed by our Developer ID team, and Gatekeeper accepts it
24
+ // (`spctl`), which means Apple notarized it. On Windows and Linux the
25
+ // hash is the check.
26
+ //
27
+ // Any failure removes the temporary directory and installs nothing.
28
+ //
29
+ // Every download is HTTPS. The base URL is a parameter for the tests, which
30
+ // stand in for the release with a local HTTP server; plain HTTP is accepted
31
+ // only when that base is itself a loopback address. There is deliberately no
32
+ // environment variable to point this elsewhere.
33
+
34
+ import crypto from 'crypto';
35
+ import fs from 'fs';
36
+ import http from 'http';
37
+ import https from 'https';
38
+ import os from 'os';
39
+ import path from 'path';
40
+ import { spawn } from 'child_process';
41
+ import { Transform } from 'stream';
42
+ import { pipeline } from 'stream/promises';
43
+
44
+ /** Where people can pick a file by hand when there is nothing to install here. */
45
+ export const RELEASES_PAGE = 'https://github.com/bvisible/mcp-ssh-manager/releases';
46
+
47
+ /** Release assets live under `<this>/v<version>/<file>`. */
48
+ const RELEASE_BASE_URL = `${RELEASES_PAGE}/download`;
49
+
50
+ /** A version this project releases: 4.0.0, 4.0.0-beta.3. Nothing else reaches a URL. */
51
+ const RELEASE_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*)?$/;
52
+
53
+ /** The Developer ID team of bVisible Sarl, which signs and notarizes the macOS build. */
54
+ const TEAM_ID = 'BT249938WK';
55
+
56
+ /** electron-builder's productName: the bundle, the Windows directory and executable. */
57
+ const APP_NAME = 'SSH Manager';
58
+
59
+ /** The same name as it appears in release file names, spaces made hyphens. */
60
+ const ARTIFACT_PREFIX = 'SSH-Manager';
61
+
62
+ /** The Linux .deb puts this on the PATH (the desktop package's npm name). */
63
+ const LINUX_BINARY = 'ssh-manager-desktop';
64
+
65
+ /** Where the AppImage route installs to, under the home directory. */
66
+ const APPIMAGE_NAME = 'SSH-Manager.AppImage';
67
+
68
+ /** A manifest is a few hundred bytes; anything this large is not one. */
69
+ const MANIFEST_LIMIT_BYTES = 1024 * 1024;
70
+
71
+ /** GitHub sends one redirect, to its asset host. A chain this long is a loop. */
72
+ const MAX_REDIRECTS = 5;
73
+
74
+ /** A download that sends nothing for this long has stopped. */
75
+ const IDLE_TIMEOUT_MS = 30 * 1000;
76
+
77
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
78
+
79
+ /**
80
+ * @typedef {Object} DesktopStatus
81
+ * @property {boolean} supported - A release artifact exists for this platform and architecture
82
+ * @property {boolean} installed - The application is where its installer puts it
83
+ * @property {string|null} path - What to open: the .app, the .exe, the binary or the AppImage
84
+ * @property {string|null} version - Its version, when it can be read
85
+ * @property {'auto'|'terminal'|null} method - How a fresh install runs: by itself, or in a terminal (sudo)
86
+ */
87
+
88
+ /**
89
+ * @typedef {Object} DesktopProgress
90
+ * @property {'manifest'|'download'|'verify'|'install'} phase - Where the installation is
91
+ * @property {number} received - Bytes downloaded so far
92
+ * @property {number} total - Bytes the release says the file has; 0 before the manifest is read
93
+ * @property {string} [file] - The release file being downloaded
94
+ * @property {'sha256'|'apple'} [passed] - A check that has just passed, during `verify`
95
+ */
96
+
97
+ /**
98
+ * What a step reports; the byte counts carry over from the last report.
99
+ * @typedef {Omit<Partial<DesktopProgress>, 'phase'> & {phase: DesktopProgress['phase']}} ProgressUpdate
100
+ */
101
+
102
+ /**
103
+ * @typedef {Object} RunResult
104
+ * @property {number} code - Exit status; 0 when a detached process was started
105
+ * @property {string} stdout - Captured output (empty with `stdio: 'inherit'`)
106
+ * @property {string} stderr - Captured errors (empty with `stdio: 'inherit'`)
107
+ */
108
+
109
+ /**
110
+ * Runs a command. Injectable, so the tests never touch the real system.
111
+ * @callback Runner
112
+ * @param {string} command - Program to run
113
+ * @param {string[]} args - Its arguments, never through a shell
114
+ * @param {{detached?: boolean, stdio?: 'inherit'}} [options] - `detached` starts it and returns at once;
115
+ * `inherit` hands it the terminal (sudo asks for its password there)
116
+ * @returns {Promise<RunResult>}
117
+ */
118
+
119
+ /**
120
+ * @typedef {Object} DesktopError
121
+ * @property {'UNSUPPORTED'|'NEEDS_TERMINAL'|'NOT_FOUND'|'DOWNLOAD'|'VERIFY'|'INSTALL'} code
122
+ */
123
+
124
+ /**
125
+ * @param {DesktopError['code']} code - What kind of failure, for the caller's exit code
126
+ * @param {string} message - What a person reads
127
+ * @returns {Error & DesktopError}
128
+ */
129
+ function desktopError(code, message) {
130
+ return Object.assign(new Error(message), { code });
131
+ }
132
+
133
+ /**
134
+ * The engine's own version, which is the application version it installs.
135
+ * @returns {string}
136
+ */
137
+ export function engineVersion() {
138
+ return JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
139
+ }
140
+
141
+ /**
142
+ * Compare two versions, prereleases included: 4.0.0-beta.2 < 4.0.0-beta.10 < 4.0.0.
143
+ * @param {string} a
144
+ * @param {string} b
145
+ * @returns {number} Negative when a is older, 0 when equal, positive when newer
146
+ */
147
+ export function compareVersions(a, b) {
148
+ const split = value => {
149
+ const text = String(value).replace(/^v/, '').split('+')[0];
150
+ const dash = text.indexOf('-');
151
+ return {
152
+ core: (dash < 0 ? text : text.slice(0, dash)).split('.').map(part => Number(part) || 0),
153
+ pre: dash < 0 ? [] : text.slice(dash + 1).split('.'),
154
+ };
155
+ };
156
+ const left = split(a);
157
+ const right = split(b);
158
+ for (let i = 0; i < 3; i++) {
159
+ const diff = (left.core[i] || 0) - (right.core[i] || 0);
160
+ if (diff) return diff;
161
+ }
162
+ // A release ranks above any of its prereleases.
163
+ if (!left.pre.length || !right.pre.length) return right.pre.length - left.pre.length;
164
+ for (let i = 0; i < Math.max(left.pre.length, right.pre.length); i++) {
165
+ const x = left.pre[i];
166
+ const y = right.pre[i];
167
+ if (x === undefined) return -1;
168
+ if (y === undefined) return 1;
169
+ const numeric = /^\d+$/.test(x) && /^\d+$/.test(y);
170
+ if (numeric && Number(x) !== Number(y)) return Number(x) - Number(y);
171
+ if (!numeric && x !== y) {
172
+ // Numeric identifiers rank below alphanumeric ones, as semver has it.
173
+ if (/^\d+$/.test(x)) return -1;
174
+ if (/^\d+$/.test(y)) return 1;
175
+ return x < y ? -1 : 1;
176
+ }
177
+ }
178
+ return 0;
179
+ }
180
+
181
+ /**
182
+ * @param {NodeJS.ProcessEnv} env
183
+ * @returns {string}
184
+ */
185
+ function homeOf(env) {
186
+ return env.HOME || env.USERPROFILE || os.homedir();
187
+ }
188
+
189
+ /** @param {string} file */
190
+ function isFile(file) {
191
+ try { return fs.statSync(file).isFile(); } catch { return false; }
192
+ }
193
+
194
+ /** @param {string} dir */
195
+ function isDirectory(dir) {
196
+ try { return fs.statSync(dir).isDirectory(); } catch { return false; }
197
+ }
198
+
199
+ /** @param {string} dir */
200
+ function isWritable(dir) {
201
+ try {
202
+ fs.accessSync(dir, fs.constants.W_OK);
203
+ return isDirectory(dir);
204
+ } catch {
205
+ return false;
206
+ }
207
+ }
208
+
209
+ /**
210
+ * An executable on the PATH, found by looking rather than by running `which`.
211
+ * @param {string} name
212
+ * @param {NodeJS.ProcessEnv} env
213
+ * @param {string} platform
214
+ * @returns {string|null}
215
+ */
216
+ function findOnPath(name, env, platform) {
217
+ const delimiter = platform === 'win32' ? ';' : ':';
218
+ for (const dir of String(env.PATH || '').split(delimiter)) {
219
+ if (!dir) continue;
220
+ const candidate = path.join(dir, name);
221
+ try {
222
+ fs.accessSync(candidate, fs.constants.X_OK);
223
+ if (isFile(candidate)) return candidate;
224
+ } catch { /* not here */ }
225
+ }
226
+ return null;
227
+ }
228
+
229
+ /**
230
+ * The engine copy inside an installed application carries the same version as
231
+ * the application: they are built and released together.
232
+ * @param {string} resourcesDir - The application's `resources` directory
233
+ * @returns {string|null}
234
+ */
235
+ function bundledEngineVersion(resourcesDir) {
236
+ try {
237
+ return JSON.parse(fs.readFileSync(path.join(resourcesDir, 'engine', 'package.json'), 'utf8')).version || null;
238
+ } catch {
239
+ return null;
240
+ }
241
+ }
242
+
243
+ /**
244
+ * @param {string} app - Path to `SSH Manager.app`
245
+ * @returns {string|null}
246
+ */
247
+ function macVersion(app) {
248
+ try {
249
+ const plist = fs.readFileSync(path.join(app, 'Contents', 'Info.plist'), 'utf8');
250
+ const match = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(plist);
251
+ if (match) return match[1].trim();
252
+ } catch { /* unreadable: try the engine copy */ }
253
+ return bundledEngineVersion(path.join(app, 'Contents', 'Resources'));
254
+ }
255
+
256
+ /**
257
+ * Which release file fits this machine, and how it installs.
258
+ * @param {string} platform
259
+ * @param {string} arch
260
+ * @param {NodeJS.ProcessEnv} env
261
+ * @returns {{suffix: string, kind: 'mac'|'windows'|'deb'|'appimage', method: 'auto'|'terminal'}|null}
262
+ */
263
+ function releaseTarget(platform, arch, env) {
264
+ if (platform === 'darwin' && (arch === 'arm64' || arch === 'x64')) {
265
+ return { suffix: `${arch}.zip`, kind: 'mac', method: 'auto' };
266
+ }
267
+ // One NSIS installer carries both architectures.
268
+ if (platform === 'win32' && (arch === 'x64' || arch === 'arm64')) {
269
+ return { suffix: 'setup.exe', kind: 'windows', method: 'auto' };
270
+ }
271
+ if (platform === 'linux' && arch === 'x64') {
272
+ // The .deb sets up Chromium's sandbox and the AppArmor profile, so it is
273
+ // preferred wherever apt can install it — but that needs sudo, and so a
274
+ // terminal where the password can be typed.
275
+ return findOnPath('apt-get', env, platform)
276
+ ? { suffix: 'amd64.deb', kind: 'deb', method: 'terminal' }
277
+ : { suffix: 'x86_64.AppImage', kind: 'appimage', method: 'auto' };
278
+ }
279
+ return null;
280
+ }
281
+
282
+ /**
283
+ * Where an installed application is, looked up at the places its installers use.
284
+ * @param {string} platform
285
+ * @param {NodeJS.ProcessEnv} env
286
+ * @param {string} applicationsDir - The system-wide Applications folder (macOS)
287
+ * @returns {{path: string, version: string|null}|null}
288
+ */
289
+ function findInstalled(platform, env, applicationsDir) {
290
+ const home = homeOf(env);
291
+ if (platform === 'darwin') {
292
+ for (const dir of [applicationsDir, path.join(home, 'Applications')]) {
293
+ const app = path.join(dir, `${APP_NAME}.app`);
294
+ if (isDirectory(app)) return { path: app, version: macVersion(app) };
295
+ }
296
+ }
297
+ if (platform === 'win32') {
298
+ const base = env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
299
+ const exe = path.join(base, 'Programs', APP_NAME, `${APP_NAME}.exe`);
300
+ if (isFile(exe)) return { path: exe, version: bundledEngineVersion(path.join(path.dirname(exe), 'resources')) };
301
+ }
302
+ if (platform === 'linux') {
303
+ const binary = findOnPath(LINUX_BINARY, env, platform);
304
+ if (binary) {
305
+ let real = binary;
306
+ try { real = fs.realpathSync(binary); } catch { /* keep the link */ }
307
+ return { path: binary, version: bundledEngineVersion(path.join(path.dirname(real), 'resources')) };
308
+ }
309
+ // An AppImage is a compressed image: its version cannot be read without mounting it.
310
+ const image = path.join(home, 'Applications', APPIMAGE_NAME);
311
+ if (isFile(image)) return { path: image, version: null };
312
+ }
313
+ return null;
314
+ }
315
+
316
+ /**
317
+ * Whether the application can be installed here, and whether it already is.
318
+ * Reads files only: cheap enough for a menu's status line.
319
+ * @param {Object} [options]
320
+ * @param {string} [options.platform]
321
+ * @param {string} [options.arch]
322
+ * @param {NodeJS.ProcessEnv} [options.env]
323
+ * @param {string} [options.applicationsDir] - The system Applications folder (tests point it elsewhere)
324
+ * @returns {DesktopStatus}
325
+ */
326
+ export function desktopStatus({
327
+ platform = process.platform,
328
+ arch = process.arch,
329
+ env = process.env,
330
+ applicationsDir = '/Applications',
331
+ } = {}) {
332
+ const target = releaseTarget(platform, arch, env);
333
+ const found = findInstalled(platform, env, applicationsDir);
334
+ return {
335
+ supported: Boolean(target),
336
+ installed: Boolean(found),
337
+ path: found?.path ?? null,
338
+ version: found?.version ?? null,
339
+ method: target?.method ?? null,
340
+ };
341
+ }
342
+
343
+ /**
344
+ * The default runner: spawn, never a shell.
345
+ * @type {Runner}
346
+ */
347
+ function runCommand(command, args, options = {}) {
348
+ return new Promise((resolve, reject) => {
349
+ if (options.detached) {
350
+ const child = spawn(command, args, { detached: true, stdio: 'ignore' });
351
+ child.once('error', reject);
352
+ child.once('spawn', () => {
353
+ child.unref();
354
+ resolve({ code: 0, stdout: '', stderr: '' });
355
+ });
356
+ return;
357
+ }
358
+ const child = spawn(command, args, {
359
+ stdio: options.stdio === 'inherit' ? 'inherit' : ['ignore', 'pipe', 'pipe'],
360
+ windowsHide: options.stdio !== 'inherit',
361
+ });
362
+ let stdout = '';
363
+ let stderr = '';
364
+ child.stdout?.on('data', chunk => { stdout += chunk; });
365
+ child.stderr?.on('data', chunk => { stderr += chunk; });
366
+ child.once('error', reject);
367
+ child.once('close', code => resolve({ code: code ?? 1, stdout, stderr }));
368
+ });
369
+ }
370
+
371
+ /**
372
+ * Is the application running right now?
373
+ *
374
+ * macOS's `open` brings a running application forward, but on Linux and
375
+ * Windows launching it again starts a second copy, which then fights the first
376
+ * for the approval socket. Any failure to tell answers "no".
377
+ *
378
+ * @param {Object} [options]
379
+ * @param {string} [options.platform]
380
+ * @param {Runner} [options.run]
381
+ * @returns {Promise<boolean>}
382
+ */
383
+ export async function desktopRunning({ platform = process.platform, run = runCommand } = {}) {
384
+ try {
385
+ if (platform === 'win32') {
386
+ const { stdout } = await run('tasklist', ['/FO', 'CSV', '/NH', '/FI', `IMAGENAME eq ${APP_NAME}.exe`]);
387
+ return stdout.includes(`"${APP_NAME}.exe"`);
388
+ }
389
+ const { code, stdout } = await run('ps', ['-A', '-o', 'command=']);
390
+ if (code !== 0) return false;
391
+ const markers = platform === 'darwin'
392
+ ? [`/${APP_NAME}.app/Contents/MacOS/${APP_NAME}`]
393
+ : [`/${LINUX_BINARY}`, `/${APPIMAGE_NAME}`, `/opt/${APP_NAME}/`];
394
+ return stdout.split('\n').some(line => markers.some(marker => line.includes(marker)));
395
+ } catch {
396
+ return false;
397
+ }
398
+ }
399
+
400
+ /**
401
+ * GET a URL and hand back the response, following redirects. HTTPS only,
402
+ * except loopback HTTP when the caller allows it (a test standing in for the
403
+ * release).
404
+ * @param {URL} url
405
+ * @param {boolean} allowLoopbackHttp
406
+ * @param {number} [redirects]
407
+ * @returns {Promise<import('http').IncomingMessage>}
408
+ */
409
+ function get(url, allowLoopbackHttp, redirects = 0) {
410
+ return new Promise((resolve, reject) => {
411
+ const secure = url.protocol === 'https:';
412
+ if (!secure && !(allowLoopbackHttp && url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))) {
413
+ reject(desktopError('DOWNLOAD', `Refusing to download over ${url.protocol.replace(':', '')} from ${url.host}: HTTPS only`));
414
+ return;
415
+ }
416
+ const request = (secure ? https : http).get(url, {
417
+ headers: { 'user-agent': 'mcp-ssh-manager', accept: 'application/octet-stream, application/json' },
418
+ }, response => {
419
+ const status = response.statusCode || 0;
420
+ if (status >= 300 && status < 400 && response.headers.location) {
421
+ response.resume();
422
+ if (redirects >= MAX_REDIRECTS) {
423
+ reject(desktopError('DOWNLOAD', 'Too many redirects'));
424
+ return;
425
+ }
426
+ let next;
427
+ try {
428
+ next = new URL(response.headers.location, url);
429
+ } catch {
430
+ reject(desktopError('DOWNLOAD', 'The release answered with an unreadable redirect'));
431
+ return;
432
+ }
433
+ resolve(get(next, allowLoopbackHttp, redirects + 1));
434
+ return;
435
+ }
436
+ if (status !== 200) {
437
+ response.resume();
438
+ const file = decodeURIComponent(url.pathname.split('/').pop() || '');
439
+ reject(desktopError(status === 404 ? 'NOT_FOUND' : 'DOWNLOAD', `${file}: HTTP ${status}`));
440
+ return;
441
+ }
442
+ resolve(response);
443
+ });
444
+ request.setTimeout(IDLE_TIMEOUT_MS, () => request.destroy(desktopError('DOWNLOAD', 'The download stopped answering')));
445
+ request.on('error', reject);
446
+ });
447
+ }
448
+
449
+ /**
450
+ * @typedef {Object} ManifestEntry
451
+ * @property {string} name
452
+ * @property {number} size
453
+ * @property {string} sha256
454
+ */
455
+
456
+ /**
457
+ * Read and check the release manifest for one platform.
458
+ * @param {URL} base - The release directory, ending in `/`
459
+ * @param {string} version
460
+ * @param {string} platform
461
+ * @param {boolean} allowLoopbackHttp
462
+ * @returns {Promise<ManifestEntry[]>}
463
+ */
464
+ async function readManifest(base, version, platform, allowLoopbackHttp) {
465
+ const name = `release-manifest-${platform}.json`;
466
+ let response;
467
+ try {
468
+ response = await get(new URL(name, base), allowLoopbackHttp);
469
+ } catch (error) {
470
+ if (error.code === 'NOT_FOUND') {
471
+ throw desktopError('NOT_FOUND', `Release v${version} has no desktop build for this platform (${name} not found). `
472
+ + `See ${RELEASES_PAGE}`);
473
+ }
474
+ throw error;
475
+ }
476
+ let text = '';
477
+ response.setEncoding('utf8');
478
+ for await (const chunk of response) {
479
+ text += chunk;
480
+ if (text.length > MANIFEST_LIMIT_BYTES) {
481
+ response.destroy();
482
+ throw desktopError('VERIFY', `${name} is too large to be a release manifest`);
483
+ }
484
+ }
485
+ /** @type {any} */
486
+ let manifest;
487
+ try {
488
+ manifest = JSON.parse(text);
489
+ } catch {
490
+ throw desktopError('VERIFY', `${name} is not valid JSON`);
491
+ }
492
+ if (manifest?.version !== version || manifest?.platform !== platform || !Array.isArray(manifest.files)) {
493
+ throw desktopError('VERIFY', `${name} does not describe release v${version} for ${platform}`);
494
+ }
495
+ return manifest.files;
496
+ }
497
+
498
+ /**
499
+ * Stream a file to disk, hashing as it arrives and refusing a single byte more
500
+ * than the release announced.
501
+ * @param {URL} url
502
+ * @param {string} file - Destination, created exclusively
503
+ * @param {number} expected - Size from the manifest
504
+ * @param {(received: number) => void} onBytes
505
+ * @param {boolean} allowLoopbackHttp
506
+ * @returns {Promise<{size: number, sha256: string}>}
507
+ */
508
+ async function download(url, file, expected, onBytes, allowLoopbackHttp) {
509
+ const response = await get(url, allowLoopbackHttp);
510
+ const announced = Number(response.headers['content-length']);
511
+ if (Number.isFinite(announced) && announced > 0 && announced !== expected) {
512
+ response.destroy();
513
+ throw desktopError('VERIFY', `The server is sending ${announced} bytes; release says ${expected}`);
514
+ }
515
+ const hash = crypto.createHash('sha256');
516
+ let received = 0;
517
+ const meter = new Transform({
518
+ transform(chunk, _encoding, callback) {
519
+ received += chunk.length;
520
+ if (received > expected) {
521
+ callback(desktopError('VERIFY', `Larger than the release says (${expected} bytes): refused`));
522
+ return;
523
+ }
524
+ hash.update(chunk);
525
+ onBytes(received);
526
+ callback(null, chunk);
527
+ },
528
+ });
529
+ try {
530
+ await pipeline(response, meter, fs.createWriteStream(file, { flags: 'wx', mode: 0o600 }));
531
+ } catch (error) {
532
+ if (error.code === 'VERIFY' || error.code === 'DOWNLOAD') throw error;
533
+ throw desktopError('DOWNLOAD', `The download was interrupted (${error.message})`);
534
+ }
535
+ return { size: received, sha256: hash.digest('hex') };
536
+ }
537
+
538
+ /**
539
+ * Run a command that must succeed.
540
+ * @param {Runner} run
541
+ * @param {string} command
542
+ * @param {string[]} args
543
+ * @param {DesktopError['code']} code
544
+ * @param {string} message
545
+ * @returns {Promise<RunResult>}
546
+ */
547
+ async function mustRun(run, command, args, code, message) {
548
+ const result = await run(command, args);
549
+ if (result.code !== 0) throw desktopError(code, message);
550
+ return result;
551
+ }
552
+
553
+ /**
554
+ * Unpack, prove it is ours and notarized, then move it into Applications.
555
+ * @param {Object} context
556
+ * @param {string} context.archive
557
+ * @param {string} context.temp
558
+ * @param {Runner} context.run
559
+ * @param {string} context.applicationsDir
560
+ * @param {string} context.home
561
+ * @param {(update: ProgressUpdate) => void} context.report
562
+ * @returns {Promise<string>} Where the application now is
563
+ */
564
+ async function installMac({ archive, temp, run, applicationsDir, home, report }) {
565
+ const unpacked = path.join(temp, 'unpacked');
566
+ fs.mkdirSync(unpacked, { mode: 0o700 });
567
+ // ditto, not unzip: it keeps the bundle's symlinks and extended attributes,
568
+ // without which the signature no longer verifies.
569
+ await mustRun(run, 'ditto', ['-x', '-k', archive, unpacked], 'VERIFY', 'Unpacking the archive failed');
570
+ const app = path.join(unpacked, `${APP_NAME}.app`);
571
+ if (!isDirectory(app)) throw desktopError('VERIFY', `The archive does not contain ${APP_NAME}.app`);
572
+
573
+ await mustRun(run, 'codesign', ['--verify', '--deep', '--strict', app], 'VERIFY',
574
+ 'The code signature does not verify: nothing was installed');
575
+ const details = await run('codesign', ['-dv', '--verbose=2', app]);
576
+ const team = /^TeamIdentifier=(\S+)$/m.exec(`${details.stdout}\n${details.stderr}`)?.[1];
577
+ if (details.code !== 0 || team !== TEAM_ID) {
578
+ throw desktopError('VERIFY', `Signed by team ${team || 'unknown'}, not bVisible Sarl (${TEAM_ID}): nothing was installed`);
579
+ }
580
+ await mustRun(run, 'spctl', ['--assess', '--type', 'execute', app], 'VERIFY',
581
+ 'Gatekeeper refuses it (not notarized by Apple): nothing was installed');
582
+ report({ phase: 'verify', passed: 'apple' });
583
+
584
+ report({ phase: 'install' });
585
+ // /Applications is writable by administrators; a standard account gets the
586
+ // per-user folder, which Finder and Spotlight treat the same way.
587
+ const folder = isWritable(applicationsDir) ? applicationsDir : path.join(home, 'Applications');
588
+ fs.mkdirSync(folder, { recursive: true });
589
+ const destination = path.join(folder, `${APP_NAME}.app`);
590
+ if (fs.existsSync(destination)) throw desktopError('INSTALL', `${destination} already exists`);
591
+ try {
592
+ fs.renameSync(app, destination);
593
+ } catch (error) {
594
+ if (error.code !== 'EXDEV') throw desktopError('INSTALL', `Could not move it into ${folder}: ${error.message}`);
595
+ // The temporary directory is on another volume. ditto copies the bundle
596
+ // with everything its signature covers.
597
+ const copied = await run('ditto', [app, destination]);
598
+ if (copied.code !== 0) {
599
+ fs.rmSync(destination, { recursive: true, force: true });
600
+ throw desktopError('INSTALL', `Could not copy it into ${folder}`);
601
+ }
602
+ }
603
+ return destination;
604
+ }
605
+
606
+ /**
607
+ * Download, verify and install the desktop application. Installs nothing
608
+ * unless every check passes; when it is already installed, downloads nothing.
609
+ *
610
+ * @param {Object} [options]
611
+ * @param {string} [options.version] - Release to install; the engine's own by default
612
+ * @param {string} [options.platform]
613
+ * @param {string} [options.arch]
614
+ * @param {NodeJS.ProcessEnv} [options.env]
615
+ * @param {string} [options.baseUrl] - Release download root (tests only)
616
+ * @param {(progress: DesktopProgress) => void} [options.onProgress]
617
+ * @param {Runner} [options.run]
618
+ * @param {boolean} [options.terminal] - A person is at a terminal, so `sudo` may ask for a password
619
+ * @param {string} [options.applicationsDir] - The system Applications folder (tests only)
620
+ * @param {string} [options.tmpRoot] - Where the private temporary directory is made
621
+ * @returns {Promise<{path: string, version: string|null, downloaded: boolean}>}
622
+ */
623
+ export async function installDesktop({
624
+ version = engineVersion(),
625
+ platform = process.platform,
626
+ arch = process.arch,
627
+ env = process.env,
628
+ baseUrl = RELEASE_BASE_URL,
629
+ onProgress = () => {},
630
+ run = runCommand,
631
+ terminal = false,
632
+ applicationsDir = '/Applications',
633
+ tmpRoot = os.tmpdir(),
634
+ } = {}) {
635
+ const before = desktopStatus({ platform, arch, env, applicationsDir });
636
+ if (before.installed) return { path: before.path, version: before.version, downloaded: false };
637
+
638
+ const target = releaseTarget(platform, arch, env);
639
+ if (!target) {
640
+ throw desktopError('UNSUPPORTED', `There is no desktop build for ${platform} ${arch}. See ${RELEASES_PAGE}`);
641
+ }
642
+ if (target.method === 'terminal' && !terminal) {
643
+ throw desktopError('NEEDS_TERMINAL', 'Installing the .deb needs your password: run `ssh-manager app` in a terminal');
644
+ }
645
+
646
+ const root = new URL(baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`);
647
+ const allowLoopbackHttp = root.protocol === 'http:' && LOOPBACK_HOSTS.has(root.hostname);
648
+ if (root.protocol !== 'https:' && !allowLoopbackHttp) {
649
+ throw desktopError('DOWNLOAD', `Refusing to download from ${root.origin}: HTTPS only`);
650
+ }
651
+ // The version comes from a file (the engine's own package.json) and becomes
652
+ // part of the download URL and of the file name: only a release version may.
653
+ if (!RELEASE_VERSION.test(version)) {
654
+ throw desktopError('NOT_FOUND', `Not a release version: ${JSON.stringify(version)}. See ${RELEASES_PAGE}`);
655
+ }
656
+ const base = new URL(`v${encodeURIComponent(version)}/`, root);
657
+ const name = `${ARTIFACT_PREFIX}-${version}-${target.suffix}`;
658
+
659
+ let received = 0;
660
+ let total = 0;
661
+ /** @param {ProgressUpdate} update */
662
+ const report = update => {
663
+ received = update.received ?? received;
664
+ total = update.total ?? total;
665
+ onProgress({ ...update, received, total });
666
+ };
667
+
668
+ const temp = fs.mkdtempSync(path.join(tmpRoot, 'ssh-manager-app-'));
669
+ try {
670
+ fs.chmodSync(temp, 0o700);
671
+
672
+ report({ phase: 'manifest' });
673
+ const entry = (await readManifest(base, version, platform, allowLoopbackHttp)).find(item => item?.name === name);
674
+ if (!entry) throw desktopError('NOT_FOUND', `Release v${version} lists no ${name}. See ${RELEASES_PAGE}`);
675
+ if (!Number.isSafeInteger(entry.size) || entry.size <= 0 || !/^[0-9a-f]{64}$/.test(String(entry.sha256))) {
676
+ throw desktopError('VERIFY', `The manifest entry for ${name} has no usable size and SHA-256`);
677
+ }
678
+
679
+ const file = path.join(temp, name);
680
+ let shown = -1;
681
+ report({ phase: 'download', file: name, received: 0, total: entry.size });
682
+ const got = await download(new URL(encodeURIComponent(name), base), file, entry.size, bytes => {
683
+ // Once per percent: enough for a progress bar, few enough for an event stream.
684
+ const percent = Math.floor((bytes * 100) / entry.size);
685
+ if (percent === shown && bytes !== entry.size) return;
686
+ shown = percent;
687
+ report({ phase: 'download', file: name, received: bytes });
688
+ }, allowLoopbackHttp);
689
+
690
+ report({ phase: 'verify' });
691
+ if (got.size !== entry.size) {
692
+ throw desktopError('VERIFY', `Downloaded ${got.size} bytes; release v${version} says ${entry.size}: nothing was installed`);
693
+ }
694
+ if (got.sha256 !== entry.sha256) {
695
+ throw desktopError('VERIFY', `SHA-256 does not match release v${version}: nothing was installed`);
696
+ }
697
+ report({ phase: 'verify', passed: 'sha256' });
698
+
699
+ const home = homeOf(env);
700
+ if (target.kind === 'mac') {
701
+ await installMac({ archive: file, temp, run, applicationsDir, home, report });
702
+ } else if (target.kind === 'windows') {
703
+ report({ phase: 'install' });
704
+ // Silent, for this user only: no administrator rights, no window.
705
+ const result = await run(file, ['/S', '/currentuser']);
706
+ if (result.code !== 0) throw desktopError('INSTALL', `The installer stopped with code ${result.code}`);
707
+ } else if (target.kind === 'deb') {
708
+ report({ phase: 'install' });
709
+ const result = await run('sudo', ['apt-get', 'install', '-y', file], { stdio: 'inherit' });
710
+ if (result.code !== 0) throw desktopError('INSTALL', `apt-get stopped with code ${result.code}`);
711
+ } else {
712
+ report({ phase: 'install' });
713
+ const folder = path.join(home, 'Applications');
714
+ fs.mkdirSync(folder, { recursive: true });
715
+ const destination = path.join(folder, APPIMAGE_NAME);
716
+ const partial = path.join(folder, `.${APPIMAGE_NAME}.partial`);
717
+ try {
718
+ fs.copyFileSync(file, partial);
719
+ fs.chmodSync(partial, 0o755);
720
+ fs.renameSync(partial, destination);
721
+ } catch (error) {
722
+ fs.rmSync(partial, { force: true });
723
+ throw desktopError('INSTALL', `Could not write ${destination}: ${error.message}`);
724
+ }
725
+ }
726
+
727
+ const after = desktopStatus({ platform, arch, env, applicationsDir });
728
+ if (!after.installed) throw desktopError('INSTALL', 'The installer finished, but the application is not where it should be');
729
+ return { path: after.path, version: after.version ?? version, downloaded: true };
730
+ } finally {
731
+ fs.rmSync(temp, { recursive: true, force: true });
732
+ }
733
+ }
734
+
735
+ /**
736
+ * Start the installed application, detached: it outlives whoever opened it.
737
+ * @param {Object} options
738
+ * @param {string} options.path - From desktopStatus() or installDesktop()
739
+ * @param {string} [options.platform]
740
+ * @param {Runner} [options.run]
741
+ * @returns {Promise<void>}
742
+ */
743
+ export async function openDesktop({ path: target, platform = process.platform, run = runCommand }) {
744
+ if (!target) throw desktopError('INSTALL', 'The desktop application is not installed');
745
+ if (platform === 'darwin') await run('open', [target], { detached: true });
746
+ else await run(target, [], { detached: true });
747
+ }