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,296 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Put a screenshot — or the whole demo video — inside a laptop.
4
+
5
+ A rectangle of interface at the top of a README reads as a screenshot. The same
6
+ rectangle inside a laptop reads as software someone is using. That is the entire
7
+ argument for this file.
8
+
9
+ The laptop is drawn here, in code, rather than pulled from a mockup PSD or a
10
+ stock image: it composites at whatever size the content is, it has no licence
11
+ attached, and it stays a generic aluminium laptop rather than an imitation of a
12
+ particular manufacturer's product.
13
+
14
+ Everything is proportional to the screen, so a 1440x900 recording and a 2880x1800
15
+ still both come out looking like the same machine.
16
+
17
+ Usage:
18
+ python3 scripts/macbook-mockup.py image <in.png> <out.png>
19
+ python3 scripts/macbook-mockup.py video <in.mp4> <out.mp4> <out.gif>
20
+ """
21
+ import pathlib
22
+ import shutil
23
+ import subprocess
24
+ import sys
25
+ import tempfile
26
+
27
+ from PIL import Image, ImageDraw, ImageFilter
28
+
29
+ # Proportions, as fractions of the screen width. Measured off a 14" laptop:
30
+ # thin bezels, a deeper chin under the screen, a base a little wider than the lid.
31
+ BEZEL = 0.0125 # sides and top of the lid
32
+ CHIN = 0.021 # below the screen, where the hinge is
33
+ LID_RADIUS = 0.017
34
+ BASE_OVERHANG = 0.028 # how far the base sticks out past the lid on each side
35
+ BASE_HEIGHT = 0.017
36
+ NOTCH_W = 0.105 # the finger recess in the front edge
37
+ PAD = 0.075 # room around everything for the shadow
38
+
39
+ BODY_LIGHT = (72, 74, 78)
40
+ BODY_DARK = (38, 39, 43)
41
+ BASE_TOP = (96, 98, 103)
42
+ BASE_BOTTOM = (44, 45, 49)
43
+ SCREEN_SURROUND = (18, 18, 20)
44
+
45
+
46
+ def _gradient(size, top, bottom):
47
+ w, h = size
48
+ strip = Image.new('RGB', (1, h))
49
+ px = strip.load()
50
+ for y in range(h):
51
+ t = y / max(h - 1, 1)
52
+ px[0, y] = tuple(round(a + (b - a) * t) for a, b in zip(top, bottom))
53
+ return strip.resize(size, Image.BILINEAR)
54
+
55
+
56
+ def stage(size):
57
+ """The dark ground the laptop stands on, for formats without an alpha channel.
58
+
59
+ GIF and h264 cannot carry the soft shadow, so the choice is a flat colour or
60
+ a deliberate one. A near-black radial gradient reads as a product stage, sits
61
+ correctly on both a light and a dark README, and makes the pale interface on
62
+ the screen the brightest thing in the frame — which is where a reader should
63
+ be looking.
64
+ """
65
+ w, h = size
66
+ small = Image.new('RGB', (64, 64))
67
+ px = small.load()
68
+ cx, cy = 32, 26
69
+ for y in range(64):
70
+ for x in range(64):
71
+ d = (((x - cx) / 40) ** 2 + ((y - cy) / 34) ** 2) ** 0.5
72
+ t = min(1.0, d)
73
+ px[x, y] = (round(26 - 16 * t), round(26 - 16 * t), round(31 - 17 * t))
74
+ return small.resize(size, Image.BICUBIC)
75
+
76
+
77
+ def _rounded(size, radius):
78
+ mask = Image.new('L', size, 0)
79
+ ImageDraw.Draw(mask).rounded_rectangle([0, 0, size[0] - 1, size[1] - 1],
80
+ radius=radius, fill=255)
81
+ return mask
82
+
83
+
84
+ def layout(screen_w, screen_h):
85
+ """Every coordinate the mockup needs, derived from the screen size."""
86
+ u = lambda f: max(1, round(screen_w * f)) # noqa: E731
87
+ bezel, chin, pad = u(BEZEL), u(CHIN), u(PAD)
88
+ lid_w = screen_w + bezel * 2
89
+ lid_h = screen_h + bezel + chin
90
+ base_w = lid_w + u(BASE_OVERHANG) * 2
91
+ base_h = u(BASE_HEIGHT)
92
+ return {
93
+ 'pad': pad, 'bezel': bezel, 'chin': chin,
94
+ 'lid': (lid_w, lid_h), 'base': (base_w, base_h),
95
+ 'lid_radius': u(LID_RADIUS), 'notch_w': u(NOTCH_W),
96
+ 'canvas': (base_w + pad * 2, lid_h + base_h + pad * 2),
97
+ 'lid_xy': (pad + (base_w - lid_w) // 2, pad),
98
+ 'screen_xy': (pad + (base_w - lid_w) // 2 + bezel, pad + bezel),
99
+ }
100
+
101
+
102
+ def chrome(screen_w, screen_h, shadow=True):
103
+ """The laptop, with a transparent hole where the screen goes.
104
+
105
+ `shadow=False` for formats whose alpha is one bit (GIF): a soft shadow there
106
+ does not fade, it bands into a grey halo with a hard edge, which looks worse
107
+ than no shadow at all.
108
+ """
109
+ L = layout(screen_w, screen_h)
110
+ canvas = Image.new('RGBA', L['canvas'], (0, 0, 0, 0))
111
+
112
+ # A soft shadow on the ground, wider and flatter than the machine itself.
113
+ if shadow:
114
+ cast = Image.new('RGBA', L['canvas'], (0, 0, 0, 0))
115
+ bx = L['pad'] + round(L['base'][0] * 0.02)
116
+ by = L['pad'] + L['lid'][1]
117
+ ImageDraw.Draw(cast).rounded_rectangle(
118
+ [bx, by, L['canvas'][0] - bx, by + L['base'][1] + round(L['pad'] * 0.55)],
119
+ radius=L['base'][1], fill=(10, 10, 14, 120))
120
+ canvas.alpha_composite(cast.filter(ImageFilter.GaussianBlur(L['pad'] * 0.30)))
121
+
122
+ # The lid, in three layers, outside in: a thin aluminium rim, the black
123
+ # glass front that covers rim-to-screen, and then a hole.
124
+ #
125
+ # The hole is the whole point. Without it the frame is opaque where the
126
+ # screen should be and composites straight over the content — which is
127
+ # exactly what the first version did, and it produced a very convincing
128
+ # picture of a laptop that was switched off.
129
+ lid_w, lid_h = L['lid']
130
+ rim = max(1, round(screen_w * 0.004))
131
+ lid = _gradient(L['lid'], BODY_LIGHT, BODY_DARK).convert('RGBA')
132
+ lid.putalpha(_rounded(L['lid'], L['lid_radius']))
133
+
134
+ glass_r = max(2, round(L['lid_radius'] * 0.82))
135
+ d = ImageDraw.Draw(lid)
136
+ d.rounded_rectangle([rim, rim, lid_w - 1 - rim, lid_h - 1 - rim],
137
+ radius=glass_r, fill=SCREEN_SURROUND)
138
+
139
+ # The camera sits on the glass, above the screen.
140
+ cam = max(2, round(screen_w * 0.0032))
141
+ cx, cy = lid_w // 2, max(cam + 1, L['bezel'] // 2)
142
+ d.ellipse([cx - cam, cy - cam, cx + cam, cy + cam], fill=(52, 54, 60))
143
+
144
+ # Punch the screen out of the lid's alpha, with rounded corners so the
145
+ # content is clipped by them rather than squared off against the glass.
146
+ hole = Image.new('L', L['lid'], 255)
147
+ ImageDraw.Draw(hole).rounded_rectangle(
148
+ [L['bezel'], L['bezel'], L['bezel'] + screen_w - 1, L['bezel'] + screen_h - 1],
149
+ radius=max(2, round(L['lid_radius'] * 0.42)), fill=0)
150
+ lid.putalpha(Image.composite(lid.getchannel('A'), Image.new('L', L['lid'], 0), hole))
151
+
152
+ canvas.alpha_composite(lid, L['lid_xy'])
153
+
154
+ # The base, seen almost edge-on: a shallow slab, wider than the lid, with a
155
+ # recess cut into the front edge.
156
+ base_w, base_h = L['base']
157
+ base = _gradient((base_w, base_h), BASE_TOP, BASE_BOTTOM).convert('RGBA')
158
+ mask = Image.new('L', (base_w, base_h), 0)
159
+ md = ImageDraw.Draw(mask)
160
+ md.rounded_rectangle([0, 0, base_w - 1, base_h - 1],
161
+ radius=round(base_h * 0.45), fill=255)
162
+ md.rectangle([0, 0, base_w - 1, base_h // 2], fill=255) # square at the hinge
163
+ nx = L['notch_w'] // 2
164
+ md.rounded_rectangle(
165
+ [base_w // 2 - nx, base_h - round(base_h * 0.72),
166
+ base_w // 2 + nx, base_h + round(base_h * 0.4)],
167
+ radius=round(base_h * 0.35), fill=0) # the finger recess
168
+ base.putalpha(mask)
169
+ canvas.alpha_composite(base, (L['pad'], L['pad'] + L['lid'][1]))
170
+
171
+ return canvas, L
172
+
173
+
174
+ def place(content: Image.Image, frame: Image.Image, L) -> Image.Image:
175
+ """Drop one screen's worth of content into a prepared frame."""
176
+ out = frame.copy()
177
+ out.alpha_composite(content.convert('RGBA'), L['screen_xy'])
178
+ # The lid is composited again so its rounded screen corners clip the content.
179
+ return out
180
+
181
+
182
+ def wrap_image(src: pathlib.Path, dst: pathlib.Path):
183
+ content = Image.open(src).convert('RGB')
184
+ frame, L = chrome(*content.size)
185
+ canvas = Image.new('RGBA', L['canvas'], (0, 0, 0, 0))
186
+ canvas.alpha_composite(content.convert('RGBA'), L['screen_xy'])
187
+ canvas.alpha_composite(frame)
188
+ canvas.save(dst, optimize=True)
189
+ return dst
190
+
191
+
192
+ def ground_for(name, size):
193
+ """The surface the laptop stands on.
194
+
195
+ `transparent` returns None and the caller keeps the alpha channel — but it
196
+ is a trap for this particular job, kept only because it is occasionally the
197
+ right answer for a still. GIF alpha is one bit, and transparency defeats the
198
+ inter-frame compression that makes an animated GIF small: this clip is
199
+ **11.4 MB** transparent against 357 KB on a solid ground. The README ships a
200
+ light and a dark version instead, swapped by `prefers-color-scheme`.
201
+ """
202
+ if name == 'transparent':
203
+ return None
204
+ if name == 'stage':
205
+ return stage(size).convert('RGBA')
206
+ fill = {'light': (255, 255, 255, 255), 'dark': (13, 17, 23, 255)}.get(name)
207
+ if fill is None:
208
+ fill = tuple(int(name.lstrip('#')[i:i + 2], 16) for i in (0, 2, 4)) + (255,)
209
+ return Image.new('RGBA', size, fill)
210
+
211
+
212
+ def wrap_video(src: pathlib.Path, out_mp4: pathlib.Path, out_gif: pathlib.Path,
213
+ gif_width=1000, fps=12, background='light'):
214
+ """Composite every frame into the laptop, then re-encode.
215
+
216
+ ffmpeg could overlay a PNG in one pass, but the frame has a transparent
217
+ screen hole and soft shadow edges — compositing in Pillow keeps the alpha
218
+ correct at both, and the cost is a few seconds on a twenty-second clip.
219
+ """
220
+ work = pathlib.Path(tempfile.mkdtemp(prefix='macbook-'))
221
+ try:
222
+ # Extract and re-encode at the SAME rate. Pulling frames at the mp4's own
223
+ # 24 fps and then declaring them 10 fps on the way back in stretched a
224
+ # 22-second clip to 54 without changing a single pixel.
225
+ subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-i', str(src),
226
+ '-vf', f'fps={fps}', str(work / 'in-%05d.png')], check=True)
227
+ shots = sorted(work.glob('in-*.png'))
228
+ if not shots:
229
+ raise SystemExit('ffmpeg produced no frames')
230
+
231
+ with Image.open(shots[0]) as first:
232
+ frame, L = chrome(*first.size, shadow=(background != 'transparent'))
233
+
234
+ ground = ground_for(background, L['canvas'])
235
+ mp4_stem = 'mp4' if ground is None else 'out'
236
+ for i, shot in enumerate(shots):
237
+ with Image.open(shot) as content:
238
+ canvas = (ground.copy() if ground is not None
239
+ else Image.new('RGBA', L['canvas'], (0, 0, 0, 0)))
240
+ canvas.alpha_composite(content.convert('RGBA'), L['screen_xy'])
241
+ canvas.alpha_composite(frame)
242
+ if ground is None:
243
+ # Keep the alpha for the GIF, and write a second, white-backed
244
+ # copy for the mp4: h264 has no alpha channel, and handing
245
+ # ffmpeg transparent frames makes it flatten them onto black.
246
+ canvas.save(work / f'out-{i:05d}.png')
247
+ flat = Image.new('RGB', canvas.size, (255, 255, 255))
248
+ flat.paste(canvas, mask=canvas.getchannel('A'))
249
+ flat.save(work / f'mp4-{i:05d}.png')
250
+ else:
251
+ canvas.convert('RGB').save(work / f'out-{i:05d}.png')
252
+
253
+ subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-framerate', str(fps),
254
+ '-i', str(work / f'{mp4_stem}-%05d.png'),
255
+ '-vf', 'scale=2000:-2:flags=lanczos,format=yuv420p',
256
+ '-c:v', 'libx264', '-crf', '20', '-preset', 'slow',
257
+ '-movflags', '+faststart', '-r', '24', str(out_mp4)], check=True)
258
+
259
+ # GIF alpha is one bit: a pixel is either fully there or fully gone.
260
+ # reserve_transparent keeps a palette slot for "gone", alpha_threshold
261
+ # decides the cut. Anything soft — the drop shadow especially — has to
262
+ # go, or it bands into a grey halo.
263
+ gif_palette = ':reserve_transparent=1' if background == 'transparent' else ''
264
+ gif_use = ':alpha_threshold=128' if background == 'transparent' else ''
265
+ subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-framerate', str(fps),
266
+ '-i', str(work / 'out-%05d.png'),
267
+ '-vf', f'scale={gif_width}:-2:flags=lanczos,'
268
+ 'split[a][b];'
269
+ f'[a]palettegen=max_colors=192{gif_palette}[p];'
270
+ f'[b][p]paletteuse=dither=bayer:bayer_scale=3{gif_use}',
271
+ '-loop', '0', str(out_gif)], check=True)
272
+ finally:
273
+ shutil.rmtree(work, ignore_errors=True)
274
+ return out_mp4, out_gif
275
+
276
+
277
+ def main():
278
+ if len(sys.argv) < 4:
279
+ sys.exit(__doc__.strip().splitlines()[-3].strip())
280
+ mode = sys.argv[1]
281
+ if mode == 'image':
282
+ out = wrap_image(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3]))
283
+ print(f' {out} {out.stat().st_size // 1024} Ko')
284
+ elif mode == 'video':
285
+ background = sys.argv[5] if len(sys.argv) > 5 else 'light'
286
+ mp4, gif = wrap_video(pathlib.Path(sys.argv[2]),
287
+ pathlib.Path(sys.argv[3]), pathlib.Path(sys.argv[4]),
288
+ background=background)
289
+ for f in (mp4, gif):
290
+ print(f' {f} {f.stat().st_size // 1024} Ko')
291
+ else:
292
+ sys.exit(f'unknown mode: {mode}')
293
+
294
+
295
+ if __name__ == '__main__':
296
+ main()
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ The menu-bar icon, at the two sizes macOS asks for.
4
+
5
+ macOS menu-bar icons are *template* images: black pixels plus an alpha channel,
6
+ no colour. The system then paints them — dark on a light bar, light on a dark
7
+ one, inverted again when the menu is open. Shipping the brand's orange mark here
8
+ would look wrong in at least two of those four states, which is why this is a
9
+ separate glyph rather than a resize of resources/icon.png.
10
+
11
+ At 16 points there is room for one idea. The brand mark's chevron-and-prompt is
12
+ that idea; the AI sparks are dropped because at this size they are three grey
13
+ pixels that read as dirt.
14
+
15
+ Filenames matter: Electron looks for `<name>Template.png` and `<name>Template@2x.png`
16
+ and only treats the image as a template when the name ends in `Template`.
17
+
18
+ Usage: python3 scripts/make-tray-icon.py
19
+ """
20
+ import pathlib
21
+
22
+ from PIL import Image, ImageDraw
23
+
24
+ OUT = pathlib.Path(__file__).resolve().parent.parent / 'desktop' / 'electron' / 'resources'
25
+
26
+
27
+ def glyph(size):
28
+ """A chevron and a prompt bar, drawn at 4x and downsampled for clean edges."""
29
+ scale = 4
30
+ s = size * scale
31
+ img = Image.new('RGBA', (s, s), (0, 0, 0, 0))
32
+ d = ImageDraw.Draw(img)
33
+
34
+ stroke = max(2, round(s * 0.105))
35
+ pad = round(s * 0.16)
36
+ mid = s // 2
37
+
38
+ # > — the chevron, vertically centred on the upper two thirds
39
+ top = round(s * 0.20)
40
+ bottom = round(s * 0.66)
41
+ d.line([(pad, top), (mid + round(s * 0.02), (top + bottom) // 2), (pad, bottom)],
42
+ fill=(0, 0, 0, 255), width=stroke, joint='curve')
43
+
44
+ # _ — the prompt, sitting under the chevron's point
45
+ bar_y = round(s * 0.80)
46
+ d.line([(mid + round(s * 0.10), bar_y), (s - pad, bar_y)],
47
+ fill=(0, 0, 0, 255), width=stroke)
48
+
49
+ return img.resize((size, size), Image.LANCZOS)
50
+
51
+
52
+ def main():
53
+ OUT.mkdir(parents=True, exist_ok=True)
54
+ for size, name in ((16, 'trayTemplate.png'), (32, 'trayTemplate@2x.png')):
55
+ path = OUT / name
56
+ glyph(size).save(path)
57
+ print(f' {name:<24} {size}x{size} {path.stat().st_size} o')
58
+
59
+
60
+ if __name__ == '__main__':
61
+ main()
@@ -0,0 +1,291 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Preview a candidate with temporary credentials, files and a loopback SSH host.
4
+ * node scripts/preview-candidate.mjs --app '/path/SSH Manager.app'
5
+ * node scripts/preview-candidate.mjs --engine /path/to/mcp-ssh-manager
6
+ * Type r + Enter to restart with the same profile; q + Enter or Ctrl-C cleans up.
7
+ * Remote commands are simulated; SFTP writes only inside the temporary fixture.
8
+ */
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import crypto from 'node:crypto';
13
+ import readline from 'node:readline';
14
+ import { spawn, execFileSync } from 'node:child_process';
15
+ import { fileURLToPath, pathToFileURL } from 'node:url';
16
+ import ssh2 from 'ssh2';
17
+
18
+ const repo = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
19
+ const { STATUS_CODE: S, OPEN_MODE: O } = ssh2.utils.sftp;
20
+
21
+ function reply(command) {
22
+ if (command.includes('=== CPU ===')) return [
23
+ '=== CPU ===', '12.5', '=== MEMORY ===', '{"total":8192,"used":2048,"free":6144,"percent":25}',
24
+ '=== DISK ===', '{"mount":"/","size":"40G","used":"10G","avail":"30G","percent":25}',
25
+ '=== LOAD ===', '0.12, 0.18, 0.09', '=== UPTIME ===', 'up 2 days',
26
+ '=== NETWORK ===', '{"interface":"eth0:","rx_bytes":12000,"tx_bytes":6000}', '',
27
+ ].join('\n');
28
+ if (/\bwhoami\b/.test(command)) return 'demo\n';
29
+ if (/\bhostname\b/.test(command)) return 'local-preview-fixture\n';
30
+ if (/\buptime\b/.test(command)) return 'up 2 days, load average: 0.12, 0.18, 0.09\n';
31
+ if (/\bpwd\b/.test(command)) return '/srv\n';
32
+ if (/\b(ls|ll)\b/.test(command)) return 'README.txt reports uploads\n';
33
+ if (/\bdf\b/.test(command)) return 'Filesystem Size Used Avail Use% Mounted on\npreview 40G 10G 30G 25% /\n';
34
+ return `Simulated command; no shell was executed: ${command}\n`;
35
+ }
36
+
37
+ function serveSftp(sftp, root) {
38
+ const handles = new Map();
39
+ let counter = 0;
40
+ const target = given => {
41
+ const relative = path.posix.normalize(`/${given}`).slice(1);
42
+ const resolved = path.resolve(root, relative);
43
+ if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`)) throw new Error('Outside fixture');
44
+ // Do not follow links, including ones introduced manually during a preview.
45
+ let current = root;
46
+ for (const part of path.relative(root, resolved).split(path.sep).filter(Boolean)) {
47
+ current = path.join(current, part);
48
+ if (fs.existsSync(current) && fs.lstatSync(current).isSymbolicLink()) throw new Error('Symlinks are disabled');
49
+ }
50
+ return resolved;
51
+ };
52
+ const attrs = stat => ({ mode: stat.mode, size: stat.size, uid: 1000, gid: 1000,
53
+ atime: Math.floor(stat.atimeMs / 1000), mtime: Math.floor(stat.mtimeMs / 1000) });
54
+ const handle = state => {
55
+ const id = Buffer.from(String(++counter)); handles.set(id.toString(), state); return id;
56
+ };
57
+ const on = (event, fn) => sftp.on(event, (id, ...args) => {
58
+ try { fn(id, ...args); } catch { sftp.status(id, S.FAILURE); }
59
+ });
60
+ for (const event of ['STAT', 'LSTAT']) on(event, (id, file) => sftp.attrs(id, attrs(fs.lstatSync(target(file)))));
61
+ on('REALPATH', (id, file) => {
62
+ const remote = file === '.' ? '/srv' : path.posix.normalize(`/${file}`);
63
+ target(remote); sftp.name(id, [{ filename: remote, longname: remote, attrs: {} }]);
64
+ });
65
+ on('OPENDIR', (id, dir) => sftp.handle(id, handle({ dir: target(dir), sent: false })));
66
+ on('READDIR', (id, value) => {
67
+ const state = handles.get(value.toString());
68
+ if (state.sent) return sftp.status(id, S.EOF);
69
+ state.sent = true;
70
+ sftp.name(id, fs.readdirSync(state.dir).map(filename => ({ filename, longname: filename,
71
+ attrs: attrs(fs.lstatSync(path.join(state.dir, filename))) })));
72
+ });
73
+ on('OPEN', (id, file, flags) => {
74
+ const writable = Boolean(flags & O.WRITE);
75
+ const mode = !writable ? 'r' : flags & O.APPEND ? 'a+' : flags & O.TRUNC ? 'w+' : 'r+';
76
+ let fd;
77
+ try { fd = fs.openSync(target(file), mode, 0o600); }
78
+ catch (error) {
79
+ if (error.code !== 'ENOENT' || !(flags & O.CREAT) || !writable) throw error;
80
+ fd = fs.openSync(target(file), 'wx+', 0o600);
81
+ }
82
+ sftp.handle(id, handle({ fd }));
83
+ });
84
+ on('FSTAT', (id, value) => sftp.attrs(id, attrs(fs.fstatSync(handles.get(value.toString()).fd))));
85
+ on('READ', (id, value, offset, length) => {
86
+ const buffer = Buffer.alloc(Math.min(length, 1024 * 1024));
87
+ const size = fs.readSync(handles.get(value.toString()).fd, buffer, 0, buffer.length, offset);
88
+ size ? sftp.data(id, buffer.subarray(0, size)) : sftp.status(id, S.EOF);
89
+ });
90
+ on('WRITE', (id, value, offset, data) => {
91
+ fs.writeSync(handles.get(value.toString()).fd, data, 0, data.length, offset); sftp.status(id, S.OK);
92
+ });
93
+ on('CLOSE', (id, value) => {
94
+ const state = handles.get(value.toString());
95
+ if (state?.fd !== undefined) fs.closeSync(state.fd);
96
+ handles.delete(value.toString()); sftp.status(id, S.OK);
97
+ });
98
+ on('MKDIR', (id, dir) => { fs.mkdirSync(target(dir)); sftp.status(id, S.OK); });
99
+ on('RMDIR', (id, dir) => { fs.rmdirSync(target(dir)); sftp.status(id, S.OK); });
100
+ on('REMOVE', (id, file) => { fs.unlinkSync(target(file)); sftp.status(id, S.OK); });
101
+ on('RENAME', (id, from, to) => { fs.renameSync(target(from), target(to)); sftp.status(id, S.OK); });
102
+ for (const event of ['SETSTAT', 'FSETSTAT']) on(event, id => sftp.status(id, S.OP_UNSUPPORTED));
103
+ sftp.on('close', () => {
104
+ for (const state of handles.values()) if (state.fd !== undefined) {
105
+ try { fs.closeSync(state.fd); } catch { /* already closed */ }
106
+ }
107
+ handles.clear();
108
+ });
109
+ }
110
+
111
+ /** Create a fixture without starting a GUI or changing this process's environment. */
112
+ export async function createCandidatePreview(engine = repo) {
113
+ engine = fs.realpathSync(engine);
114
+ for (const file of ['package.json', 'src/secret-store.js', 'cli/control.js']) {
115
+ if (!fs.existsSync(path.join(engine, file))) throw new Error(`Candidate engine is missing ${file}`);
116
+ }
117
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'ssh-p-'));
118
+ const home = path.join(scratch, 'home');
119
+ const remote = path.join(scratch, 'remote');
120
+ const connections = new Set();
121
+ let server;
122
+ let listening = false;
123
+ const close = async () => {
124
+ for (const client of connections) client.end();
125
+ if (listening) { await new Promise(resolve => server.close(resolve)); listening = false; }
126
+ fs.rmSync(scratch, { recursive: true, force: true });
127
+ };
128
+ try {
129
+ for (const dir of ['home/Desktop', 'home/Documents', 'home/Downloads', 'home/.ssh', 'tmp', 'remote/srv/reports', 'remote/srv/uploads']) {
130
+ fs.mkdirSync(path.join(scratch, dir), { recursive: true });
131
+ }
132
+ fs.writeFileSync(path.join(home, 'Documents', 'upload-me.txt'), 'Temporary candidate preview upload.\n');
133
+ fs.writeFileSync(path.join(remote, 'srv', 'README.txt'), 'Temporary SSH fixture. Downloads and edits are safe here.\n');
134
+ fs.writeFileSync(path.join(remote, 'srv', 'reports', 'status.json'), '{"fixture":true,"healthy":true}\n');
135
+ const env = Object.fromEntries(['PATH', 'SystemRoot', 'WINDIR', 'COMSPEC', 'SHELL', 'LANG', 'LC_ALL',
136
+ 'DISPLAY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS']
137
+ .filter(key => process.env[key]).map(key => [key, process.env[key]]));
138
+ Object.assign(env, {
139
+ HOME: home, USERPROFILE: home, ZDOTDIR: home,
140
+ APPDATA: path.join(scratch, 'app-data'), LOCALAPPDATA: path.join(scratch, 'local-data'),
141
+ XDG_CONFIG_HOME: path.join(home, '.config'), XDG_CACHE_HOME: path.join(home, '.cache'),
142
+ XDG_DATA_HOME: path.join(home, '.local/share'), TMPDIR: path.join(scratch, 'tmp'),
143
+ TEMP: path.join(scratch, 'tmp'), TMP: path.join(scratch, 'tmp'),
144
+ SSH_MANAGER_HOME: scratch, SSH_MANAGER_PREVIEW_HOME: scratch, SSH_MANAGER_KEY_SOURCE: 'file',
145
+ SSH_MANAGER_APPROVAL_SOCKET: process.platform === 'win32'
146
+ ? `\\\\.\\pipe\\mcp-ssh-${path.basename(scratch)}` : path.join(scratch, 'approval.sock'),
147
+ SSH_MANAGER_VAULT: path.join(scratch, 'vault.json'),
148
+ SSH_MANAGER_KNOWN_HOSTS: path.join(home, '.ssh/known_hosts'),
149
+ SSH_ENV_PATH: path.join(scratch, 'empty.env'), SSH_CONFIG_PATH: path.join(scratch, 'empty.toml'),
150
+ SSH_LOG_FILE: path.join(scratch, 'engine.log'), SSH_HISTORY_FILE: path.join(scratch, 'history.json'),
151
+ SSH_GROUPS_FILE: path.join(scratch, 'groups.json'),
152
+ });
153
+ fs.writeFileSync(env.SSH_ENV_PATH, ''); fs.writeFileSync(env.SSH_CONFIG_PATH, '');
154
+ const password = crypto.randomBytes(18).toString('hex');
155
+ const key = crypto.generateKeyPairSync('rsa', { modulusLength: 2048,
156
+ privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, publicKeyEncoding: { type: 'spki', format: 'pem' } }).privateKey;
157
+ server = new ssh2.Server({ hostKeys: [key] }, client => {
158
+ connections.add(client);
159
+ client.on('close', () => connections.delete(client));
160
+ client.on('error', () => {});
161
+ client.on('authentication', ctx => ctx.method === 'password' && ctx.username === 'demo' && ctx.password === password
162
+ ? ctx.accept() : ctx.reject(['password']));
163
+ client.on('ready', () => client.on('session', accept => {
164
+ const session = accept();
165
+ session.on('sftp', start => serveSftp(start(), remote));
166
+ session.on('exec', (start, _reject, info) => {
167
+ const stream = start(); stream.write(reply(info.command)); stream.exit(0); stream.end();
168
+ });
169
+ session.on('pty', acceptPty => acceptPty?.());
170
+ session.on('window-change', acceptResize => acceptResize?.());
171
+ session.on('shell', start => {
172
+ const stream = start();
173
+ const prompt = 'demo@local-preview:/srv$ ';
174
+ stream.write(`Temporary SSH fixture — commands are simulated.\r\n${prompt}`);
175
+ let line = '';
176
+ stream.on('data', data => {
177
+ for (const ch of data.toString()) {
178
+ if (ch === '\r' || ch === '\n') {
179
+ stream.write('\r\n');
180
+ if (line.trim() === 'exit') { stream.exit(0); stream.end(); return; }
181
+ if (line) stream.write(reply(line).replaceAll('\n', '\r\n'));
182
+ line = ''; stream.write(prompt);
183
+ } else if (ch === '\x03') { line = ''; stream.write(`^C\r\n${prompt}`); }
184
+ else if (ch === '\x7f' || ch === '\b') { if (line) { line = line.slice(0, -1); stream.write('\b \b'); } }
185
+ else if (line.length < 8192) { line += ch; stream.write(ch); }
186
+ }
187
+ });
188
+ });
189
+ }));
190
+ });
191
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
192
+ listening = true;
193
+ const port = server.address().port;
194
+ const configs = Object.fromEntries(['demo_app', 'demo_backup'].map((name, index) => [name, {
195
+ host: '127.0.0.1', port, user: 'demo', password, defaultDir: '/srv',
196
+ description: 'Local preview fixture: simulated commands, temporary files.',
197
+ group: index ? 'Preview backups' : 'Preview applications', mode: 'unrestricted', approval: 'never',
198
+ }]));
199
+ // Seed using the candidate's actual implementation, in a separate process
200
+ // whose home and key source have been isolated before any engine import.
201
+ execFileSync(process.execPath, ['--input-type=module', '-e',
202
+ `import {SecretStore} from ${JSON.stringify(pathToFileURL(path.join(engine, 'src/secret-store.js')).href)};
203
+ const store = new SecretStore();
204
+ for (const [name, config] of Object.entries(JSON.parse(await new Promise(resolve => {
205
+ let text=''; process.stdin.on('data', chunk => text+=chunk); process.stdin.on('end', () => resolve(text));
206
+ })))) store.setServer(name, config);`],
207
+ { env, cwd: home, input: JSON.stringify(configs), stdio: ['pipe', 'ignore', 'pipe'], timeout: 10000 });
208
+ return { scratch, home, remote, env, port, password, engine, close };
209
+ } catch (error) { await close(); throw error; }
210
+ }
211
+
212
+ /** Resolve only the Electron candidate bundle, without altering it. */
213
+ export function resolveCandidateApp(given) {
214
+ const app = fs.realpathSync(given);
215
+ const executable = app.endsWith('.app') ? path.join(app, 'Contents/MacOS/SSH Manager') : app;
216
+ const resources = app.endsWith('.app') ? path.join(app, 'Contents/Resources') : path.join(path.dirname(app), 'resources');
217
+ if (!fs.statSync(executable).isFile()) throw new Error('Pass the Electron application bundle or executable');
218
+ // asar entries are uncompressed; this also rejects older candidates that
219
+ // would ignore the profile override and open the operator's real UI profile.
220
+ if (!fs.readFileSync(path.join(resources, 'app.asar')).includes(Buffer.from('SSH_MANAGER_PREVIEW_HOME'))) {
221
+ throw new Error('This candidate lacks isolated preview support; use the current CI artifact');
222
+ }
223
+ return { executable, engine: path.join(resources, 'engine') };
224
+ }
225
+
226
+ async function main() {
227
+ const args = process.argv.slice(2);
228
+ if (args.length !== 2 || !['--app', '--engine'].includes(args[0])) {
229
+ console.log('Usage: node scripts/preview-candidate.mjs --app "/path/SSH Manager.app"\n'
230
+ + ' or: node scripts/preview-candidate.mjs --engine /path/to/mcp-ssh-manager');
231
+ process.exitCode = args.includes('--help') ? 0 : 1; return;
232
+ }
233
+ const candidate = args[0] === '--app' ? resolveCandidateApp(args[1]) : { engine: args[1] };
234
+ const preview = await createCandidatePreview(candidate.engine);
235
+ let child;
236
+ let stopping = false;
237
+ let restarting = false;
238
+ const input = readline.createInterface({ input: process.stdin });
239
+ const stopChild = async () => {
240
+ if (!child?.pid || child.exitCode !== null || child.signalCode !== null) return;
241
+ await new Promise(resolve => {
242
+ const target = child;
243
+ const kill = signal => {
244
+ try { process.platform === 'win32' ? target.kill(signal) : process.kill(-target.pid, signal); } catch { /* already exited */ }
245
+ };
246
+ const deadline = setTimeout(() => kill('SIGKILL'), 5000);
247
+ target.once('exit', () => { clearTimeout(deadline); resolve(); });
248
+ kill('SIGTERM');
249
+ });
250
+ };
251
+ const stop = async () => {
252
+ if (stopping) return;
253
+ stopping = true;
254
+ input.close();
255
+ process.stdin.pause();
256
+ process.stdin.unref?.();
257
+ await stopChild();
258
+ await preview.close();
259
+ console.log('Candidate preview stopped; its temporary profile was removed.');
260
+ };
261
+ const start = () => {
262
+ const executable = candidate.executable || process.execPath;
263
+ const commandArgs = candidate.executable ? [] : [path.join(preview.engine, 'cli/control.js')];
264
+ child = spawn(executable, commandArgs, { env: preview.env, cwd: preview.home,
265
+ stdio: ['ignore', 'inherit', 'inherit'], detached: process.platform !== 'win32' });
266
+ child.once('error', error => { console.error(`Candidate launch failed: ${error.message}`); process.exitCode = 1; void stop(); });
267
+ child.once('exit', code => {
268
+ if (!restarting && !stopping) { process.exitCode = code || 0; void stop(); }
269
+ });
270
+ };
271
+ console.log(`Candidate preview profile: ${preview.scratch}\n`
272
+ + `SSH fixture: 127.0.0.1:${preview.port} — demo_app and demo_backup\n`
273
+ + `Upload sample: ${path.join(preview.home, 'Documents/upload-me.txt')}\n`
274
+ + 'Only these temporary fixtures are configured. Remote commands are simulated.\n'
275
+ + 'Type r + Enter to restart with this profile; q + Enter or Ctrl-C to quit and delete it.');
276
+ input.on('line', async line => {
277
+ if (line.trim() === 'q') return void stop();
278
+ if (line.trim() !== 'r' || restarting || stopping) return;
279
+ restarting = true;
280
+ await stopChild();
281
+ if (!stopping) start();
282
+ restarting = false;
283
+ });
284
+ process.once('SIGINT', () => void stop());
285
+ process.once('SIGTERM', () => void stop());
286
+ start();
287
+ }
288
+
289
+ if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) {
290
+ main().catch(error => { console.error(error.message); process.exitCode = 1; });
291
+ }