mcp-ssh-manager 3.8.4 → 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.
@@ -1,5 +1,6 @@
1
1
  import path from 'path';
2
2
  import crypto from 'crypto';
3
+ import { shellQuote } from './shell-quote.js';
3
4
 
4
5
  /**
5
6
  * Deploy helper functions for secure file deployment
@@ -11,8 +12,11 @@ import crypto from 'crypto';
11
12
  export function getTempFilename(originalName) {
12
13
  const timestamp = Date.now();
13
14
  const random = crypto.randomBytes(4).toString('hex');
14
- const ext = path.extname(originalName);
15
- const base = path.basename(originalName, ext);
15
+ // The local name is only a hint for whoever reads /tmp: keep the characters
16
+ // that need no quoting anywhere, so the name stays inert in every command.
17
+ const safe = text => text.replace(/[^A-Za-z0-9._-]/g, '_');
18
+ const ext = safe(path.extname(originalName));
19
+ const base = safe(path.basename(originalName, path.extname(originalName)));
16
20
  return `/tmp/${base}_${timestamp}_${random}${ext}`;
17
21
  }
18
22
 
@@ -33,11 +37,15 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
33
37
  requiresSudo: false
34
38
  };
35
39
 
40
+ // Every value below reaches the remote shell. Up to 3.8.5 the path sat in
41
+ // double quotes, where $(…) still runs, and owner and permissions were bare.
42
+ const target = shellQuote(remotePath);
43
+
36
44
  // Step 1: Backup existing file if requested
37
45
  if (backup) {
38
46
  strategy.steps.push({
39
47
  type: 'backup',
40
- command: `if [ -f "${remotePath}" ]; then cp "${remotePath}" "${remotePath}.bak.$(date +%Y%m%d_%H%M%S)"; fi`
48
+ command: `if [ -f ${target} ]; then cp ${target} ${target}.bak.$(date +%Y%m%d_%H%M%S); fi`
41
49
  });
42
50
  }
43
51
 
@@ -60,8 +68,8 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
60
68
 
61
69
  // Step 3: Copy from temp to final location
62
70
  const copyCmd = needsSudo ?
63
- `${sudoPrefix}cp {{tempFile}} "${remotePath}"` :
64
- `cp {{tempFile}} "${remotePath}"`;
71
+ `${sudoPrefix}cp {{tempFile}} ${target}` :
72
+ `cp {{tempFile}} ${target}`;
65
73
 
66
74
  strategy.steps.push(needsSudo ? withSudoStdin({
67
75
  type: 'copy',
@@ -75,7 +83,7 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
75
83
  if (owner) {
76
84
  strategy.steps.push(withSudoStdin({
77
85
  type: 'chown',
78
- command: `${sudoPrefix}chown ${owner} "${remotePath}"`
86
+ command: `${sudoPrefix}chown ${shellQuote(owner)} ${target}`
79
87
  }));
80
88
  }
81
89
 
@@ -83,7 +91,7 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
83
91
  if (permissions) {
84
92
  strategy.steps.push(withSudoStdin({
85
93
  type: 'chmod',
86
- command: `${sudoPrefix}chmod ${permissions} "${remotePath}"`
94
+ command: `${sudoPrefix}chmod ${shellQuote(permissions)} ${target}`
87
95
  }));
88
96
  }
89
97
 
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import { logger } from './logger.js';
7
+ import { shellQuote, safeInteger } from './shell-quote.js';
7
8
 
8
9
  // Health status levels
9
10
  export const HEALTH_STATUS = {
@@ -169,17 +170,21 @@ function determineOverallHealth(cpu, memory, disks) {
169
170
  * Build command to check service status (systemd or sysv)
170
171
  */
