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.
- package/.eslintignore +5 -0
- package/.gitattributes +5 -0
- package/CHANGELOG.md +371 -6
- package/CLAUDE.md +6 -0
- package/CODE_OF_CONDUCT.md +18 -0
- package/CONTRIBUTING.md +30 -0
- package/Formula/ssh-manager.rb +60 -0
- package/README.md +484 -964
- package/ROADMAP-V4.md +451 -0
- package/brand/README.md +43 -0
- package/brand/icon.svg +32 -0
- package/brand/mark.svg +18 -0
- package/brand/wordmark.svg +30 -0
- package/cli/app.js +230 -0
- package/cli/control.js +116 -0
- package/cli/lib/colors.sh +15 -0
- package/cli/lib/menu.sh +145 -96
- package/cli/portability.js +186 -0
- package/cli/ssh-manager +197 -91
- package/cli/ssh-manager.js +14 -0
- package/cli/style.js +17 -0
- package/cli/vault.js +411 -0
- package/desktop/ControlPlaneApp.swift +219 -0
- package/desktop/build.sh +58 -0
- package/desktop/electron/after-pack.cjs +39 -0
- package/desktop/electron/electron-builder.yml +148 -0
- package/desktop/electron/finalize-artifacts.mjs +83 -0
- package/desktop/electron/main.js +815 -0
- package/desktop/electron/package-lock.json +3656 -0
- package/desktop/electron/package.json +30 -0
- package/desktop/electron/prepare-engine.mjs +84 -0
- package/desktop/electron/resources/entitlements.mac.plist +22 -0
- package/desktop/electron/resources/icon.png +0 -0
- package/desktop/electron/resources/trayTemplate.png +0 -0
- package/desktop/electron/resources/trayTemplate@2x.png +0 -0
- package/desktop/electron/smoke-test.mjs +184 -0
- package/dist/ui/app.css +1 -0
- package/dist/ui/app.js +501 -0
- package/dist/ui/assets/Forum-Regular.woff2 +0 -0
- package/dist/ui/assets/JetBrainsMono-Bold.woff2 +0 -0
- package/dist/ui/assets/JetBrainsMono-Regular.woff2 +0 -0
- package/dist/ui/assets/Karla-Variable.woff2 +0 -0
- package/dist/ui/index.html +16 -0
- package/docs/DISTRIBUTION.md +136 -0
- package/docs/FINAL-TEST-V4.md +209 -0
- package/docs/MIGRATION.md +334 -0
- package/docs/TESTING-V4.md +119 -0
- package/docs/superpowers/specs/2026-10-08-desktop-from-npm-and-cli-design.md +187 -0
- package/docs/videos/control-plane.mp4 +0 -0
- package/package.json +61 -30
- package/scripts/build-interface.mjs +73 -0
- package/scripts/capture-screenshots.mjs +191 -0
- package/scripts/demo-env.mjs +461 -0
- package/scripts/frame-screenshots.py +176 -0
- package/scripts/macbook-mockup.py +296 -0
- package/scripts/make-tray-icon.py +61 -0
- package/scripts/preview-candidate.mjs +291 -0
- package/scripts/publish-desktop.mjs +46 -0
- package/scripts/record-demo.mjs +229 -0
- package/scripts/release-version.mjs +32 -0
- package/scripts/render-cli-menu.py +157 -0
- package/scripts/requirements-dev.in +12 -0
- package/scripts/requirements-dev.txt +424 -0
- package/scripts/run-ui-regression.mjs +48 -0
- package/scripts/setup-hooks.sh +7 -13
- package/scripts/smoke-desktop.mjs +80 -0
- package/scripts/test-drag-and-drop.mjs +114 -0
- package/scripts/test-first-run.mjs +5 -0
- package/scripts/test-import-ui.mjs +5 -0
- package/scripts/test-preferences-persist.mjs +5 -0
- package/scripts/test-upgrade-from-published.mjs +226 -0
- package/scripts/verify-mac-build.sh +153 -0
- package/scripts/verify-windows-build.ps1 +15 -0
- package/server.json +3 -3
- package/skills/README.md +42 -0
- package/skills/ssh-incident/SKILL.md +55 -0
- package/skills/ssh-operations/SKILL.md +62 -0
- package/skills/ssh-restricted/SKILL.md +57 -0
- package/src/agent-clients.js +482 -0
- package/src/approval.js +291 -0
- package/src/audit.js +11 -1
- package/src/command-log.js +162 -0
- package/src/config-loader.js +119 -4
- package/src/config-paths.js +101 -0
- package/src/control-plane.js +2730 -0
- package/src/desktop-install.js +747 -0
- package/src/index.js +179 -213
- package/src/live-stream.js +261 -0
- package/src/saved-commands.js +150 -0
- package/src/secret-store.js +573 -0
- package/src/server-aliases.js +8 -7
- package/src/server-config-manager.js +33 -7
- package/src/server-export.js +106 -0
- package/src/server-groups.js +82 -21
- package/src/server-import.js +477 -0
- package/src/shell-quote.js +9 -2
- package/src/ssh-connection.js +155 -0
- package/src/ssh-manager.js +186 -13
- package/src/tunnel-manager.js +79 -0
- package/src/vault-recovery.js +206 -0
- package/src/xlsx.js +322 -0
- package/docs/images/social-preview.png +0 -0
- package/docs/images/social-preview@2x.png +0 -0
- package/docs/images/ssh-manager-cli-menu.png +0 -0
|
@@ -0,0 +1,2730 @@
|
|
|
1
|
+
// The control plane — the thing that answers "what did my agents do on my
|
|
2
|
+
// servers, and what am I letting them do next".
|
|
3
|
+
//
|
|
4
|
+
// It is two servers in one process:
|
|
5
|
+
//
|
|
6
|
+
// * a **stream socket** the engine connects to when it needs a decision
|
|
7
|
+
// (the protocol in approval.js), and
|
|
8
|
+
// * a **local HTTP server** serving one page and a small API, so a human can
|
|
9
|
+
// see the queue and decide.
|
|
10
|
+
//
|
|
11
|
+
// It is deliberately not an Electron app and adds no dependency: Node's http
|
|
12
|
+
// and net, plus one HTML file. That keeps it runnable anywhere the engine runs
|
|
13
|
+
// — including on a server, reached through the SSH tunnels this project already
|
|
14
|
+
// manages — and leaves the door open to wrapping it in a desktop shell later.
|
|
15
|
+
//
|
|
16
|
+
// ## Why the token is not optional
|
|
17
|
+
//
|
|
18
|
+
// This process approves root shell commands. An unauthenticated HTTP server on
|
|
19
|
+
// localhost is reachable by **every process on the machine, and by any web page
|
|
20
|
+
// the user has open** (a page can POST to 127.0.0.1). Without a secret in the
|
|
21
|
+
// URL, a visited website could approve an agent's `rm -rf`. So:
|
|
22
|
+
//
|
|
23
|
+
// * a random token is required on every request,
|
|
24
|
+
// * the Host header must be a loopback literal, which blocks DNS rebinding,
|
|
25
|
+
// * the listener binds 127.0.0.1 explicitly, never 0.0.0.0.
|
|
26
|
+
|
|
27
|
+
import crypto from 'crypto';
|
|
28
|
+
import fs from 'fs';
|
|
29
|
+
import http from 'http';
|
|
30
|
+
import net from 'net';
|
|
31
|
+
import os from 'os';
|
|
32
|
+
import { execFile } from 'child_process';
|
|
33
|
+
import path from 'path';
|
|
34
|
+
import { fileURLToPath } from 'url';
|
|
35
|
+
import { logger } from './logger.js';
|
|
36
|
+
import { safeInteger } from './shell-quote.js';
|
|
37
|
+
import { SecretStore, defaultVaultPath, SECRET_FIELDS, publicServerConfig } from './secret-store.js';
|
|
38
|
+
import { ConfigLoader } from './config-loader.js';
|
|
39
|
+
import { serializeRecovery, decryptRecoveryContent } from './vault-recovery.js';
|
|
40
|
+
import { StreamRegistry, listenForStreams, streamSocketPath } from './live-stream.js';
|
|
41
|
+
import { appendCommand, readCommandLog, trimCommandLog, clearCommandLog, commandLogPath, recordsOutput } from './command-log.js';
|
|
42
|
+
import { MAX_SOCKET_PATH, VALID_APPROVAL_MODES } from './approval.js';
|
|
43
|
+
import { VALID_MODES } from './policy.js';
|
|
44
|
+
import { connectServer } from './ssh-connection.js';
|
|
45
|
+
import { buildComprehensiveHealthCheckCommand, parseComprehensiveHealthCheck, createAlertConfig, checkAlertThresholds } from './health-monitor.js';
|
|
46
|
+
import { listKnownHosts, removeHostKey } from './ssh-key-manager.js';
|
|
47
|
+
import { listSavedCommands, commandsForServer, saveCommand, deleteCommand as deleteSavedCommand, suggestedCommands } from './saved-commands.js';
|
|
48
|
+
import { READERS, WELL_KNOWN, importFile, readTransmit, plan } from './server-import.js';
|
|
49
|
+
import { listGroups, getGroup, createGroup, updateGroup, deleteGroup, executeOnGroup, setServerConfigProvider } from './server-groups.js';
|
|
50
|
+
import { readPublishedTunnels } from './tunnel-manager.js';
|
|
51
|
+
import { desktopStatus, installDesktop, openDesktop, desktopRunning, engineVersion, RELEASES_PAGE } from './desktop-install.js';
|
|
52
|
+
import { agentContext, agentsStatus, useEngine } from './agent-clients.js';
|
|
53
|
+
|
|
54
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
55
|
+
|
|
56
|
+
/** Host headers accepted. Anything else is a rebinding attempt or a mistake. */
|
|
57
|
+
const ALLOWED_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
58
|
+
|
|
59
|
+
/** Merge form edits while preserving fields the form did not display.
|
|
60
|
+
* Empty secret inputs mean unchanged; explicit null removes a secret.
|
|
61
|
+
* @param {Record<string, any>} existing
|
|
62
|
+
* @param {Record<string, any>} patch
|
|
63
|
+
* @returns {Record<string, any>}
|
|
64
|
+
*/
|
|
65
|
+
function mergeServerPatch(existing, patch) {
|
|
66
|
+
const result = { ...existing };
|
|
67
|
+
for (const [field, value] of Object.entries(patch)) {
|
|
68
|
+
if (['name', '__proto__', 'prototype', 'constructor'].includes(field)
|
|
69
|
+
|| /^has(?:Password|Passphrase|SudoPassword)$/.test(field) || value === undefined) continue;
|
|
70
|
+
if (SECRET_FIELDS.includes(field)) {
|
|
71
|
+
if (value === null) delete result[field];
|
|
72
|
+
else if (value !== '') result[field] = value;
|
|
73
|
+
} else if (field === 'accounts' && Array.isArray(value)) {
|
|
74
|
+
result.accounts = value.map(account => {
|
|
75
|
+
if (!account || typeof account !== 'object' || Array.isArray(account)) throw new Error('Invalid account');
|
|
76
|
+
const old = existing.accounts?.find(item => item.id === account.id) || {};
|
|
77
|
+
return mergeServerPatch(old, account);
|
|
78
|
+
});
|
|
79
|
+
} else {
|
|
80
|
+
// Keep an explicit empty value so the lower-priority .env cannot fill
|
|
81
|
+
// the cleared field back in when the engine merges config sources.
|
|
82
|
+
result[field] = value === null ? '' : value;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return result;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** How many audit entries the timeline holds in memory. */
|
|
89
|
+
const TIMELINE_LIMIT = 500;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* A pending decision: the engine is blocked on this until someone answers.
|
|
93
|
+
* @typedef {Object} PendingRequest
|
|
94
|
+
* @property {Object} request - What the engine asked
|
|
95
|
+
* @property {(decision: string, reason?: string) => void} settle - Answer it
|
|
96
|
+
* @property {number} receivedAt - Epoch ms, for showing how long it has waited
|
|
97
|
+
*/
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* How much terminal output is replayed to a screen that attaches late. Enough
|
|
101
|
+
* for a login banner and a screenful, small enough that idle shells cost little.
|
|
102
|
+
*/
|
|
103
|
+
const TERMINAL_BACKLOG_BYTES = 64 * 1024;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* How long an idle SFTP connection is kept. Long enough that browsing feels
|
|
107
|
+
* instant, short enough that walking away closes the session.
|
|
108
|
+
*/
|
|
109
|
+
const SFTP_IDLE_MS = 5 * 60 * 1000;
|
|
110
|
+
|
|
111
|
+
/** Where `npm run build:ui` puts the built interface. */
|
|
112
|
+
const APP_DIR = path.resolve(__dirname, '..', 'dist', 'ui');
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A pooled SFTP session can stop answering without ever failing: the machine
|
|
118
|
+
* went away, the network moved, the far end was killed. ssh2 has no deadline of
|
|
119
|
+
* its own for a request in flight, so the screen would sit on "Loading…"
|
|
120
|
+
* forever — which is worse than an error, because the operator cannot tell it
|
|
121
|
+
* apart from a slow directory.
|
|
122
|
+
*
|
|
123
|
+
* @template T
|
|
124
|
+
* @param {Promise<T>} work - The operation in flight
|
|
125
|
+
* @param {number} [ms] - How long to wait
|
|
126
|
+
* @returns {Promise<T>}
|
|
127
|
+
*/
|
|
128
|
+
function withTimeout(work, ms = 15000) {
|
|
129
|
+
return Promise.race([
|
|
130
|
+
work,
|
|
131
|
+
new Promise((_, reject) =>
|
|
132
|
+
setTimeout(() => reject(new Error('The server stopped answering')), ms).unref()),
|
|
133
|
+
]);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Whether a group exists, without the exception.
|
|
139
|
+
*
|
|
140
|
+
* `getGroup` throws for an unknown name — reasonable for a tool call, wrong as
|
|
141
|
+
* a test, and using it as one made every "create" report the group missing.
|
|
142
|
+
*
|
|
143
|
+
* @param {string} name - Group name
|
|
144
|
+
* @returns {any|null}
|
|
145
|
+
*/
|
|
146
|
+
function findGroup(name) {
|
|
147
|
+
try {
|
|
148
|
+
return getGroup(name);
|
|
149
|
+
} catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** @param {any} sftp - SFTP session @param {string} dir - Path to resolve */
|
|
155
|
+
function realpath(sftp, dir) {
|
|
156
|
+
return new Promise(resolve => {
|
|
157
|
+
sftp.realpath(dir, (/** @type {Error|null} */ error, /** @type {string} */ resolved) =>
|
|
158
|
+
resolve(error ? dir : resolved));
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** @param {any} sftp - SFTP session @param {string} dir - Directory to list */
|
|
163
|
+
function readdir(sftp, dir) {
|
|
164
|
+
return new Promise((resolve, reject) => {
|
|
165
|
+
sftp.readdir(dir, (/** @type {Error|null} */ error, /** @type {any[]} */ list) =>
|
|
166
|
+
(error ? reject(error) : resolve(list)));
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* One SFTP entry as a file browser wants it: types decoded from the POSIX mode,
|
|
172
|
+
* times in milliseconds, and the full path already joined so the caller never
|
|
173
|
+
* has to guess how to join at the root.
|
|
174
|
+
*
|
|
175
|
+
* @param {string} dir - The directory being listed
|
|
176
|
+
* @param {any} item - An ssh2 directory entry
|
|
177
|
+
*/
|
|
178
|
+
function describe(dir, item) {
|
|
179
|
+
const attrs = item.attrs || {};
|
|
180
|
+
const mode = attrs.mode || 0;
|
|
181
|
+
const S_IFMT = 0o170000;
|
|
182
|
+
return {
|
|
183
|
+
name: item.filename,
|
|
184
|
+
path: dir === '/' ? `/${item.filename}` : `${dir}/${item.filename}`,
|
|
185
|
+
size: attrs.size ?? 0,
|
|
186
|
+
isDirectory: (mode & S_IFMT) === 0o040000,
|
|
187
|
+
isSymlink: (mode & S_IFMT) === 0o120000,
|
|
188
|
+
modifyTime: (attrs.mtime ?? 0) * 1000,
|
|
189
|
+
accessTime: (attrs.atime ?? 0) * 1000,
|
|
190
|
+
permissions: mode & 0o7777,
|
|
191
|
+
owner: attrs.uid ?? 0,
|
|
192
|
+
group: attrs.gid ?? 0,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* How much JSON a request may carry.
|
|
198
|
+
*
|
|
199
|
+
* Every route but one takes a handful of fields, and 8 KB was plenty for those
|
|
200
|
+
* — until import, where confirming a hundred servers read out of another
|
|
201
|
+
* application is a perfectly ordinary thing to do and lands around 20 KB. One
|
|
202
|
+
* megabyte is far more than any of them needs and still refuses anything that
|
|
203
|
+
* looks like an attempt to fill memory.
|
|
204
|
+
*/
|
|
205
|
+
/**
|
|
206
|
+
* One open shell, remote or local. `close` releases whatever is behind it.
|
|
207
|
+
*
|
|
208
|
+
* @typedef {Object} TerminalEntry
|
|
209
|
+
* @property {string} label - What to call it in a log line
|
|
210
|
+
* @property {(data: Buffer) => void} write - Keystrokes in
|
|
211
|
+
* @property {(rows: number, cols: number) => void} resize - Window size
|
|
212
|
+
* @property {() => void} close - Release the shell and its connection
|
|
213
|
+
* @property {Set<import('http').ServerResponse>} subscribers - Attached pages
|
|
214
|
+
* @property {string[]} backlog - Frames kept for a page that attaches late
|
|
215
|
+
* @property {number} backlogBytes - Size of that backlog
|
|
216
|
+
*/
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Opens a pseudo-terminal on the machine this process runs on.
|
|
220
|
+
*
|
|
221
|
+
* @typedef {(options: {cols: number, rows: number, cwd?: string}) => Promise<{
|
|
222
|
+
* onData: (handler: (chunk: Buffer|string) => void) => void,
|
|
223
|
+
* onExit: (handler: () => void) => void,
|
|
224
|
+
* write: (data: Buffer) => void,
|
|
225
|
+
* resize: (cols: number, rows: number) => void,
|
|
226
|
+
* kill: () => void,
|
|
227
|
+
* shell: string,
|
|
228
|
+
* }>} LocalShellFactory
|
|
229
|
+
*/
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* `attachment` with an ASCII fallback name and the exact UTF-8 name.
|
|
233
|
+
* @param {string} name - Remote filename
|
|
234
|
+
* @returns {string}
|
|
235
|
+
*/
|
|
236
|
+
export function contentDisposition(name) {
|
|
237
|
+
const fallback = name.replace(/[^\x20-\x7e]|["\\]/g, '_') || 'download';
|
|
238
|
+
const exact = encodeURIComponent(name).replace(/['()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
239
|
+
return `attachment; filename="${fallback}"; filename*=UTF-8''${exact}`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const MAX_BODY_BYTES = 1024 * 1024;
|
|
243
|
+
const MAX_RECOVERY_BYTES = 16 * 1024 * 1024;
|
|
244
|
+
|
|
245
|
+
// Preferences are a handful of booleans and a list of folded category names.
|
|
246
|
+
const PREFERENCES_LIMIT_BYTES = 64 * 1024;
|
|
247
|
+
|
|
248
|
+
// How long an announcement nobody heard is kept for the first page that opens.
|
|
249
|
+
// Sized for the worst real case: a file dropped on a *cold* Dock icon launches
|
|
250
|
+
// the application, so the event exists long before there is an interface to
|
|
251
|
+
// tell. Long enough for a slow machine to get a window up; short enough that
|
|
252
|
+
// nobody is asked about a file they dropped in another session.
|
|
253
|
+
const ANNOUNCE_REPLAY_MS = 30 * 1000;
|
|
254
|
+
|
|
255
|
+
// How long the page is told "continued in the desktop app" before this plane
|
|
256
|
+
// stops: long enough to read, short enough that the socket is soon free.
|
|
257
|
+
const HANDOVER_MS = 4000;
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Getting the desktop application, as the control plane uses it. The real
|
|
261
|
+
* functions of desktop-install.js by default; the tests stand in for them.
|
|
262
|
+
* @typedef {Object} DesktopHooks
|
|
263
|
+
* @property {() => import('./desktop-install.js').DesktopStatus} status
|
|
264
|
+
* @property {(options: {onProgress: (progress: import('./desktop-install.js').DesktopProgress) => void}) =>
|
|
265
|
+
* Promise<{path: string, version: string|null}>} install
|
|
266
|
+
* @property {(options: {path: string}) => Promise<void>} open
|
|
267
|
+
* @property {() => Promise<boolean>} running - Is the application already running?
|
|
268
|
+
* @property {string} platform - Decides the hand-over order (see #handOver)
|
|
269
|
+
*/
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* What the desktop application knows about its own updates, handed to the
|
|
273
|
+
* control plane by the application's main process. Absent everywhere else:
|
|
274
|
+
* `ssh-manager control` in a browser has no application to update.
|
|
275
|
+
*
|
|
276
|
+
* @typedef {Object} AppUpdateSnapshot
|
|
277
|
+
* @property {string} currentVersion - The version running now
|
|
278
|
+
* @property {'idle'|'checking'|'available'|'downloading'|'ready'|'error'} status
|
|
279
|
+
* @property {string} [version] - The version on offer (available, downloading, ready)
|
|
280
|
+
* @property {number} [percent] - Download progress, 0 to 100
|
|
281
|
+
* @property {string} [checkedAt] - ISO time of the last completed check
|
|
282
|
+
* @property {string} [error] - Why the last check or download failed
|
|
283
|
+
* @property {'stable'|'preview'} channel - Previews are offered newer previews and the stable release
|
|
284
|
+
*
|
|
285
|
+
* @typedef {Object} AppUpdates
|
|
286
|
+
* @property {() => AppUpdateSnapshot} snapshot
|
|
287
|
+
* @property {() => Promise<unknown>} check
|
|
288
|
+
* @property {() => Promise<unknown>} download
|
|
289
|
+
* @property {() => void} install - Quits and installs; the application restarts
|
|
290
|
+
* @property {(listener: (snapshot: AppUpdateSnapshot) => void) => (() => void)} subscribe
|
|
291
|
+
*/
|
|
292
|
+
|
|
293
|
+
export class ControlPlane {
|
|
294
|
+
/**
|
|
295
|
+
* @param {Object} options - Configuration
|
|
296
|
+
* @param {string} options.socketPath - Where the engine connects
|
|
297
|
+
* @param {number} [options.port] - HTTP port; 0 picks a free one
|
|
298
|
+
* @param {string[]} [options.auditPaths] - JSONL audit logs to read
|
|
299
|
+
* @param {string} [options.vaultPath] - Encrypted store to manage servers in
|
|
300
|
+
* @param {boolean} [options.offerDesktop] - Offer to install and open the desktop
|
|
301
|
+
* application. Only `ssh-manager control` sets it; never the application itself
|
|
302
|
+
* @param {Partial<DesktopHooks>} [options.desktop] - Stand-ins for desktop-install.js (tests)
|
|
303
|
+
* @param {number} [options.handoverMs] - Delay between "continued in the app" and stopping
|
|
304
|
+
* @param {() => void} [options.onHandover] - Called once this plane has stopped for the app
|
|
305
|
+
* @param {Partial<import('./agent-clients.js').Context>} [options.agents] - Stand-ins for the
|
|
306
|
+
* AI tools' configuration files and commands (tests)
|
|
307
|
+
* @param {AppUpdates|null} [options.appUpdates] - The application's own updates; only the
|
|
308
|
+
* desktop application sets it
|
|
309
|
+
*/
|
|
310
|
+
constructor({
|
|
311
|
+
socketPath, port = 0, auditPaths = [], vaultPath = defaultVaultPath(),
|
|
312
|
+
offerDesktop = false, desktop = {}, handoverMs = HANDOVER_MS, onHandover = null, agents = {},
|
|
313
|
+
appUpdates = null,
|
|
314
|
+
}) {
|
|
315
|
+
this.socketPath = socketPath;
|
|
316
|
+
this.port = port;
|
|
317
|
+
this.auditPaths = auditPaths;
|
|
318
|
+
this.store = new SecretStore(vaultPath);
|
|
319
|
+
|
|
320
|
+
// The desktop application, offered from a browser tab. Off unless asked
|
|
321
|
+
// for: inside the application there is nothing to offer, and an embedder
|
|
322
|
+
// that never heard of it must not grow new endpoints.
|
|
323
|
+
this.offerDesktop = offerDesktop;
|
|
324
|
+
/** @type {DesktopHooks} */
|
|
325
|
+
this.desktop = {
|
|
326
|
+
status: () => desktopStatus(),
|
|
327
|
+
install: ({ onProgress }) => installDesktop({ onProgress }),
|
|
328
|
+
open: ({ path: target }) => openDesktop({ path: target }),
|
|
329
|
+
running: () => desktopRunning(),
|
|
330
|
+
platform: process.platform,
|
|
331
|
+
...desktop,
|
|
332
|
+
};
|
|
333
|
+
this.handoverMs = handoverMs;
|
|
334
|
+
this.onHandover = onHandover;
|
|
335
|
+
/** Where the AI tools' configurations are read and written (tests point it elsewhere). */
|
|
336
|
+
this.agentContext = agentContext(agents);
|
|
337
|
+
/** The application's updates, or null: then /api/app-update is a 404 like any unknown path. */
|
|
338
|
+
this.appUpdates = appUpdates;
|
|
339
|
+
this.stopAppUpdates = appUpdates
|
|
340
|
+
? appUpdates.subscribe(snapshot => this.#broadcast({ type: 'app-update', ...snapshot }))
|
|
341
|
+
: null;
|
|
342
|
+
/** @type {{installing: boolean, handingOver: boolean, phase: string|null, received: number, total: number, error: string|null}} */
|
|
343
|
+
this.desktopState = { installing: false, handingOver: false, phase: null, received: 0, total: 0, error: null };
|
|
344
|
+
// Live command output from the engine, kept with a bounded scrollback so a
|
|
345
|
+
// window opened mid-command still shows what came before.
|
|
346
|
+
this.streams = new StreamRegistry();
|
|
347
|
+
this.streamServer = null;
|
|
348
|
+
// Interactive shells opened from the terminal screen, keyed by id. An
|
|
349
|
+
// entry hides where it came from behind write/resize/close, because a
|
|
350
|
+
// local shell and a remote one differ only in how they were opened.
|
|
351
|
+
/** @type {Map<string, TerminalEntry>} */
|
|
352
|
+
this.terminals = new Map();
|
|
353
|
+
|
|
354
|
+
// Set by a desktop shell that can allocate a local pseudo-terminal. Left
|
|
355
|
+
// null everywhere else — the engine ships no native module and will not
|
|
356
|
+
// grow one, so a shell on *this* machine is something the host process
|
|
357
|
+
// offers, not something the control plane can conjure.
|
|
358
|
+
/** @type {LocalShellFactory|null} */
|
|
359
|
+
this.localShell = null;
|
|
360
|
+
|
|
361
|
+
// SFTP connections, kept alive between requests. A file manager makes tens
|
|
362
|
+
// of calls to browse one directory tree, and an SSH handshake per `ls` —
|
|
363
|
+
// several hundred milliseconds each — would make the screen unusable. Idle
|
|
364
|
+
// connections are dropped after SFTP_IDLE_MS so nothing stays open on a
|
|
365
|
+
// machine nobody is looking at.
|
|
366
|
+
/** @type {Map<string, {ssh: any, sftp: any, timer: NodeJS.Timeout|null, revision: string}>} */
|
|
367
|
+
this.sftpPool = new Map();
|
|
368
|
+
|
|
369
|
+
/** @type {string|null} The tokenised URL, once the server is listening. */
|
|
370
|
+
this.url = null;
|
|
371
|
+
this.token = crypto.randomBytes(24).toString('hex');
|
|
372
|
+
|
|
373
|
+
/** @type {Map<string, PendingRequest>} */
|
|
374
|
+
this.pending = new Map();
|
|
375
|
+
/** @type {Object[]} */
|
|
376
|
+
this.timeline = [];
|
|
377
|
+
/** @type {Set<import('http').ServerResponse>} */
|
|
378
|
+
this.subscribers = new Set();
|
|
379
|
+
/** @type {{event: Record<string, any>, at: number}[]} */
|
|
380
|
+
this.undelivered = [];
|
|
381
|
+
|
|
382
|
+
this.socketServer = null;
|
|
383
|
+
this.httpServer = null;
|
|
384
|
+
/** @type {Map<string, number>} */
|
|
385
|
+
this.auditOffsets = new Map();
|
|
386
|
+
this.auditTimer = null;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Start both servers.
|
|
391
|
+
* @returns {Promise<{url: string, socketPath: string}>} Where to point a browser
|
|
392
|
+
*/
|
|
393
|
+
async start() {
|
|
394
|
+
// Groups are the union of .server-groups.json and the per-server `group`
|
|
395
|
+
// field, so the group layer needs to know what servers exist. Wired here
|
|
396
|
+
// rather than inside the options handler: the write routes need it too, and
|
|
397
|
+
// without it they cannot tell a config-derived group from an unknown one.
|
|
398
|
+
setServerConfigProvider(() => {
|
|
399
|
+
try {
|
|
400
|
+
const raw = this.store.read();
|
|
401
|
+
return Object.fromEntries(
|
|
402
|
+
Object.entries(raw.servers).map(([name, config]) => [name, { ...config, name }])
|
|
403
|
+
);
|
|
404
|
+
} catch {
|
|
405
|
+
// An unreadable vault means no config-derived groups, not a failure.
|
|
406
|
+
return {};
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
// Checked before binding, because bind() reports an over-long path as
|
|
411
|
+
// EADDRINUSE — an error that sends you looking for a process that does not
|
|
412
|
+
// exist, on a socket file that is not there. macOS/BSD cap sun_path at 104
|
|
413
|
+
// bytes, and a project checked out under a long path reaches that easily.
|
|
414
|
+
for (const [label, socket] of [['approval', this.socketPath], ['stream', streamSocketPath()]]) {
|
|
415
|
+
const size = Buffer.byteLength(socket);
|
|
416
|
+
if (size > MAX_SOCKET_PATH) {
|
|
417
|
+
throw new Error(
|
|
418
|
+
`The ${label} socket path is ${size} bytes, over the ${MAX_SOCKET_PATH}-byte limit for Unix sockets: `
|
|
419
|
+
+ `${socket}\nSet SSH_MANAGER_HOME to a shorter directory.`
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
await this.#startSocketServer();
|
|
424
|
+
await this.#startStreamServer();
|
|
425
|
+
const url = await this.#startHttpServer();
|
|
426
|
+
this.#startAuditTail();
|
|
427
|
+
return { url, socketPath: this.socketPath };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async #startStreamServer() {
|
|
431
|
+
this.streamServer = await listenForStreams(this.streams);
|
|
432
|
+
this.#rememberSocketFile(streamSocketPath());
|
|
433
|
+
this.#trackConnections(this.streamServer);
|
|
434
|
+
|
|
435
|
+
// Every command an agent runs passes through here, which is why the log can
|
|
436
|
+
// exist without anything being configured on the servers themselves.
|
|
437
|
+
trimCommandLog();
|
|
438
|
+
this.streams.subscribe(event => {
|
|
439
|
+
if (event.type !== 'end') return;
|
|
440
|
+
const stream = this.streams.get(event.id);
|
|
441
|
+
if (!stream) return;
|
|
442
|
+
appendCommand({
|
|
443
|
+
ts: new Date().toISOString(),
|
|
444
|
+
server: stream.server,
|
|
445
|
+
command: stream.command,
|
|
446
|
+
code: event.code ?? null,
|
|
447
|
+
durationMs: stream.startedAt ? Date.now() - Date.parse(stream.startedAt) : undefined,
|
|
448
|
+
output: stream.scrollback,
|
|
449
|
+
});
|
|
450
|
+
});
|
|
451
|
+
// Push every stream event straight to open pages: this is the "watch the
|
|
452
|
+
// agent work" path, and buffering it would defeat the point.
|
|
453
|
+
this.streams.subscribe(event => this.#broadcast({ type: 'stream', event }));
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** Stop everything and release the socket. */
|
|
457
|
+
/** Every socket any of this plane's servers accepted, until it closes. */
|
|
458
|
+
#connections = new Set();
|
|
459
|
+
|
|
460
|
+
/** @type {Map<string, {dev: number, ino: number}>} The socket files this plane bound, by path. */
|
|
461
|
+
#socketFiles = new Map();
|
|
462
|
+
|
|
463
|
+
/** When a hand-over to the desktop application stops this plane (epoch ms). */
|
|
464
|
+
#handoverDeadline = 0;
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Remember which file a listener created, so stop() removes that file and
|
|
468
|
+
* not one another process has since put at the same path.
|
|
469
|
+
* @param {string} socketPath - A Unix socket this plane listens on
|
|
470
|
+
*/
|
|
471
|
+
#rememberSocketFile(socketPath) {
|
|
472
|
+
try {
|
|
473
|
+
const { dev, ino } = fs.statSync(socketPath);
|
|
474
|
+
this.#socketFiles.set(socketPath, { dev, ino });
|
|
475
|
+
} catch { /* a Windows named pipe has no file to remember */ }
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Remember each connection a server accepts, so stop() can end it.
|
|
480
|
+
* @param {import('net').Server | null} server - Any of the three servers
|
|
481
|
+
*/
|
|
482
|
+
#trackConnections(server) {
|
|
483
|
+
server?.on('connection', socket => {
|
|
484
|
+
this.#connections.add(socket);
|
|
485
|
+
socket.once('close', () => this.#connections.delete(socket));
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
async stop() {
|
|
490
|
+
if (this.stopAppUpdates) this.stopAppUpdates();
|
|
491
|
+
if (this.auditTimer) clearInterval(this.auditTimer);
|
|
492
|
+
for (const response of this.subscribers) response.end();
|
|
493
|
+
this.subscribers.clear();
|
|
494
|
+
|
|
495
|
+
// Answer anything still waiting rather than leaving the engine hanging on a
|
|
496
|
+
// socket that is about to disappear.
|
|
497
|
+
for (const [, entry] of this.pending) {
|
|
498
|
+
entry.settle('deny', 'Control plane shutting down');
|
|
499
|
+
}
|
|
500
|
+
this.pending.clear();
|
|
501
|
+
|
|
502
|
+
// Interactive shells hold an SSH connection each; leaving them would leak
|
|
503
|
+
// a session per terminal ever opened.
|
|
504
|
+
for (const id of [...this.terminals.keys()]) this.#disposeTerminal(id);
|
|
505
|
+
for (const name of [...this.sftpPool.keys()]) this.#releaseSftp(name);
|
|
506
|
+
|
|
507
|
+
// A control plane started on the same path since — the desktop application
|
|
508
|
+
// taking over from `ssh-manager control` — has replaced our socket files
|
|
509
|
+
// with its own. libuv unlinks a Unix socket's *path* when its server
|
|
510
|
+
// closes, whatever file is there by then, which would leave the other plane
|
|
511
|
+
// listening where no engine can find it. So a file that is no longer ours
|
|
512
|
+
// is moved aside while our servers close (libuv does it inside close()),
|
|
513
|
+
// and put straight back.
|
|
514
|
+
/** @type {[string, string][]} */
|
|
515
|
+
const moved = [];
|
|
516
|
+
for (const [socket, identity] of this.#socketFiles) {
|
|
517
|
+
try {
|
|
518
|
+
const current = fs.statSync(socket);
|
|
519
|
+
if (current.dev === identity.dev && current.ino === identity.ino) continue;
|
|
520
|
+
const aside = `${socket}.${process.pid}.keep`;
|
|
521
|
+
fs.renameSync(socket, aside);
|
|
522
|
+
moved.push([aside, socket]);
|
|
523
|
+
} catch { /* nothing there: nothing to protect */ }
|
|
524
|
+
}
|
|
525
|
+
const closed = Promise.all([
|
|
526
|
+
new Promise(resolve => (this.socketServer ? this.socketServer.close(() => resolve(undefined)) : resolve(undefined))),
|
|
527
|
+
new Promise(resolve => (this.httpServer ? this.httpServer.close(() => resolve(undefined)) : resolve(undefined))),
|
|
528
|
+
new Promise(resolve => (this.streamServer ? this.streamServer.close(() => resolve(undefined)) : resolve(undefined))),
|
|
529
|
+
]);
|
|
530
|
+
for (const [aside, socket] of moved) {
|
|
531
|
+
try { fs.renameSync(aside, socket); } catch (error) {
|
|
532
|
+
logger.warn('Could not put back another control plane\'s socket', { socket, error: error.message });
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
// close() only stops a server accepting; it then waits for every connection
|
|
536
|
+
// it already has to end, and some never do on their own. An MCP engine stays
|
|
537
|
+
// connected to the approval socket for as long as it runs, and a page's
|
|
538
|
+
// open requests can outlive the page. Either held the desktop application
|
|
539
|
+
// open indefinitely after Quit — its before-quit handler awaits this — which
|
|
540
|
+
// is the normal situation while an agent is using it. An engine waiting on
|
|
541
|
+
// a decision was already answered `deny` above; ending its socket is the
|
|
542
|
+
// fail-closed path it expects when the control plane goes away.
|
|
543
|
+
for (const socket of this.#connections) socket.destroy();
|
|
544
|
+
await closed;
|
|
545
|
+
// Our own files, should libuv have left any; never another plane's.
|
|
546
|
+
for (const [socket, identity] of this.#socketFiles) {
|
|
547
|
+
try {
|
|
548
|
+
const current = fs.statSync(socket);
|
|
549
|
+
if (current.dev === identity.dev && current.ino === identity.ino) fs.unlinkSync(socket);
|
|
550
|
+
} catch { /* already gone */ }
|
|
551
|
+
}
|
|
552
|
+
this.#socketFiles.clear();
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
async #startSocketServer() {
|
|
556
|
+
// A socket left behind by a crash makes bind() fail; clearing it is what
|
|
557
|
+
// lets the control plane restart without manual cleanup.
|
|
558
|
+
try {
|
|
559
|
+
if (fs.statSync(this.socketPath).isSocket()) fs.unlinkSync(this.socketPath);
|
|
560
|
+
} catch { /* nothing there */ }
|
|
561
|
+
|
|
562
|
+
fs.mkdirSync(path.dirname(this.socketPath), { recursive: true, mode: 0o700 });
|
|
563
|
+
|
|
564
|
+
this.socketServer = net.createServer(socket => this.#handleEngineConnection(socket));
|
|
565
|
+
this.#trackConnections(this.socketServer);
|
|
566
|
+
await new Promise((resolve, reject) => {
|
|
567
|
+
this.socketServer?.once('error', reject);
|
|
568
|
+
this.socketServer?.listen(this.socketPath, () => resolve(undefined));
|
|
569
|
+
});
|
|
570
|
+
// Only this user may ask us to decide.
|
|
571
|
+
try { fs.chmodSync(this.socketPath, 0o600); } catch { /* best effort */ }
|
|
572
|
+
this.#rememberSocketFile(this.socketPath);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* One engine connection carries one request and waits for one reply.
|
|
577
|
+
* @param {import('net').Socket} socket - The engine's connection
|
|
578
|
+
*/
|
|
579
|
+
#handleEngineConnection(socket) {
|
|
580
|
+
let buffer = '';
|
|
581
|
+
let handled = false;
|
|
582
|
+
|
|
583
|
+
socket.on('data', chunk => {
|
|
584
|
+
if (handled) return;
|
|
585
|
+
buffer += chunk.toString();
|
|
586
|
+
const newline = buffer.indexOf('\n');
|
|
587
|
+
if (newline === -1) return;
|
|
588
|
+
handled = true;
|
|
589
|
+
|
|
590
|
+
/** @type {any} */
|
|
591
|
+
let request;
|
|
592
|
+
try {
|
|
593
|
+
request = JSON.parse(buffer.slice(0, newline));
|
|
594
|
+
} catch (error) {
|
|
595
|
+
logger.warn('Unreadable approval request', { error: error.message });
|
|
596
|
+
socket.destroy();
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const settle = (decision, reason) => {
|
|
601
|
+
if (socket.destroyed) return;
|
|
602
|
+
socket.write(`${JSON.stringify({ id: request.id, decision, reason })}\n`);
|
|
603
|
+
socket.end();
|
|
604
|
+
this.pending.delete(request.id);
|
|
605
|
+
this.#broadcast({ type: 'resolved', id: request.id, decision, reason });
|
|
606
|
+
this.#record({
|
|
607
|
+
ts: new Date().toISOString(),
|
|
608
|
+
server: request.server,
|
|
609
|
+
tool: request.tool,
|
|
610
|
+
command: request.command,
|
|
611
|
+
allowed: decision === 'allow',
|
|
612
|
+
reason: `approval ${decision}${reason ? `: ${reason}` : ''}`,
|
|
613
|
+
source: 'control-plane',
|
|
614
|
+
});
|
|
615
|
+
};
|
|
616
|
+
|
|
617
|
+
this.pending.set(request.id, { request, settle, receivedAt: Date.now() });
|
|
618
|
+
this.#broadcast({ type: 'pending', request });
|
|
619
|
+
logger.info('Approval requested', { server: request.server, tool: request.tool });
|
|
620
|
+
|
|
621
|
+
// If the engine gives up first (its own deadline), drop the entry so the
|
|
622
|
+
// UI does not offer a decision nobody is waiting for.
|
|
623
|
+
socket.on('close', () => {
|
|
624
|
+
if (this.pending.has(request.id)) {
|
|
625
|
+
this.pending.delete(request.id);
|
|
626
|
+
this.#broadcast({ type: 'expired', id: request.id });
|
|
627
|
+
}
|
|
628
|
+
});
|
|
629
|
+
});
|
|
630
|
+
|
|
631
|
+
socket.on('error', () => { /* engine went away */ });
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* @returns {Promise<string>} The URL to open, token included
|
|
636
|
+
*/
|
|
637
|
+
async #startHttpServer() {
|
|
638
|
+
this.httpServer = http.createServer((req, res) => {
|
|
639
|
+
Promise.resolve().then(() => this.#handleHttp(req, res)).catch(error => {
|
|
640
|
+
logger.error('Control plane request failed', { error: error.message });
|
|
641
|
+
if (!res.headersSent) this.#json(res, 500, { error: 'Request failed' });
|
|
642
|
+
else if (!res.writableEnded) res.end();
|
|
643
|
+
});
|
|
644
|
+
});
|
|
645
|
+
this.#trackConnections(this.httpServer);
|
|
646
|
+
await new Promise((resolve, reject) => {
|
|
647
|
+
this.httpServer?.once('error', reject);
|
|
648
|
+
// 127.0.0.1, never 0.0.0.0: this must not be reachable from the network.
|
|
649
|
+
this.httpServer?.listen(this.port, '127.0.0.1', () => resolve(undefined));
|
|
650
|
+
});
|
|
651
|
+
const address = /** @type {import('net').AddressInfo} */ (this.httpServer.address());
|
|
652
|
+
// Port 0 asks the OS to choose; remember what it chose, or callers that
|
|
653
|
+
// outlive the returned URL — a desktop window reopening, a status command —
|
|
654
|
+
// have no way to build it again.
|
|
655
|
+
this.port = address.port;
|
|
656
|
+
this.url = `http://127.0.0.1:${address.port}/?token=${this.token}`;
|
|
657
|
+
return this.url;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
662
|
+
* @param {import('http').ServerResponse} res - Response
|
|
663
|
+
*/
|
|
664
|
+
#handleHttp(req, res) {
|
|
665
|
+
let url;
|
|
666
|
+
try {
|
|
667
|
+
url = new URL(req.url || '/', 'http://127.0.0.1');
|
|
668
|
+
} catch {
|
|
669
|
+
return this.#json(res, 400, { error: 'Malformed request URL' });
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// DNS rebinding: a hostile page can resolve its own domain to 127.0.0.1 and
|
|
673
|
+
// reach us. The Host header is what tells the two apart.
|
|
674
|
+
const host = (req.headers.host || '').replace(/:\d+$/, '');
|
|
675
|
+
if (!ALLOWED_HOSTS.has(host)) {
|
|
676
|
+
res.writeHead(403, { 'content-type': 'text/plain' });
|
|
677
|
+
res.end('Forbidden host\n');
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
const token = url.searchParams.get('token') || req.headers['x-control-token'];
|
|
682
|
+
if (typeof token !== 'string' || !this.#tokenMatches(token)) {
|
|
683
|
+
res.writeHead(401, { 'content-type': 'text/plain' });
|
|
684
|
+
res.end('Missing or invalid token\n');
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
if (req.method === 'GET' && url.pathname === '/') return this.#serveApp(res);
|
|
689
|
+
if (req.method === 'GET' && url.pathname === '/legacy') return this.#serveUi(res);
|
|
690
|
+
if (req.method === 'GET' && (url.pathname === '/app.js' || url.pathname === '/app.css'
|
|
691
|
+
|| url.pathname.startsWith('/assets/'))) return this.#serveAppAsset(url.pathname, res);
|
|
692
|
+
if (req.method === 'GET' && url.pathname === '/api/state') return this.#serveState(res);
|
|
693
|
+
if (req.method === 'GET' && url.pathname === '/api/events') return this.#serveEvents(res);
|
|
694
|
+
if (req.method === 'POST' && url.pathname === '/api/decide') return this.#handleDecision(req, res);
|
|
695
|
+
if (req.method === 'POST' && url.pathname === '/api/terminal') return this.#openTerminal(req, res);
|
|
696
|
+
if (req.method === 'GET' && url.pathname === '/api/terminal/stream') return this.#streamTerminal(url.searchParams.get('id'), res);
|
|
697
|
+
if (req.method === 'POST' && url.pathname === '/api/terminal/input') return this.#terminalInput(url.searchParams.get('id'), req, res);
|
|
698
|
+
if (req.method === 'POST' && url.pathname === '/api/terminal/resize') return this.#terminalResize(url.searchParams.get('id'), req, res);
|
|
699
|
+
if (req.method === 'DELETE' && url.pathname === '/api/terminal') return this.#closeTerminal(url.searchParams.get('id'), res);
|
|
700
|
+
|
|
701
|
+
// Files. Deliberately not path-restricted, for the same reason the terminal
|
|
702
|
+
// is not: whoever holds this token already has a shell on the machine.
|
|
703
|
+
if (req.method === 'GET' && url.pathname === '/api/files') return this.#listFiles(url.searchParams, res);
|
|
704
|
+
if (req.method === 'GET' && url.pathname === '/api/files/read') return this.#readFile(url.searchParams, res);
|
|
705
|
+
if (req.method === 'POST' && url.pathname === '/api/files/write') return this.#writeFile(url.searchParams, req, res);
|
|
706
|
+
if (req.method === 'POST' && url.pathname === '/api/files/mkdir') return this.#fileOp('mkdir', req, res);
|
|
707
|
+
if (req.method === 'POST' && url.pathname === '/api/files/rename') return this.#fileOp('rename', req, res);
|
|
708
|
+
if (req.method === 'POST' && url.pathname === '/api/files/delete') return this.#fileOp('delete', req, res);
|
|
709
|
+
|
|
710
|
+
// The local side of the file browser. This process runs on the operator's
|
|
711
|
+
// own machine, so it can read that machine's filesystem — which is what
|
|
712
|
+
// makes a local/remote pair possible at all. A page in a browser could not,
|
|
713
|
+
// but the page is not what reads the disk here.
|
|
714
|
+
if (req.method === 'GET' && url.pathname === '/api/local/files') return this.#listLocal(url.searchParams, res);
|
|
715
|
+
if (req.method === 'GET' && url.pathname === '/api/local/read') return this.#readLocal(url.searchParams, res);
|
|
716
|
+
if (req.method === 'POST' && url.pathname === '/api/local/mkdir') return this.#localOp('mkdir', req, res);
|
|
717
|
+
if (req.method === 'POST' && url.pathname === '/api/local/touch') return this.#localOp('touch', req, res);
|
|
718
|
+
if (req.method === 'POST' && url.pathname === '/api/local/rename') return this.#localOp('rename', req, res);
|
|
719
|
+
if (req.method === 'POST' && url.pathname === '/api/local/delete') return this.#localOp('delete', req, res);
|
|
720
|
+
if (req.method === 'POST' && url.pathname === '/api/local/reveal') return this.#localOp('reveal', req, res);
|
|
721
|
+
if (req.method === 'POST' && url.pathname === '/api/transfer') return this.#transfer(req, res);
|
|
722
|
+
if (req.method === 'POST' && url.pathname === '/api/execute') return this.#execute(req, res);
|
|
723
|
+
if (req.method === 'GET' && url.pathname === '/api/preferences') return this.#servePreferences(res);
|
|
724
|
+
if (req.method === 'PUT' && url.pathname === '/api/preferences') return this.#savePreferences(req, res);
|
|
725
|
+
if (req.method === 'GET' && url.pathname === '/api/options') return this.#serveOptions(res);
|
|
726
|
+
|
|
727
|
+
// The desktop application, offered from a browser tab. When the plane was
|
|
728
|
+
// not started to offer it these paths do not exist: a 404, like any other.
|
|
729
|
+
if (this.offerDesktop) {
|
|
730
|
+
if (req.method === 'GET' && url.pathname === '/api/desktop') return this.#serveDesktop(res);
|
|
731
|
+
if (req.method === 'POST' && url.pathname === '/api/desktop/install') return this.#installDesktopApp(req, res);
|
|
732
|
+
if (req.method === 'POST' && url.pathname === '/api/desktop/open') return this.#openDesktopApp(req, res);
|
|
733
|
+
}
|
|
734
|
+
// Which engine each AI tool runs, npm's or the application's, and the
|
|
735
|
+
// switch between them. Offered everywhere: to whoever uses npm and to
|
|
736
|
+
// whoever has only the application.
|
|
737
|
+
if (req.method === 'GET' && url.pathname === '/api/agents') return this.#serveAgents(res);
|
|
738
|
+
if (req.method === 'POST' && url.pathname === '/api/agents/use') {
|
|
739
|
+
return this.#readJsonBody(req, res, payload => this.#useAgentEngine(payload, res));
|
|
740
|
+
}
|
|
741
|
+
// The desktop application's own updates: what is running, what is on offer,
|
|
742
|
+
// and the three things a person can do about it. 404 outside the application.
|
|
743
|
+
if (this.appUpdates && url.pathname.startsWith('/api/app-update')) {
|
|
744
|
+
if (req.method === 'GET' && url.pathname === '/api/app-update') return this.#json(res, 200, this.appUpdates.snapshot());
|
|
745
|
+
if (req.method === 'POST') {
|
|
746
|
+
const action = url.pathname.slice('/api/app-update/'.length);
|
|
747
|
+
if (action === 'check' || action === 'download' || action === 'install') return this.#appUpdateAction(action, res);
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
if (req.method === 'DELETE' && url.pathname === '/api/hostkey') {
|
|
751
|
+
return this.#forgetHostKey(url.searchParams.get('host'), url.searchParams.get('port'), res);
|
|
752
|
+
}
|
|
753
|
+
if (req.method === 'POST' && url.pathname === '/api/health') {
|
|
754
|
+
return this.#probeHealth(url.searchParams.get('name'), res);
|
|
755
|
+
}
|
|
756
|
+
if (req.method === 'GET' && url.pathname === '/api/streams') {
|
|
757
|
+
const id = url.searchParams.get('id');
|
|
758
|
+
return this.#json(res, 200, id ? { stream: this.streams.get(id) } : { streams: this.streams.list() });
|
|
759
|
+
}
|
|
760
|
+
if (req.method === 'GET' && url.pathname === '/api/servers') return this.#serveServers(res);
|
|
761
|
+
if (req.method === 'GET' && url.pathname === '/api/vault/status') return this.#vaultStatus(res);
|
|
762
|
+
if (req.method === 'POST' && url.pathname === '/api/vault/backup') return this.#vaultBackup(req, res);
|
|
763
|
+
if (req.method === 'POST' && url.pathname === '/api/vault/restore') return this.#vaultRestore(req, res);
|
|
764
|
+
if (req.method === 'GET' && url.pathname === '/api/import/sources') return this.#importSources(res);
|
|
765
|
+
if (req.method === 'POST' && url.pathname === '/api/import/preview') return this.#importPreview(req, res);
|
|
766
|
+
if (req.method === 'POST' && url.pathname === '/api/import/apply') return this.#importApply(req, res);
|
|
767
|
+
if (req.method === 'GET' && url.pathname === '/api/history') {
|
|
768
|
+
return this.#json(res, 200, {
|
|
769
|
+
entries: readCommandLog(safeInteger(url.searchParams.get('limit'), 500)),
|
|
770
|
+
path: commandLogPath(),
|
|
771
|
+
recordsOutput: recordsOutput(),
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
if (req.method === 'DELETE' && url.pathname === '/api/history') {
|
|
775
|
+
// Offered because it is the operator's machine and their record.
|
|
776
|
+
clearCommandLog();
|
|
777
|
+
return this.#json(res, 200, { ok: true });
|
|
778
|
+
}
|
|
779
|
+
if (req.method === 'GET' && url.pathname === '/api/thresholds') {
|
|
780
|
+
return this.#json(res, 200, { thresholds: this.#readThresholds() });
|
|
781
|
+
}
|
|
782
|
+
if (req.method === 'POST' && url.pathname === '/api/thresholds') {
|
|
783
|
+
return this.#readJsonBody(req, res, payload => {
|
|
784
|
+
const thresholds = createAlertConfig({
|
|
785
|
+
cpu: safeInteger(payload.cpu, 80),
|
|
786
|
+
memory: safeInteger(payload.memory, 90),
|
|
787
|
+
disk: safeInteger(payload.disk, 85),
|
|
788
|
+
enabled: payload.enabled !== false,
|
|
789
|
+
});
|
|
790
|
+
fs.mkdirSync(path.dirname(this.#thresholdsPath()), { recursive: true, mode: 0o700 });
|
|
791
|
+
fs.writeFileSync(this.#thresholdsPath(), `${JSON.stringify(thresholds, null, 2)}\n`, { mode: 0o600 });
|
|
792
|
+
this.#broadcast({ type: 'thresholds' });
|
|
793
|
+
return this.#json(res, 200, { thresholds });
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
if (req.method === 'GET' && url.pathname === '/api/migration') return this.#migrationState(res);
|
|
797
|
+
if (req.method === 'POST' && url.pathname === '/api/groups') return this.#saveGroup(req, res);
|
|
798
|
+
if (req.method === 'DELETE' && url.pathname === '/api/groups') return this.#deleteGroup(url.searchParams.get('name'), res);
|
|
799
|
+
if (req.method === 'POST' && url.pathname === '/api/groups/run') return this.#runOnGroup(req, res);
|
|
800
|
+
|
|
801
|
+
// Saved commands: named shortcuts a person picks from a list, as opposed to
|
|
802
|
+
// the aliases an agent expands.
|
|
803
|
+
if (req.method === 'GET' && url.pathname === '/api/commands') {
|
|
804
|
+
const server = url.searchParams.get('server');
|
|
805
|
+
return this.#json(res, 200, {
|
|
806
|
+
commands: server ? commandsForServer(server) : listSavedCommands(),
|
|
807
|
+
suggestions: listSavedCommands().length === 0 ? suggestedCommands() : [],
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
if (req.method === 'POST' && url.pathname === '/api/commands') {
|
|
811
|
+
return this.#readJsonBody(req, res, payload => {
|
|
812
|
+
try {
|
|
813
|
+
return this.#json(res, 200, { command: saveCommand(payload) });
|
|
814
|
+
} catch (error) {
|
|
815
|
+
return this.#json(res, 400, { error: error.message });
|
|
816
|
+
}
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
if (req.method === 'DELETE' && url.pathname === '/api/commands') {
|
|
820
|
+
const id = url.searchParams.get('id');
|
|
821
|
+
return this.#json(res, id && deleteSavedCommand(id) ? 200 : 404,
|
|
822
|
+
id ? { ok: true } : { error: 'Which command?' });
|
|
823
|
+
}
|
|
824
|
+
if (req.method === 'POST' && url.pathname === '/api/migration') return this.#runMigration(req, res);
|
|
825
|
+
if (req.method === 'POST' && url.pathname === '/api/servers') return this.#saveServer(req, res);
|
|
826
|
+
if (req.method === 'DELETE' && url.pathname === '/api/servers') {
|
|
827
|
+
return this.#deleteServer(url.searchParams.get('name'), res);
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
res.writeHead(404, { 'content-type': 'text/plain' });
|
|
831
|
+
res.end('Not found\n');
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* Constant-time token comparison, so a caller cannot learn the token one
|
|
836
|
+
* character at a time from response timings.
|
|
837
|
+
* @param {string} candidate - Token supplied by the caller
|
|
838
|
+
* @returns {boolean} True on match
|
|
839
|
+
*/
|
|
840
|
+
#tokenMatches(candidate) {
|
|
841
|
+
const expected = Buffer.from(this.token);
|
|
842
|
+
const actual = Buffer.from(candidate);
|
|
843
|
+
if (expected.length !== actual.length) return false;
|
|
844
|
+
return crypto.timingSafeEqual(expected, actual);
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* Shown only when the built interface is missing — a source checkout that has
|
|
849
|
+
* not run `npm run build:ui`.
|
|
850
|
+
*
|
|
851
|
+
* This used to be a second, complete implementation of every screen. Keeping
|
|
852
|
+
* two of those in step is work nobody does, and the one that drifts is always
|
|
853
|
+
* the one nobody looks at. A fallback that says what to run is more useful
|
|
854
|
+
* than a fallback that quietly behaves differently.
|
|
855
|
+
*
|
|
856
|
+
* @param {import('http').ServerResponse} res - Response
|
|
857
|
+
*/
|
|
858
|
+
#serveUi(res) {
|
|
859
|
+
res.writeHead(200, {
|
|
860
|
+
'content-type': 'text/html; charset=utf-8',
|
|
861
|
+
'cache-control': 'no-store',
|
|
862
|
+
'content-security-policy': 'default-src \'none\'; style-src \'unsafe-inline\'',
|
|
863
|
+
});
|
|
864
|
+
res.end(`<!doctype html>
|
|
865
|
+
<meta charset="utf-8">
|
|
866
|
+
<title>SSH Manager — interface not built</title>
|
|
867
|
+
<style>
|
|
868
|
+
body { font: 15px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
869
|
+
max-width: 34rem; margin: 20vh auto; padding: 0 1.5rem; color: #111418; }
|
|
870
|
+
code { background: #edeff3; border-radius: 4px; padding: 0.15em 0.4em; font-size: 0.9em; }
|
|
871
|
+
p { color: #4a5058; }
|
|
872
|
+
@media (prefers-color-scheme: dark) {
|
|
873
|
+
body { background: #111418; color: #e6e8eb; } code { background: #23272e; } p { color: #99a1ab; }
|
|
874
|
+
}
|
|
875
|
+
</style>
|
|
876
|
+
<h1>The interface has not been built</h1>
|
|
877
|
+
<p>The control plane is running and its API is answering — only the page is missing.
|
|
878
|
+
This happens in a source checkout that has not built it yet.</p>
|
|
879
|
+
<p>From the repository root:</p>
|
|
880
|
+
<p><code>npm run build:ui</code></p>
|
|
881
|
+
<p>Then reload. An installed copy from npm ships the built interface, so this
|
|
882
|
+
page should never appear there.</p>
|
|
883
|
+
`);
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/** @param {import('http').ServerResponse} res - Response */
|
|
887
|
+
#serveState(res) {
|
|
888
|
+
const pending = [...this.pending.values()].map(entry => ({
|
|
889
|
+
...entry.request,
|
|
890
|
+
waitingMs: Date.now() - entry.receivedAt,
|
|
891
|
+
}));
|
|
892
|
+
res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
893
|
+
res.end(JSON.stringify({ pending, timeline: this.timeline.slice(-TIMELINE_LIMIT) }));
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/** @param {import('http').ServerResponse} res - Response */
|
|
897
|
+
#serveEvents(res) {
|
|
898
|
+
res.writeHead(200, {
|
|
899
|
+
'content-type': 'text/event-stream',
|
|
900
|
+
'cache-control': 'no-store',
|
|
901
|
+
connection: 'keep-alive',
|
|
902
|
+
});
|
|
903
|
+
res.write(': connected\n\n');
|
|
904
|
+
this.subscribers.add(res);
|
|
905
|
+
res.on('close', () => this.subscribers.delete(res));
|
|
906
|
+
|
|
907
|
+
// Anything the shell said while there was nobody to hear it. Drained
|
|
908
|
+
// whether or not it is still fresh, so a stale event is discarded rather
|
|
909
|
+
// than kept for the next page.
|
|
910
|
+
const held = this.undelivered.splice(0, this.undelivered.length);
|
|
911
|
+
const now = Date.now();
|
|
912
|
+
for (const item of held) {
|
|
913
|
+
if (now - item.at < ANNOUNCE_REPLAY_MS) this.#broadcast(item.event);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
919
|
+
* @param {import('http').ServerResponse} res - Response
|
|
920
|
+
*/
|
|
921
|
+
#handleDecision(req, res) {
|
|
922
|
+
let body = '';
|
|
923
|
+
req.on('data', chunk => {
|
|
924
|
+
body += chunk;
|
|
925
|
+
// A decision is a few dozen bytes; anything larger is not one.
|
|
926
|
+
if (body.length > 4096) req.destroy();
|
|
927
|
+
});
|
|
928
|
+
req.on('end', () => {
|
|
929
|
+
/** @type {any} */
|
|
930
|
+
let payload;
|
|
931
|
+
try {
|
|
932
|
+
payload = JSON.parse(body);
|
|
933
|
+
} catch {
|
|
934
|
+
res.writeHead(400, { 'content-type': 'application/json' });
|
|
935
|
+
res.end('{"error":"malformed body"}');
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
const entry = this.pending.get(payload.id);
|
|
940
|
+
if (!entry) {
|
|
941
|
+
// Already answered, or the engine timed out while the page was open.
|
|
942
|
+
res.writeHead(409, { 'content-type': 'application/json' });
|
|
943
|
+
res.end('{"error":"no longer pending"}');
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
entry.settle(payload.decision === 'allow' ? 'allow' : 'deny', payload.reason);
|
|
948
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
949
|
+
res.end('{"ok":true}');
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* Servers held in the vault.
|
|
955
|
+
*
|
|
956
|
+
* Never returns a secret, only whether one is set: the page is the most
|
|
957
|
+
* exposed surface here, and a credential has no reason to travel to it. The
|
|
958
|
+
* CLI does not print them either.
|
|
959
|
+
*
|
|
960
|
+
* @param {import('http').ServerResponse} res - Response
|
|
961
|
+
*/
|
|
962
|
+
/**
|
|
963
|
+
* Push an event to every open page.
|
|
964
|
+
*
|
|
965
|
+
* The desktop shell is in this same process and occasionally knows something
|
|
966
|
+
* the interface cannot ask for — a file dropped on the Dock icon, which
|
|
967
|
+
* arrives as an AppKit event with no HTTP request behind it. This is the door
|
|
968
|
+
* for that, and deliberately the only one: everything else the page needs, it
|
|
969
|
+
* fetches.
|
|
970
|
+
*
|
|
971
|
+
* An announcement made while no page is listening would simply vanish, and
|
|
972
|
+
* that is exactly the case that matters: the drop is what *launched* the
|
|
973
|
+
* application, so the event is ready a second or two before the interface
|
|
974
|
+
* has connected its stream. Held, then, and handed to the first page that
|
|
975
|
+
* arrives — once, and only if it arrives soon.
|
|
976
|
+
*
|
|
977
|
+
* @param {Record<string, any>} event - Must carry a `type` the page knows
|
|
978
|
+
*/
|
|
979
|
+
announce(event) {
|
|
980
|
+
if (this.subscribers.size === 0) {
|
|
981
|
+
this.undelivered.push({ event, at: Date.now() });
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
this.#broadcast(event);
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* Offer a shell on the machine this process runs on.
|
|
989
|
+
*
|
|
990
|
+
* The second door for a host process, beside `announce()`. A pseudo-terminal
|
|
991
|
+
* cannot be allocated from plain Node — it needs `forkpty`, which means a
|
|
992
|
+
* native module — and the engine deliberately has none: it is published on
|
|
993
|
+
* npm and installs on machines with no compiler. So the desktop shell, which
|
|
994
|
+
* is built with a toolchain and already rebuilds native modules for Electron,
|
|
995
|
+
* hands one down instead.
|
|
996
|
+
*
|
|
997
|
+
* Nothing calls this in the npm package, and the interface asks before it
|
|
998
|
+
* offers: no local shell is not a broken local shell.
|
|
999
|
+
*
|
|
1000
|
+
* @param {LocalShellFactory|null} factory - Opens a local pseudo-terminal
|
|
1001
|
+
*/
|
|
1002
|
+
setLocalShellProvider(factory) {
|
|
1003
|
+
this.localShell = factory;
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
/**
|
|
1007
|
+
* Which places on *this* machine actually hold servers to import.
|
|
1008
|
+
*
|
|
1009
|
+
* Offering "FileZilla" to somebody who has never installed it is a dead end
|
|
1010
|
+
* dressed as a feature, so each source is probed and only the ones with
|
|
1011
|
+
* something in them come back. The count is part of the answer: "23 servers"
|
|
1012
|
+
* is a reason to click, "FileZilla" on its own is a question.
|
|
1013
|
+
*/
|
|
1014
|
+
#importSources(res) {
|
|
1015
|
+
/** @type {{id: string, label: string, count: number}[]} */
|
|
1016
|
+
const found = [];
|
|
1017
|
+
|
|
1018
|
+
for (const [id, candidates] of Object.entries(WELL_KNOWN)) {
|
|
1019
|
+
const file = candidates().find(path => fs.existsSync(path));
|
|
1020
|
+
if (!file) continue;
|
|
1021
|
+
try {
|
|
1022
|
+
const { servers, source } = importFile(file);
|
|
1023
|
+
if (servers.length) found.push({ id, label: source, count: servers.length });
|
|
1024
|
+
} catch {
|
|
1025
|
+
// A file that exists but cannot be parsed is not worth offering.
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
if (process.platform === 'darwin') {
|
|
1030
|
+
try {
|
|
1031
|
+
const transmit = readTransmit([]);
|
|
1032
|
+
if (transmit.length) {
|
|
1033
|
+
found.push({ id: 'transmit', label: 'Transmit favourites', count: transmit.length });
|
|
1034
|
+
}
|
|
1035
|
+
} catch { /* Transmit is not installed, or plutil said no */ }
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
return this.#json(res, 200, { sources: found, formats: READERS.map(r => r.id) });
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
/**
|
|
1042
|
+
* Read something without writing anything.
|
|
1043
|
+
*
|
|
1044
|
+
* Import is the one operation where "show me what you are about to do" is not
|
|
1045
|
+
* a nicety: the alternative is finding out afterwards that forty rows landed
|
|
1046
|
+
* with the wrong names.
|
|
1047
|
+
*
|
|
1048
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1049
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1050
|
+
*/
|
|
1051
|
+
#importPreview(req, res) {
|
|
1052
|
+
this.#readJsonBody(req, res, payload => {
|
|
1053
|
+
/** @type {string|null} */
|
|
1054
|
+
let temporary = null;
|
|
1055
|
+
try {
|
|
1056
|
+
let servers = [];
|
|
1057
|
+
let source = '';
|
|
1058
|
+
/** @type {string[]} */
|
|
1059
|
+
const warnings = [];
|
|
1060
|
+
|
|
1061
|
+
if (payload.source === 'transmit') {
|
|
1062
|
+
servers = readTransmit(warnings);
|
|
1063
|
+
source = 'Transmit favourites';
|
|
1064
|
+
} else if (payload.source) {
|
|
1065
|
+
const candidates = WELL_KNOWN[String(payload.source)];
|
|
1066
|
+
if (!candidates) return this.#json(res, 400, { error: `Unknown source: ${payload.source}` });
|
|
1067
|
+
const file = candidates().find(path => fs.existsSync(path));
|
|
1068
|
+
if (!file) return this.#json(res, 404, { error: 'Nothing found for that source on this machine' });
|
|
1069
|
+
({ servers, source } = importFile(file));
|
|
1070
|
+
} else if (payload.filename && typeof payload.content === 'string') {
|
|
1071
|
+
// The browser can hand over a file's bytes but not its path, and the
|
|
1072
|
+
// readers open files themselves (a spreadsheet is a zip). So it lands
|
|
1073
|
+
// in a temp file, keeping its extension, which is what detection uses.
|
|
1074
|
+
const safe = path.basename(String(payload.filename)).replace(/[^\w.-]/g, '_');
|
|
1075
|
+
temporary = path.join(os.tmpdir(), `ssh-manager-import-${Date.now()}-${safe}`);
|
|
1076
|
+
fs.writeFileSync(temporary, Buffer.from(payload.content, 'base64'), { mode: 0o600 });
|
|
1077
|
+
({ servers, source } = importFile(temporary, payload.format || undefined));
|
|
1078
|
+
} else {
|
|
1079
|
+
return this.#json(res, 400, { error: 'Give either a source or a file' });
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
const existing = [...Object.keys(this.store.exists() ? this.store.read().servers : {})];
|
|
1083
|
+
const { fresh, conflicts } = plan(servers, existing);
|
|
1084
|
+
return this.#json(res, 200, { source, fresh, conflicts, warnings });
|
|
1085
|
+
} catch (error) {
|
|
1086
|
+
return this.#json(res, 400, { error: error.message });
|
|
1087
|
+
} finally {
|
|
1088
|
+
if (temporary) { try { fs.rmSync(temporary, { force: true }); } catch { /* temp */ } }
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
/**
|
|
1094
|
+
* Write the servers the operator just looked at.
|
|
1095
|
+
*
|
|
1096
|
+
* Takes the list back rather than re-reading the file: what they confirmed is
|
|
1097
|
+
* what gets written, even if the file changed underneath in the meantime.
|
|
1098
|
+
*
|
|
1099
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1100
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1101
|
+
*/
|
|
1102
|
+
#importApply(req, res) {
|
|
1103
|
+
this.#readJsonBody(req, res, payload => {
|
|
1104
|
+
const servers = Array.isArray(payload.servers) ? payload.servers : [];
|
|
1105
|
+
if (!servers.length) return this.#json(res, 400, { error: 'Nothing to import' });
|
|
1106
|
+
let written = 0;
|
|
1107
|
+
try {
|
|
1108
|
+
for (const server of servers) {
|
|
1109
|
+
const { name, ...config } = server;
|
|
1110
|
+
if (!name || !config.host) continue;
|
|
1111
|
+
this.store.setServer(String(name), config);
|
|
1112
|
+
written++;
|
|
1113
|
+
}
|
|
1114
|
+
} catch (error) {
|
|
1115
|
+
return this.#json(res, 500, { error: error.message });
|
|
1116
|
+
}
|
|
1117
|
+
logger.info('Servers imported from the control plane', { count: written });
|
|
1118
|
+
this.#broadcast({ type: 'servers' });
|
|
1119
|
+
return this.#json(res, 200, { ok: true, written });
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
#serveServers(res) {
|
|
1124
|
+
/** @type {any[]} */
|
|
1125
|
+
let servers = [];
|
|
1126
|
+
try {
|
|
1127
|
+
const raw = this.store.read();
|
|
1128
|
+
servers = Object.entries(raw.servers).map(([name, config]) => ({ ...publicServerConfig(config), name }));
|
|
1129
|
+
} catch (error) {
|
|
1130
|
+
logger.error('Cannot read the vault', { error: error.message });
|
|
1131
|
+
return this.#json(res, 500, { error: 'Cannot read the vault. Restore it before editing servers.' });
|
|
1132
|
+
}
|
|
1133
|
+
res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
1134
|
+
res.end(JSON.stringify({ servers, vaultPath: this.store.vaultPath }));
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
/** @param {import('http').ServerResponse} res */
|
|
1138
|
+
#vaultStatus(res) {
|
|
1139
|
+
const check = this.store.checkKey();
|
|
1140
|
+
let count = 0;
|
|
1141
|
+
try { count = this.store.listServers().length; } catch { /* reported by checkKey */ }
|
|
1142
|
+
return this.#json(res, 200, {
|
|
1143
|
+
exists: this.store.exists(), readable: check.ok, reason: check.reason,
|
|
1144
|
+
servers: count, secrets: check.checked, keySource: this.store.keySource,
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
/** @param {import('http').IncomingMessage} req @param {import('http').ServerResponse} res */
|
|
1149
|
+
#vaultBackup(req, res) {
|
|
1150
|
+
this.#readJsonBody(req, res, payload => {
|
|
1151
|
+
try {
|
|
1152
|
+
const servers = this.store.getAllDecrypted();
|
|
1153
|
+
if (!Object.keys(servers).length) return this.#json(res, 400, { error: 'The vault is empty' });
|
|
1154
|
+
const content = serializeRecovery(servers, String(payload.passphrase || ''));
|
|
1155
|
+
if (Buffer.byteLength(content) > MAX_RECOVERY_BYTES) {
|
|
1156
|
+
return this.#json(res, 413, { error: 'Recovery exceeds the 16 MB interface limit. Use ssh-manager vault backup for this vault.' });
|
|
1157
|
+
}
|
|
1158
|
+
return this.#json(res, 200, {
|
|
1159
|
+
filename: `ssh-manager-recovery-${new Date().toISOString().slice(0, 10)}.json`, content,
|
|
1160
|
+
});
|
|
1161
|
+
} catch (error) {
|
|
1162
|
+
return this.#json(res, 400, { error: error.message });
|
|
1163
|
+
}
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
/** @returns {string} */
|
|
1168
|
+
#vaultRevision() {
|
|
1169
|
+
try {
|
|
1170
|
+
return crypto.createHash('sha256').update(fs.readFileSync(this.store.vaultPath)).digest('hex');
|
|
1171
|
+
} catch (error) {
|
|
1172
|
+
if (error.code === 'ENOENT') return 'missing';
|
|
1173
|
+
throw error;
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/** @param {import('http').IncomingMessage} req @param {import('http').ServerResponse} res */
|
|
1178
|
+
#vaultRestore(req, res) {
|
|
1179
|
+
this.#readJsonBody(req, res, payload => {
|
|
1180
|
+
try {
|
|
1181
|
+
const content = String(payload.content || '');
|
|
1182
|
+
if (Buffer.byteLength(content) > MAX_RECOVERY_BYTES) return this.#json(res, 413, { error: 'Recovery files must be at most 16 MB.' });
|
|
1183
|
+
const servers = decryptRecoveryContent(content, String(payload.passphrase || ''));
|
|
1184
|
+
const names = Object.keys(servers);
|
|
1185
|
+
if (!names.length) return this.#json(res, 400, { error: 'The recovery file contains no servers' });
|
|
1186
|
+
const revision = this.#vaultRevision();
|
|
1187
|
+
const check = this.store.checkKey();
|
|
1188
|
+
let existing = [];
|
|
1189
|
+
try { existing = this.store.listServers(); } catch { /* unreadable vault will be replaced explicitly */ }
|
|
1190
|
+
const preview = {
|
|
1191
|
+
servers: names,
|
|
1192
|
+
conflicts: names.filter(name => existing.includes(name)),
|
|
1193
|
+
removed: check.ok ? [] : existing.filter(name => !names.includes(name)),
|
|
1194
|
+
replacesUnreadable: !check.ok,
|
|
1195
|
+
revision,
|
|
1196
|
+
};
|
|
1197
|
+
if (payload.confirm !== true) return this.#json(res, 200, preview);
|
|
1198
|
+
if (payload.revision !== revision) {
|
|
1199
|
+
return this.#json(res, 409, { error: 'The vault changed. Preview the recovery file again before restoring.' });
|
|
1200
|
+
}
|
|
1201
|
+
this.store.restoreServers(servers, { replaceUnreadable: !check.ok, expectedRevision: revision });
|
|
1202
|
+
this.#broadcast({ type: 'servers' });
|
|
1203
|
+
return this.#json(res, 200, { ok: true, ...preview });
|
|
1204
|
+
} catch (error) {
|
|
1205
|
+
return this.#json(res, error.code === 'VAULT_CHANGED' ? 409 : 400, { error: error.message });
|
|
1206
|
+
}
|
|
1207
|
+
}, MAX_RECOVERY_BYTES * 2 + 4096);
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
/**
|
|
1213
|
+
* Create or edit a group.
|
|
1214
|
+
*
|
|
1215
|
+
* Groups come from two places: explicit lists in `.server-groups.json`, and
|
|
1216
|
+
* the per-server `group` field of the config. The second kind is derived at
|
|
1217
|
+
* read time and cannot be edited here — writing it back would duplicate into
|
|
1218
|
+
* a file what the config already says, and the two would drift.
|
|
1219
|
+
*
|
|
1220
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1221
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1222
|
+
*/
|
|
1223
|
+
#saveGroup(req, res) {
|
|
1224
|
+
this.#readJsonBody(req, res, payload => {
|
|
1225
|
+
const name = String(payload.name || '').trim();
|
|
1226
|
+
if (!name || !/^[a-zA-Z0-9_-]+$/.test(name)) {
|
|
1227
|
+
return this.#json(res, 400, { error: 'Name must use letters, digits, dashes and underscores' });
|
|
1228
|
+
}
|
|
1229
|
+
const servers = Array.isArray(payload.servers) ? payload.servers.map(String) : [];
|
|
1230
|
+
const options = {
|
|
1231
|
+
description: payload.description ? String(payload.description) : undefined,
|
|
1232
|
+
strategy: payload.strategy === 'sequential' ? 'sequential' : 'parallel',
|
|
1233
|
+
delay: safeInteger(payload.delay, 0),
|
|
1234
|
+
stopOnError: Boolean(payload.stopOnError),
|
|
1235
|
+
};
|
|
1236
|
+
|
|
1237
|
+
try {
|
|
1238
|
+
const existing = findGroup(name);
|
|
1239
|
+
// A config-derived group has no entry to update; saving one would write
|
|
1240
|
+
// a shadow copy that stops following the config.
|
|
1241
|
+
if (existing?.fromConfig && !existing.explicit) {
|
|
1242
|
+
return this.#json(res, 409, {
|
|
1243
|
+
error: `"${name}" comes from the servers' own group field. Edit it there, or pick another name.`,
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
if (existing) updateGroup(name, { servers, ...options });
|
|
1247
|
+
else createGroup(name, servers, options);
|
|
1248
|
+
this.#broadcast({ type: 'options' });
|
|
1249
|
+
return this.#json(res, 200, { ok: true, name });
|
|
1250
|
+
} catch (error) {
|
|
1251
|
+
return this.#json(res, 400, { error: error.message });
|
|
1252
|
+
}
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
/**
|
|
1257
|
+
* @param {string|null} name - Group to delete
|
|
1258
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1259
|
+
*/
|
|
1260
|
+
#deleteGroup(name, res) {
|
|
1261
|
+
if (!name) return this.#json(res, 400, { error: 'Which group?' });
|
|
1262
|
+
try {
|
|
1263
|
+
const existing = findGroup(name);
|
|
1264
|
+
if (existing?.fromConfig && !existing.explicit) {
|
|
1265
|
+
return this.#json(res, 409, {
|
|
1266
|
+
error: `"${name}" is derived from the servers' group field — remove it there instead.`,
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
deleteGroup(name);
|
|
1270
|
+
this.#broadcast({ type: 'options' });
|
|
1271
|
+
return this.#json(res, 200, { ok: true });
|
|
1272
|
+
} catch (error) {
|
|
1273
|
+
return this.#json(res, 400, { error: error.message });
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
/**
|
|
1278
|
+
* Run one command across a group.
|
|
1279
|
+
*
|
|
1280
|
+
* Answered immediately and reported on the event stream, like transfers: a
|
|
1281
|
+
* command across twenty machines takes as long as the slowest one, and a
|
|
1282
|
+
* request held open that long times out somewhere in between.
|
|
1283
|
+
*
|
|
1284
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1285
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1286
|
+
*/
|
|
1287
|
+
#runOnGroup(req, res) {
|
|
1288
|
+
this.#readJsonBody(req, res, async payload => {
|
|
1289
|
+
const name = String(payload.group || '');
|
|
1290
|
+
const command = String(payload.command || '');
|
|
1291
|
+
if (!command.trim()) return this.#json(res, 400, { error: 'A command is required' });
|
|
1292
|
+
|
|
1293
|
+
const group = findGroup(name);
|
|
1294
|
+
if (!group) return this.#json(res, 404, { error: 'No such group' });
|
|
1295
|
+
|
|
1296
|
+
const id = crypto.randomUUID();
|
|
1297
|
+
this.#json(res, 200, { id, servers: group.servers.length });
|
|
1298
|
+
|
|
1299
|
+
/** @type {Record<string, any>} */
|
|
1300
|
+
let vault = {};
|
|
1301
|
+
try {
|
|
1302
|
+
vault = this.store.getAllDecrypted();
|
|
1303
|
+
} catch (error) {
|
|
1304
|
+
this.#broadcast({ type: 'group-run', id, state: 'failed', error: error.message });
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
this.#broadcast({ type: 'group-run', id, group: name, command, state: 'started', total: group.servers.length });
|
|
1309
|
+
let done = 0;
|
|
1310
|
+
|
|
1311
|
+
await executeOnGroup(name, async serverName => {
|
|
1312
|
+
const config = vault[serverName];
|
|
1313
|
+
if (!config) throw new Error(`${serverName} is not in the vault`);
|
|
1314
|
+
let ssh;
|
|
1315
|
+
try {
|
|
1316
|
+
ssh = await connectServer(serverName, vault, { readyTimeout: 15000, actor: 'human' });
|
|
1317
|
+
const result = await ssh.execCommand(command, { timeout: 120000 });
|
|
1318
|
+
done++;
|
|
1319
|
+
this.#broadcast({
|
|
1320
|
+
type: 'group-run', id, state: 'progress', done, server: serverName,
|
|
1321
|
+
code: result.code, stdout: result.stdout, stderr: result.stderr,
|
|
1322
|
+
});
|
|
1323
|
+
return result;
|
|
1324
|
+
} finally {
|
|
1325
|
+
try { ssh?.dispose(); } catch { /* best effort */ }
|
|
1326
|
+
}
|
|
1327
|
+
}).then(
|
|
1328
|
+
() => this.#broadcast({ type: 'group-run', id, state: 'done', done }),
|
|
1329
|
+
error => this.#broadcast({ type: 'group-run', id, state: 'failed', error: error.message })
|
|
1330
|
+
);
|
|
1331
|
+
});
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
|
|
1335
|
+
/** @returns {string} Beside the vault, like the thresholds. */
|
|
1336
|
+
#preferencesPath() {
|
|
1337
|
+
return path.join(path.dirname(this.store.vaultPath), 'preferences.json');
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
/**
|
|
1341
|
+
* What the interface remembers about itself: the introduction has been seen,
|
|
1342
|
+
* the rail is collapsed, the theme is dark, this category is folded.
|
|
1343
|
+
*
|
|
1344
|
+
* Held here rather than in the browser's `localStorage`, which cannot work.
|
|
1345
|
+
* The control plane binds port 0 — the operating system picks a free one —
|
|
1346
|
+
* so the page's origin is `http://127.0.0.1:<a different port>` on every
|
|
1347
|
+
* launch, and `localStorage` is scoped to an origin. Every preference was
|
|
1348
|
+
* therefore forgotten between launches, which is why the introduction came
|
|
1349
|
+
* back each time however carefully it had been finished.
|
|
1350
|
+
*
|
|
1351
|
+
* Opaque on purpose: the interface owns the shape, this owns the file. The
|
|
1352
|
+
* only rules are that it is a flat object and that it stays small.
|
|
1353
|
+
*
|
|
1354
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1355
|
+
*/
|
|
1356
|
+
#servePreferences(res) {
|
|
1357
|
+
this.#json(res, 200, { preferences: this.#readPreferences() });
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
/** @returns {Record<string, any>} */
|
|
1361
|
+
#readPreferences() {
|
|
1362
|
+
try {
|
|
1363
|
+
const parsed = JSON.parse(fs.readFileSync(this.#preferencesPath(), 'utf8'));
|
|
1364
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
1365
|
+
} catch {
|
|
1366
|
+
// Absent on a first run, and unreadable is the same answer: no
|
|
1367
|
+
// preferences yet. Never a reason to fail the screen.
|
|
1368
|
+
return {};
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
/**
|
|
1373
|
+
* Merge, never replace. Two screens can each remember one thing without
|
|
1374
|
+
* the second erasing the first, and an interface that only knows about the
|
|
1375
|
+
* key it just changed does not have to send the rest back.
|
|
1376
|
+
*
|
|
1377
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1378
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1379
|
+
*/
|
|
1380
|
+
#savePreferences(req, res) {
|
|
1381
|
+
this.#readJsonBody(req, res, payload => {
|
|
1382
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
1383
|
+
return this.#json(res, 400, { error: 'Preferences must be an object' });
|
|
1384
|
+
}
|
|
1385
|
+
const merged = { ...this.#readPreferences(), ...payload };
|
|
1386
|
+
// A cap, because this is a preferences file and not a database, and
|
|
1387
|
+
// nothing should be able to grow it without limit.
|
|
1388
|
+
const encoded = JSON.stringify(merged, null, 2);
|
|
1389
|
+
if (encoded.length > PREFERENCES_LIMIT_BYTES) {
|
|
1390
|
+
return this.#json(res, 413, { error: 'Too many preferences' });
|
|
1391
|
+
}
|
|
1392
|
+
try {
|
|
1393
|
+
fs.mkdirSync(path.dirname(this.#preferencesPath()), { recursive: true });
|
|
1394
|
+
fs.writeFileSync(this.#preferencesPath(), `${encoded}\n`, { mode: 0o600 });
|
|
1395
|
+
} catch (error) {
|
|
1396
|
+
return this.#json(res, 500, { error: error.message });
|
|
1397
|
+
}
|
|
1398
|
+
return this.#json(res, 200, { preferences: merged });
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/** @returns {string} Where the thresholds live — beside the vault, not on the servers. */
|
|
1403
|
+
#thresholdsPath() {
|
|
1404
|
+
return path.join(path.dirname(this.store.vaultPath), 'thresholds.json');
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
/**
|
|
1408
|
+
* The levels at which a machine is worth mentioning.
|
|
1409
|
+
*
|
|
1410
|
+
* Kept on this machine rather than pushed to each server, which is what the
|
|
1411
|
+
* engine's `ssh_alert_setup` does: writing a config file onto twenty
|
|
1412
|
+
* production boxes to hold three numbers is a lot of blast radius for a
|
|
1413
|
+
* preference, and it only helps something that runs *there* — nothing does.
|
|
1414
|
+
* The watching happens here.
|
|
1415
|
+
*
|
|
1416
|
+
* @returns {{cpu: number, memory: number, disk: number, enabled: boolean}}
|
|
1417
|
+
*/
|
|
1418
|
+
#readThresholds() {
|
|
1419
|
+
try {
|
|
1420
|
+
return { ...createAlertConfig({}), ...JSON.parse(fs.readFileSync(this.#thresholdsPath(), 'utf8')) };
|
|
1421
|
+
} catch {
|
|
1422
|
+
return createAlertConfig({});
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
/**
|
|
1427
|
+
* What is still living in a .env rather than in the vault.
|
|
1428
|
+
*
|
|
1429
|
+
* Offered, never performed. Somebody upgrading from 3.8 has a working setup
|
|
1430
|
+
* and no obligation to change it; the vault earns its place by being better,
|
|
1431
|
+
* not by moving their files while they are not looking. This route exists so
|
|
1432
|
+
* the interface can *mention* it — which is the part that was missing, since
|
|
1433
|
+
* nobody reads a changelog.
|
|
1434
|
+
*
|
|
1435
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1436
|
+
*/
|
|
1437
|
+
async #migrationState(res) {
|
|
1438
|
+
try {
|
|
1439
|
+
const loader = new ConfigLoader();
|
|
1440
|
+
// Deliberately without the vault: what is wanted here is what the files
|
|
1441
|
+
// alone hold, so a server present in both is not counted as pending.
|
|
1442
|
+
const loaded = await loader.load({ vaultPath: null });
|
|
1443
|
+
const fromFiles = loaded instanceof Map ? Object.fromEntries(loaded) : loaded;
|
|
1444
|
+
const inVault = new Set(this.store.exists() ? this.store.listServers() : []);
|
|
1445
|
+
|
|
1446
|
+
const pending = Object.entries(fromFiles)
|
|
1447
|
+
.filter(([name]) => !inVault.has(name))
|
|
1448
|
+
.map(([name, config]) => ({
|
|
1449
|
+
name,
|
|
1450
|
+
host: config.host,
|
|
1451
|
+
user: config.user,
|
|
1452
|
+
// The count, never the values: this travels to a browser.
|
|
1453
|
+
secrets: SECRET_FIELDS.filter(field => config[field]).length,
|
|
1454
|
+
source: config.source ?? 'env',
|
|
1455
|
+
}));
|
|
1456
|
+
|
|
1457
|
+
return this.#json(res, 200, {
|
|
1458
|
+
pending,
|
|
1459
|
+
inVault: inVault.size,
|
|
1460
|
+
envPath: loader.envPath ?? null,
|
|
1461
|
+
// A vault with no recovery file is a vault that does not survive this
|
|
1462
|
+
// machine, and that is exactly what the operator should know before
|
|
1463
|
+
// being told they can clean up their .env.
|
|
1464
|
+
hasVault: this.store.exists(),
|
|
1465
|
+
});
|
|
1466
|
+
} catch (error) {
|
|
1467
|
+
return this.#json(res, 200, { pending: [], inVault: 0, error: error.message });
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
/**
|
|
1472
|
+
* Copy servers from the files into the vault. Named ones only — a button
|
|
1473
|
+
* that moves everything is a button somebody presses by accident.
|
|
1474
|
+
*
|
|
1475
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1476
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1477
|
+
*/
|
|
1478
|
+
#runMigration(req, res) {
|
|
1479
|
+
this.#readJsonBody(req, res, async payload => {
|
|
1480
|
+
const wanted = Array.isArray(payload.servers) ? payload.servers.map(String) : [];
|
|
1481
|
+
if (wanted.length === 0) return this.#json(res, 400, { error: 'Name the servers to import' });
|
|
1482
|
+
|
|
1483
|
+
try {
|
|
1484
|
+
const loaded = await new ConfigLoader().load({ vaultPath: null });
|
|
1485
|
+
const fromFiles = loaded instanceof Map ? Object.fromEntries(loaded) : loaded;
|
|
1486
|
+
|
|
1487
|
+
const imported = [];
|
|
1488
|
+
for (const name of wanted) {
|
|
1489
|
+
if (!fromFiles[name]) continue;
|
|
1490
|
+
this.store.setServer(name, fromFiles[name]);
|
|
1491
|
+
imported.push(name);
|
|
1492
|
+
}
|
|
1493
|
+
// The .env is not touched, here or anywhere: it stays the fallback, and
|
|
1494
|
+
// removing it is the operator's decision to make later, deliberately.
|
|
1495
|
+
logger.info('Servers imported from files into the vault', { count: imported.length });
|
|
1496
|
+
this.#broadcast({ type: 'servers' });
|
|
1497
|
+
return this.#json(res, 200, { imported });
|
|
1498
|
+
} catch (error) {
|
|
1499
|
+
return this.#json(res, 500, { error: error.message });
|
|
1500
|
+
}
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
/**
|
|
1505
|
+
* Add or replace a server.
|
|
1506
|
+
*
|
|
1507
|
+
* A field left empty on an existing server keeps its stored value, so editing
|
|
1508
|
+
* the port does not silently wipe the password — the form cannot show it, so
|
|
1509
|
+
* it must not require re-typing it either.
|
|
1510
|
+
*
|
|
1511
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1512
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1513
|
+
*/
|
|
1514
|
+
#saveServer(req, res) {
|
|
1515
|
+
this.#readJsonBody(req, res, payload => {
|
|
1516
|
+
const name = String(payload.name || '').trim().toLowerCase();
|
|
1517
|
+
if (!name || !/^[a-z0-9_]+$/.test(name)) {
|
|
1518
|
+
return this.#json(res, 400, { error: 'Name must use letters, digits and underscores only' });
|
|
1519
|
+
}
|
|
1520
|
+
if (!payload.host) return this.#json(res, 400, { error: 'A host is required' });
|
|
1521
|
+
if (payload.mode && !VALID_MODES.has(payload.mode)) {
|
|
1522
|
+
return this.#json(res, 400, { error: 'Invalid security mode' });
|
|
1523
|
+
}
|
|
1524
|
+
if (payload.approval && !VALID_APPROVAL_MODES.has(payload.approval)) {
|
|
1525
|
+
return this.#json(res, 400, { error: 'Invalid approval mode' });
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
try {
|
|
1529
|
+
// The UI shows only some fields. Omitting proxy, platform, audit or
|
|
1530
|
+
// policy settings while changing a port must leave them intact.
|
|
1531
|
+
const existing = this.store.getAllDecrypted()[name] || {};
|
|
1532
|
+
const config = mergeServerPatch(existing, payload);
|
|
1533
|
+
this.store.setServer(name, config);
|
|
1534
|
+
} catch (error) {
|
|
1535
|
+
return this.#json(res, 500, { error: error.message });
|
|
1536
|
+
}
|
|
1537
|
+
logger.info('Server saved from the control plane', { server: name });
|
|
1538
|
+
this.#broadcast({ type: 'servers' });
|
|
1539
|
+
return this.#json(res, 200, { ok: true, name });
|
|
1540
|
+
});
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
/**
|
|
1544
|
+
* @param {string|null} name - Server to remove
|
|
1545
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1546
|
+
*/
|
|
1547
|
+
#deleteServer(name, res) {
|
|
1548
|
+
if (!name) return this.#json(res, 400, { error: 'No server named' });
|
|
1549
|
+
const removed = this.store.removeServer(name);
|
|
1550
|
+
if (!removed) return this.#json(res, 404, { error: 'No such server in the vault' });
|
|
1551
|
+
logger.info('Server removed from the control plane', { server: name });
|
|
1552
|
+
this.#broadcast({ type: 'servers' });
|
|
1553
|
+
return this.#json(res, 200, { ok: true });
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
/**
|
|
1557
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1558
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1559
|
+
* @param {(payload: any) => any} handler - Called with the parsed body
|
|
1560
|
+
* @param {number} [maxBytes] - Route-specific request size limit
|
|
1561
|
+
*/
|
|
1562
|
+
#readJsonBody(req, res, handler, maxBytes = MAX_BODY_BYTES) {
|
|
1563
|
+
req.setEncoding('utf8');
|
|
1564
|
+
let body = '';
|
|
1565
|
+
let bytes = 0;
|
|
1566
|
+
let refused = false;
|
|
1567
|
+
req.on('data', chunk => {
|
|
1568
|
+
if (refused) return;
|
|
1569
|
+
body += chunk;
|
|
1570
|
+
bytes += Buffer.byteLength(chunk);
|
|
1571
|
+
if (bytes > maxBytes) {
|
|
1572
|
+
// Answer, then stop reading. Destroying the socket silently — which is
|
|
1573
|
+
// what this did — reaches the browser as "Failed to fetch" with no
|
|
1574
|
+
// status and no message, and the operator has no way to know that a
|
|
1575
|
+
// limit was the reason. Importing a hundred servers hit it and looked
|
|
1576
|
+
// like a network fault.
|
|
1577
|
+
refused = true;
|
|
1578
|
+
this.#json(res, 413, {
|
|
1579
|
+
error: `Body too large: over ${Math.round(maxBytes / 1024)} KB`,
|
|
1580
|
+
});
|
|
1581
|
+
req.destroy();
|
|
1582
|
+
}
|
|
1583
|
+
});
|
|
1584
|
+
req.on('end', async () => {
|
|
1585
|
+
if (refused) return;
|
|
1586
|
+
let payload;
|
|
1587
|
+
try {
|
|
1588
|
+
payload = JSON.parse(body);
|
|
1589
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('object required');
|
|
1590
|
+
} catch {
|
|
1591
|
+
return this.#json(res, 400, { error: 'malformed body' });
|
|
1592
|
+
}
|
|
1593
|
+
try {
|
|
1594
|
+
await handler(payload);
|
|
1595
|
+
} catch (error) {
|
|
1596
|
+
logger.error('Control plane request failed', { error: error.message });
|
|
1597
|
+
if (!res.headersSent) this.#json(res, 500, { error: 'Request failed' });
|
|
1598
|
+
else if (!res.writableEnded) res.end();
|
|
1599
|
+
}
|
|
1600
|
+
});
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
/**
|
|
1604
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1605
|
+
* @param {number} status - HTTP status
|
|
1606
|
+
* @param {any} payload - JSON body
|
|
1607
|
+
*/
|
|
1608
|
+
#json(res, status, payload) {
|
|
1609
|
+
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
1610
|
+
res.end(JSON.stringify(payload));
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
|
|
1614
|
+
/**
|
|
1615
|
+
* The control plane's interface: a built React app under `dist/ui`.
|
|
1616
|
+
*
|
|
1617
|
+
* Generated, not committed: `prepack` builds it into the npm package and the
|
|
1618
|
+
* desktop app builds it when it is assembled, so `npm install` never compiles
|
|
1619
|
+
* anything. If the build is missing (a source checkout that has not run
|
|
1620
|
+
* `npm run build:ui`) this falls back to a page that says which command to
|
|
1621
|
+
* run rather than showing a blank screen.
|
|
1622
|
+
*
|
|
1623
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1624
|
+
*/
|
|
1625
|
+
#serveApp(res) {
|
|
1626
|
+
const index = path.join(APP_DIR, 'index.html');
|
|
1627
|
+
if (!fs.existsSync(index)) return this.#serveUi(res);
|
|
1628
|
+
try {
|
|
1629
|
+
// Vite emits root-relative asset URLs; the token has to ride along on
|
|
1630
|
+
// them for the same reason it does on the vendored files — a <script>
|
|
1631
|
+
// tag cannot authenticate itself.
|
|
1632
|
+
const html = fs.readFileSync(index, 'utf8')
|
|
1633
|
+
.replace(/(src|href)="\.?\/(app\.(?:js|css))"/g, (_, attr, file) => `${attr}="/${file}?token=${this.token}"`);
|
|
1634
|
+
res.writeHead(200, {
|
|
1635
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1636
|
+
'cache-control': 'no-store',
|
|
1637
|
+
'content-security-policy':
|
|
1638
|
+
'default-src \'none\'; style-src \'self\' \'unsafe-inline\'; '
|
|
1639
|
+
+ 'script-src \'self\'; connect-src \'self\'; img-src \'self\' data:; font-src \'self\'',
|
|
1640
|
+
});
|
|
1641
|
+
res.end(html);
|
|
1642
|
+
} catch {
|
|
1643
|
+
this.#serveUi(res);
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
/**
|
|
1648
|
+
* Static files from the build. The allowlist is by shape rather than by name
|
|
1649
|
+
* because the font filenames are chosen by the bundler, but the shape is
|
|
1650
|
+
* narrow and every path is resolved and checked to be inside APP_DIR — a
|
|
1651
|
+
* path from a URL is how traversal happens.
|
|
1652
|
+
*
|
|
1653
|
+
* @param {string} pathname - Requested path
|
|
1654
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1655
|
+
*/
|
|
1656
|
+
#serveAppAsset(pathname, res) {
|
|
1657
|
+
const types = {
|
|
1658
|
+
'.js': 'text/javascript', '.css': 'text/css', '.ttf': 'font/ttf',
|
|
1659
|
+
'.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.png': 'image/png',
|
|
1660
|
+
};
|
|
1661
|
+
const type = types[path.extname(pathname)];
|
|
1662
|
+
const resolved = path.resolve(APP_DIR, `.${pathname}`);
|
|
1663
|
+
if (!type || !resolved.startsWith(APP_DIR + path.sep)) {
|
|
1664
|
+
res.writeHead(404, { 'content-type': 'text/plain' });
|
|
1665
|
+
res.end('Not found\n');
|
|
1666
|
+
return;
|
|
1667
|
+
}
|
|
1668
|
+
try {
|
|
1669
|
+
let body = fs.readFileSync(resolved);
|
|
1670
|
+
// A stylesheet's url() references are fetched by the browser with no way
|
|
1671
|
+
// to add the token, exactly like a <script> tag. Same fix, same reason:
|
|
1672
|
+
// stamp it in when serving. Without this the fonts 401 and the page
|
|
1673
|
+
// silently falls back to the system stack.
|
|
1674
|
+
if (type === 'text/css') {
|
|
1675
|
+
body = Buffer.from(
|
|
1676
|
+
body.toString('utf8').replace(/url\(([^)"']*\/assets\/[^)"']+)\)/g,
|
|
1677
|
+
(_, asset) => `url(${asset}?token=${this.token})`)
|
|
1678
|
+
);
|
|
1679
|
+
}
|
|
1680
|
+
res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' });
|
|
1681
|
+
res.end(body);
|
|
1682
|
+
} catch {
|
|
1683
|
+
res.writeHead(404, { 'content-type': 'text/plain' });
|
|
1684
|
+
res.end('Not found\n');
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
/**
|
|
1689
|
+
* Open an interactive shell on a server.
|
|
1690
|
+
*
|
|
1691
|
+
* `ssh2` allocates the remote pseudo-terminal itself, so this needs no native
|
|
1692
|
+
* module: colours, `top`, `vim`, Ctrl-C and window resizing all work because
|
|
1693
|
+
* the remote side believes it is talking to a real terminal.
|
|
1694
|
+
*
|
|
1695
|
+
* Deliberately not subject to the readonly/restricted modes: those exist to
|
|
1696
|
+
* constrain an *agent*, and whoever holds this token is the operator who
|
|
1697
|
+
* configured them and already has the credentials. Constraining them here
|
|
1698
|
+
* would be theatre.
|
|
1699
|
+
*
|
|
1700
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1701
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1702
|
+
*/
|
|
1703
|
+
#openTerminal(req, res) {
|
|
1704
|
+
this.#readJsonBody(req, res, async payload => {
|
|
1705
|
+
const cols = payload.cols || 80;
|
|
1706
|
+
const rows = payload.rows || 24;
|
|
1707
|
+
if (payload.local) return this.#openLocalTerminal(res, cols, rows, payload.cwd);
|
|
1708
|
+
|
|
1709
|
+
const name = String(payload.server || '').toLowerCase();
|
|
1710
|
+
/** @type {Record<string, any>} */
|
|
1711
|
+
let servers = {};
|
|
1712
|
+
try {
|
|
1713
|
+
servers = this.store.getAllDecrypted();
|
|
1714
|
+
} catch (error) {
|
|
1715
|
+
return this.#json(res, 500, { error: `Cannot read the vault: ${error.message}` });
|
|
1716
|
+
}
|
|
1717
|
+
if (!servers[name]) return this.#json(res, 404, { error: 'No such server in the vault' });
|
|
1718
|
+
|
|
1719
|
+
const id = crypto.randomUUID();
|
|
1720
|
+
let ssh;
|
|
1721
|
+
|
|
1722
|
+
try {
|
|
1723
|
+
ssh = await connectServer(name, servers, { readyTimeout: 15000, actor: 'human' });
|
|
1724
|
+
const stream = await new Promise((resolve, reject) => {
|
|
1725
|
+
ssh.client.shell(
|
|
1726
|
+
{ term: 'xterm-256color', cols, rows },
|
|
1727
|
+
(error, channel) => (error ? reject(error) : resolve(channel))
|
|
1728
|
+
);
|
|
1729
|
+
});
|
|
1730
|
+
|
|
1731
|
+
const entry = this.#registerTerminal(id, {
|
|
1732
|
+
label: name,
|
|
1733
|
+
write: data => stream.write(data),
|
|
1734
|
+
resize: (nextRows, nextCols) => stream.setWindow(nextRows, nextCols, 0, 0),
|
|
1735
|
+
close: () => {
|
|
1736
|
+
try { stream.end(); } catch { /* already closed */ }
|
|
1737
|
+
try { ssh.dispose(); } catch { /* best effort */ }
|
|
1738
|
+
},
|
|
1739
|
+
});
|
|
1740
|
+
|
|
1741
|
+
stream.on('data', chunk => entry.push('stdout', chunk));
|
|
1742
|
+
stream.stderr?.on('data', chunk => entry.push('stderr', chunk));
|
|
1743
|
+
stream.on('close', () => this.#disposeTerminal(id));
|
|
1744
|
+
|
|
1745
|
+
logger.info('Interactive shell opened', { server: name });
|
|
1746
|
+
return this.#json(res, 200, { id, server: name });
|
|
1747
|
+
} catch (error) {
|
|
1748
|
+
try { ssh?.dispose(); } catch { /* best effort */ }
|
|
1749
|
+
return this.#json(res, 502, { error: error.message });
|
|
1750
|
+
}
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
/**
|
|
1755
|
+
* A shell on the machine this process is running on.
|
|
1756
|
+
*
|
|
1757
|
+
* Only when a host has offered one. `ssh-manager ui` served in a browser has
|
|
1758
|
+
* no local shell and says so plainly rather than pretending: the page asks
|
|
1759
|
+
* the options endpoint first and does not offer what cannot be given.
|
|
1760
|
+
*
|
|
1761
|
+
* Not gated by the readonly/restricted modes, for the same reason the remote
|
|
1762
|
+
* shell is not: those constrain an *agent*, and whoever holds this token is
|
|
1763
|
+
* the person sitting at the machine.
|
|
1764
|
+
*
|
|
1765
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1766
|
+
* @param {number} cols - Terminal width
|
|
1767
|
+
* @param {number} rows - Terminal height
|
|
1768
|
+
* @param {string} [cwd] - Where to start
|
|
1769
|
+
*/
|
|
1770
|
+
async #openLocalTerminal(res, cols, rows, cwd) {
|
|
1771
|
+
if (!this.localShell) {
|
|
1772
|
+
return this.#json(res, 501, { error: 'No local shell here — this build cannot open one' });
|
|
1773
|
+
}
|
|
1774
|
+
const id = crypto.randomUUID();
|
|
1775
|
+
try {
|
|
1776
|
+
const pty = await this.localShell({ cols, rows, cwd });
|
|
1777
|
+
const entry = this.#registerTerminal(id, {
|
|
1778
|
+
label: `local:${pty.shell}`,
|
|
1779
|
+
write: data => pty.write(data),
|
|
1780
|
+
resize: (nextRows, nextCols) => pty.resize(nextCols, nextRows),
|
|
1781
|
+
close: () => { try { pty.kill(); } catch { /* already gone */ } },
|
|
1782
|
+
});
|
|
1783
|
+
pty.onData(chunk => entry.push('stdout', Buffer.from(chunk)));
|
|
1784
|
+
pty.onExit(() => this.#disposeTerminal(id));
|
|
1785
|
+
logger.info('Local shell opened', { shell: pty.shell });
|
|
1786
|
+
return this.#json(res, 200, { id, server: 'This machine', local: true });
|
|
1787
|
+
} catch (error) {
|
|
1788
|
+
return this.#json(res, 500, { error: error.message });
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
/**
|
|
1793
|
+
* Everything an open shell needs that has nothing to do with where it runs:
|
|
1794
|
+
* the subscriber set, the bounded backlog, and the frame format.
|
|
1795
|
+
*
|
|
1796
|
+
* @param {string} id - Terminal id
|
|
1797
|
+
* @param {{label: string, write: (data: Buffer) => void, resize: (rows: number, cols: number) => void, close: () => void}} plumbing - What differs
|
|
1798
|
+
* @returns {TerminalEntry & {push: (channel: string, chunk: Buffer) => void}}
|
|
1799
|
+
*/
|
|
1800
|
+
#registerTerminal(id, plumbing) {
|
|
1801
|
+
const entry = /** @type {any} */ ({
|
|
1802
|
+
...plumbing,
|
|
1803
|
+
subscribers: new Set(),
|
|
1804
|
+
backlog: [],
|
|
1805
|
+
backlogBytes: 0,
|
|
1806
|
+
});
|
|
1807
|
+
// Base64 because terminal output is bytes, not text: escape sequences and
|
|
1808
|
+
// partial UTF-8 do not survive a round trip through JSON strings.
|
|
1809
|
+
entry.push = (channel, chunk) => {
|
|
1810
|
+
const line = `data: ${JSON.stringify({ channel, chunk: chunk.toString('base64') })}\n\n`;
|
|
1811
|
+
// Kept so a screen that attaches after the shell opened still shows the
|
|
1812
|
+
// login banner and the first prompt, which arrive in the gap between the
|
|
1813
|
+
// shell opening and the browser subscribing. Bounded, or a `tail -f` left
|
|
1814
|
+
// running would grow the process without limit.
|
|
1815
|
+
entry.backlog.push(line);
|
|
1816
|
+
entry.backlogBytes += line.length;
|
|
1817
|
+
while (entry.backlogBytes > TERMINAL_BACKLOG_BYTES && entry.backlog.length > 1) {
|
|
1818
|
+
entry.backlogBytes -= entry.backlog.shift().length;
|
|
1819
|
+
}
|
|
1820
|
+
for (const subscriber of entry.subscribers) {
|
|
1821
|
+
try { subscriber.write(line); } catch { entry.subscribers.delete(subscriber); }
|
|
1822
|
+
}
|
|
1823
|
+
};
|
|
1824
|
+
this.terminals.set(id, entry);
|
|
1825
|
+
return entry;
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
/**
|
|
1829
|
+
* @param {string|null} id - Terminal id
|
|
1830
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1831
|
+
*/
|
|
1832
|
+
#streamTerminal(id, res) {
|
|
1833
|
+
const entry = id ? this.terminals.get(id) : null;
|
|
1834
|
+
if (!entry) return this.#json(res, 404, { error: 'No such terminal' });
|
|
1835
|
+
res.writeHead(200, {
|
|
1836
|
+
'content-type': 'text/event-stream',
|
|
1837
|
+
'cache-control': 'no-store',
|
|
1838
|
+
connection: 'keep-alive',
|
|
1839
|
+
});
|
|
1840
|
+
res.write(': connected\n\n');
|
|
1841
|
+
for (const line of entry.backlog) {
|
|
1842
|
+
try { res.write(line); } catch { break; }
|
|
1843
|
+
}
|
|
1844
|
+
entry.subscribers.add(res);
|
|
1845
|
+
res.on('close', () => entry.subscribers.delete(res));
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
/**
|
|
1849
|
+
* @param {string|null} id - Terminal id
|
|
1850
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1851
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1852
|
+
*/
|
|
1853
|
+
#terminalInput(id, req, res) {
|
|
1854
|
+
const entry = id ? this.terminals.get(id) : null;
|
|
1855
|
+
if (!entry) return this.#json(res, 404, { error: 'No such terminal' });
|
|
1856
|
+
this.#readJsonBody(req, res, payload => {
|
|
1857
|
+
try {
|
|
1858
|
+
entry.write(Buffer.from(String(payload.data || ''), 'base64'));
|
|
1859
|
+
return this.#json(res, 200, { ok: true });
|
|
1860
|
+
} catch (error) {
|
|
1861
|
+
return this.#json(res, 500, { error: error.message });
|
|
1862
|
+
}
|
|
1863
|
+
});
|
|
1864
|
+
}
|
|
1865
|
+
|
|
1866
|
+
/**
|
|
1867
|
+
* @param {string|null} id - Terminal id
|
|
1868
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1869
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1870
|
+
*/
|
|
1871
|
+
#terminalResize(id, req, res) {
|
|
1872
|
+
const entry = id ? this.terminals.get(id) : null;
|
|
1873
|
+
if (!entry) return this.#json(res, 404, { error: 'No such terminal' });
|
|
1874
|
+
this.#readJsonBody(req, res, payload => {
|
|
1875
|
+
try {
|
|
1876
|
+
// Without this, a full-screen program draws for the wrong window size
|
|
1877
|
+
// and the display is garbled the moment anyone resizes.
|
|
1878
|
+
entry.resize(payload.rows || 24, payload.cols || 80);
|
|
1879
|
+
return this.#json(res, 200, { ok: true });
|
|
1880
|
+
} catch (error) {
|
|
1881
|
+
return this.#json(res, 500, { error: error.message });
|
|
1882
|
+
}
|
|
1883
|
+
});
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
/**
|
|
1887
|
+
* @param {string|null} id - Terminal id
|
|
1888
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1889
|
+
*/
|
|
1890
|
+
#closeTerminal(id, res) {
|
|
1891
|
+
if (!id || !this.terminals.has(id)) return this.#json(res, 404, { error: 'No such terminal' });
|
|
1892
|
+
this.#disposeTerminal(id);
|
|
1893
|
+
return this.#json(res, 200, { ok: true });
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
/**
|
|
1897
|
+
* Close a shell and release its SSH connection.
|
|
1898
|
+
* @param {string} id - Terminal id
|
|
1899
|
+
*/
|
|
1900
|
+
#disposeTerminal(id) {
|
|
1901
|
+
const entry = this.terminals.get(id);
|
|
1902
|
+
if (!entry) return;
|
|
1903
|
+
this.terminals.delete(id);
|
|
1904
|
+
for (const subscriber of entry.subscribers) {
|
|
1905
|
+
try { subscriber.end(); } catch { /* already gone */ }
|
|
1906
|
+
}
|
|
1907
|
+
try { entry.close(); } catch { /* best effort */ }
|
|
1908
|
+
logger.info('Interactive shell closed', { shell: entry.label });
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
|
|
1912
|
+
|
|
1913
|
+
|
|
1914
|
+
|
|
1915
|
+
/**
|
|
1916
|
+
* Move files between this machine and a server, in either direction.
|
|
1917
|
+
*
|
|
1918
|
+
* Done here rather than by the browser downloading and re-uploading: the
|
|
1919
|
+
* bytes never leave this process, which is both faster and the only way a
|
|
1920
|
+
* multi-gigabyte file works at all. Progress is reported on the event stream
|
|
1921
|
+
* so the page can show it without polling.
|
|
1922
|
+
*
|
|
1923
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
1924
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1925
|
+
*/
|
|
1926
|
+
#transfer(req, res) {
|
|
1927
|
+
this.#readJsonBody(req, res, async payload => {
|
|
1928
|
+
const name = String(payload.server || '').toLowerCase();
|
|
1929
|
+
const direction = payload.direction === 'download' ? 'download' : 'upload';
|
|
1930
|
+
const items = Array.isArray(payload.items) ? payload.items : [];
|
|
1931
|
+
if (items.length === 0) return this.#json(res, 400, { error: 'Nothing to transfer' });
|
|
1932
|
+
|
|
1933
|
+
const id = crypto.randomUUID();
|
|
1934
|
+
// Answered immediately: a transfer can take minutes, and a request left
|
|
1935
|
+
// open that long is a request that times out somewhere in between.
|
|
1936
|
+
this.#json(res, 200, { id, count: items.length });
|
|
1937
|
+
|
|
1938
|
+
let done = 0;
|
|
1939
|
+
const announce = (extra = {}) =>
|
|
1940
|
+
this.#broadcast({ type: 'transfer', id, direction, server: name, done, total: items.length, ...extra });
|
|
1941
|
+
announce({ state: 'started' });
|
|
1942
|
+
|
|
1943
|
+
try {
|
|
1944
|
+
await this.#withSftp(name, async sftp => {
|
|
1945
|
+
for (const item of items) {
|
|
1946
|
+
const local = path.resolve(String(item.local));
|
|
1947
|
+
const remote = String(item.remote);
|
|
1948
|
+
await new Promise((resolve, reject) => {
|
|
1949
|
+
const from = direction === 'upload' ? fs.createReadStream(local) : sftp.createReadStream(remote);
|
|
1950
|
+
const to = direction === 'upload' ? sftp.createWriteStream(remote) : fs.createWriteStream(local);
|
|
1951
|
+
from.on('error', reject);
|
|
1952
|
+
to.on('error', reject);
|
|
1953
|
+
to.on('close', resolve);
|
|
1954
|
+
to.on('finish', resolve);
|
|
1955
|
+
from.pipe(to);
|
|
1956
|
+
});
|
|
1957
|
+
done++;
|
|
1958
|
+
announce({ state: 'progress', file: path.basename(local) });
|
|
1959
|
+
}
|
|
1960
|
+
});
|
|
1961
|
+
announce({ state: 'done' });
|
|
1962
|
+
logger.info('Transfer finished', { server: name, direction, count: items.length });
|
|
1963
|
+
} catch (error) {
|
|
1964
|
+
announce({ state: 'failed', error: error.message });
|
|
1965
|
+
logger.warn('Transfer failed', { server: name, direction, error: error.message });
|
|
1966
|
+
}
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
|
|
1970
|
+
/**
|
|
1971
|
+
* List a directory on this machine.
|
|
1972
|
+
*
|
|
1973
|
+
* No path restriction, deliberately and for the same reason as the terminal:
|
|
1974
|
+
* whoever holds this token already has a shell here. A sandbox that a shell
|
|
1975
|
+
* sits next to is decoration.
|
|
1976
|
+
*
|
|
1977
|
+
* @param {URLSearchParams} params - Query
|
|
1978
|
+
* @param {import('http').ServerResponse} res - Response
|
|
1979
|
+
*/
|
|
1980
|
+
#listLocal(params, res) {
|
|
1981
|
+
const dir = params.get('path') || os.homedir();
|
|
1982
|
+
try {
|
|
1983
|
+
const resolved = path.resolve(dir);
|
|
1984
|
+
const entries = fs.readdirSync(resolved, { withFileTypes: true }).map(entry => {
|
|
1985
|
+
const full = path.join(resolved, entry.name);
|
|
1986
|
+
let stat;
|
|
1987
|
+
try {
|
|
1988
|
+
// lstat, not stat: a symlink must report as one rather than as
|
|
1989
|
+
// whatever it points at, and a broken link must not throw.
|
|
1990
|
+
stat = fs.lstatSync(full);
|
|
1991
|
+
} catch {
|
|
1992
|
+
stat = null;
|
|
1993
|
+
}
|
|
1994
|
+
return {
|
|
1995
|
+
name: entry.name,
|
|
1996
|
+
path: full,
|
|
1997
|
+
size: stat?.size ?? 0,
|
|
1998
|
+
isDirectory: entry.isDirectory(),
|
|
1999
|
+
isSymlink: entry.isSymbolicLink(),
|
|
2000
|
+
modifyTime: stat?.mtimeMs ?? 0,
|
|
2001
|
+
accessTime: stat?.atimeMs ?? 0,
|
|
2002
|
+
permissions: stat ? stat.mode & 0o7777 : 0,
|
|
2003
|
+
owner: stat?.uid ?? 0,
|
|
2004
|
+
group: stat?.gid ?? 0,
|
|
2005
|
+
};
|
|
2006
|
+
});
|
|
2007
|
+
return this.#json(res, 200, { path: resolved, entries, home: os.homedir(), separator: path.sep });
|
|
2008
|
+
} catch (error) {
|
|
2009
|
+
return this.#json(res, error.code === 'ENOENT' ? 404 : 403, { error: error.message });
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
/**
|
|
2014
|
+
* Stream a local file out, so the remote pane can upload it without the
|
|
2015
|
+
* browser ever holding the bytes.
|
|
2016
|
+
*
|
|
2017
|
+
* @param {URLSearchParams} params - Query
|
|
2018
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2019
|
+
*/
|
|
2020
|
+
#readLocal(params, res) {
|
|
2021
|
+
const file = params.get('path') || '';
|
|
2022
|
+
try {
|
|
2023
|
+
const resolved = path.resolve(file);
|
|
2024
|
+
const stream = fs.createReadStream(resolved);
|
|
2025
|
+
res.writeHead(200, {
|
|
2026
|
+
'content-type': 'application/octet-stream',
|
|
2027
|
+
'content-disposition': `attachment; filename="${path.basename(resolved).replace(/["\r\n]/g, '_')}"`,
|
|
2028
|
+
});
|
|
2029
|
+
stream.on('error', () => res.end());
|
|
2030
|
+
stream.pipe(res);
|
|
2031
|
+
} catch (error) {
|
|
2032
|
+
return this.#json(res, 404, { error: error.message });
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
/**
|
|
2037
|
+
* mkdir / rename / delete / reveal on this machine.
|
|
2038
|
+
*
|
|
2039
|
+
* @param {'mkdir'|'touch'|'rename'|'delete'|'reveal'} kind - Which operation
|
|
2040
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
2041
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2042
|
+
*/
|
|
2043
|
+
#localOp(kind, req, res) {
|
|
2044
|
+
this.#readJsonBody(req, res, payload => {
|
|
2045
|
+
try {
|
|
2046
|
+
if (kind === 'mkdir') fs.mkdirSync(path.resolve(String(payload.path)), { recursive: true });
|
|
2047
|
+
else if (kind === 'touch') {
|
|
2048
|
+
// 'wx' fails when the file exists rather than truncating it: "New
|
|
2049
|
+
// file" must never be a way to silently empty one.
|
|
2050
|
+
fs.closeSync(fs.openSync(path.resolve(String(payload.path)), 'wx'));
|
|
2051
|
+
}
|
|
2052
|
+
else if (kind === 'rename') fs.renameSync(path.resolve(String(payload.from)), path.resolve(String(payload.to)));
|
|
2053
|
+
else if (kind === 'delete') fs.rmSync(path.resolve(String(payload.path)), { recursive: Boolean(payload.isDirectory), force: false });
|
|
2054
|
+
else if (kind === 'reveal') {
|
|
2055
|
+
// execFile, never a shell: a path is not ours to trust even when it
|
|
2056
|
+
// came from our own listing, and this one round-trips through a
|
|
2057
|
+
// browser on the way.
|
|
2058
|
+
const opener = process.platform === 'darwin' ? 'open'
|
|
2059
|
+
: process.platform === 'win32' ? 'explorer' : 'xdg-open';
|
|
2060
|
+
execFile(opener, [path.resolve(String(payload.path))], () => { /* best effort */ });
|
|
2061
|
+
}
|
|
2062
|
+
logger.info(`Local ${kind}`, { path: payload.path ?? payload.to });
|
|
2063
|
+
return this.#json(res, 200, { ok: true });
|
|
2064
|
+
} catch (error) {
|
|
2065
|
+
return this.#json(res, 400, { error: error.message });
|
|
2066
|
+
}
|
|
2067
|
+
});
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
/**
|
|
2071
|
+
* Run one command on a server and hand back what it printed.
|
|
2072
|
+
*
|
|
2073
|
+
* Same reasoning as the terminal and the file routes: this is the operator's
|
|
2074
|
+
* own hands, not an agent's, so the readonly/restricted modes do not apply.
|
|
2075
|
+
* It exists because a file browser needs `chmod` and `chown`, and because
|
|
2076
|
+
* "run this on that machine" is the shortest path between a screen and an
|
|
2077
|
+
* answer.
|
|
2078
|
+
*
|
|
2079
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
2080
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2081
|
+
*/
|
|
2082
|
+
#execute(req, res) {
|
|
2083
|
+
this.#readJsonBody(req, res, async payload => {
|
|
2084
|
+
const name = String(payload.server || '').toLowerCase();
|
|
2085
|
+
const command = String(payload.command || '');
|
|
2086
|
+
if (!command.trim()) return this.#json(res, 400, { error: 'A command is required' });
|
|
2087
|
+
|
|
2088
|
+
/** @type {Record<string, any>} */
|
|
2089
|
+
let servers = {};
|
|
2090
|
+
try {
|
|
2091
|
+
servers = this.store.getAllDecrypted();
|
|
2092
|
+
} catch (error) {
|
|
2093
|
+
return this.#json(res, 500, { error: `Cannot read the vault: ${error.message}` });
|
|
2094
|
+
}
|
|
2095
|
+
if (!servers[name]) return this.#json(res, 404, { error: 'No such server in the vault' });
|
|
2096
|
+
|
|
2097
|
+
let ssh;
|
|
2098
|
+
try {
|
|
2099
|
+
ssh = await connectServer(name, servers, { readyTimeout: 15000, actor: 'human' });
|
|
2100
|
+
const result = await ssh.execCommand(command, { timeout: 60000 });
|
|
2101
|
+
logger.info('Command run from the control plane', { server: name });
|
|
2102
|
+
return this.#json(res, 200, { stdout: result.stdout, stderr: result.stderr, code: result.code });
|
|
2103
|
+
} catch (error) {
|
|
2104
|
+
return this.#json(res, 502, { error: error.message });
|
|
2105
|
+
} finally {
|
|
2106
|
+
try { ssh?.dispose(); } catch { /* best effort */ }
|
|
2107
|
+
}
|
|
2108
|
+
});
|
|
2109
|
+
}
|
|
2110
|
+
|
|
2111
|
+
/**
|
|
2112
|
+
* Borrow a live SFTP session for a server, opening one if needed.
|
|
2113
|
+
*
|
|
2114
|
+
* The idle timer restarts on every use, so an operator browsing a tree keeps
|
|
2115
|
+
* one connection and someone who wandered off keeps none.
|
|
2116
|
+
*
|
|
2117
|
+
* @param {string} name - Server name, already lowercased
|
|
2118
|
+
* @returns {Promise<any>} an ssh2 SFTP session
|
|
2119
|
+
*/
|
|
2120
|
+
async #sftp(name) {
|
|
2121
|
+
const revision = this.#vaultRevision();
|
|
2122
|
+
const existing = this.sftpPool.get(name);
|
|
2123
|
+
if (existing && existing.revision === revision) {
|
|
2124
|
+
if (existing.timer) clearTimeout(existing.timer);
|
|
2125
|
+
existing.timer = setTimeout(() => this.#releaseSftp(name), SFTP_IDLE_MS);
|
|
2126
|
+
return existing.sftp;
|
|
2127
|
+
}
|
|
2128
|
+
if (existing) this.#releaseSftp(name);
|
|
2129
|
+
|
|
2130
|
+
/** @type {Record<string, any>} */
|
|
2131
|
+
const servers = this.store.getAllDecrypted();
|
|
2132
|
+
if (!servers[name]) throw Object.assign(new Error('No such server in the vault'), { status: 404 });
|
|
2133
|
+
|
|
2134
|
+
const ssh = await connectServer(name, servers, { readyTimeout: 15000, actor: 'human' });
|
|
2135
|
+
let sftp;
|
|
2136
|
+
try { sftp = await ssh.getSFTP(); } catch (error) { ssh.dispose(); throw error; }
|
|
2137
|
+
const entry = { ssh, sftp, revision, timer: setTimeout(() => this.#releaseSftp(name), SFTP_IDLE_MS) };
|
|
2138
|
+
this.sftpPool.set(name, entry);
|
|
2139
|
+
logger.info('SFTP session opened', { server: name });
|
|
2140
|
+
return sftp;
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
/** @param {string} name - Server name */
|
|
2144
|
+
#releaseSftp(name) {
|
|
2145
|
+
const entry = this.sftpPool.get(name);
|
|
2146
|
+
if (!entry) return;
|
|
2147
|
+
this.sftpPool.delete(name);
|
|
2148
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
2149
|
+
try { entry.ssh.dispose(); } catch { /* best effort */ }
|
|
2150
|
+
logger.info('SFTP session released', { server: name });
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
/**
|
|
2154
|
+
* Turn an SFTP callback into a promise, and a dropped connection into a
|
|
2155
|
+
* retry. A pooled session can die between two requests — the machine
|
|
2156
|
+
* rebooted, the network moved — and the operator should not have to know
|
|
2157
|
+
* that; they clicked a folder.
|
|
2158
|
+
*
|
|
2159
|
+
* @param {string} name - Server name
|
|
2160
|
+
* @param {(sftp: any) => Promise<any>} run - What to do with the session
|
|
2161
|
+
*/
|
|
2162
|
+
async #withSftp(name, run) {
|
|
2163
|
+
try {
|
|
2164
|
+
return await withTimeout(run(await this.#sftp(name)));
|
|
2165
|
+
} catch (error) {
|
|
2166
|
+
if (/** @type {any} */ (error).status === 404) throw error;
|
|
2167
|
+
this.#releaseSftp(name);
|
|
2168
|
+
return withTimeout(run(await this.#sftp(name)));
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
/**
|
|
2173
|
+
* List a directory. Returns the shape a file browser wants — one stat per
|
|
2174
|
+
* entry, already merged — because a browser that has to stat every row makes
|
|
2175
|
+
* one round trip per file.
|
|
2176
|
+
*
|
|
2177
|
+
* @param {URLSearchParams} params - Query
|
|
2178
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2179
|
+
*/
|
|
2180
|
+
async #listFiles(params, res) {
|
|
2181
|
+
const name = String(params.get('server') || '').toLowerCase();
|
|
2182
|
+
const requested = params.get('path') || '.';
|
|
2183
|
+
try {
|
|
2184
|
+
const result = await this.#withSftp(name, async sftp => {
|
|
2185
|
+
// '.' means the home directory, and the browser needs its real name:
|
|
2186
|
+
// without resolving it the breadcrumb has nothing to show, and every
|
|
2187
|
+
// path built from there is relative to a directory it cannot name.
|
|
2188
|
+
const dir = requested === '.' ? await realpath(sftp, '.') : requested;
|
|
2189
|
+
const list = await readdir(sftp, dir);
|
|
2190
|
+
return { dir, entries: list.map(item => describe(dir, item)) };
|
|
2191
|
+
});
|
|
2192
|
+
return this.#json(res, 200, { path: result.dir, entries: result.entries });
|
|
2193
|
+
} catch (error) {
|
|
2194
|
+
return this.#json(res, /** @type {any} */ (error).status || 502, { error: error.message });
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
/**
|
|
2199
|
+
* Stream a file down. Streamed rather than buffered: a control plane that
|
|
2200
|
+
* reads a 4 GB log into memory to hand it over is a control plane that dies.
|
|
2201
|
+
*
|
|
2202
|
+
* @param {URLSearchParams} params - Query
|
|
2203
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2204
|
+
*/
|
|
2205
|
+
async #readFile(params, res) {
|
|
2206
|
+
const name = String(params.get('server') || '').toLowerCase();
|
|
2207
|
+
const file = params.get('path') || '';
|
|
2208
|
+
try {
|
|
2209
|
+
const sftp = await this.#sftp(name);
|
|
2210
|
+
const stream = sftp.createReadStream(file);
|
|
2211
|
+
res.writeHead(200, {
|
|
2212
|
+
'content-type': 'application/octet-stream',
|
|
2213
|
+
// A filename is remote input, and this header is parsed by the browser.
|
|
2214
|
+
// The quoted form gets an ASCII stand-in — no quote or backslash to end
|
|
2215
|
+
// or escape the string, no control character, nothing Node refuses to
|
|
2216
|
+
// put in a header (an emoji in a name threw ERR_INVALID_CHAR here) —
|
|
2217
|
+
// and filename* carries the real name, UTF-8 and percent-encoded, which
|
|
2218
|
+
// every current browser prefers (RFC 6266).
|
|
2219
|
+
'content-disposition': contentDisposition(String(file.split('/').pop())),
|
|
2220
|
+
});
|
|
2221
|
+
stream.on('error', (/** @type {Error} */ error) => {
|
|
2222
|
+
logger.warn('File read failed', { server: name, error: error.message });
|
|
2223
|
+
res.end();
|
|
2224
|
+
});
|
|
2225
|
+
stream.pipe(res);
|
|
2226
|
+
} catch (error) {
|
|
2227
|
+
return this.#json(res, /** @type {any} */ (error).status || 502, { error: error.message });
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
|
|
2231
|
+
/**
|
|
2232
|
+
* Stream a file up.
|
|
2233
|
+
* @param {URLSearchParams} params - Query
|
|
2234
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
2235
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2236
|
+
*/
|
|
2237
|
+
async #writeFile(params, req, res) {
|
|
2238
|
+
const name = String(params.get('server') || '').toLowerCase();
|
|
2239
|
+
const file = params.get('path') || '';
|
|
2240
|
+
try {
|
|
2241
|
+
const sftp = await this.#sftp(name);
|
|
2242
|
+
await new Promise((resolve, reject) => {
|
|
2243
|
+
const stream = sftp.createWriteStream(file);
|
|
2244
|
+
stream.on('close', resolve);
|
|
2245
|
+
stream.on('error', reject);
|
|
2246
|
+
req.on('error', reject);
|
|
2247
|
+
req.pipe(stream);
|
|
2248
|
+
});
|
|
2249
|
+
logger.info('File written', { server: name, path: file });
|
|
2250
|
+
return this.#json(res, 200, { ok: true });
|
|
2251
|
+
} catch (error) {
|
|
2252
|
+
return this.#json(res, /** @type {any} */ (error).status || 502, { error: error.message });
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
/**
|
|
2257
|
+
* mkdir / rename / delete. One handler because they differ only in the call.
|
|
2258
|
+
*
|
|
2259
|
+
* @param {'mkdir'|'rename'|'delete'} kind - Which operation
|
|
2260
|
+
* @param {import('http').IncomingMessage} req - Request
|
|
2261
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2262
|
+
*/
|
|
2263
|
+
#fileOp(kind, req, res) {
|
|
2264
|
+
this.#readJsonBody(req, res, async payload => {
|
|
2265
|
+
const name = String(payload.server || '').toLowerCase();
|
|
2266
|
+
try {
|
|
2267
|
+
await this.#withSftp(name, sftp => new Promise((resolve, reject) => {
|
|
2268
|
+
const done = (/** @type {Error|null} */ error) => (error ? reject(error) : resolve(true));
|
|
2269
|
+
if (kind === 'mkdir') return sftp.mkdir(String(payload.path), done);
|
|
2270
|
+
if (kind === 'rename') return sftp.rename(String(payload.from), String(payload.to), done);
|
|
2271
|
+
// rmdir and unlink are different calls, and the caller knows which it
|
|
2272
|
+
// clicked on — asking SFTP to guess would mean a stat per delete.
|
|
2273
|
+
return payload.isDirectory
|
|
2274
|
+
? sftp.rmdir(String(payload.path), done)
|
|
2275
|
+
: sftp.unlink(String(payload.path), done);
|
|
2276
|
+
}));
|
|
2277
|
+
logger.info(`File ${kind}`, { server: name });
|
|
2278
|
+
return this.#json(res, 200, { ok: true });
|
|
2279
|
+
} catch (error) {
|
|
2280
|
+
return this.#json(res, /** @type {any} */ (error).status || 502, { error: error.message });
|
|
2281
|
+
}
|
|
2282
|
+
});
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
/**
|
|
2286
|
+
* Groups and known host keys — the two pieces of state that live in files and
|
|
2287
|
+
* are therefore readable from here.
|
|
2288
|
+
*
|
|
2289
|
+
* Tunnels are deliberately absent: tunnel-manager keeps them in a Map inside
|
|
2290
|
+
* the MCP server's process, so this process cannot see them. Showing an empty
|
|
2291
|
+
* or stale tunnel list would be worse than showing none.
|
|
2292
|
+
*
|
|
2293
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2294
|
+
*/
|
|
2295
|
+
#serveOptions(res) {
|
|
2296
|
+
/** @type {any[]} */
|
|
2297
|
+
let groups = [];
|
|
2298
|
+
try {
|
|
2299
|
+
groups = listGroups();
|
|
2300
|
+
} catch (error) {
|
|
2301
|
+
logger.warn('Cannot list groups', { error: error.message });
|
|
2302
|
+
}
|
|
2303
|
+
|
|
2304
|
+
/** @type {any[]} */
|
|
2305
|
+
let hostKeys = [];
|
|
2306
|
+
try {
|
|
2307
|
+
hostKeys = listKnownHosts();
|
|
2308
|
+
} catch (error) {
|
|
2309
|
+
logger.warn('Cannot read known_hosts', { error: error.message });
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
// Tunnels are opened inside the MCP server's process; it publishes them to
|
|
2313
|
+
// a file so this one can show them. `stale` means the file was written by a
|
|
2314
|
+
// process that is no longer running — showing those as open would be a lie.
|
|
2315
|
+
const tunnelState = readPublishedTunnels();
|
|
2316
|
+
|
|
2317
|
+
this.#json(res, 200, {
|
|
2318
|
+
groups,
|
|
2319
|
+
hostKeys,
|
|
2320
|
+
tunnels: tunnelState.tunnels,
|
|
2321
|
+
tunnelsStale: tunnelState.stale,
|
|
2322
|
+
// Whether a shell on *this* machine can be opened at all. False for a
|
|
2323
|
+
// control plane served over the network, where it would be a stranger's
|
|
2324
|
+
// shell on somebody's laptop.
|
|
2325
|
+
localShell: Boolean(this.localShell),
|
|
2326
|
+
// Whether /api/desktop exists: true only under `ssh-manager control`.
|
|
2327
|
+
offerDesktop: Boolean(this.offerDesktop),
|
|
2328
|
+
});
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
/**
|
|
2332
|
+
* Can the desktop application be installed here, is it already, and where
|
|
2333
|
+
* is an installation that is running. Read by the page's banner.
|
|
2334
|
+
*
|
|
2335
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2336
|
+
*/
|
|
2337
|
+
/**
|
|
2338
|
+
* What each AI tool's ssh-manager entry runs, and the engines on offer.
|
|
2339
|
+
*
|
|
2340
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2341
|
+
*/
|
|
2342
|
+
async #serveAgents(res) {
|
|
2343
|
+
try {
|
|
2344
|
+
this.#json(res, 200, await agentsStatus(this.agentContext));
|
|
2345
|
+
} catch (error) {
|
|
2346
|
+
logger.warn('Cannot read the AI tools configuration', { error: error.message });
|
|
2347
|
+
this.#json(res, 500, { error: error.message });
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
/**
|
|
2352
|
+
* Point one tool at the npm engine or the application's. Only ever on a
|
|
2353
|
+
* request: nothing in a tool's configuration changes by itself.
|
|
2354
|
+
*
|
|
2355
|
+
* @param {{client?: unknown, engine?: unknown}} payload - `{client, engine: 'app'|'npm'}`
|
|
2356
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2357
|
+
*/
|
|
2358
|
+
async #useAgentEngine(payload, res) {
|
|
2359
|
+
const engine = payload?.engine;
|
|
2360
|
+
if (typeof payload?.client !== 'string' || (engine !== 'app' && engine !== 'npm')) {
|
|
2361
|
+
return this.#json(res, 400, { error: 'Expected { client, engine: "app" | "npm" }' });
|
|
2362
|
+
}
|
|
2363
|
+
try {
|
|
2364
|
+
const client = await useEngine(payload.client, engine, this.agentContext);
|
|
2365
|
+
this.#broadcast({ type: 'agents' });
|
|
2366
|
+
return this.#json(res, 200, { client });
|
|
2367
|
+
} catch (error) {
|
|
2368
|
+
return this.#json(res, error.status || 500, { error: error.message });
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
|
|
2372
|
+
/**
|
|
2373
|
+
* Check for an update, download the one on offer, or restart into it. Each is a
|
|
2374
|
+
* deliberate click: nothing here downloads or restarts by itself, because the
|
|
2375
|
+
* application holds SSH connections and the approval socket agents wait on.
|
|
2376
|
+
*
|
|
2377
|
+
* @param {'check'|'download'|'install'} action
|
|
2378
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2379
|
+
*/
|
|
2380
|
+
async #appUpdateAction(action, res) {
|
|
2381
|
+
const updates = /** @type {AppUpdates} */ (this.appUpdates);
|
|
2382
|
+
try {
|
|
2383
|
+
const { status } = updates.snapshot();
|
|
2384
|
+
if (action === 'download' && status !== 'available') {
|
|
2385
|
+
return this.#json(res, 409, { error: 'There is no update on offer to download', snapshot: updates.snapshot() });
|
|
2386
|
+
}
|
|
2387
|
+
if (action === 'install' && status !== 'ready') {
|
|
2388
|
+
return this.#json(res, 409, { error: 'No update has been downloaded yet', snapshot: updates.snapshot() });
|
|
2389
|
+
}
|
|
2390
|
+
if (action === 'install') {
|
|
2391
|
+
// Answer first: the application is about to quit, and the page should
|
|
2392
|
+
// be told before it loses its connection.
|
|
2393
|
+
this.#json(res, 200, { ok: true, restarting: true });
|
|
2394
|
+
setTimeout(() => updates.install(), 200);
|
|
2395
|
+
return;
|
|
2396
|
+
}
|
|
2397
|
+
await updates[action]();
|
|
2398
|
+
return this.#json(res, 200, updates.snapshot());
|
|
2399
|
+
} catch (error) {
|
|
2400
|
+
logger.warn('Application update action failed', { action, error: error.message });
|
|
2401
|
+
return this.#json(res, 500, { error: error.message, snapshot: updates.snapshot() });
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
|
|
2405
|
+
#serveDesktop(res) {
|
|
2406
|
+
let status;
|
|
2407
|
+
try {
|
|
2408
|
+
status = this.desktop.status();
|
|
2409
|
+
} catch (error) {
|
|
2410
|
+
logger.warn('Cannot read the desktop application status', { error: error.message });
|
|
2411
|
+
status = { supported: false, installed: false, path: null, version: null, method: null };
|
|
2412
|
+
}
|
|
2413
|
+
const { installing, handingOver, phase, received, total, error } = this.desktopState;
|
|
2414
|
+
this.#json(res, 200, {
|
|
2415
|
+
...status,
|
|
2416
|
+
engineVersion: engineVersion(),
|
|
2417
|
+
releases: RELEASES_PAGE,
|
|
2418
|
+
installing,
|
|
2419
|
+
handingOver,
|
|
2420
|
+
phase,
|
|
2421
|
+
received,
|
|
2422
|
+
total,
|
|
2423
|
+
error,
|
|
2424
|
+
});
|
|
2425
|
+
}
|
|
2426
|
+
|
|
2427
|
+
/**
|
|
2428
|
+
* Install the desktop application, then hand over to it. Answers 202 at
|
|
2429
|
+
* once; progress goes out on the event stream as `{type: 'desktop', …}`.
|
|
2430
|
+
* One at a time: a second click while it runs is a 409.
|
|
2431
|
+
*
|
|
2432
|
+
* @param {import('http').IncomingMessage} req - Request (its body is ignored)
|
|
2433
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2434
|
+
*/
|
|
2435
|
+
#installDesktopApp(req, res) {
|
|
2436
|
+
req.resume();
|
|
2437
|
+
if (this.desktopState.installing || this.desktopState.handingOver) {
|
|
2438
|
+
return this.#json(res, 409, { error: this.desktopState.installing
|
|
2439
|
+
? 'The desktop app is already being installed'
|
|
2440
|
+
: 'Already handing over to the desktop app' });
|
|
2441
|
+
}
|
|
2442
|
+
const status = this.desktop.status();
|
|
2443
|
+
if (!status.installed && !status.supported) {
|
|
2444
|
+
return this.#json(res, 400, { error: 'There is no desktop build for this platform', releases: RELEASES_PAGE });
|
|
2445
|
+
}
|
|
2446
|
+
// A .deb needs sudo, and a click cannot type a password. The page shows
|
|
2447
|
+
// the command instead; this is for a page that asked anyway.
|
|
2448
|
+
if (!status.installed && status.method === 'terminal') {
|
|
2449
|
+
return this.#json(res, 400, {
|
|
2450
|
+
error: 'Installing the desktop app here asks for your password: run `ssh-manager app` in a terminal',
|
|
2451
|
+
method: 'terminal',
|
|
2452
|
+
command: 'ssh-manager app',
|
|
2453
|
+
});
|
|
2454
|
+
}
|
|
2455
|
+
this.desktopState = { installing: true, handingOver: false, phase: null, received: 0, total: 0, error: null };
|
|
2456
|
+
this.#json(res, 202, { ok: true });
|
|
2457
|
+
this.#runDesktopInstall();
|
|
2458
|
+
}
|
|
2459
|
+
|
|
2460
|
+
/** The install itself, after the 202. Failures end up on the event stream. */
|
|
2461
|
+
async #runDesktopInstall() {
|
|
2462
|
+
try {
|
|
2463
|
+
const installed = await this.desktop.install({ onProgress: progress => this.#desktopEvent(progress) });
|
|
2464
|
+
this.desktopState.installing = false;
|
|
2465
|
+
await this.#handOver(installed.path);
|
|
2466
|
+
} catch (error) {
|
|
2467
|
+
logger.warn('The desktop application was not installed', { error: error.message });
|
|
2468
|
+
this.desktopState.installing = false;
|
|
2469
|
+
this.desktopState.handingOver = false;
|
|
2470
|
+
this.#desktopEvent({ phase: 'error', error: error.message });
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
|
|
2474
|
+
/**
|
|
2475
|
+
* Open the installed desktop application, then hand over to it.
|
|
2476
|
+
*
|
|
2477
|
+
* @param {import('http').IncomingMessage} req - Request (its body is ignored)
|
|
2478
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2479
|
+
*/
|
|
2480
|
+
async #openDesktopApp(req, res) {
|
|
2481
|
+
req.resume();
|
|
2482
|
+
// Already on its way — an install that finished hands over by itself, and
|
|
2483
|
+
// a page that asks to open the app as well is asking for what is happening.
|
|
2484
|
+
if (this.desktopState.handingOver) {
|
|
2485
|
+
return this.#json(res, 200, { ok: true, stopsInMs: Math.max(0, this.#handoverDeadline - Date.now()) });
|
|
2486
|
+
}
|
|
2487
|
+
if (this.desktopState.installing) {
|
|
2488
|
+
return this.#json(res, 409, { error: 'The desktop app is still being installed' });
|
|
2489
|
+
}
|
|
2490
|
+
const status = this.desktop.status();
|
|
2491
|
+
if (!status.installed) return this.#json(res, 409, { error: 'The desktop app is not installed' });
|
|
2492
|
+
try {
|
|
2493
|
+
await this.#handOver(status.path);
|
|
2494
|
+
} catch (error) {
|
|
2495
|
+
this.desktopState.handingOver = false;
|
|
2496
|
+
this.#desktopEvent({ phase: 'error', error: error.message });
|
|
2497
|
+
return this.#json(res, 500, { error: `Could not open the desktop app: ${error.message}` });
|
|
2498
|
+
}
|
|
2499
|
+
return this.#json(res, 200, { ok: true, stopsInMs: this.handoverMs });
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2502
|
+
/**
|
|
2503
|
+
* Leave the stage to the desktop application.
|
|
2504
|
+
*
|
|
2505
|
+
* The application binds the same approval socket when it starts. Left
|
|
2506
|
+
* running, this plane would keep a page nobody needs and, on Windows, the
|
|
2507
|
+
* very pipe the application needs. So it tells the page it continues in the
|
|
2508
|
+
* application, waits a few seconds for that to be read, and stops.
|
|
2509
|
+
*
|
|
2510
|
+
* The order depends on the platform. A Windows named pipe cannot be bound
|
|
2511
|
+
* twice, so there this plane stops first and opens the application after.
|
|
2512
|
+
* Elsewhere the application opens first, so a failure to open is reported
|
|
2513
|
+
* while the page can still show it; the application then replaces the
|
|
2514
|
+
* socket files, and stop() leaves alone files that are no longer its own.
|
|
2515
|
+
*
|
|
2516
|
+
* @param {string} appPath - The installed application
|
|
2517
|
+
*/
|
|
2518
|
+
async #handOver(appPath) {
|
|
2519
|
+
this.desktopState.handingOver = true;
|
|
2520
|
+
const opensFirst = this.desktop.platform !== 'win32';
|
|
2521
|
+
const launch = async () => {
|
|
2522
|
+
// macOS brings a running application forward; elsewhere a second launch
|
|
2523
|
+
// would start a second copy competing for the socket.
|
|
2524
|
+
if (this.desktop.platform !== 'darwin' && await this.desktop.running()) return;
|
|
2525
|
+
await this.desktop.open({ path: appPath });
|
|
2526
|
+
};
|
|
2527
|
+
this.#desktopEvent({ phase: 'open' });
|
|
2528
|
+
if (opensFirst) await launch();
|
|
2529
|
+
this.#handoverDeadline = Date.now() + this.handoverMs;
|
|
2530
|
+
this.#desktopEvent({
|
|
2531
|
+
phase: 'handover',
|
|
2532
|
+
stopsInMs: this.handoverMs,
|
|
2533
|
+
message: 'Continued in the desktop app — you can close this tab',
|
|
2534
|
+
});
|
|
2535
|
+
setTimeout(async () => {
|
|
2536
|
+
try {
|
|
2537
|
+
await this.stop();
|
|
2538
|
+
if (!opensFirst) await launch();
|
|
2539
|
+
} catch (error) {
|
|
2540
|
+
logger.error('Handing over to the desktop application failed', { error: error.message });
|
|
2541
|
+
}
|
|
2542
|
+
this.onHandover?.();
|
|
2543
|
+
}, this.handoverMs);
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2546
|
+
/**
|
|
2547
|
+
* Note where the desktop installation is and tell every open page. Every
|
|
2548
|
+
* event carries the byte counts, so a page that joins late can draw the bar.
|
|
2549
|
+
*
|
|
2550
|
+
* @param {{phase: string} & Record<string, any>} update - From installDesktop or the hand-over
|
|
2551
|
+
*/
|
|
2552
|
+
#desktopEvent(update) {
|
|
2553
|
+
const state = this.desktopState;
|
|
2554
|
+
state.phase = update.phase;
|
|
2555
|
+
if (typeof update.received === 'number') state.received = update.received;
|
|
2556
|
+
if (typeof update.total === 'number') state.total = update.total;
|
|
2557
|
+
state.error = update.phase === 'error' ? update.error : null;
|
|
2558
|
+
this.#broadcast({ ...update, type: 'desktop', received: state.received, total: state.total });
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
/**
|
|
2562
|
+
* Forget a host key.
|
|
2563
|
+
*
|
|
2564
|
+
* The reason this belongs in a control plane: when a server is rebuilt its
|
|
2565
|
+
* host key changes, every connection then fails with a warning, and the fix
|
|
2566
|
+
* is to remove the stale entry. Doing that by hand means editing
|
|
2567
|
+
* ~/.ssh/known_hosts with a line number from an error message.
|
|
2568
|
+
*
|
|
2569
|
+
* @param {string|null} host - Host to forget
|
|
2570
|
+
* @param {string|null} port - Port, defaults to 22
|
|
2571
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2572
|
+
*/
|
|
2573
|
+
#forgetHostKey(host, port, res) {
|
|
2574
|
+
if (!host) return this.#json(res, 400, { error: 'No host named' });
|
|
2575
|
+
try {
|
|
2576
|
+
const removed = removeHostKey(host, Number(port) || 22);
|
|
2577
|
+
if (!removed) return this.#json(res, 404, { error: 'No such host key' });
|
|
2578
|
+
logger.info('Host key forgotten from the control plane', { host, port });
|
|
2579
|
+
this.#broadcast({ type: 'options' });
|
|
2580
|
+
return this.#json(res, 200, { ok: true });
|
|
2581
|
+
} catch (error) {
|
|
2582
|
+
return this.#json(res, 500, { error: error.message });
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
|
|
2586
|
+
/**
|
|
2587
|
+
* Probe one server's health, or every server when no name is given.
|
|
2588
|
+
*
|
|
2589
|
+
* The control plane opens its own SSH connection for this: it holds the
|
|
2590
|
+
* vault, so it has the credentials, and the MCP server is driven by an agent
|
|
2591
|
+
* rather than by us. Connections are opened per probe and closed straight
|
|
2592
|
+
* after — a dashboard that quietly holds a connection open to every machine
|
|
2593
|
+
* is a dashboard nobody should run.
|
|
2594
|
+
*
|
|
2595
|
+
* Only ever on request. Nothing is polled in the background: each probe costs
|
|
2596
|
+
* an SSH handshake, and a control plane that connects to every production box
|
|
2597
|
+
* on a timer would be worse than no dashboard at all.
|
|
2598
|
+
*
|
|
2599
|
+
* @param {string|null} name - Server to probe, or null for all
|
|
2600
|
+
* @param {import('http').ServerResponse} res - Response
|
|
2601
|
+
*/
|
|
2602
|
+
async #probeHealth(name, res) {
|
|
2603
|
+
/** @type {Record<string, any>} */
|
|
2604
|
+
let servers = {};
|
|
2605
|
+
try {
|
|
2606
|
+
servers = this.store.getAllDecrypted();
|
|
2607
|
+
} catch (error) {
|
|
2608
|
+
return this.#json(res, 500, { error: `Cannot read the vault: ${error.message}` });
|
|
2609
|
+
}
|
|
2610
|
+
|
|
2611
|
+
const targets = name ? [name.toLowerCase()].filter(n => servers[n]) : Object.keys(servers);
|
|
2612
|
+
if (targets.length === 0) {
|
|
2613
|
+
return this.#json(res, 200, { results: [] });
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
const thresholds = this.#readThresholds();
|
|
2617
|
+
|
|
2618
|
+
// In parallel: one slow or unreachable machine must not delay the others.
|
|
2619
|
+
const results = await Promise.all(targets.map(async serverName => {
|
|
2620
|
+
const config = { ...servers[serverName], name: serverName };
|
|
2621
|
+
const started = Date.now();
|
|
2622
|
+
let ssh;
|
|
2623
|
+
try {
|
|
2624
|
+
// Short, because this is a dashboard: a machine that has not answered
|
|
2625
|
+
// in eight seconds is "unreachable" as far as the screen is concerned,
|
|
2626
|
+
// and the operator would rather see that than watch a spinner.
|
|
2627
|
+
ssh = await connectServer(serverName, servers, { readyTimeout: 8000, actor: 'human' });
|
|
2628
|
+
const result = await ssh.execCommand(buildComprehensiveHealthCheckCommand(), { timeout: 20000 });
|
|
2629
|
+
const health = parseComprehensiveHealthCheck(result.stdout);
|
|
2630
|
+
// Crossings are computed here rather than in the page: the same answer
|
|
2631
|
+
// has to serve a notification, and a threshold evaluated in a browser
|
|
2632
|
+
// cannot raise one when nobody is looking at the browser.
|
|
2633
|
+
const alerts = thresholds.enabled ? checkAlertThresholds(health, thresholds) : [];
|
|
2634
|
+
return {
|
|
2635
|
+
server: serverName, host: config.host, reachable: true,
|
|
2636
|
+
tookMs: Date.now() - started, alerts, ...health,
|
|
2637
|
+
};
|
|
2638
|
+
} catch (error) {
|
|
2639
|
+
// Unreachable is a legitimate answer, not an error: it is exactly what
|
|
2640
|
+
// the operator wants to see on the screen.
|
|
2641
|
+
return {
|
|
2642
|
+
server: serverName,
|
|
2643
|
+
host: config.host,
|
|
2644
|
+
reachable: false,
|
|
2645
|
+
tookMs: Date.now() - started,
|
|
2646
|
+
error: error.message,
|
|
2647
|
+
};
|
|
2648
|
+
} finally {
|
|
2649
|
+
try { ssh?.dispose(); } catch { /* best effort */ }
|
|
2650
|
+
}
|
|
2651
|
+
}));
|
|
2652
|
+
|
|
2653
|
+
this.#broadcast({ type: 'health', results });
|
|
2654
|
+
return this.#json(res, 200, { results });
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
/**
|
|
2658
|
+
* Follow the audit logs so the timeline shows what happened without approval
|
|
2659
|
+
* too — the engine writes them whether or not anyone is watching.
|
|
2660
|
+
*/
|
|
2661
|
+
#startAuditTail() {
|
|
2662
|
+
if (this.auditPaths.length === 0) return;
|
|
2663
|
+
|
|
2664
|
+
const readNew = () => {
|
|
2665
|
+
for (const auditPath of this.auditPaths) {
|
|
2666
|
+
let fd = null;
|
|
2667
|
+
try {
|
|
2668
|
+
// Open first and size the open file, rather than stat a path and then
|
|
2669
|
+
// open whatever is at it: a rotation between the two read the new
|
|
2670
|
+
// file at the old file's offset (CodeQL js/file-system-race).
|
|
2671
|
+
fd = fs.openSync(auditPath, 'r');
|
|
2672
|
+
const { size } = fs.fstatSync(fd);
|
|
2673
|
+
// First sight of this file: start at its end, so opening the control
|
|
2674
|
+
// plane does not replay months of history. Record the offset even when
|
|
2675
|
+
// there is nothing to read — otherwise an empty log is treated as
|
|
2676
|
+
// "unseen" forever and every later line is skipped as history.
|
|
2677
|
+
if (!this.auditOffsets.has(auditPath)) {
|
|
2678
|
+
this.auditOffsets.set(auditPath, size);
|
|
2679
|
+
continue;
|
|
2680
|
+
}
|
|
2681
|
+
const from = /** @type {number} */ (this.auditOffsets.get(auditPath));
|
|
2682
|
+
if (size <= from) {
|
|
2683
|
+
// Truncated or rotated: start over rather than reading garbage.
|
|
2684
|
+
if (size < from) this.auditOffsets.set(auditPath, 0);
|
|
2685
|
+
continue;
|
|
2686
|
+
}
|
|
2687
|
+
const buffer = Buffer.alloc(size - from);
|
|
2688
|
+
// Only what was actually read: a short read left zero bytes on the
|
|
2689
|
+
// end of the buffer, which then reached JSON.parse as a line.
|
|
2690
|
+
const read = fs.readSync(fd, buffer, 0, buffer.length, from);
|
|
2691
|
+
// And only up to the last complete line. The offset used to move past
|
|
2692
|
+
// a line the engine was still writing, so its first half failed to
|
|
2693
|
+
// parse now and its second half later — the entry was lost, whatever
|
|
2694
|
+
// the comment below had promised.
|
|
2695
|
+
const complete = buffer.subarray(0, read).lastIndexOf(0x0a) + 1;
|
|
2696
|
+
this.auditOffsets.set(auditPath, from + complete);
|
|
2697
|
+
|
|
2698
|
+
for (const line of buffer.subarray(0, complete).toString('utf8').split('\n')) {
|
|
2699
|
+
if (!line.trim()) continue;
|
|
2700
|
+
try {
|
|
2701
|
+
this.#record({ ...JSON.parse(line), source: 'audit' });
|
|
2702
|
+
} catch { /* a malformed line is skipped, not retried */ }
|
|
2703
|
+
}
|
|
2704
|
+
} catch { /* file not created yet */ }
|
|
2705
|
+
finally {
|
|
2706
|
+
if (fd !== null) fs.closeSync(fd);
|
|
2707
|
+
}
|
|
2708
|
+
}
|
|
2709
|
+
};
|
|
2710
|
+
|
|
2711
|
+
readNew();
|
|
2712
|
+
this.auditTimer = setInterval(readNew, 1000);
|
|
2713
|
+
this.auditTimer.unref?.();
|
|
2714
|
+
}
|
|
2715
|
+
|
|
2716
|
+
/** @param {Object} entry - Timeline entry */
|
|
2717
|
+
#record(entry) {
|
|
2718
|
+
this.timeline.push(entry);
|
|
2719
|
+
if (this.timeline.length > TIMELINE_LIMIT) this.timeline.shift();
|
|
2720
|
+
this.#broadcast({ type: 'timeline', entry });
|
|
2721
|
+
}
|
|
2722
|
+
|
|
2723
|
+
/** @param {Object} event - Event to push to every open page */
|
|
2724
|
+
#broadcast(event) {
|
|
2725
|
+
const payload = `data: ${JSON.stringify(event)}\n\n`;
|
|
2726
|
+
for (const response of this.subscribers) {
|
|
2727
|
+
try { response.write(payload); } catch { this.subscribers.delete(response); }
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
}
|