mcp-ssh-manager 3.8.5 → 3.8.6
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/CHANGELOG.md +80 -0
- package/README.md +12 -11
- package/cli/lib/menu.sh +2 -2
- package/docs/ALIASES_AND_HOOKS.md +54 -25
- package/docs/SECURITY_MODES.md +33 -3
- package/package.json +5 -3
- package/profiles/default.json +6 -4
- package/server.json +2 -2
- package/src/backup-manager.js +24 -1
- package/src/command-aliases.js +9 -6
- package/src/config-paths.js +12 -0
- package/src/database-manager.js +200 -21
- package/src/deploy-helper.js +15 -7
- package/src/hooks-system.js +298 -57
- package/src/index.js +39 -22
- package/src/logger.js +43 -17
- package/src/policy.js +46 -25
- package/src/profile-loader.js +18 -12
- package/src/server-aliases.js +9 -6
- package/src/shell-quote.js +8 -0
- package/src/shell-segments.js +189 -0
- package/src/ssh-key-manager.js +123 -76
- package/src/ssh-manager.js +17 -41
- package/src/user-state.js +60 -0
- package/.hooks-config.json +0 -131
package/src/hooks-system.js
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Hooks System for MCP SSH Manager
|
|
3
3
|
* Provides automation through pre/post execution hooks
|
|
4
|
+
*
|
|
5
|
+
* A hook action is one of:
|
|
6
|
+
* - `log`: appends a line to a file in SSH_MANAGER_HOME, in JavaScript,
|
|
7
|
+
* with no shell involved. The default `on-error` hook is one.
|
|
8
|
+
* - `command`: a shell command run on this machine.
|
|
9
|
+
* - `remoteCommand`: a shell command run on the server, when the caller
|
|
10
|
+
* hands the hook an open connection.
|
|
11
|
+
*
|
|
12
|
+
* Context values ({server}, {error}, ...) never become part of a command's
|
|
13
|
+
* text. Up to 3.8.5 they were spliced in raw, and the default `on-error` hook
|
|
14
|
+
* put the connection error inside double quotes: a server that disconnected
|
|
15
|
+
* with `Bye $(touch /tmp/x)` ran that command on the machine running the MCP
|
|
16
|
+
* server (GHSA-759m-wfpq-xmx3). Each placeholder is now replaced by a
|
|
17
|
+
* reference to a shell variable that carries the value, and a shell does not
|
|
18
|
+
* re-parse what a variable expands to.
|
|
4
19
|
*/
|
|
5
20
|
|
|
6
21
|
import fs from 'fs';
|
|
@@ -9,13 +24,19 @@ import { exec } from 'child_process';
|
|
|
9
24
|
import { promisify } from 'util';
|
|
10
25
|
import { fileURLToPath } from 'url';
|
|
11
26
|
import { loadProfile } from './profile-loader.js';
|
|
27
|
+
import { managerHome } from './config-paths.js';
|
|
28
|
+
import { shellQuote } from './shell-quote.js';
|
|
29
|
+
import { readUserState, writeUserState } from './user-state.js';
|
|
12
30
|
|
|
13
31
|
const execAsync = promisify(exec);
|
|
14
32
|
const __filename = fileURLToPath(import.meta.url);
|
|
15
33
|
const __dirname = path.dirname(__filename);
|
|
16
34
|
|
|
17
|
-
const
|
|
18
|
-
|
|
35
|
+
const HOOKS_CONFIG_NAME = 'hooks.json';
|
|
36
|
+
// Where 3.8.5 and earlier kept the file, inside the package. Read only; see
|
|
37
|
+
// user-state.js. The package also used to ship a development copy of it,
|
|
38
|
+
// which turned on Frappe hooks for every npm user (issue #87).
|
|
39
|
+
const LEGACY_HOOKS_CONFIG_FILE = path.join(__dirname, '..', '.hooks-config.json');
|
|
19
40
|
|
|
20
41
|
// Get hooks from the active profile
|
|
21
42
|
let profileHooks = {};
|
|
@@ -34,9 +55,10 @@ const DEFAULT_HOOKS = {
|
|
|
34
55
|
description: 'Run when an error occurs',
|
|
35
56
|
actions: [
|
|
36
57
|
{
|
|
37
|
-
type: '
|
|
58
|
+
type: 'log',
|
|
38
59
|
name: 'log-error',
|
|
39
|
-
|
|
60
|
+
file: 'errors.log',
|
|
61
|
+
message: 'Error on {server}: {error}'
|
|
40
62
|
}
|
|
41
63
|
]
|
|
42
64
|
},
|
|
@@ -46,9 +68,10 @@ const DEFAULT_HOOKS = {
|
|
|
46
68
|
description: 'Run before accepting a changed SSH host key',
|
|
47
69
|
actions: [
|
|
48
70
|
{
|
|
49
|
-
type: '
|
|
71
|
+
type: 'log',
|
|
50
72
|
name: 'log-key-change',
|
|
51
|
-
|
|
73
|
+
file: 'ssh-key-changes.log',
|
|
74
|
+
message: 'SSH key change detected for {server} ({host}:{port})'
|
|
52
75
|
}
|
|
53
76
|
]
|
|
54
77
|
},
|
|
@@ -57,67 +80,274 @@ const DEFAULT_HOOKS = {
|
|
|
57
80
|
description: 'Run after updating an SSH host key',
|
|
58
81
|
actions: [
|
|
59
82
|
{
|
|
60
|
-
type: '
|
|
83
|
+
type: 'log',
|
|
61
84
|
name: 'log-key-updated',
|
|
62
|
-
|
|
85
|
+
file: 'ssh-key-changes.log',
|
|
86
|
+
message: 'SSH key {action} for {server} ({host}:{port})'
|
|
63
87
|
}
|
|
64
88
|
]
|
|
65
89
|
}
|
|
66
90
|
};
|
|
67
91
|
|
|
92
|
+
const PLACEHOLDER = /^\{([A-Za-z_][A-Za-z0-9_]*)\}/;
|
|
93
|
+
|
|
94
|
+
/** @param {any} value */
|
|
95
|
+
function isScalar(value) {
|
|
96
|
+
return ['string', 'number', 'boolean'].includes(typeof value);
|
|
97
|
+
}
|
|
98
|
+
|
|
68
99
|
/**
|
|
69
|
-
*
|
|
100
|
+
* Name of the variable that carries a context value: `server` becomes
|
|
101
|
+
* SSH_MANAGER_HOOK_SERVER, `backupId` becomes SSH_MANAGER_HOOK_BACKUP_ID.
|
|
102
|
+
* Hook authors can also read these directly.
|
|
103
|
+
* @param {string} key
|
|
70
104
|
*/
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
105
|
+
function hookVariable(key) {
|
|
106
|
+
return `SSH_MANAGER_HOOK_${key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Rewrite a POSIX shell command so that every {placeholder} found in `context`
|
|
111
|
+
* becomes a reference to a variable holding the value, quoted for where it
|
|
112
|
+
* sits: `"${V}"` in plain text, `${V}` inside double quotes, and `'"${V}"'`
|
|
113
|
+
* inside single quotes. The quoting only keeps a value one word; safety does
|
|
114
|
+
* not depend on it, since an expanded variable is never parsed as code, even
|
|
115
|
+
* when a template nests quotes in ways this scanner reads imperfectly.
|
|
116
|
+
*
|
|
117
|
+
* Heredoc bodies get `${V}` when the delimiter is unquoted, since the body is
|
|
118
|
+
* expanded but not re-parsed, and the value itself with line breaks removed
|
|
119
|
+
* when it is quoted, since nothing expands there and a value cut into lines
|
|
120
|
+
* could otherwise end the heredoc early.
|
|
121
|
+
*
|
|
122
|
+
* What stays the hook author's responsibility: handing a variable to
|
|
123
|
+
* something that evaluates its text again (eval, sh -c, arithmetic).
|
|
124
|
+
*
|
|
125
|
+
* @param {string} template
|
|
126
|
+
* @param {Record<string, any>} context
|
|
127
|
+
* @returns {{command: string, values: Record<string, string>}}
|
|
128
|
+
*/
|
|
129
|
+
export function renderShellCommand(template, context = {}) {
|
|
130
|
+
/** @type {Record<string, string>} */
|
|
131
|
+
const values = {};
|
|
132
|
+
/** @type {{kind: string, parens: number}[]} */
|
|
133
|
+
const frames = [{ kind: 'plain', parens: 0 }];
|
|
134
|
+
/** @type {{delimiter: string, quoted: boolean, stripTabs: boolean}[]} */
|
|
135
|
+
const heredocs = [];
|
|
136
|
+
let out = '';
|
|
137
|
+
|
|
138
|
+
/** @param {string} text @param {number} at */
|
|
139
|
+
const placeholderAt = (text, at) => {
|
|
140
|
+
if (text[at] !== '{' || text[at - 1] === '$') return null;
|
|
141
|
+
const match = PLACEHOLDER.exec(text.slice(at));
|
|
142
|
+
return match && Object.hasOwn(context, match[1]) && isScalar(context[match[1]])
|
|
143
|
+
? { key: match[1], length: match[0].length } : null;
|
|
144
|
+
};
|
|
145
|
+
/** @param {string} key */
|
|
146
|
+
const reference = key => {
|
|
147
|
+
const name = hookVariable(key);
|
|
148
|
+
values[name] = String(context[key]);
|
|
149
|
+
return name;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// Copy the heredoc bodies that start at `start`, rendering placeholders in
|
|
153
|
+
// them, and return the index just past the last delimiter line.
|
|
154
|
+
/** @param {number} start */
|
|
155
|
+
const consumeHeredocs = start => {
|
|
156
|
+
let at = start;
|
|
157
|
+
for (const heredoc of heredocs.splice(0)) {
|
|
158
|
+
while (at < template.length) {
|
|
159
|
+
const end = template.indexOf('\n', at);
|
|
160
|
+
const line = template.slice(at, end < 0 ? template.length : end);
|
|
161
|
+
at = end < 0 ? template.length : end + 1;
|
|
162
|
+
const bare = heredoc.stripTabs ? line.replace(/^\t+/, '') : line;
|
|
163
|
+
let rendered = '';
|
|
164
|
+
for (let p = 0; p < line.length; p++) {
|
|
165
|
+
const placeholder = bare !== heredoc.delimiter && placeholderAt(line, p);
|
|
166
|
+
if (!placeholder) { rendered += line[p]; continue; }
|
|
167
|
+
rendered += heredoc.quoted
|
|
168
|
+
? String(context[placeholder.key]).replace(/[\r\n]+/g, ' ')
|
|
169
|
+
: `\${${reference(placeholder.key)}}`;
|
|
170
|
+
p += placeholder.length - 1;
|
|
171
|
+
}
|
|
172
|
+
out += rendered + (end < 0 ? '' : '\n');
|
|
173
|
+
if (bare === heredoc.delimiter) break;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return at;
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
for (let i = 0; i < template.length; i++) {
|
|
180
|
+
const ch = template[i];
|
|
181
|
+
const frame = frames[frames.length - 1];
|
|
182
|
+
const unquoted = frame.kind !== 'single' && frame.kind !== 'double';
|
|
183
|
+
|
|
184
|
+
if (ch === '\n' && heredocs.length && unquoted) {
|
|
185
|
+
out += ch;
|
|
186
|
+
i = consumeHeredocs(i + 1) - 1;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (unquoted && ch === '<' && template[i + 1] === '<' && template[i + 2] !== '<') {
|
|
190
|
+
// A heredoc operator: record its delimiter; the body starts on the next line.
|
|
191
|
+
let at = i + 2;
|
|
192
|
+
const stripTabs = template[at] === '-';
|
|
193
|
+
if (stripTabs) at++;
|
|
194
|
+
while (template[at] === ' ' || template[at] === '\t') at++;
|
|
195
|
+
let delimiter = '';
|
|
196
|
+
let quoted = false;
|
|
197
|
+
while (at < template.length && !/[\s;&|<>()]/.test(template[at])) {
|
|
198
|
+
const c = template[at];
|
|
199
|
+
if (c === '\'' || c === '"') {
|
|
200
|
+
const close = template.indexOf(c, at + 1);
|
|
201
|
+
if (close < 0) break;
|
|
202
|
+
delimiter += template.slice(at + 1, close);
|
|
203
|
+
quoted = true;
|
|
204
|
+
at = close + 1;
|
|
205
|
+
} else if (c === '\\') {
|
|
206
|
+
delimiter += template[at + 1] ?? '';
|
|
207
|
+
quoted = true;
|
|
208
|
+
at += 2;
|
|
209
|
+
} else {
|
|
210
|
+
delimiter += c;
|
|
211
|
+
at++;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (delimiter) heredocs.push({ delimiter, quoted, stripTabs });
|
|
215
|
+
out += template.slice(i, at);
|
|
216
|
+
i = at - 1;
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (frame.kind === 'single') {
|
|
221
|
+
if (ch === '\'') frames.pop();
|
|
222
|
+
} else if (ch === '\\') {
|
|
223
|
+
out += template.slice(i, i + 2);
|
|
224
|
+
i++;
|
|
225
|
+
continue;
|
|
226
|
+
} else if (frame.kind === 'double' && ch === '"') {
|
|
227
|
+
frames.pop();
|
|
228
|
+
} else if (frame.kind !== 'double' && (ch === '\'' || ch === '"')) {
|
|
229
|
+
frames.push({ kind: ch === '\'' ? 'single' : 'double', parens: 0 });
|
|
230
|
+
} else if (ch === '`') {
|
|
231
|
+
if (frame.kind === 'backtick') frames.pop();
|
|
232
|
+
else frames.push({ kind: 'backtick', parens: 0 });
|
|
233
|
+
} else if (ch === '$' && template[i + 1] === '(') {
|
|
234
|
+
frames.push({ kind: 'subst', parens: 0 });
|
|
235
|
+
out += '$(';
|
|
236
|
+
i++;
|
|
237
|
+
continue;
|
|
238
|
+
} else if (frame.kind === 'subst' && ch === '(') {
|
|
239
|
+
frame.parens++;
|
|
240
|
+
} else if (frame.kind === 'subst' && ch === ')') {
|
|
241
|
+
if (frame.parens === 0) frames.pop();
|
|
242
|
+
else frame.parens--;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const placeholder = placeholderAt(template, i);
|
|
246
|
+
if (placeholder) {
|
|
247
|
+
const name = reference(placeholder.key);
|
|
248
|
+
if (frame.kind === 'single') out += `'"\${${name}}"'`;
|
|
249
|
+
else if (frame.kind === 'double') out += `\${${name}}`;
|
|
250
|
+
else out += `"\${${name}}"`;
|
|
251
|
+
i += placeholder.length - 1;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
out += ch;
|
|
75
255
|
}
|
|
76
256
|
|
|
77
|
-
|
|
78
|
-
|
|
257
|
+
return { command: out, values };
|
|
258
|
+
}
|
|
79
259
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
260
|
+
/**
|
|
261
|
+
* The cmd.exe counterpart, for local hooks on Windows. cmd expands %VAR%
|
|
262
|
+
* before it parses a line, so a variable would not protect anything there.
|
|
263
|
+
* Values are spliced in with every character cmd treats specially removed,
|
|
264
|
+
* and wrapped in double quotes when the placeholder sits outside them.
|
|
265
|
+
* @param {string} template
|
|
266
|
+
* @param {Record<string, any>} context
|
|
267
|
+
* @returns {string}
|
|
268
|
+
*/
|
|
269
|
+
export function renderCmdCommand(template, context = {}) {
|
|
270
|
+
let out = '';
|
|
271
|
+
let quoted = false;
|
|
272
|
+
for (let i = 0; i < template.length; i++) {
|
|
273
|
+
const ch = template[i];
|
|
274
|
+
if (ch === '"') quoted = !quoted;
|
|
275
|
+
const match = ch === '{' && PLACEHOLDER.exec(template.slice(i));
|
|
276
|
+
if (match && Object.hasOwn(context, match[1]) && isScalar(context[match[1]])) {
|
|
277
|
+
const value = String(context[match[1]]).replace(/["%!^&|<>()\r\n]/g, '_');
|
|
278
|
+
out += quoted ? value : `"${value}"`;
|
|
279
|
+
i += match[0].length - 1;
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
out += ch;
|
|
83
283
|
}
|
|
284
|
+
return out;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Plain-text substitution for `log` messages, which never reach a shell.
|
|
289
|
+
* @param {string} template
|
|
290
|
+
* @param {Record<string, any>} context
|
|
291
|
+
*/
|
|
292
|
+
function renderText(template, context) {
|
|
293
|
+
return String(template).replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (whole, key) =>
|
|
294
|
+
Object.hasOwn(context, key) && isScalar(context[key]) ? String(context[key]) : whole);
|
|
295
|
+
}
|
|
84
296
|
|
|
297
|
+
/**
|
|
298
|
+
* Append one line to a hook log. A relative file name lands in the manager
|
|
299
|
+
* home, never in the working directory, which under an MCP client is whatever
|
|
300
|
+
* project the user has open. The home is not created just for a log: without
|
|
301
|
+
* it, the line still reaches stderr through the hook's own reporting.
|
|
302
|
+
* @param {string} file
|
|
303
|
+
* @param {string} message
|
|
304
|
+
* @returns {string|null} The file written, or null when skipped
|
|
305
|
+
*/
|
|
306
|
+
function appendHookLog(file, message) {
|
|
307
|
+
const home = managerHome();
|
|
308
|
+
if (!path.isAbsolute(file) && !fs.existsSync(home)) return null;
|
|
309
|
+
const target = path.resolve(home, file);
|
|
310
|
+
// One entry per line: a newline from a server must not forge a second one,
|
|
311
|
+
// and no other control character reaches the file either.
|
|
312
|
+
const text = Array.from(message.replace(/[\r\n]+/g, ' '),
|
|
313
|
+
c => (c < ' ' && c !== '\t') || c === '\u007f' ? '' : c).join('');
|
|
314
|
+
fs.appendFileSync(target, `[${new Date().toISOString()}] ${text}\n`, { mode: 0o600 });
|
|
315
|
+
return target;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Initialize hooks. Nothing is written: defaults live in memory, and the
|
|
320
|
+
* settings file appears only when a hook is changed.
|
|
321
|
+
*/
|
|
322
|
+
export async function initializeHooks() {
|
|
85
323
|
return true;
|
|
86
324
|
}
|
|
87
325
|
|
|
326
|
+
/**
|
|
327
|
+
* Read the user's hook settings, or null when there are none
|
|
328
|
+
*/
|
|
329
|
+
function readHooksFile() {
|
|
330
|
+
const state = readUserState(HOOKS_CONFIG_NAME, LEGACY_HOOKS_CONFIG_FILE);
|
|
331
|
+
return state ? JSON.parse(state.text) : null;
|
|
332
|
+
}
|
|
333
|
+
|
|
88
334
|
/**
|
|
89
335
|
* Load hooks configuration
|
|
90
336
|
*/
|
|
91
337
|
export function loadHooksConfig() {
|
|
338
|
+
// Copies, so toggling a hook never mutates the defaults held in memory.
|
|
339
|
+
const hooks = structuredClone({ ...DEFAULT_HOOKS, ...profileHooks });
|
|
92
340
|
try {
|
|
93
|
-
|
|
94
|
-
let hooks = { ...profileHooks };
|
|
95
|
-
|
|
96
|
-
// Merge with custom hooks from file
|
|
97
|
-
if (fs.existsSync(HOOKS_CONFIG_FILE)) {
|
|
98
|
-
const data = fs.readFileSync(HOOKS_CONFIG_FILE, 'utf8');
|
|
99
|
-
const customHooks = JSON.parse(data);
|
|
100
|
-
|
|
101
|
-
// Deep merge hooks
|
|
102
|
-
for (const [hookName, hookConfig] of Object.entries(customHooks)) {
|
|
103
|
-
if (hooks[hookName]) {
|
|
104
|
-
// Merge existing hook
|
|
105
|
-
hooks[hookName] = {
|
|
106
|
-
...hooks[hookName],
|
|
107
|
-
...hookConfig
|
|
108
|
-
};
|
|
109
|
-
} else {
|
|
110
|
-
// Add new hook
|
|
111
|
-
hooks[hookName] = hookConfig;
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
}
|
|
341
|
+
const customHooks = readHooksFile() || {};
|
|
115
342
|
|
|
116
|
-
|
|
343
|
+
// Deep merge hooks
|
|
344
|
+
for (const [hookName, hookConfig] of Object.entries(customHooks)) {
|
|
345
|
+
hooks[hookName] = hooks[hookName] ? { ...hooks[hookName], ...hookConfig } : hookConfig;
|
|
346
|
+
}
|
|
117
347
|
} catch (error) {
|
|
118
348
|
console.error(`Error loading hooks config: ${error.message}`);
|
|
119
349
|
}
|
|
120
|
-
return
|
|
350
|
+
return hooks;
|
|
121
351
|
}
|
|
122
352
|
|
|
123
353
|
/**
|
|
@@ -125,7 +355,7 @@ export function loadHooksConfig() {
|
|
|
125
355
|
*/
|
|
126
356
|
function saveHooksConfig(config) {
|
|
127
357
|
try {
|
|
128
|
-
|
|
358
|
+
writeUserState(HOOKS_CONFIG_NAME, `${JSON.stringify(config, null, 2)}\n`);
|
|
129
359
|
return true;
|
|
130
360
|
} catch (error) {
|
|
131
361
|
console.error(`Error saving hooks config: ${error.message}`);
|
|
@@ -147,7 +377,7 @@ export async function executeHook(hookName, context = {}) {
|
|
|
147
377
|
console.error(`🎣 Executing hook: ${hookName}`);
|
|
148
378
|
const results = [];
|
|
149
379
|
|
|
150
|
-
for (const action of hook.actions) {
|
|
380
|
+
for (const action of hook.actions || []) {
|
|
151
381
|
try {
|
|
152
382
|
// Check environment variables if required
|
|
153
383
|
if (action.requiresEnv) {
|
|
@@ -161,14 +391,8 @@ export async function executeHook(hookName, context = {}) {
|
|
|
161
391
|
}
|
|
162
392
|
}
|
|
163
393
|
|
|
164
|
-
// Replace placeholders in command
|
|
165
|
-
let command = action.command || action.remoteCommand || '';
|
|
166
|
-
for (const [key, value] of Object.entries(context)) {
|
|
167
|
-
command = command.replace(new RegExp(`{${key}}`, 'g'), value);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
394
|
// Execute action based on type
|
|
171
|
-
const result = await executeAction(action,
|
|
395
|
+
const result = await executeAction(action, context);
|
|
172
396
|
results.push(result);
|
|
173
397
|
|
|
174
398
|
// Check validation results
|
|
@@ -204,7 +428,7 @@ export async function executeHook(hookName, context = {}) {
|
|
|
204
428
|
/**
|
|
205
429
|
* Execute a single action
|
|
206
430
|
*/
|
|
207
|
-
async function executeAction(action,
|
|
431
|
+
async function executeAction(action, context) {
|
|
208
432
|
const result = {
|
|
209
433
|
action: action.name,
|
|
210
434
|
type: action.type,
|
|
@@ -212,9 +436,17 @@ async function executeAction(action, command, context) {
|
|
|
212
436
|
};
|
|
213
437
|
|
|
214
438
|
try {
|
|
215
|
-
if (action.
|
|
216
|
-
|
|
217
|
-
|
|
439
|
+
if (action.type === 'log') {
|
|
440
|
+
const file = appendHookLog(action.file || 'hooks.log', renderText(action.message || '', context));
|
|
441
|
+
result.success = true;
|
|
442
|
+
result.output = file ? `logged to ${file}` : 'skipped: no manager home to write the log in';
|
|
443
|
+
} else if (action.remoteCommand && context.sshConnection) {
|
|
444
|
+
// The variables are set in the remote shell itself: an SSH exec request
|
|
445
|
+
// cannot rely on the server accepting environment variables.
|
|
446
|
+
const { command, values } = renderShellCommand(action.remoteCommand, context);
|
|
447
|
+
const assignments = Object.entries(values).map(([name, value]) => `${name}=${shellQuote(value)}; `).join('');
|
|
448
|
+
const remote = assignments ? `{ ${assignments}${command}\n}` : command;
|
|
449
|
+
const output = await context.sshConnection.execCommand(remote, {
|
|
218
450
|
cwd: context.cwd || context.defaultDir
|
|
219
451
|
});
|
|
220
452
|
|
|
@@ -227,7 +459,16 @@ async function executeAction(action, command, context) {
|
|
|
227
459
|
}
|
|
228
460
|
} else if (action.command) {
|
|
229
461
|
// Execute locally
|
|
230
|
-
|
|
462
|
+
let command;
|
|
463
|
+
let env = process.env;
|
|
464
|
+
if (process.platform === 'win32') {
|
|
465
|
+
command = renderCmdCommand(action.command, context);
|
|
466
|
+
} else {
|
|
467
|
+
const rendered = renderShellCommand(action.command, context);
|
|
468
|
+
command = rendered.command;
|
|
469
|
+
env = { ...process.env, ...rendered.values };
|
|
470
|
+
}
|
|
471
|
+
const { stdout, stderr } = await execAsync(command, { env });
|
|
231
472
|
|
|
232
473
|
result.output = stdout;
|
|
233
474
|
result.error = stderr;
|
|
@@ -243,7 +484,7 @@ async function executeAction(action, command, context) {
|
|
|
243
484
|
case 'backup':
|
|
244
485
|
result.backupInfo = {
|
|
245
486
|
timestamp: new Date().toISOString(),
|
|
246
|
-
command: command
|
|
487
|
+
command: action.command || action.remoteCommand
|
|
247
488
|
};
|
|
248
489
|
break;
|
|
249
490
|
|
package/src/index.js
CHANGED
|
@@ -99,7 +99,8 @@ import {
|
|
|
99
99
|
buildListBackupsCommand,
|
|
100
100
|
parseBackupsList,
|
|
101
101
|
buildCleanupCommand,
|
|
102
|
-
buildCronScheduleCommand
|
|
102
|
+
buildCronScheduleCommand,
|
|
103
|
+
isCronSchedule
|
|
103
104
|
} from './backup-manager.js';
|
|
104
105
|
import {
|
|
105
106
|
HEALTH_STATUS,
|
|
@@ -143,7 +144,7 @@ import {
|
|
|
143
144
|
} from './database-manager.js';
|
|
144
145
|
import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
|
|
145
146
|
import { evaluatePolicy } from './policy.js';
|
|
146
|
-
import { shellQuote, safeInteger } from './shell-quote.js';
|
|
147
|
+
import { shellQuote, shellPath, safeInteger } from './shell-quote.js';
|
|
147
148
|
import { auditLog } from './audit.js';
|
|
148
149
|
|
|
149
150
|
const __filename = fileURLToPath(import.meta.url);
|
|
@@ -719,9 +720,9 @@ registerToolConditional(
|
|
|
719
720
|
if (workingDir) {
|
|
720
721
|
if (platform === 'windows') {
|
|
721
722
|
const escapedDir = workingDir.replace(/'/g, '\'\'');
|
|
722
|
-
fullCommand = `Set-Location '${escapedDir}'; ${expandedCommand}`;
|
|
723
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${expandedCommand}`;
|
|
723
724
|
} else {
|
|
724
|
-
fullCommand = `cd ${workingDir} && ${expandedCommand}`;
|
|
725
|
+
fullCommand = `cd -- ${shellPath(workingDir)} && ${expandedCommand}`;
|
|
725
726
|
}
|
|
726
727
|
} else {
|
|
727
728
|
fullCommand = expandedCommand;
|
|
@@ -1956,9 +1957,9 @@ registerToolConditional(
|
|
|
1956
1957
|
if (platform === 'windows') {
|
|
1957
1958
|
// Single-quote escaping: replace ' with '' (PowerShell convention)
|
|
1958
1959
|
const escapedDir = workingDir.replace(/'/g, '\'\'');
|
|
1959
|
-
fullCommand = `Set-Location '${escapedDir}'; ${command}`;
|
|
1960
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${command}`;
|
|
1960
1961
|
} else {
|
|
1961
|
-
fullCommand = `cd ${workingDir} && ${command}`;
|
|
1962
|
+
fullCommand = `cd -- ${shellPath(workingDir)} && ${command}`;
|
|
1962
1963
|
}
|
|
1963
1964
|
} else {
|
|
1964
1965
|
fullCommand = command;
|
|
@@ -2292,7 +2293,7 @@ registerToolConditional(
|
|
|
2292
2293
|
const deployServers = await loadServerConfig();
|
|
2293
2294
|
const deployServerConfig = deployServers[server.toLowerCase()];
|
|
2294
2295
|
for (const step of strategy.steps) {
|
|
2295
|
-
const command = step.command.replace('{{tempFile}}', tempFile);
|
|
2296
|
+
const command = step.command.replace('{{tempFile}}', () => shellQuote(tempFile));
|
|
2296
2297
|
|
|
2297
2298
|
// step.stdin carries the sudo password for steps that need it, so it
|
|
2298
2299
|
// never reaches the remote command line (issue #34).
|
|
@@ -2403,16 +2404,16 @@ registerToolConditional(
|
|
|
2403
2404
|
if (cwd) {
|
|
2404
2405
|
if (platform === 'windows') {
|
|
2405
2406
|
const escapedDir = cwd.replace(/'/g, '\'\'');
|
|
2406
|
-
fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
|
|
2407
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${fullCommand}`;
|
|
2407
2408
|
} else {
|
|
2408
|
-
fullCommand = `cd ${cwd} && ${fullCommand}`;
|
|
2409
|
+
fullCommand = `cd -- ${shellPath(cwd)} && ${fullCommand}`;
|
|
2409
2410
|
}
|
|
2410
2411
|
} else if (serverConfig?.defaultDir) {
|
|
2411
2412
|
if (platform === 'windows') {
|
|
2412
2413
|
const escapedDir = serverConfig.defaultDir.replace(/'/g, '\'\'');
|
|
2413
|
-
fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
|
|
2414
|
+
fullCommand = `Set-Location -LiteralPath '${escapedDir}'; ${fullCommand}`;
|
|
2414
2415
|
} else {
|
|
2415
|
-
fullCommand = `cd ${serverConfig.defaultDir} && ${fullCommand}`;
|
|
2416
|
+
fullCommand = `cd -- ${shellPath(serverConfig.defaultDir)} && ${fullCommand}`;
|
|
2416
2417
|
}
|
|
2417
2418
|
}
|
|
2418
2419
|
|
|
@@ -3850,6 +3851,16 @@ registerToolConditional(
|
|
|
3850
3851
|
if (denied) return denied;
|
|
3851
3852
|
|
|
3852
3853
|
try {
|
|
3854
|
+
// The name becomes a file name, a cron comment and a find pattern, and
|
|
3855
|
+
// the schedule the first fields of a crontab line, where anything past
|
|
3856
|
+
// the fifth field is the command cron runs and a line break starts a
|
|
3857
|
+
// new job. Both are checked before anything reaches the server.
|
|
3858
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) {
|
|
3859
|
+
throw new Error('Backup name may only contain letters, digits, ".", "_" and "-"');
|
|
3860
|
+
}
|
|
3861
|
+
if (!isCronSchedule(schedule)) {
|
|
3862
|
+
throw new Error('Schedule must be five cron fields (e.g. "0 2 * * *") or a macro such as @daily');
|
|
3863
|
+
}
|
|
3853
3864
|
const ssh = await getConnection(serverName);
|
|
3854
3865
|
|
|
3855
3866
|
// Build backup script path
|
|
@@ -3871,29 +3882,31 @@ registerToolConditional(
|
|
|
3871
3882
|
scriptContent += `BACKUP_FILE="${backupFile}"\n\n`;
|
|
3872
3883
|
scriptContent += 'mkdir -p "$BACKUP_DIR"\n\n';
|
|
3873
3884
|
|
|
3874
|
-
// Add backup command based on type
|
|
3885
|
+
// Add backup command based on type. The script runs later from cron, so
|
|
3886
|
+
// a value spliced in raw here would run every night, not once.
|
|
3875
3887
|
switch (type) {
|
|
3876
3888
|
case BACKUP_TYPES.MYSQL:
|
|
3877
|
-
scriptContent += `mysqldump --single-transaction --routines --triggers ${database} | gzip > "$BACKUP_FILE"\n`;
|
|
3889
|
+
scriptContent += `mysqldump --single-transaction --routines --triggers ${shellQuote(database)} | gzip > "$BACKUP_FILE"\n`;
|
|
3878
3890
|
break;
|
|
3879
3891
|
case BACKUP_TYPES.POSTGRESQL:
|
|
3880
|
-
scriptContent += `pg_dump --format=custom --clean --if-exists ${database} | gzip > "$BACKUP_FILE"\n`;
|
|
3892
|
+
scriptContent += `pg_dump --format=custom --clean --if-exists ${shellQuote(database)} | gzip > "$BACKUP_FILE"\n`;
|
|
3881
3893
|
break;
|
|
3882
3894
|
case BACKUP_TYPES.MONGODB:
|
|
3883
|
-
scriptContent += `mongodump --db ${database} --out /tmp/mongo_\${RANDOM} && tar -czf "$BACKUP_FILE" -C /tmp mongo_*\n`;
|
|
3895
|
+
scriptContent += `mongodump --db ${shellQuote(database)} --out /tmp/mongo_\${RANDOM} && tar -czf "$BACKUP_FILE" -C /tmp mongo_*\n`;
|
|
3884
3896
|
break;
|
|
3885
3897
|
case BACKUP_TYPES.FILES:
|
|
3886
|
-
scriptContent += `tar -czf "$BACKUP_FILE" ${paths.join(' ')}\n`;
|
|
3898
|
+
scriptContent += `tar -czf "$BACKUP_FILE" ${(paths || []).map(shellQuote).join(' ')}\n`;
|
|
3887
3899
|
break;
|
|
3888
3900
|
}
|
|
3889
3901
|
|
|
3890
3902
|
// Add cleanup command
|
|
3891
3903
|
scriptContent += '\n# Cleanup old backups\n';
|
|
3892
|
-
scriptContent += `find "$BACKUP_DIR" -name "*_${name}_*" -type f -mtime +${retention} -delete\n`;
|
|
3904
|
+
scriptContent += `find "$BACKUP_DIR" -name "*_${name}_*" -type f -mtime +${safeInteger(retention, 7)} -delete\n`;
|
|
3893
3905
|
|
|
3894
|
-
// Save script to remote server
|
|
3895
|
-
|
|
3896
|
-
|
|
3906
|
+
// Save script to remote server. printf, not echo: dash's echo rewrites
|
|
3907
|
+
// backslashes, which would alter a quoted path inside the script.
|
|
3908
|
+
const quotedPath = shellQuote(scriptPath);
|
|
3909
|
+
await ssh.execCommand(`printf '%s' ${shellQuote(scriptContent)} > ${quotedPath} && chmod +x ${quotedPath}`);
|
|
3897
3910
|
|
|
3898
3911
|
// Add to crontab
|
|
3899
3912
|
const cronComment = `ssh-manager-backup-${name}`;
|
|
@@ -4824,7 +4837,7 @@ registerToolConditional(
|
|
|
4824
4837
|
registerToolConditional(
|
|
4825
4838
|
'ssh_db_query',
|
|
4826
4839
|
{
|
|
4827
|
-
description: 'Runs a read-only query against a remote database. For mysql and postgresql it is strictly limited to SELECT: the query must begin with SELECT and any insert, update, delete, drop, create, alter, truncate, grant, revoke, or exec keyword
|
|
4840
|
+
description: 'Runs a read-only query against a remote database. For mysql and postgresql it is strictly limited to one SELECT statement: the query must begin with SELECT, and INTO, file functions, and any insert, update, delete, drop, create, alter, truncate, grant, revoke, or exec keyword are rejected before execution; it then runs inside a read-only transaction, so the database itself refuses any write. For mongodb it runs a find() and requires the collection parameter; the query must be a filter document (JSON or mongo shell syntax such as ObjectId("…")), and $where, $function and $accumulator are refused. Returns the raw command output as text.',
|
|
4828
4841
|
inputSchema: {
|
|
4829
4842
|
server: z.string().describe('Server name'),
|
|
4830
4843
|
type: z.enum(['mysql', 'postgresql', 'mongodb'])
|
|
@@ -4886,7 +4899,11 @@ registerToolConditional(
|
|
|
4886
4899
|
// Execute query
|
|
4887
4900
|
const result = await ssh.execCommand(queryCommand);
|
|
4888
4901
|
|
|
4889
|
-
|
|
4902
|
+
// The MySQL JSON output is piped through awk, whose exit status hides the
|
|
4903
|
+
// client's: a write refused by the read-only transaction (ERROR 1792) or
|
|
4904
|
+
// a syntax error would otherwise come back as an empty result.
|
|
4905
|
+
const clientError = type === DB_TYPES.MYSQL && /^ERROR \d+/m.test(result.stderr || '');
|
|
4906
|
+
if (result.code !== 0 || clientError) {
|
|
4890
4907
|
throw new Error(`Query failed: ${result.stderr || result.stdout}`);
|
|
4891
4908
|
}
|
|
4892
4909
|
|