(sql: string)
| 377 | * @throws {Error} If the statement is not a single read-only SELECT/WITH statement |
| 378 | */ |
| 379 | export const assertReadOnlySqlStatement = (sql: string): void => { |
| 380 | if (!sql || typeof sql !== 'string') { |
| 381 | throw new Error('Invalid SQL statement: statement is required and must be a string') |
| 382 | } |
| 383 | |
| 384 | let trimmed = sql.trim() |
| 385 | // Strip at most one trailing semicolon (+ trailing whitespace) |
| 386 | trimmed = trimmed.replace(/;\s*$/, '') |
| 387 | |
| 388 | if (trimmed.includes(';')) { |
| 389 | throw new Error('Invalid SQL statement: multiple statements are not allowed') |
| 390 | } |
| 391 | |
| 392 | if (!/^(SELECT|WITH)\b/i.test(trimmed)) { |
| 393 | throw new Error('Invalid SQL statement: only read-only SELECT/WITH statements are allowed') |
| 394 | } |
| 395 | |
| 396 | if (/load_extension\s*\(/i.test(trimmed)) { |
| 397 | throw new Error('Invalid SQL statement: load_extension is not allowed') |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | /** |
| 402 | * Sanitize a file name to prevent path traversal attacks. |
no test coverage detected