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.
@@ -7,6 +7,7 @@
7
7
  import path from 'path';
8
8
  import crypto from 'crypto';
9
9
  import { logger } from './logger.js';
10
+ import { shellQuote, safeInteger } from './shell-quote.js';
10
11
 
11
12
  // Backup types
12
13
  export const BACKUP_TYPES = {
@@ -61,23 +62,23 @@ export function buildMySQLDumpCommand(options) {
61
62
  let command = 'mysqldump';
62
63
 
63
64
  // Connection parameters
64
- if (user) command += ` -u${user}`;
65
- if (password) command += ` -p'${password}'`;
66
- if (host) command += ` -h ${host}`;
67
- if (port) command += ` -P ${port}`;
65
+ if (user) command += ` -u${shellQuote(user)}`;
66
+ if (password) command += ` -p${shellQuote(password)}`;
67
+ if (host) command += ` -h ${shellQuote(host)}`;
68
+ if (port) command += ` -P ${safeInteger(port, 3306)}`;
68
69
 
69
70
  // Dump options
70
71
  if (singleTransaction) command += ' --single-transaction';
71
72
  command += ' --routines --triggers';
72
73
 
73
74
  // Database name
74
- command += ` ${database}`;
75
+ command += ` ${shellQuote(database)}`;
75
76
 
76
77
  // Output handling
77
78
  if (compress) {
78
- command += ` | gzip > "${outputFile}"`;
79
+ command += ` | gzip > ${shellQuote(outputFile)}`;
79
80
  } else {
80
- command += ` > "${outputFile}"`;
81
+ command += ` > ${shellQuote(outputFile)}`;
81
82
  }
82
83
 
83
84
  return command;
@@ -100,27 +101,27 @@ export function buildPostgreSQLDumpCommand(options) {
100
101
  // PostgreSQL uses PGPASSWORD environment variable
101
102
  let command = '';
102
103
  if (password) {
103
- command = `PGPASSWORD='${password}' `;
104
+ command = `PGPASSWORD=${shellQuote(password)} `;
104
105
  }
105
106
 
106
107
  command += 'pg_dump';
107
108
 
108
109
  // Connection parameters
109
- if (user) command += ` -U ${user}`;
110
- if (host) command += ` -h ${host}`;
111
- if (port) command += ` -p ${port}`;
110
+ if (user) command += ` -U ${shellQuote(user)}`;
111
+ if (host) command += ` -h ${shellQuote(host)}`;
112
+ if (port) command += ` -p ${safeInteger(port, 5432)}`;
112
113
 
113
114
  // Dump options
114
115
  command += ' --format=custom --clean --if-exists';
115
116
 
116
117
  // Database name
117
- command += ` ${database}`;
118
+ command += ` ${shellQuote(database)}`;
118
119
 
119
120
  // Output handling
120
121
  if (compress) {
121
- command += ` | gzip > "${outputFile}"`;
122
+ command += ` | gzip > ${shellQuote(outputFile)}`;
122
123
  } else {
123
- command += ` > "${outputFile}"`;
124
+ command += ` > ${shellQuote(outputFile)}`;
124
125
  }
125
126
 
126
127
  return command;
@@ -143,22 +144,24 @@ export function buildMongoDBDumpCommand(options) {
143
144
  let command = 'mongodump';
144
145
 
145
146
  // Connection parameters
146
- if (host) command += ` --host ${host}`;
147
- if (port) command += ` --port ${port}`;
148
- if (user) command += ` --username ${user}`;
149
- if (password) command += ` --password '${password}'`;
147
+ if (host) command += ` --host ${shellQuote(host)}`;
148
+ if (port) command += ` --port ${safeInteger(port, 27017)}`;
149
+ if (user) command += ` --username ${shellQuote(user)}`;
150
+ if (password) command += ` --password ${shellQuote(password)}`;
150
151
 
151
152
  // Database selection
152
- if (database) command += ` --db ${database}`;
153
+ if (database) command += ` --db ${shellQuote(database)}`;
153
154
 
154
155
  // Output directory
155
- command += ` --out "${outputDir}"`;
156
+ command += ` --out ${shellQuote(outputDir)}`;
156
157
 
157
158
  // Compress the output directory
158
159
  if (compress) {
159
160
  const archiveName = `${outputDir}.tar.gz`;
160
- command += ` && tar -czf "${archiveName}" -C "$(dirname ${outputDir})" "$(basename ${outputDir})"`;
161
- command += ` && rm -rf "${outputDir}"`;
161
+ // dirname/basename receive the quoted value, so the substitution itself
162
+ // cannot be steered by the caller.
163
+ command += ` && tar -czf ${shellQuote(archiveName)} -C "$(dirname ${shellQuote(outputDir)})" "$(basename ${shellQuote(outputDir)})"`;
164
+ command += ` && rm -rf ${shellQuote(outputDir)}`;
162
165
  }
163
166
 
164
167
  return command;
@@ -189,15 +192,15 @@ export function buildFilesBackupCommand(options) {
189
192
  }
190
193
 
191
194
  // Output file
192
- command += ` "${outputFile}"`;
195
+ command += ` ${shellQuote(outputFile)}`;
193
196
 
194
197
  // Exclude patterns
195
198
  for (const pattern of exclude) {
196
- command += ` --exclude="${pattern}"`;
199
+ command += ` --exclude=${shellQuote(pattern)}`;
197
200
  }
198
201
 
199
202
  // Paths to backup
200
- command += ` ${paths.map(p => `"${p}"`).join(' ')}`;
203
+ command += ` ${paths.map(p => shellQuote(p)).join(' ')}`;
201
204
 
202
205
  return command;
203
206
  }
@@ -236,19 +239,19 @@ function buildMySQLRestoreCommand(backupFile, options) {
236
239
 
237
240
  // Decompress if needed
238
241
  if (backupFile.endsWith('.gz')) {
239
- command = `gunzip -c "${backupFile}" | `;
242
+ command = `gunzip -c ${shellQuote(backupFile)} | `;
240
243
  } else {
241
- command = `cat "${backupFile}" | `;
244
+ command = `cat ${shellQuote(backupFile)} | `;
242
245
  }
243
246
 
244
247
  command += 'mysql';
245
248
 
246
249
  // Connection parameters
247
- if (user) command += ` -u${user}`;
248
- if (password) command += ` -p'${password}'`;
249
- if (host) command += ` -h ${host}`;
250
- if (port) command += ` -P ${port}`;
251
- if (database) command += ` ${database}`;
250
+ if (user) command += ` -u${shellQuote(user)}`;
251
+ if (password) command += ` -p${shellQuote(password)}`;
252
+ if (host) command += ` -h ${shellQuote(host)}`;
253
+ if (port) command += ` -P ${safeInteger(port, 3306)}`;
254
+ if (database) command += ` ${shellQuote(database)}`;
252
255
 
253
256
  return command;
254
257
  }
@@ -267,25 +270,25 @@ function buildPostgreSQLRestoreCommand(backupFile, options) {
267
270
 
268
271
  let command = '';
269
272
  if (password) {
270
- command = `PGPASSWORD='${password}' `;
273
+ command = `PGPASSWORD=${shellQuote(password)} `;
271
274
  }
272
275
 
273
276
  command += 'pg_restore';
274
277
 
275
278
  // Connection parameters
276
- if (user) command += ` -U ${user}`;
277
- if (host) command += ` -h ${host}`;
278
- if (port) command += ` -p ${port}`;
279
- if (database) command += ` -d ${database}`;
279
+ if (user) command += ` -U ${shellQuote(user)}`;
280
+ if (host) command += ` -h ${shellQuote(host)}`;
281
+ if (port) command += ` -p ${safeInteger(port, 5432)}`;
282
+ if (database) command += ` -d ${shellQuote(database)}`;
280
283
 
281
284
  // Restore options
282
285
  command += ' --clean --if-exists';
283
286
 
284
287
  // Handle compressed files
285
288
  if (backupFile.endsWith('.gz')) {
286
- command = `gunzip -c "${backupFile}" | ${command}`;
289
+ command = `gunzip -c ${shellQuote(backupFile)} | ${command}`;
287
290
  } else {
288
- command += ` "${backupFile}"`;
291
+ command += ` ${shellQuote(backupFile)}`;
289
292
  }
290
293
 
291
294
  return command;
@@ -308,25 +311,25 @@ function buildMongoDBRestoreCommand(backupFile, options) {
308
311
  // Extract if compressed
309
312
  if (backupFile.endsWith('.tar.gz')) {
310
313
  const extractDir = backupFile.replace('.tar.gz', '');
311
- command = `tar -xzf "${backupFile}" -C "$(dirname ${backupFile})" && `;
314
+ command = `tar -xzf ${shellQuote(backupFile)} -C "$(dirname ${shellQuote(backupFile)})" && `;
312
315
  command += 'mongorestore';
313
316
 
314
317
  if (drop) command += ' --drop';
315
- if (host) command += ` --host ${host}`;
316
- if (port) command += ` --port ${port}`;
317
- if (user) command += ` --username ${user}`;
318
- if (password) command += ` --password '${password}'`;
318
+ if (host) command += ` --host ${shellQuote(host)}`;
319
+ if (port) command += ` --port ${safeInteger(port, 27017)}`;
320
+ if (user) command += ` --username ${shellQuote(user)}`;
321
+ if (password) command += ` --password ${shellQuote(password)}`;
319
322
 
320
- command += ` "${extractDir}"`;
321
- command += ` && rm -rf "${extractDir}"`;
323
+ command += ` ${shellQuote(extractDir)}`;
324
+ command += ` && rm -rf ${shellQuote(extractDir)}`;
322
325
  } else {
323
326
  command = 'mongorestore';
324
327
  if (drop) command += ' --drop';
325
- if (host) command += ` --host ${host}`;
326
- if (port) command += ` --port ${port}`;
327
- if (user) command += ` --username ${user}`;
328
- if (password) command += ` --password '${password}'`;
329
- command += ` "${backupFile}"`;
328
+ if (host) command += ` --host ${shellQuote(host)}`;
329
+ if (port) command += ` --port ${safeInteger(port, 27017)}`;
330
+ if (user) command += ` --username ${shellQuote(user)}`;
331
+ if (password) command += ` --password ${shellQuote(password)}`;
332
+ command += ` ${shellQuote(backupFile)}`;
330
333
  }
331
334
 
332
335
  return command;
@@ -347,8 +350,8 @@ function buildFilesRestoreCommand(backupFile, options) {
347
350
  command += ' -xf';
348
351
  }
349
352
 
350
- command += ` "${backupFile}"`;
351
- command += ` -C "${targetPath}"`;
353
+ command += ` ${shellQuote(backupFile)}`;
354
+ command += ` -C ${shellQuote(targetPath)}`;
352
355
 
353
356
  return command;
354
357
  }
@@ -377,19 +380,20 @@ export function createBackupMetadata(backupId, type, options = {}) {
377
380
  */
378
381
  export function buildSaveMetadataCommand(metadata, metadataPath) {
379
382
  const jsonData = JSON.stringify(metadata, null, 2);
380
- // Escape single quotes in JSON for shell
381
- const escapedJson = jsonData.replace(/'/g, '\'\\\'\'');
382
- return `echo '${escapedJson}' > "${metadataPath}"`;
383
+ // The metadata carries caller-supplied fields (database name, paths...), so
384
+ // both the payload and the destination go through shellQuote rather than
385
+ // hand-rolled escaping.
386
+ return `echo ${shellQuote(jsonData)} > ${shellQuote(metadataPath)}`;
383
387
  }
384
388
 
385
389
  /**
386
390
  * Build command to list backups from remote server
387
391
  */
388
392
  export function buildListBackupsCommand(backupDir = DEFAULT_BACKUP_DIR, type = null) {
389
- let command = `find "${backupDir}" -name "*.meta.json" -type f`;
393
+ let command = `find ${shellQuote(backupDir)} -name '*.meta.json' -type f`;
390
394
 
391
395
  if (type) {
392
- command += ` | grep "${type}_"`;
396
+ command += ` | grep ${shellQuote(`${type}_`)}`;
393
397
  }
394
398
 
395
399
  // Read and parse each metadata file
@@ -427,14 +431,40 @@ export function parseBackupsList(output) {
427
431
  */
428
432
  export function buildCleanupCommand(backupDir = DEFAULT_BACKUP_DIR, retentionDays = 7) {
429
433
  // Find backup files older than retention period and delete them
430
- return `find "${backupDir}" -name "*_*_*" -type f -mtime +${retentionDays} -delete`;
434
+ return `find ${shellQuote(backupDir)} -name '*_*_*' -type f -mtime +${safeInteger(retentionDays, 7)} -delete`;
431
435
  }
432
436
 
433
437
  /**
434
438
  * Build cron schedule command
435
439
  */
436
440
  export function buildCronScheduleCommand(schedule, backupCommand, cronComment) {
437
- // Add cron job with comment
438
- const cronLine = `${schedule} ${backupCommand} # ${cronComment}`;
439
- return `(crontab -l 2>/dev/null; echo '${cronLine}') | crontab -`;
441
+ // A crontab line is data here, not a command to evaluate: the whole line goes
442
+ // through shellQuote so a schedule or comment carrying quotes cannot break
443
+ // out of the echo and run something else. backupCommand is built by the
444
+ // builders above, which quote their own arguments.
445
+ //
446
+ // Quoting the echo was the 3.8.5 fix, and it was not enough: cron reads
447
+ // everything after the fifth field as the command to run, and a line break
448
+ // as the start of another job, so `* * * * * curl … | sh #` installed a job
449
+ // of the caller's choosing. The schedule must now be a schedule.
450
+ if (!isCronSchedule(schedule)) {
451
+ throw new Error('Schedule must be five cron fields (e.g. "0 2 * * *") or a macro such as @daily');
452
+ }
453
+ const comment = String(cronComment).replace(/[\r\n]+/g, ' ');
454
+ const cronLine = `${schedule.trim()} ${backupCommand} # ${comment}`;
455
+ return `(crontab -l 2>/dev/null; echo ${shellQuote(cronLine)}) | crontab -`;
456
+ }
457
+
458
+ /**
459
+ * Whether a string is a crontab schedule and nothing more: five time fields,
460
+ * or one of cron's @ macros.
461
+ * @param {any} schedule
462
+ * @returns {boolean}
463
+ */
464
+ export function isCronSchedule(schedule) {
465
+ if (typeof schedule !== 'string') return false;
466
+ const text = schedule.trim();
467
+ if (/^@(yearly|annually|monthly|weekly|daily|midnight|hourly|reboot)$/.test(text)) return true;
468
+ const fields = text.split(/[ \t]+/);
469
+ return fields.length === 5 && fields.every(field => /^[0-9A-Za-z*/,-]+$/.test(field));
440
470
  }
@@ -3,15 +3,18 @@
3
3
  * Provides shortcuts for frequently used commands
4
4
  */
5
5
 
6
- import fs from 'fs';
7
6
  import path from 'path';
8
7
  import { fileURLToPath } from 'url';
9
8
  import { loadProfile } from './profile-loader.js';
9
+ import { readUserState, writeUserState } from './user-state.js';
10
10
 
11
11
  const __filename = fileURLToPath(import.meta.url);
12
12
  const __dirname = path.dirname(__filename);
13
13
 
14
- const ALIASES_FILE = path.join(__dirname, '..', '.command-aliases.json');
14
+ // Custom aliases live in the manager home; the package copy is read only as a
15
+ // fallback for a source checkout (see user-state.js, issue #87).
16
+ const ALIASES_NAME = 'command-aliases.json';
17
+ const LEGACY_ALIASES_FILE = path.join(__dirname, '..', '.command-aliases.json');
15
18
 
16
19
  // Get aliases from the active profile
17
20
  let profileAliases = {};
@@ -31,9 +34,9 @@ export function loadCommandAliases() {
31
34
  let aliases = { ...profileAliases };
32
35
 
33
36
  // Merge with custom aliases from file
34
- if (fs.existsSync(ALIASES_FILE)) {
35
- const data = fs.readFileSync(ALIASES_FILE, 'utf8');
36
- aliases = { ...aliases, ...JSON.parse(data) };
37
+ const state = readUserState(ALIASES_NAME, LEGACY_ALIASES_FILE);
38
+ if (state) {
39
+ aliases = { ...aliases, ...JSON.parse(state.text) };
37
40
  }
38
41
 
39
42
  return aliases;
@@ -56,7 +59,7 @@ function saveCommandAliases(aliases) {
56
59
  }
57
60
  }
58
61
 
59
- fs.writeFileSync(ALIASES_FILE, JSON.stringify(customAliases, null, 2));
62
+ writeUserState(ALIASES_NAME, JSON.stringify(customAliases, null, 2));
60
63
  return true;
61
64
  } catch (error) {
62
65
  console.error(`Error saving command aliases: ${error.message}`);
@@ -0,0 +1,12 @@
1
+ import os from 'os';
2
+ import path from 'path';
3
+
4
+ /**
5
+ * The directory that holds this user's settings and state: SSH_MANAGER_HOME,
6
+ * or ~/.ssh-manager. Read at call time so a test or a host that sets the
7
+ * variable after import still gets its own directory.
8
+ * @returns {string}
9
+ */
10
+ export function managerHome() {
11
+ return process.env.SSH_MANAGER_HOME || path.join(os.homedir(), '.ssh-manager');
12
+ }
@@ -12,25 +12,8 @@ export const DB_TYPES = {
12
12
 
13
13
  // A single quote character as a constant, so shellQuote()'s escaping stays
14
14
  // readable under the repo's single-quote lint style.
15
- const SQ = '\'';
16
-
17
- /**
18
- * Quote a value for safe inclusion as a single POSIX shell word.
19
- *
20
- * Wraps the value in single quotes and escapes any embedded single quote as
21
- * '\'' so the remote shell treats it literally — it never interprets $(...),
22
- * backticks, $VAR, ;, |, &, redirects, spaces, or newlines inside the value.
23
- * EVERY caller-controlled value interpolated into a database command string
24
- * MUST go through this: the database/table/collection names, file paths, and
25
- * connection fields all arrive from tool arguments (issue #48 — command
26
- * injection via ssh_db_list / ssh_db_dump / ssh_db_import builder arguments).
27
- * Numbers are coerced to string; null/undefined become an empty quoted word.
28
- */
29
- export function shellQuote(value) {
30
- if (value === null || value === undefined) return SQ + SQ;
31
- // Replace every ' with '\'' (close quote, escaped quote, reopen), then wrap.
32
- return SQ + String(value).replace(/'/g, SQ + '\\' + SQ + SQ) + SQ;
33
- }
15
+ import { shellQuote } from './shell-quote.js';
16
+ export { shellQuote };
34
17
 
35
18
  /**
36
19
  * Build MySQL dump command
@@ -410,6 +393,7 @@ export function buildMySQLQueryCommand(options) {
410
393
  if (!isSafeQuery(query)) {
411
394
  throw new Error('Only SELECT queries are allowed');
412
395
  }
396
+ const script = readOnlyScript(DB_TYPES.MYSQL, query);
413
397
 
414
398
  let command = 'mysql';
415
399
  if (user) command += ` -u${shellQuote(user)}`;
@@ -425,9 +409,9 @@ export function buildMySQLQueryCommand(options) {
425
409
  // Use JSON output if MySQL 5.7.8+. The awk pipe stays on the heredoc opening line so
426
410
  // the terminator remains alone on its own line.
427
411
  const awk = 'awk \'BEGIN{print "["} {if(NR>1)print ","; printf "{\\"row\\":%d,\\"data\\":\\"%s\\"}", NR, $0} END{print "]"}\'';
428
- command += ` --batch --skip-column-names${buildHeredoc(query, { pipeline: `| ${awk}` })}`;
412
+ command += ` --batch --skip-column-names${buildHeredoc(script, { pipeline: `| ${awk}` })}`;
429
413
  } else {
430
- command += buildHeredoc(query);
414
+ command += buildHeredoc(script);
431
415
  }
432
416
 
433
417
  return command;
@@ -448,14 +432,16 @@ export function buildPostgreSQLQueryCommand(options) {
448
432
  command = `PGPASSWORD=${shellQuote(password)} `;
449
433
  }
450
434
 
451
- command += 'psql';
435
+ // -q keeps the BEGIN/ROLLBACK of the read-only wrapper out of the output, and
436
+ // ON_ERROR_STOP keeps the query from running if the wrapper itself fails.
437
+ command += 'psql -q -v ON_ERROR_STOP=1';
452
438
  if (user) command += ` -U ${shellQuote(user)}`;
453
439
  if (host) command += ` -h ${shellQuote(host)}`;
454
440
  if (port) command += ` -p ${shellQuote(port)}`;
455
441
  command += ` -d ${shellQuote(database)}`;
456
442
  // Feed SQL via stdin (quoted heredoc) instead of `-c "${query}"` so the remote shell
457
443
  // never parses it. See buildHeredoc and issue #44.
458
- command += buildHeredoc(query);
444
+ command += buildHeredoc(readOnlyScript(DB_TYPES.POSTGRESQL, query));
459
445
 
460
446
  return command;
461
447
  }
@@ -473,38 +459,214 @@ export function buildMongoDBQueryCommand(options) {
473
459
  if (password) command += ` --password ${shellQuote(password)}`;
474
460
  command += ` ${shellQuote(database)}`;
475
461
  // Feed the JS script via stdin (quoted heredoc) instead of `--eval "..."` so the
476
- // remote shell never expands backticks/`$` in the query. mongo still evaluates the
477
- // script as JavaScript (expected). See buildHeredoc and issue #44.
478
- const script = `db.${collection}.find(${query || '{}'}).forEach(printjson)`;
462
+ // remote shell never expands backticks/`$` in the query. See buildHeredoc and issue #44.
463
+ //
464
+ // The heredoc only keeps the shell out: mongo evaluates the script as
465
+ // JavaScript. Up to 3.8.5 the collection and the query were spliced into it
466
+ // raw, so `{}).forEach(printjson); db.dropDatabase(); db.x.find({` ran on a
467
+ // tool documented as read-only (GHSA-q37w-vhpx-q5q9). The collection now
468
+ // travels as a string literal, and the query must parse as a plain filter
469
+ // document: literals and a few type constructors, never code.
470
+ const filter = query && query.trim() ? checkMongoFilter(query) : '{}';
471
+ const script = `db.getCollection(${jsString(collection)}).find(${filter}).forEach(printjson)`;
479
472
  command += ` --quiet${buildHeredoc(script)}`;
480
473
 
481
474
  return command;
482
475
  }
483
476
 
484
477
  /**
485
- * Validate query is safe (SELECT only)
478
+ * A JavaScript string literal for any text. JSON.stringify leaves U+2028 and
479
+ * U+2029 raw, which older JavaScript engines read as line breaks.
480
+ * @param {any} value
481
+ */
482
+ function jsString(value) {
483
+ if (typeof value !== 'string' || !value || value.includes('\0')) {
484
+ throw new Error('A MongoDB collection name must be a non-empty string');
485
+ }
486
+ return JSON.stringify(value).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
487
+ }
488
+
489
+ // Constructors a filter document may call, as the mongo shell spells them.
490
+ const MONGO_CONSTRUCTORS = new Set([
491
+ 'ObjectId', 'ISODate', 'Date', 'NumberLong', 'NumberInt', 'NumberDecimal',
492
+ 'Timestamp', 'UUID', 'BinData', 'MinKey', 'MaxKey', 'RegExp',
493
+ ]);
494
+ // Operators that run JavaScript on the database server.
495
+ const MONGO_CODE_OPERATORS = new Set(['$where', '$function', '$accumulator']);
496
+
497
+ /**
498
+ * Check that a MongoDB query is a filter document and nothing else, and
499
+ * return it unchanged. Accepted: JSON, or the mongo shell's relaxed form
500
+ * (unquoted keys, single-quoted strings, regex literals, ObjectId("…") and
501
+ * the other constructors above). Refused: anything that is code — function
502
+ * calls outside that list, property access, operators, statements — and the
503
+ * operators that evaluate JavaScript on the server ($where, $function,
504
+ * $accumulator), which a read-only tool has no use for.
505
+ * @param {string} query
506
+ * @returns {string}
507
+ */
508
+ export function checkMongoFilter(query) {
509
+ const text = String(query);
510
+ let i = 0;
511
+ const fail = (what) => {
512
+ throw new Error(`MongoDB query must be a filter document such as {"status": "active"}: ${what} at offset ${i}`);
513
+ };
514
+ const skip = () => { while (i < text.length && /\s/.test(text[i])) i++; };
515
+ const identifier = () => {
516
+ const m = /^[$A-Za-z_][\w$]*/.exec(text.slice(i));
517
+ if (!m) return null;
518
+ i += m[0].length;
519
+ return m[0];
520
+ };
521
+ const string = () => {
522
+ const quote = text[i];
523
+ let value = '';
524
+ i++;
525
+ while (i < text.length && text[i] !== quote) {
526
+ if (text[i] === '\n' || text[i] === '\r') fail('a line break inside a string');
527
+ if (text[i] === '\\') { value += text[i + 1]; i += 2; continue; }
528
+ value += text[i++];
529
+ }
530
+ if (i >= text.length) fail('an unterminated string');
531
+ i++;
532
+ return value;
533
+ };
534
+ const number = () => {
535
+ const m = /^-?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(text.slice(i));
536
+ if (!m) return false;
537
+ i += m[0].length;
538
+ return true;
539
+ };
540
+ const value = () => {
541
+ skip();
542
+ const ch = text[i];
543
+ if (ch === '{') return object();
544
+ if (ch === '[') return array();
545
+ if (ch === '"' || ch === '\'') { string(); return; }
546
+ if (ch === '/') {
547
+ const m = /^\/(?:\\.|[^/\\\n])+\/[gimsuy]*/.exec(text.slice(i));
548
+ if (!m) fail('an invalid regular expression');
549
+ i += m[0].length;
550
+ return;
551
+ }
552
+ if (number()) return;
553
+ const start = i;
554
+ let name = identifier();
555
+ if (name === 'new') { skip(); name = identifier(); }
556
+ if (name === 'true' || name === 'false' || name === 'null' || name === 'undefined') return;
557
+ if (name && MONGO_CONSTRUCTORS.has(name)) {
558
+ skip();
559
+ if (text[i] !== '(') fail(`${name} without arguments`);
560
+ i++;
561
+ skip();
562
+ while (text[i] !== ')') {
563
+ skip();
564
+ if (text[i] === '"' || text[i] === '\'') string();
565
+ else if (!number()) fail(`an argument to ${name} that is not a string or a number`);
566
+ skip();
567
+ if (text[i] === ',') { i++; continue; }
568
+ if (text[i] !== ')') fail(`an unterminated ${name}(`);
569
+ }
570
+ i++;
571
+ return;
572
+ }
573
+ i = start;
574
+ fail(name ? `"${name}", which is not a value` : 'something that is not a value');
575
+ };
576
+ const key = () => {
577
+ skip();
578
+ const ch = text[i];
579
+ const name = ch === '"' || ch === '\'' ? string() : identifier() ?? (number() ? '' : fail('a key that is not a name'));
580
+ if (MONGO_CODE_OPERATORS.has(name)) fail(`${name}, which runs JavaScript on the server`);
581
+ };
582
+ const object = () => {
583
+ i++;
584
+ skip();
585
+ while (text[i] !== '}') {
586
+ key();
587
+ skip();
588
+ if (text[i] !== ':') fail('a missing ":"');
589
+ i++;
590
+ value();
591
+ skip();
592
+ if (text[i] === ',') { i++; skip(); continue; }
593
+ if (text[i] !== '}') fail('a missing "," or "}"');
594
+ }
595
+ i++;
596
+ };
597
+ const array = () => {
598
+ i++;
599
+ skip();
600
+ while (text[i] !== ']') {
601
+ value();
602
+ skip();
603
+ if (text[i] === ',') { i++; skip(); continue; }
604
+ if (text[i] !== ']') fail('a missing "," or "]"');
605
+ }
606
+ i++;
607
+ };
608
+
609
+ skip();
610
+ if (text[i] !== '{') fail('no opening "{"');
611
+ object();
612
+ skip();
613
+ if (i < text.length) fail('text after the filter');
614
+ return text.trim();
615
+ }
616
+
617
+ // Words a read-only SELECT has no business containing. The statement verbs
618
+ // were always refused; INTO and the file functions were not, and a SELECT can
619
+ // write: `SELECT … INTO OUTFILE` writes a file on the database server
620
+ // (GHSA-9w6j-vg8f-hp8g), `SELECT … INTO new_table` creates a table in
621
+ // PostgreSQL, and the server-file functions read or write outside the
622
+ // database. Matched as whole words, case-insensitively.
623
+ const FORBIDDEN_SQL_WORDS = [
624
+ 'insert', 'update', 'delete', 'drop', 'create', 'alter',
625
+ 'truncate', 'grant', 'revoke', 'exec', 'execute',
626
+ 'into', 'outfile', 'dumpfile', 'load_file', 'sys_exec', 'sys_eval',
627
+ 'pg_read_file', 'pg_read_binary_file', 'pg_ls_dir', 'pg_stat_file',
628
+ 'pg_file_write', 'pg_file_rename', 'pg_file_unlink',
629
+ 'lo_import', 'lo_export', 'lo_from_bytea', 'lo_put', 'lo_create', 'lo_unlink',
630
+ 'dblink', 'dblink_exec', 'pg_terminate_backend', 'pg_cancel_backend',
631
+ 'pg_reload_conf', 'pg_rotate_logfile', 'pg_promote', 'set_config',
632
+ ];
633
+ const FORBIDDEN_SQL = new RegExp(`\\b(${FORBIDDEN_SQL_WORDS.join('|')})\\b`, 'i');
634
+
635
+ /**
636
+ * Validate query is safe (SELECT only): one statement, beginning with SELECT,
637
+ * containing none of the words above. The builders also run it inside a
638
+ * read-only transaction, which catches what a word list cannot see, such as a
639
+ * stored function that writes.
486
640
  */
487
641
  export function isSafeQuery(query) {
488
- const trimmedQuery = query.trim().toLowerCase();
642
+ if (typeof query !== 'string') return false;
643
+ const statement = query.trim().replace(/;\s*$/, '');
489
644
 
490
645
  // Must start with SELECT
491
- if (!trimmedQuery.startsWith('select')) {
646
+ if (!/^select\b/i.test(statement)) {
492
647
  return false;
493
648
  }
494
649
 
495
- // Block dangerous keywords
496
- const dangerousKeywords = [
497
- 'insert', 'update', 'delete', 'drop', 'create', 'alter',
498
- 'truncate', 'grant', 'revoke', 'exec', 'execute'
499
- ];
500
-
501
- for (const keyword of dangerousKeywords) {
502
- if (trimmedQuery.includes(keyword)) {
503
- return false;
504
- }
650
+ // One statement only: a second one would run after the check, unchecked.
651
+ if (statement.includes(';')) {
652
+ return false;
505
653
  }
506
654
 
507
- return true;
655
+ return !FORBIDDEN_SQL.test(statement);
656
+ }
657
+
658
+ /**
659
+ * The SQL fed to the client: the query inside a read-only transaction. The
660
+ * database then refuses any write the query would make, including one hidden
661
+ * in a function it calls (MySQL 5.6.5+, MariaDB 10.0+, every PostgreSQL).
662
+ * @param {string} type - DB_TYPES.MYSQL or DB_TYPES.POSTGRESQL
663
+ * @param {string} query - A query that passed isSafeQuery
664
+ */
665
+ function readOnlyScript(type, query) {
666
+ const statement = query.trim().replace(/;\s*$/, '');
667
+ return type === DB_TYPES.MYSQL
668
+ ? `SET SESSION TRANSACTION READ ONLY;\n${statement};`
669
+ : `BEGIN TRANSACTION READ ONLY;\n${statement};\nROLLBACK;`;
508
670
  }
509
671
 
510
672
  /**