171
172
  export function buildServiceStatusCommand(serviceName) {
173
+ // serviceName is a tool argument: resolveServiceName returns non-aliases
174
+ // unchanged, so it reaches the shell as-is. Quoting every occurrence is what
175
+ // stops `nginx; id > /tmp/pwned` from executing (GHSA-m793-whw6-f537).
176
+ const name = shellQuote(serviceName);
172
177
  // Try systemd first, fallback to sysv
173
178
  return `
174
179
  if command -v systemctl >/dev/null 2>&1; then
175
- systemctl is-active ${serviceName} 2>/dev/null >/dev/null && echo "ACTIVE" || echo "INACTIVE"
176
- systemctl is-enabled ${serviceName} 2>/dev/null >/dev/null && echo "ENABLED" || echo "DISABLED"
177
- systemctl status ${serviceName} 2>/dev/null | grep "Main PID" | awk '{print $3}' | cut -d'(' -f1
178
- systemctl status ${serviceName} 2>/dev/null | grep "Active:" | sed 's/.*Active: //' | awk '{print $1,$2,$3}'
180
+ systemctl is-active ${name} 2>/dev/null >/dev/null && echo "ACTIVE" || echo "INACTIVE"
181
+ systemctl is-enabled ${name} 2>/dev/null >/dev/null && echo "ENABLED" || echo "DISABLED"
182
+ systemctl status ${name} 2>/dev/null | grep "Main PID" | awk '{print $3}' | cut -d'(' -f1
183
+ systemctl status ${name} 2>/dev/null | grep "Active:" | sed 's/.*Active: //' | awk '{print $1,$2,$3}'
179
184
  elif command -v service >/dev/null 2>&1; then
180
- service ${serviceName} status >/dev/null 2>&1 && echo "ACTIVE" || echo "INACTIVE"
185
+ service ${name} status >/dev/null 2>&1 && echo "ACTIVE" || echo "INACTIVE"
181
186
  echo "UNKNOWN"
182
- pgrep -f ${serviceName} | head -1 || echo ""
187
+ pgrep -f ${name} | head -1 || echo ""
183
188
  echo "sysv"
184
189
  else
185
190
  echo "UNKNOWN"
@@ -218,10 +223,10 @@ export function buildProcessListCommand(options = {}) {
218
223
  } = options;
219
224
 
220
225
  let sortFlag = sortBy === 'memory' ? '-m' : '-c'; // -c for CPU, -m for memory
221
- let command = `ps aux --sort=${sortFlag === '-c' ? '-pcpu' : '-pmem'} | head -n ${limit + 1}`;
226
+ let command = `ps aux --sort=${sortFlag === '-c' ? '-pcpu' : '-pmem'} | head -n ${safeInteger(limit, 20) + 1}`;
222
227
 
223
228
  if (filter) {
224
- command += ` | grep -i "${filter}"`;
229
+ command += ` | grep -i ${shellQuote(filter)}`;
225
230
  }
226
231
 
227
232
  // Format output as JSON-like structure
@@ -270,6 +275,11 @@ export function buildKillProcessCommand(pid, signal = 'TERM') {
270
275
  * Build command to get process info
271
276
  */
272
277
  export function buildProcessInfoCommand(pid) {
278
+ // Same guard as buildKillProcessCommand: a PID is a number, and anything else
279
+ // has no business reaching the shell.
280
+ if (!Number.isInteger(pid) || pid <= 0) {
281
+ throw new Error(`Invalid PID: ${pid}`);
282
+ }
273
283
  return `ps -p ${pid} -o user,pid,pcpu,pmem,vsz,rss,stat,start,time,cmd --no-headers | awk '{printf "{\\"user\\":\\"%s\\",\\"pid\\":%s,\\"cpu\\":%.1f,\\"mem\\":%.1f,\\"vsz\\":%s,\\"rss\\":%s,\\"stat\\":\\"%s\\",\\"start\\":\\"%s\\",\\"time\\":\\"%s\\",\\"command\\":\\"%s\\"}", $1,$2,$3,$4,$5,$6,$7,$8,$9,substr($0,index($0,$10))}'`;
274
284
  }
275
285
 
@@ -296,15 +306,14 @@ export function createAlertConfig(thresholds) {
296
306
  */
297
307
  export function buildSaveAlertConfigCommand(config, configPath = '/etc/ssh-manager-alerts.json') {
298
308
  const jsonData = JSON.stringify(config, null, 2);
299
- const escapedJson = jsonData.replace(/'/g, '\'\\\'\'');
300
- return `echo '${escapedJson}' > "${configPath}"`;
309
+ return `echo ${shellQuote(jsonData)} > ${shellQuote(configPath)}`;
301
310
  }
302
311
 
303
312
  /**
304
313
  * Build command to load alert config
305
314
  */
306
315
  export function buildLoadAlertConfigCommand(configPath = '/etc/ssh-manager-alerts.json') {
307
- return `cat "${configPath}" 2>/dev/null || echo '{}'`;
316
+ return `cat ${shellQuote(configPath)} 2>/dev/null || echo '{}'`;
308
317
  }
309
318
 
310
319
  /**
@@ -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 HOOKS_CONFIG_FILE = path.join(__dirname, '..', '.hooks-config.json');
18
- const HOOKS_DIR = path.join(__dirname, '..', 'hooks');
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: 'notification',
58
+ type: 'log',
38
59
  name: 'log-error',
39
- command: 'echo "[$(date)] Error on {server}: {error}" >> errors.log'
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: 'notification',
71
+ type: 'log',
50
72
  name: 'log-key-change',
51
- command: 'echo "[$(date)] SSH key change detected for {server} ({host}:{port})" >> ssh-key-changes.log'
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: 'notification',
83
+ type: 'log',
61
84
  name: 'log-key-updated',
62
- command: 'echo "[$(date)] SSH key {action} for {server} ({host}:{port})" >> ssh-key-changes.log'
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
- * Initialize hooks directory and configuration
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
- export async function initializeHooks() {
72
- // Create hooks directory if it doesn't exist
73
- if (!fs.existsSync(HOOKS_DIR)) {
74
- fs.mkdirSync(HOOKS_DIR, { recursive: true });
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
- // Merge profile hooks with defaults
78
- const mergedHooks = { ...DEFAULT_HOOKS, ...profileHooks };
257
+ return { command: out, values };
258
+ }
79
259
 
80
- // Create hooks configuration if it doesn't exist
81
- if (!fs.existsSync(HOOKS_CONFIG_FILE)) {
82
- saveHooksConfig(mergedHooks);
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
- // Start with profile hooks
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
- return hooks;
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 { ...DEFAULT_HOOKS, ...profileHooks };
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
- fs.writeFileSync(HOOKS_CONFIG_FILE, JSON.stringify(config, null, 2));
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, command, context);
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, command, context) {
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.remoteCommand && context.sshConnection) {
216
- // Execute on remote server
217
- const output = await context.sshConnection.execCommand(command, {
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
- const { stdout, stderr } = await execAsync(command);
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