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
package/src/approval.js
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
// Human-in-the-loop approval — the v4 control plane hook.
|
|
2
|
+
//
|
|
3
|
+
// The engine can pause an action and ask a person before touching a machine.
|
|
4
|
+
// That is the one thing a command line cannot offer well and the whole reason
|
|
5
|
+
// the control plane exists: `readonly` mode is a blunt yes/no decided in
|
|
6
|
+
// advance, while approval is a decision taken with the actual command in view.
|
|
7
|
+
//
|
|
8
|
+
// How it stays out of the way:
|
|
9
|
+
//
|
|
10
|
+
// * **Off unless asked for.** No `approval` setting on a server, no socket
|
|
11
|
+
// listening → this module is never consulted and nothing changes.
|
|
12
|
+
// * **It cannot wedge an agent.** Every wait has a deadline, and what happens
|
|
13
|
+
// at the deadline is configurable. A crashed control plane must fail one
|
|
14
|
+
// action, not hang the session forever.
|
|
15
|
+
// * **Secrets never travel.** The request carries the same sanitized view the
|
|
16
|
+
// audit log records, so a password cannot leak into a UI or its logs.
|
|
17
|
+
//
|
|
18
|
+
// Protocol: one JSON object per line over a local stream socket. The engine
|
|
19
|
+
// writes a request and waits for a reply carrying the same `id`. Newline-
|
|
20
|
+
// delimited JSON keeps a control plane implementable in any language, and
|
|
21
|
+
// debuggable with `nc`.
|
|
22
|
+
|
|
23
|
+
import net from 'net';
|
|
24
|
+
import os from 'os';
|
|
25
|
+
import path from 'path';
|
|
26
|
+
import crypto from 'crypto';
|
|
27
|
+
import fs from 'fs';
|
|
28
|
+
import { READONLY_BLOCKED_TOOLS, COMMAND_BEARING_TOOLS } from './policy.js';
|
|
29
|
+
import { logger } from './logger.js';
|
|
30
|
+
|
|
31
|
+
/** Never ask (default — v3 behaviour). */
|
|
32
|
+
const ASK_NEVER = 'never';
|
|
33
|
+
/** Ask only for actions that change or destroy remote state. */
|
|
34
|
+
const ASK_DESTRUCTIVE = 'destructive';
|
|
35
|
+
/** Ask for everything that reaches a machine. */
|
|
36
|
+
const ASK_ALWAYS = 'always';
|
|
37
|
+
|
|
38
|
+
export const VALID_APPROVAL_MODES = new Set([ASK_NEVER, ASK_DESTRUCTIVE, ASK_ALWAYS]);
|
|
39
|
+
|
|
40
|
+
// These operations inspect local state or release resources that are already
|
|
41
|
+
// open. Closing a connection must remain possible when the approval UI is gone.
|
|
42
|
+
const APPROVAL_EXEMPT_TOOLS = new Set([
|
|
43
|
+
'ssh_list_servers', 'ssh_history', 'ssh_session_list', 'ssh_session_close',
|
|
44
|
+
'ssh_tunnel_list', 'ssh_tunnel_close', 'ssh_alias', 'ssh_command_alias',
|
|
45
|
+
'ssh_hooks', 'ssh_profile', 'ssh_group_manage',
|
|
46
|
+
]);
|
|
47
|
+
|
|
48
|
+
// These two identify their targets through a session or a group, so their
|
|
49
|
+
// handlers apply the same gate after resolving each underlying server.
|
|
50
|
+
export const HANDLER_GATED_TOOLS = new Set(['ssh_session_send', 'ssh_execute_group']);
|
|
51
|
+
|
|
52
|
+
/** Whether this invocation only inspects local state or closes a connection. */
|
|
53
|
+
export function isApprovalExempt(toolName, args = {}) {
|
|
54
|
+
return APPROVAL_EXEMPT_TOOLS.has(toolName)
|
|
55
|
+
|| (toolName === 'ssh_connection_status' && args.action !== 'reconnect')
|
|
56
|
+
|| (toolName === 'ssh_key_manage' && args.action === 'list');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Read actions on tools that also offer mutations retain readonly access. */
|
|
60
|
+
export function isReadOnlyAction(toolName, args = {}) {
|
|
61
|
+
return (toolName === 'ssh_process_manager' && args.action !== 'kill')
|
|
62
|
+
|| (toolName === 'ssh_alert_setup' && args.action !== 'set')
|
|
63
|
+
|| (toolName === 'ssh_key_manage' && ['verify', 'check', 'list'].includes(args.action));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// sun_path limit for Unix domain sockets: 104 bytes on macOS/BSD, 108 on Linux.
|
|
67
|
+
// Take the smaller so a path that works on one platform works on both.
|
|
68
|
+
export const MAX_SOCKET_PATH = 104;
|
|
69
|
+
|
|
70
|
+
// Commands that destroy data or take a service down. Deliberately short: this
|
|
71
|
+
// decides what interrupts a human, and a list that cries wolf gets clicked
|
|
72
|
+
// through without reading, which is worse than no prompt at all.
|
|
73
|
+
const DESTRUCTIVE_COMMAND_PATTERNS = [
|
|
74
|
+
/\brm\s+(-[a-zA-Z]*\s+)*-?[a-zA-Z]*[rf]/,
|
|
75
|
+
/\bdd\s+.*\bof=/,
|
|
76
|
+
/\bmkfs(\.\w+)?\b/,
|
|
77
|
+
/\b(shutdown|reboot|halt|poweroff)\b/,
|
|
78
|
+
/\bsystemctl\s+(stop|disable|mask)\b/,
|
|
79
|
+
/\b(drop|truncate)\s+(database|table|schema)\b/i,
|
|
80
|
+
/\bchown\s+-R\b/,
|
|
81
|
+
/\bchmod\s+-R\s+0?777\b/,
|
|
82
|
+
// No \b before -F: a space and a hyphen are both non-word characters,
|
|
83
|
+
// so there is no word boundary between them and the pattern never matched.
|
|
84
|
+
/\b(iptables|nft)\b.*\s(-F|--flush|flush)(\s|$)/,
|
|
85
|
+
/:\(\)\s*\{.*\}\s*;/,
|
|
86
|
+
];
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Where the control plane listens.
|
|
90
|
+
*
|
|
91
|
+
* A Unix socket on POSIX, a named pipe on Windows. Both live outside the
|
|
92
|
+
* project directory so a repository copy never carries one.
|
|
93
|
+
* @returns {string} Socket path
|
|
94
|
+
*/
|
|
95
|
+
export function defaultSocketPath() {
|
|
96
|
+
if (process.env.SSH_MANAGER_APPROVAL_SOCKET) return process.env.SSH_MANAGER_APPROVAL_SOCKET;
|
|
97
|
+
if (process.platform === 'win32') return '\\\\.\\pipe\\mcp-ssh-manager-approval';
|
|
98
|
+
const home = process.env.SSH_MANAGER_HOME || path.join(os.homedir(), '.ssh-manager');
|
|
99
|
+
return path.join(home, 'approval.sock');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Approval mode for a server, defaulting to never.
|
|
104
|
+
* @param {any} serverConfig - Resolved server config
|
|
105
|
+
* @returns {string} One of VALID_APPROVAL_MODES
|
|
106
|
+
*/
|
|
107
|
+
export function approvalMode(serverConfig) {
|
|
108
|
+
// Only the vault reaches this field: ConfigLoader does not read `approval`
|
|
109
|
+
// from a .env, a TOML file or the environment. An environment variable would
|
|
110
|
+
// be the easiest of all to set from inside a compromised shell.
|
|
111
|
+
const raw = serverConfig?.approval ?? ASK_NEVER;
|
|
112
|
+
const normalized = String(raw).toLowerCase();
|
|
113
|
+
if (!VALID_APPROVAL_MODES.has(normalized)) {
|
|
114
|
+
logger.warn(`Unknown approval mode "${raw}", requiring approval`, {
|
|
115
|
+
server: serverConfig?.name,
|
|
116
|
+
});
|
|
117
|
+
return ASK_ALWAYS;
|
|
118
|
+
}
|
|
119
|
+
return normalized;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Would this action change remote state, or destroy something?
|
|
124
|
+
*
|
|
125
|
+
* Reuses the classification the security modes already rely on, so a tool
|
|
126
|
+
* blocked by `readonly` is the same tool that prompts under `destructive`.
|
|
127
|
+
*
|
|
128
|
+
* @param {string} toolName - MCP tool name
|
|
129
|
+
* @param {string} [command] - Command string, for command-bearing tools
|
|
130
|
+
* @returns {boolean} True when the action deserves a human
|
|
131
|
+
*/
|
|
132
|
+
export function isDestructive(toolName, command) {
|
|
133
|
+
if (READONLY_BLOCKED_TOOLS.has(toolName)) return true;
|
|
134
|
+
if (COMMAND_BEARING_TOOLS.has(toolName) && typeof command === 'string') {
|
|
135
|
+
return DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(command));
|
|
136
|
+
}
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Does this action need a human's decision?
|
|
142
|
+
* @param {any} serverConfig - Resolved server config
|
|
143
|
+
* @param {string} toolName - MCP tool name
|
|
144
|
+
* @param {string} [command] - Command string
|
|
145
|
+
* @returns {boolean} True when approval must be requested
|
|
146
|
+
*/
|
|
147
|
+
export function needsApproval(serverConfig, toolName, command) {
|
|
148
|
+
const mode = approvalMode(serverConfig);
|
|
149
|
+
if (mode === ASK_NEVER) return false;
|
|
150
|
+
if (mode === ASK_ALWAYS) return true;
|
|
151
|
+
return isDestructive(toolName, command);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Is a control plane listening?
|
|
156
|
+
*
|
|
157
|
+
* Checked before every request rather than cached: the UI can be started and
|
|
158
|
+
* stopped at any time, and a stale "yes" would make the engine wait on a socket
|
|
159
|
+
* nobody is reading.
|
|
160
|
+
*
|
|
161
|
+
* @param {string} [socketPath] - Socket to test
|
|
162
|
+
* @returns {boolean} True when something is there to ask
|
|
163
|
+
*/
|
|
164
|
+
export function isControlPlaneListening(socketPath = defaultSocketPath()) {
|
|
165
|
+
if (process.platform === 'win32') return true; // named pipes: only connect() can tell
|
|
166
|
+
|
|
167
|
+
// Unix sockets cap their path at sun_path — 104 bytes on macOS/BSD, 108 on
|
|
168
|
+
// Linux. Past it, bind() fails with a misleading EADDRINUSE on a path where
|
|
169
|
+
// nothing is listening, which costs an hour to diagnose. Say it plainly.
|
|
170
|
+
if (Buffer.byteLength(socketPath) > MAX_SOCKET_PATH) {
|
|
171
|
+
logger.warn(
|
|
172
|
+
`Approval socket path is ${Buffer.byteLength(socketPath)} bytes, over the ${MAX_SOCKET_PATH}-byte limit — `
|
|
173
|
+
+ 'no control plane can listen there. Set SSH_MANAGER_APPROVAL_SOCKET to a shorter path.',
|
|
174
|
+
{ socketPath }
|
|
175
|
+
);
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
try {
|
|
180
|
+
return fs.statSync(socketPath).isSocket();
|
|
181
|
+
} catch {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Ask the control plane to decide, and wait.
|
|
188
|
+
*
|
|
189
|
+
* @param {Object} request - What the human is being asked to approve
|
|
190
|
+
* @param {Object} [options] - Socket path and deadline
|
|
191
|
+
* @param {string} [options.socketPath] - Where to connect
|
|
192
|
+
* @param {number} [options.timeoutMs] - How long to wait
|
|
193
|
+
* @returns {Promise<{decision: 'allow'|'deny', reason?: string, source: string}>}
|
|
194
|
+
* `source` says who decided: the operator, or the timeout default.
|
|
195
|
+
*/
|
|
196
|
+
export function requestDecision(request, options = {}) {
|
|
197
|
+
const socketPath = options.socketPath || defaultSocketPath();
|
|
198
|
+
const timeoutMs = options.timeoutMs
|
|
199
|
+
?? Number(process.env.SSH_MANAGER_APPROVAL_TIMEOUT_MS || 120000);
|
|
200
|
+
|
|
201
|
+
return new Promise(resolve => {
|
|
202
|
+
let settled = false;
|
|
203
|
+
/** @type {import('net').Socket|null} */
|
|
204
|
+
let socket = null;
|
|
205
|
+
|
|
206
|
+
// Every exit path goes through here, so the socket is closed exactly once
|
|
207
|
+
// and a late reply can never resolve a promise twice.
|
|
208
|
+
const finish = (decision, reason, source) => {
|
|
209
|
+
if (settled) return;
|
|
210
|
+
settled = true;
|
|
211
|
+
if (timer) clearTimeout(timer);
|
|
212
|
+
if (socket) { socket.removeAllListeners(); socket.destroy(); }
|
|
213
|
+
resolve({ decision, reason, source });
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
const timer = setTimeout(() => {
|
|
217
|
+
// The deadline is the safety net: a control plane that crashed mid-review,
|
|
218
|
+
// or an operator who walked away, must not leave the agent hanging.
|
|
219
|
+
finish('deny', `No decision within ${timeoutMs}ms`, 'timeout');
|
|
220
|
+
}, timeoutMs);
|
|
221
|
+
|
|
222
|
+
try {
|
|
223
|
+
socket = net.createConnection(socketPath);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
finish('deny', `Cannot reach the control plane: ${error.message}`, 'error');
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
let buffer = '';
|
|
230
|
+
|
|
231
|
+
socket.on('connect', () => {
|
|
232
|
+
socket?.write(`${JSON.stringify(request)}\n`);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
socket.on('data', chunk => {
|
|
236
|
+
buffer += chunk.toString();
|
|
237
|
+
// One JSON object per line; anything after the first complete line is
|
|
238
|
+
// ignored, since one request has exactly one answer.
|
|
239
|
+
const newline = buffer.indexOf('\n');
|
|
240
|
+
if (newline === -1) return;
|
|
241
|
+
try {
|
|
242
|
+
const reply = JSON.parse(buffer.slice(0, newline));
|
|
243
|
+
if (reply.id !== request.id) {
|
|
244
|
+
finish('deny', 'Control plane replied about a different request', 'error');
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
finish(
|
|
248
|
+
reply.decision === 'allow' ? 'allow' : 'deny',
|
|
249
|
+
reply.reason,
|
|
250
|
+
'operator'
|
|
251
|
+
);
|
|
252
|
+
} catch (error) {
|
|
253
|
+
finish('deny', `Unreadable reply: ${error.message}`, 'error');
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
socket.on('error', error => {
|
|
258
|
+
// No listener, wrong permissions, socket removed mid-flight. Denying is
|
|
259
|
+
// the safe reading: approval was requested and did not happen.
|
|
260
|
+
finish('deny', `Control plane unreachable: ${error.message}`, 'error');
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
socket.on('close', () => {
|
|
264
|
+
finish('deny', 'Control plane closed the connection without deciding', 'error');
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Build the request handed to the control plane.
|
|
271
|
+
*
|
|
272
|
+
* @param {any} serverConfig - Resolved server config
|
|
273
|
+
* @param {string} toolName - MCP tool name
|
|
274
|
+
* @param {any} sanitizedArgs - Arguments, already stripped of secrets
|
|
275
|
+
* @param {string} [command] - Command string
|
|
276
|
+
* @returns {Object} The request object
|
|
277
|
+
*/
|
|
278
|
+
export function buildRequest(serverConfig, toolName, sanitizedArgs, command) {
|
|
279
|
+
return {
|
|
280
|
+
id: crypto.randomUUID(),
|
|
281
|
+
ts: new Date().toISOString(),
|
|
282
|
+
server: serverConfig?.name,
|
|
283
|
+
host: serverConfig?.host,
|
|
284
|
+
user: serverConfig?.user,
|
|
285
|
+
mode: serverConfig?.mode || 'unrestricted',
|
|
286
|
+
tool: toolName,
|
|
287
|
+
command,
|
|
288
|
+
destructive: !isReadOnlyAction(toolName, sanitizedArgs) && isDestructive(toolName, command),
|
|
289
|
+
args: sanitizedArgs,
|
|
290
|
+
};
|
|
291
|
+
}
|
package/src/audit.js
CHANGED
|
@@ -29,7 +29,17 @@ const REDACT_FIELDS = new Set([
|
|
|
29
29
|
|
|
30
30
|
const REDACTED = '***';
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Deep-copy a value with secret-looking fields replaced.
|
|
34
|
+
*
|
|
35
|
+
* Exported because the approval request must carry the same redacted view the
|
|
36
|
+
* audit log records: a second implementation would eventually drift, and the
|
|
37
|
+
* drift would be a password reaching a UI.
|
|
38
|
+
*
|
|
39
|
+
* @param {any} value - Value to sanitize
|
|
40
|
+
* @returns {any} A redacted copy
|
|
41
|
+
*/
|
|
42
|
+
export function sanitize(value) {
|
|
33
43
|
if (value === null || typeof value !== 'object') return value;
|
|
34
44
|
if (Array.isArray(value)) return value.map(sanitize);
|
|
35
45
|
const out = {};
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What your agents ran, kept on this machine.
|
|
3
|
+
*
|
|
4
|
+
* ## Why this exists next to the audit log
|
|
5
|
+
*
|
|
6
|
+
* `audit.js` writes a per-server JSONL file, and only when that server has
|
|
7
|
+
* `AUDIT_LOG` set. That is the right shape for shipping to a log collector, and
|
|
8
|
+
* the wrong shape for the question an operator actually asks — *what has my
|
|
9
|
+
* agent been doing?* — because answering it means having remembered to
|
|
10
|
+
* configure every server first, and nobody has.
|
|
11
|
+
*
|
|
12
|
+
* The control plane already sees every command: the engine streams them here as
|
|
13
|
+
* they run. Writing them down costs one append per command and needs nothing
|
|
14
|
+
* configured anywhere.
|
|
15
|
+
*
|
|
16
|
+
* ## What is written, and what is not
|
|
17
|
+
*
|
|
18
|
+
* The command, the server, when, how long, and the exit code. **Not the
|
|
19
|
+
* output.** A stream carries whatever the program printed — a config being
|
|
20
|
+
* catted, a token echoed by a deploy script, a database row — and a file of
|
|
21
|
+
* that sitting in a home directory is a liability nobody asked for. The output
|
|
22
|
+
* stays in memory, capped, and disappears with the window.
|
|
23
|
+
*
|
|
24
|
+
* `SSH_MANAGER_LOG_OUTPUT=1` includes it, truncated, for someone who has
|
|
25
|
+
* decided they want that on their own machine. Off by default, and the setting
|
|
26
|
+
* says what it does rather than being buried in a config file.
|
|
27
|
+
*/
|
|
28
|
+
import fs from 'fs';
|
|
29
|
+
import os from 'os';
|
|
30
|
+
import path from 'path';
|
|
31
|
+
import { logger } from './logger.js';
|
|
32
|
+
|
|
33
|
+
/** How much output is kept per command when it is kept at all. */
|
|
34
|
+
const OUTPUT_LIMIT = 4096;
|
|
35
|
+
|
|
36
|
+
/** Entries kept before the oldest are dropped. Roughly a month of ordinary use. */
|
|
37
|
+
const MAX_ENTRIES = 5000;
|
|
38
|
+
|
|
39
|
+
/** @returns {string} The log file, beside the vault. */
|
|
40
|
+
export function commandLogPath() {
|
|
41
|
+
const home = process.env.SSH_MANAGER_HOME || path.join(os.homedir(), '.ssh-manager');
|
|
42
|
+
return path.join(home, 'commands.log.jsonl');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @returns {boolean} Whether output is recorded as well as the command. */
|
|
46
|
+
export function recordsOutput() {
|
|
47
|
+
return process.env.SSH_MANAGER_LOG_OUTPUT === '1';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {object} CommandLogEntry
|
|
52
|
+
* @property {string} ts - When it finished, ISO 8601
|
|
53
|
+
* @property {string} server
|
|
54
|
+
* @property {string} command
|
|
55
|
+
* @property {number|null} code - Exit code, null if it never reported one
|
|
56
|
+
* @property {number} [durationMs]
|
|
57
|
+
* @property {string} [output] - Only when SSH_MANAGER_LOG_OUTPUT=1
|
|
58
|
+
*/
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Append one finished command.
|
|
62
|
+
*
|
|
63
|
+
* Failures are logged and swallowed: a log that cannot be written must never
|
|
64
|
+
* take down the thing it is recording.
|
|
65
|
+
*
|
|
66
|
+
* @param {CommandLogEntry} entry - The command that just finished
|
|
67
|
+
*/
|
|
68
|
+
export function appendCommand(entry) {
|
|
69
|
+
try {
|
|
70
|
+
const file = commandLogPath();
|
|
71
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
72
|
+
|
|
73
|
+
/** @type {CommandLogEntry} */
|
|
74
|
+
const line = {
|
|
75
|
+
ts: entry.ts,
|
|
76
|
+
server: entry.server,
|
|
77
|
+
command: entry.command,
|
|
78
|
+
code: entry.code,
|
|
79
|
+
};
|
|
80
|
+
if (typeof entry.durationMs === 'number') line.durationMs = entry.durationMs;
|
|
81
|
+
if (recordsOutput() && entry.output) {
|
|
82
|
+
line.output = entry.output.length > OUTPUT_LIMIT
|
|
83
|
+
? `${entry.output.slice(-OUTPUT_LIMIT)}\n[… truncated, kept the last ${OUTPUT_LIMIT} bytes]`
|
|
84
|
+
: entry.output;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
fs.appendFileSync(file, `${JSON.stringify(line)}\n`, { mode: 0o600 });
|
|
88
|
+
} catch (error) {
|
|
89
|
+
logger.warn('Cannot append to the command log', { error: error.message });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Read the log back, newest first.
|
|
95
|
+
*
|
|
96
|
+
* @param {number} [limit] - How many to return
|
|
97
|
+
* @returns {CommandLogEntry[]}
|
|
98
|
+
*/
|
|
99
|
+
export function readCommandLog(limit = 500) {
|
|
100
|
+
const file = commandLogPath();
|
|
101
|
+
if (!fs.existsSync(file)) return [];
|
|
102
|
+
try {
|
|
103
|
+
const lines = fs.readFileSync(file, 'utf8').split('\n').filter(Boolean);
|
|
104
|
+
return lines
|
|
105
|
+
.slice(-limit)
|
|
106
|
+
.map(line => {
|
|
107
|
+
try {
|
|
108
|
+
return JSON.parse(line);
|
|
109
|
+
} catch {
|
|
110
|
+
// One bad line does not invalidate the file; skip it.
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
})
|
|
114
|
+
.filter(Boolean)
|
|
115
|
+
.reverse();
|
|
116
|
+
} catch (error) {
|
|
117
|
+
logger.warn('Cannot read the command log', { error: error.message });
|
|
118
|
+
return [];
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Drop the oldest entries when the file has grown past MAX_ENTRIES.
|
|
124
|
+
*
|
|
125
|
+
* Called on startup rather than on every append: rewriting a file to add one
|
|
126
|
+
* line would turn an append into an O(n) operation, and the growth this guards
|
|
127
|
+
* against takes weeks.
|
|
128
|
+
*/
|
|
129
|
+
export function trimCommandLog() {
|
|
130
|
+
const file = commandLogPath();
|
|
131
|
+
let lines;
|
|
132
|
+
try {
|
|
133
|
+
lines = fs.readFileSync(file, 'utf8').split('\n').filter(Boolean);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
// Absent is the ordinary first run, not a failure; no separate existence
|
|
136
|
+
// check, which only opened a window between checking and reading.
|
|
137
|
+
if (error.code !== 'ENOENT') logger.warn('Cannot read the command log', { error: error.message });
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (lines.length <= MAX_ENTRIES) return;
|
|
141
|
+
// Written beside it and renamed over it: a crash mid-write used to leave a
|
|
142
|
+
// truncated record, which is the one outcome a log must not have.
|
|
143
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
144
|
+
try {
|
|
145
|
+
fs.writeFileSync(temporary, `${lines.slice(-MAX_ENTRIES).join('\n')}\n`, { mode: 0o600 });
|
|
146
|
+
fs.renameSync(temporary, file);
|
|
147
|
+
logger.info('Command log trimmed', { kept: MAX_ENTRIES, dropped: lines.length - MAX_ENTRIES });
|
|
148
|
+
} catch (error) {
|
|
149
|
+
try { fs.rmSync(temporary, { force: true }); } catch { /* nothing to clean */ }
|
|
150
|
+
logger.warn('Cannot trim the command log', { error: error.message });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Delete the log. Offered because it is the operator's machine and their record. */
|
|
155
|
+
export function clearCommandLog() {
|
|
156
|
+
try {
|
|
157
|
+
fs.rmSync(commandLogPath(), { force: true });
|
|
158
|
+
return true;
|
|
159
|
+
} catch {
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
}
|