@b2y/ai-service 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,983 @@
1
+ import libpgQuery from "libpg-query";
2
+ import { createHash } from "node:crypto";
3
+ import { AiServiceError, ErrorCodes } from "../core/Errors.js";
4
+ import { brandValidatedQuery, isSqlPolicy, reject, relationshipKey, SqlValidationCodes } from "./SqlPolicy.js";
5
+
6
+ /**
7
+ * Small, type-safe accessors over the JSON parse tree from libpg-query. Every node is an object with a single key naming its type ({ "SelectStmt": { ... } }); lists are plain arrays.
8
+ * @typedef {Readonly<Record<string, unknown>>} Json
9
+ */
10
+
11
+ /** Small, type-safe accessors over the JSON parse tree from libpg-query. */
12
+
13
+ export function asObject(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
15
+ }
16
+
17
+ export function asArray(value) {
18
+ return Array.isArray(value) ? value : [];
19
+ }
20
+
21
+ /** [type, body] of a wrapped node, or undefined when the value is not a single-key node. */
22
+ export function nodeOf(value) {
23
+ const object = asObject(value);
24
+ if (object === undefined) return undefined;
25
+ const keys = Object.keys(object);
26
+ if (keys.length !== 1) return undefined;
27
+ const type = keys[0] ?? "";
28
+ const body = asObject(object[type]);
29
+ return body === undefined ? undefined : [type, body];
30
+ }
31
+
32
+ export function asString(value) {
33
+ return typeof value === "string" ? value : undefined;
34
+ }
35
+
36
+ /** The sval strings of a list of { String: { sval } } nodes, or undefined if any entry is something else. */
37
+ export function stringList(value) {
38
+ const out = [];
39
+ for (const item of asArray(value)) {
40
+ const node = nodeOf(item);
41
+ if (node?.[0] !== "String") return undefined;
42
+ const text = asString(node[1].sval);
43
+ if (text === undefined) return undefined;
44
+ out.push(text);
45
+ }
46
+ return out;
47
+ }
48
+
49
+ export function locationOf(body) {
50
+ const location = body.location;
51
+ return typeof location === "number" && location >= 0 ? location : undefined;
52
+ }
53
+
54
+ /** Integer value of an A_Const node (ival; libpg-query omits 0 as {}), or undefined for other constants. */
55
+ export function integerConst(value) {
56
+ const node = nodeOf(value);
57
+ if (node?.[0] !== "A_Const") return undefined;
58
+ const ival = asObject(node[1].ival);
59
+ if (ival === undefined) return undefined;
60
+ const number = ival.ival;
61
+ return number === undefined ? 0 : typeof number === "number" ? number : undefined;
62
+ }
63
+
64
+ /** JSON of a node without location fields, for comparing expressions structurally. */
65
+ export function structuralKey(value) {
66
+ return JSON.stringify(value, (key, inner) => (key === "location" ? undefined : inner));
67
+ }
68
+
69
+ /** Counts nodes and maximum nesting depth of a parse tree, iteratively (no recursion limit issues). */
70
+ export function treeSize(root) {
71
+ let nodes = 0;
72
+ let depth = 0;
73
+ const stack = [{ value: root, level: 0 }];
74
+ while (stack.length > 0) {
75
+ const entry = stack.pop();
76
+ if (entry === undefined) break;
77
+ const { value, level } = entry;
78
+ if (typeof value !== "object" || value === null) continue;
79
+ nodes += 1;
80
+ depth = Math.max(depth, level);
81
+ for (const child of Array.isArray(value) ? value : Object.values(value)) {
82
+ stack.push({ value: child, level: level + 1 });
83
+ }
84
+ }
85
+ return { nodes, depth };
86
+ }
87
+
88
+ /**
89
+ * Checks on the raw text before parsing, for things the parse tree no longer shows: - comments (-- and slash-
90
+ * star), which can hide text from reviewers and from the appended LIMIT - dollar quoting and $n parameters
91
+ * (the package adds its own parameters) - prefixed string literals (E'', U&'', B'', X'', N''), whose escapes
92
+ * make offset-based rewriting unsafe - a semicolon anywhere except one trailing statement terminator -
93
+ * control characters other than tab, line feed and carriage return Returns the statement without its trailing
94
+ * semicolon, or a rejection.
95
+ */
96
+ export function lexicalCheck(sql, maxChars, allowParams = false) {
97
+ const trimmed = sql.trim();
98
+ if (trimmed === "") return reject(SqlValidationCodes.SQL_EMPTY, "SQL is empty");
99
+ if (trimmed.length > maxChars)
100
+ return reject(SqlValidationCodes.SQL_TOO_LONG, `SQL is longer than ${String(maxChars)} characters`);
101
+ for (const character of trimmed) {
102
+ const code = character.charCodeAt(0);
103
+ if ((code < 32 && code !== 9 && code !== 10 && code !== 13) || code === 127) {
104
+ return reject(SqlValidationCodes.SQL_INVALID_CHARACTERS, "SQL contains control characters");
105
+ }
106
+ }
107
+
108
+ const body = trimmed.endsWith(";") ? trimmed.slice(0, -1).trimEnd() : trimmed;
109
+ let state = "code";
110
+ for (let index = 0; index < body.length; index += 1) {
111
+ const character = body[index];
112
+ const next = body[index + 1];
113
+ if (state === "string") {
114
+ if (character === "'") {
115
+ if (next === "'") index += 1;
116
+ else state = "code";
117
+ }
118
+ continue;
119
+ }
120
+ if (state === "identifier") {
121
+ if (character === '"') {
122
+ if (next === '"') index += 1;
123
+ else state = "code";
124
+ }
125
+ continue;
126
+ }
127
+ if (character === "'") {
128
+ const before = index > 0 ? (body[index - 1] ?? "") : "";
129
+ if (/[A-Za-z0-9_&]/.test(before)) {
130
+ return reject(
131
+ SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED,
132
+ "Prefixed string literals (E'', U&'', B'', X'') are not allowed",
133
+ );
134
+ }
135
+ state = "string";
136
+ } else if (character === '"') {
137
+ state = "identifier";
138
+ } else if ((character === "-" && next === "-") || (character === "/" && next === "*")) {
139
+ return reject(SqlValidationCodes.SQL_COMMENT_NOT_ALLOWED, "SQL comments are not allowed");
140
+ } else if (character === "$") {
141
+ // Only the package's own rewritten SQL may contain $n, and only as plain parameter numbers.
142
+ if (allowParams && next !== undefined && /[1-9]/.test(next)) {
143
+ while (/[0-9]/.test(body[index + 1] ?? "")) index += 1;
144
+ continue;
145
+ }
146
+ return reject(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Dollar quoting and $n parameters are not allowed");
147
+ } else if (character === ";") {
148
+ return reject(SqlValidationCodes.SQL_NOT_SINGLE_SELECT, "Only a single statement is allowed");
149
+ } else if (character === "\\") {
150
+ return reject(SqlValidationCodes.SQL_INVALID_CHARACTERS, "Backslashes are only allowed inside string literals");
151
+ }
152
+ }
153
+ if (state !== "code") return reject(SqlValidationCodes.SQL_PARSE_FAILED, "Unterminated string literal or quoted identifier");
154
+ return { ok: true, sql: body };
155
+ }
156
+
157
+ /**
158
+ * A literal compared with a column: it becomes a bind parameter when the statement is rewritten.
159
+ * @typedef {Object} LiftableLiteral
160
+ * @property {number} location
161
+ * @property {"string" | "number"} kind
162
+ * @property {SqlParam} value
163
+ */
164
+
165
+ /**
166
+ * @typedef {Object} CheckResult
167
+ * @property {ReadonlySet<string>} tables
168
+ * @property {ReadonlySet<string>} columns
169
+ * @property {readonly LiftableLiteral[]} literals
170
+ * @property {ReadonlySet<number>} paramRefs
171
+ * @property {{ readonly value: number; readonly location: number | undefined } | null} topLimit
172
+ */
173
+
174
+ /**
175
+ * @typedef {Object} CheckOptions
176
+ * @property {boolean} allowParams - The rewritten statement may contain $n parameters (and no longer contains liftable literals).
177
+ */
178
+
179
+ /** Allow-list walk over one PostgreSQL SELECT parse tree. */
180
+ export class StatementRejected extends Error {
181
+ code;
182
+ reason;
183
+
184
+ constructor(code, reason) {
185
+ super(reason);
186
+ this.name = "StatementRejected";
187
+ this.code = code;
188
+ this.reason = reason;
189
+ }
190
+ }
191
+
192
+ function fail(code, reason) {
193
+ throw new StatementRejected(code, reason);
194
+ }
195
+
196
+ /** A literal compared with a column: it becomes a bind parameter when the statement is rewritten. */
197
+
198
+ const COMPARISON_OPERATORS = new Set(["=", "<>", "!=", "<", ">", "<=", ">="]);
199
+ const EQUALITY_OPERATORS = new Set(["=", "<>", "!="]);
200
+ const ARITHMETIC_OPERATORS = new Set(["+", "-", "*", "/", "%", "||"]);
201
+ const LIKE_OPERATORS = new Set(["~~", "!~~", "~~*", "!~~*"]);
202
+ const ALLOWED_SQL_VALUE_FUNCTIONS = new Set([
203
+ "SVFOP_CURRENT_DATE",
204
+ "SVFOP_CURRENT_TIMESTAMP",
205
+ "SVFOP_CURRENT_TIMESTAMP_N",
206
+ "SVFOP_LOCALTIMESTAMP",
207
+ "SVFOP_LOCALTIMESTAMP_N",
208
+ ]);
209
+ /** Type casts that cannot look anything up (no regclass, regproc or other catalog-resolving types). */
210
+ const ALLOWED_CAST_TYPES = new Map([
211
+ ["date", "date"],
212
+ ["timestamp", "timestamp"],
213
+ ["timestamptz", "timestamptz"],
214
+ ["interval", null],
215
+ ["text", "text"],
216
+ ["varchar", "text"],
217
+ ["int2", "integer"],
218
+ ["int4", "integer"],
219
+ ["int8", "integer"],
220
+ ["integer", "integer"],
221
+ ["bigint", "integer"],
222
+ ["smallint", "integer"],
223
+ ["numeric", "numeric"],
224
+ ["decimal", "numeric"],
225
+ ["float4", "numeric"],
226
+ ["float8", "numeric"],
227
+ ["bool", "boolean"],
228
+ ["boolean", "boolean"],
229
+ ]);
230
+ const JOIN_TYPES = new Set(["JOIN_INNER", "JOIN_LEFT", "JOIN_RIGHT", "JOIN_FULL"]);
231
+ const SUBLINK_TYPES = new Set(["EXISTS_SUBLINK", "ANY_SUBLINK", "EXPR_SUBLINK"]);
232
+
233
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
234
+ const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2}(\.\d{1,6})?)?(Z|[+-]\d{2}(:?\d{2})?)?$/;
235
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
236
+
237
+ const short = (name) => name.slice(0, 64);
238
+
239
+ export function checkStatement(select, policy, options) {
240
+ const tables = new Set();
241
+ const columns = new Set();
242
+ const literals = [];
243
+ const paramRefs = new Set();
244
+
245
+ function findCte(scope, name) {
246
+ for (let current = scope; current !== null; current = current.parent) {
247
+ const cte = current.ctes.get(name);
248
+ if (cte !== undefined) return cte;
249
+ }
250
+ return undefined;
251
+ }
252
+
253
+ function addSource(scope, name, source) {
254
+ if (scope.sources.has(name)) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, `Name "${short(name)}" is used twice in FROM`);
255
+ scope.sources.set(name, source);
256
+ }
257
+
258
+ function aliasName(body) {
259
+ const alias = asObject(body.alias);
260
+ if (alias === undefined) return undefined;
261
+ if (asArray(alias.colnames).length > 0)
262
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Column aliases in FROM are not allowed");
263
+ return asString(alias.aliasname);
264
+ }
265
+
266
+ /** Registers one FROM item; returns the table sources it contributed (for join checks). */
267
+ function fromItem(item, scope) {
268
+ const node = nodeOf(item);
269
+ if (node === undefined) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Unsupported FROM item");
270
+ const [type, body] = node;
271
+ if (type === "RangeVar") {
272
+ if (body.schemaname !== undefined || body.catalogname !== undefined) {
273
+ fail(SqlValidationCodes.SQL_TABLE_NOT_ALLOWED, "Schema-qualified table names are not allowed");
274
+ }
275
+ const name = asString(body.relname) ?? "";
276
+ const alias = aliasName(body) ?? name;
277
+ const cte = findCte(scope, name);
278
+ if (cte !== undefined) {
279
+ addSource(scope, alias, { kind: "derived", columns: cte });
280
+ return;
281
+ }
282
+ const allowed = policy.tables.get(name);
283
+ if (allowed === undefined) fail(SqlValidationCodes.SQL_TABLE_NOT_ALLOWED, `Table "${short(name)}" is not allowed`);
284
+ tables.add(name);
285
+ addSource(scope, alias, { kind: "table", table: name, columns: allowed });
286
+ return;
287
+ }
288
+ if (type === "RangeSubselect") {
289
+ if (!policy.allowSubqueries) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Subqueries are not allowed");
290
+ if (body.lateral === true) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "LATERAL is not allowed");
291
+ const sub = nodeOf(body.subquery);
292
+ if (sub?.[0] !== "SelectStmt") fail(SqlValidationCodes.SQL_NOT_SINGLE_SELECT, "A subquery must be a SELECT");
293
+ // A non-lateral FROM subquery sees WITH names and outer queries, but not its siblings in this FROM list.
294
+ const outputs = selectStmt(sub[1], { sources: new Map(), ctes: scope.ctes, parent: scope.parent }, false, false);
295
+ const alias = aliasName(body) ?? `subquery_${String(scope.sources.size + 1)}`;
296
+ addSource(scope, alias, { kind: "derived", columns: outputs });
297
+ return;
298
+ }
299
+ if (type === "JoinExpr") {
300
+ if (policy.allowJoins === "none") fail(SqlValidationCodes.SQL_JOIN_NOT_ALLOWED, "Joins are not allowed");
301
+ if (body.isNatural === true || asArray(body.usingClause).length > 0) {
302
+ fail(SqlValidationCodes.SQL_JOIN_NOT_ALLOWED, "NATURAL and USING joins are not allowed; use ON with declared keys");
303
+ }
304
+ if (!JOIN_TYPES.has(asString(body.jointype) ?? ""))
305
+ fail(SqlValidationCodes.SQL_JOIN_NOT_ALLOWED, "This join type is not allowed");
306
+ if (body.alias !== undefined) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Aliased joins are not allowed");
307
+ for (const side of [body.larg, body.rarg]) {
308
+ const sideType = nodeOf(side)?.[0];
309
+ if (sideType !== "RangeVar" && sideType !== "JoinExpr")
310
+ fail(SqlValidationCodes.SQL_JOIN_NOT_ALLOWED, "Joins may only combine allowed tables");
311
+ fromItem(side, scope);
312
+ }
313
+ checkJoinCondition(body.quals, scope);
314
+ return;
315
+ }
316
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, `FROM item ${short(type)} is not allowed`);
317
+ }
318
+
319
+ /** ON must be one or more ANDed equalities between columns of a declared relationship. */
320
+ function checkJoinCondition(quals, scope) {
321
+ const pairs = [];
322
+ const collect = (value) => {
323
+ const node = nodeOf(value);
324
+ if (node?.[0] === "BoolExpr" && node[1].boolop === "AND_EXPR") {
325
+ for (const arg of asArray(node[1].args)) collect(arg);
326
+ return;
327
+ }
328
+ if (node?.[0] === "A_Expr" && node[1].kind === "AEXPR_OP" && stringList(node[1].name)?.join(".") === "=") {
329
+ pairs.push([node[1].lexpr, node[1].rexpr]);
330
+ return;
331
+ }
332
+ fail(SqlValidationCodes.SQL_JOIN_NOT_ALLOWED, "Join conditions may only be equalities on declared keys");
333
+ };
334
+ if (quals === undefined) fail(SqlValidationCodes.SQL_JOIN_NOT_ALLOWED, "Joins need an ON condition");
335
+ collect(quals);
336
+ for (const [left, right] of pairs) {
337
+ const a = columnRef(left, scope, "join");
338
+ const b = columnRef(right, scope, "join");
339
+ if (
340
+ a === null ||
341
+ b === null ||
342
+ !policy.relationships.has(relationshipKey(`${a.table}.${a.name}`, `${b.table}.${b.name}`))
343
+ ) {
344
+ fail(SqlValidationCodes.SQL_JOIN_NOT_ALLOWED, "Join keys must be a declared relationship");
345
+ }
346
+ }
347
+ }
348
+
349
+ /** Resolves a ColumnRef to an allowed table column (returned) or a derived column (null). */
350
+ function columnRef(value, scope, clause) {
351
+ const node = nodeOf(value);
352
+ if (node?.[0] !== "ColumnRef") fail(SqlValidationCodes.SQL_JOIN_NOT_ALLOWED, `Expected a column in ${clause}`);
353
+ const fieldNodes = asArray(node[1].fields);
354
+ if (fieldNodes.some((field) => nodeOf(field)?.[0] === "A_Star"))
355
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "SELECT * and table.* are not allowed");
356
+ const fields = stringList(node[1].fields);
357
+ if (fields === undefined || fields.length === 0 || fields.length > 2)
358
+ fail(SqlValidationCodes.SQL_COLUMN_NOT_ALLOWED, "Column references must be column or table.column");
359
+ const column = fields[fields.length - 1] ?? "";
360
+ const qualifier = fields.length === 2 ? fields[0] : undefined;
361
+
362
+ for (let current = scope; current !== null; current = current.parent) {
363
+ const candidates = [];
364
+ if (qualifier !== undefined) {
365
+ const source = current.sources.get(qualifier);
366
+ if (source !== undefined) candidates.push(source);
367
+ } else {
368
+ candidates.push(...current.sources.values());
369
+ }
370
+ const matches = candidates.filter((source) => source.columns.has(column));
371
+ if (matches.length > 1)
372
+ fail(SqlValidationCodes.SQL_COLUMN_NOT_ALLOWED, `Column "${short(column)}" is ambiguous; qualify it`);
373
+ const match = matches[0];
374
+ if (match !== undefined) {
375
+ if (match.kind === "derived") return null;
376
+ const info = match.columns.get(column);
377
+ if (info === undefined) break;
378
+ columns.add(`${info.table}.${info.name}`);
379
+ return info;
380
+ }
381
+ // A qualifier that names a source here but lacks the column must not fall through to outer scopes.
382
+ if (qualifier !== undefined && current.sources.has(qualifier)) break;
383
+ }
384
+ fail(
385
+ SqlValidationCodes.SQL_COLUMN_NOT_ALLOWED,
386
+ `Column "${qualifier === undefined ? "" : `${short(qualifier)}.`}${short(column)}" is not allowed`,
387
+ );
388
+ }
389
+
390
+ function constValue(body) {
391
+ if (body.isnull === true) return { kind: "null", value: null };
392
+ const sval = asObject(body.sval);
393
+ if (sval !== undefined) return { kind: "string", value: asString(sval.sval) ?? "" };
394
+ const ival = asObject(body.ival);
395
+ if (ival !== undefined) return { kind: "number", value: typeof ival.ival === "number" ? ival.ival : 0 };
396
+ const fval = asObject(body.fval);
397
+ if (fval !== undefined) return { kind: "number", value: asString(fval.fval) ?? "0" };
398
+ const boolval = asObject(body.boolval);
399
+ if (boolval !== undefined) return { kind: "boolean", value: boolval.boolval === true };
400
+ return fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Unsupported constant");
401
+ }
402
+
403
+ function literalMatchesType(kind, value, type) {
404
+ const text = typeof value === "number" ? String(value) : typeof value === "string" ? value : "";
405
+ switch (type) {
406
+ case "text":
407
+ return kind === "string";
408
+ case "integer":
409
+ return /^-?\d{1,18}$/.test(text);
410
+ case "numeric":
411
+ return /^-?\d{1,30}(\.\d{1,30})?$/.test(text);
412
+ case "boolean":
413
+ return kind === "boolean" || /^(true|false)$/i.test(text);
414
+ case "date":
415
+ return kind === "string" && ISO_DATE.test(text) && !Number.isNaN(Date.parse(text));
416
+ case "timestamp":
417
+ case "timestamptz":
418
+ return (
419
+ kind === "string" &&
420
+ (ISO_DATE.test(text) || ISO_DATETIME.test(text)) &&
421
+ !Number.isNaN(Date.parse(text.replace(" ", "T")))
422
+ );
423
+ case "uuid":
424
+ return kind === "string" && UUID.test(text);
425
+ }
426
+ }
427
+
428
+ /**
429
+ * A constant compared with a table column: its type must suit the column (or the cast applied to it), an
430
+ * equality on a column with allowedValues must use one of them, and string and number constants become bind
431
+ * parameters.
432
+ */
433
+ function comparedLiteral(value, column, operator) {
434
+ let node = nodeOf(value);
435
+ let castType;
436
+ if (node?.[0] === "TypeCast") {
437
+ castType = castTarget(node[1]);
438
+ node = nodeOf(node[1].arg);
439
+ }
440
+ if (node?.[0] !== "A_Const") return;
441
+ const { kind, value: literal } = constValue(node[1]);
442
+ if (kind === "null") return;
443
+ const type = castType === undefined ? column.type : castType;
444
+ if (type !== null && !literalMatchesType(kind, literal, type)) {
445
+ fail(
446
+ SqlValidationCodes.SQL_LITERAL_INVALID,
447
+ `A value compared with ${short(column.table)}.${short(column.name)} does not match its type`,
448
+ );
449
+ }
450
+ if (column.allowedValues !== null && EQUALITY_OPERATORS.has(operator) && !column.allowedValues.includes(String(literal))) {
451
+ fail(
452
+ SqlValidationCodes.SQL_LITERAL_INVALID,
453
+ `A value compared with ${short(column.table)}.${short(column.name)} is not one of its allowed values`,
454
+ );
455
+ }
456
+ const location = locationOf(node[1]);
457
+ if ((kind === "string" || kind === "number") && location !== undefined) literals.push({ location, kind, value: literal });
458
+ }
459
+
460
+ function castTarget(body) {
461
+ const typeName = asObject(body.typeName) ?? nodeOf(body.typeName)?.[1];
462
+ if (typeName === undefined) fail(SqlValidationCodes.SQL_TYPE_NOT_ALLOWED, "Unsupported type cast");
463
+ if (asArray(typeName.arrayBounds).length > 0 || asArray(typeName.typmods).length > 0 || typeName.setof === true) {
464
+ fail(SqlValidationCodes.SQL_TYPE_NOT_ALLOWED, "Array, sized and SETOF casts are not allowed");
465
+ }
466
+ const names = stringList(typeName.names);
467
+ if (names === undefined || names.length === 0 || names.length > 2 || (names.length === 2 && names[0] !== "pg_catalog")) {
468
+ fail(SqlValidationCodes.SQL_TYPE_NOT_ALLOWED, "Only built-in types can be used in casts");
469
+ }
470
+ const name = (names[names.length - 1] ?? "").toLowerCase();
471
+ const mapped = ALLOWED_CAST_TYPES.get(name);
472
+ if (mapped === undefined) fail(SqlValidationCodes.SQL_TYPE_NOT_ALLOWED, `Casting to ${short(name)} is not allowed`);
473
+ return mapped;
474
+ }
475
+
476
+ function expression(value, scope, clause) {
477
+ const node = nodeOf(value);
478
+ if (node === undefined) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, `Unsupported expression in ${clause}`);
479
+ const [type, body] = node;
480
+ switch (type) {
481
+ case "ColumnRef":
482
+ columnRef(value, scope, clause);
483
+ return;
484
+ case "A_Const": {
485
+ const { kind, value: literal } = constValue(body);
486
+ if (kind === "string" && typeof literal === "string" && literal.length > policy.maxLiteralChars) {
487
+ fail(SqlValidationCodes.SQL_LITERAL_INVALID, "A string value is too long");
488
+ }
489
+ return;
490
+ }
491
+ case "ParamRef": {
492
+ const number = body.number;
493
+ if (!options.allowParams || typeof number !== "number" || number < 1)
494
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Parameters are not allowed");
495
+ paramRefs.add(number);
496
+ return;
497
+ }
498
+ case "TypeCast":
499
+ castTarget(body);
500
+ expression(body.arg, scope, clause);
501
+ return;
502
+ case "A_Expr":
503
+ operatorExpression(body, scope, clause);
504
+ return;
505
+ case "BoolExpr":
506
+ if (!["AND_EXPR", "OR_EXPR", "NOT_EXPR"].includes(asString(body.boolop) ?? ""))
507
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Unsupported boolean operator");
508
+ for (const arg of asArray(body.args)) expression(arg, scope, clause);
509
+ return;
510
+ case "NullTest":
511
+ case "BooleanTest":
512
+ expression(body.arg, scope, clause);
513
+ return;
514
+ case "FuncCall":
515
+ functionCall(body, scope, clause);
516
+ return;
517
+ case "SQLValueFunction":
518
+ if (!ALLOWED_SQL_VALUE_FUNCTIONS.has(asString(body.op) ?? "")) {
519
+ fail(
520
+ SqlValidationCodes.SQL_FUNCTION_NOT_ALLOWED,
521
+ "Only CURRENT_DATE, CURRENT_TIMESTAMP and LOCALTIMESTAMP are allowed",
522
+ );
523
+ }
524
+ return;
525
+ case "CaseExpr":
526
+ if (body.arg !== undefined) expression(body.arg, scope, clause);
527
+ for (const when of asArray(body.args)) {
528
+ const caseWhen = nodeOf(when);
529
+ if (caseWhen?.[0] !== "CaseWhen") fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Malformed CASE");
530
+ expression(caseWhen[1].expr, scope, clause);
531
+ expression(caseWhen[1].result, scope, clause);
532
+ }
533
+ if (body.defresult !== undefined) expression(body.defresult, scope, clause);
534
+ return;
535
+ case "CoalesceExpr":
536
+ case "MinMaxExpr":
537
+ for (const arg of asArray(body.args)) expression(arg, scope, clause);
538
+ return;
539
+ case "SubLink": {
540
+ if (!policy.allowSubqueries) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Subqueries are not allowed");
541
+ if (!SUBLINK_TYPES.has(asString(body.subLinkType) ?? ""))
542
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Only EXISTS, IN and scalar subqueries are allowed");
543
+ if (
544
+ body.subLinkType === "ANY_SUBLINK" &&
545
+ asArray(body.operName).length > 0 &&
546
+ stringList(body.operName)?.join(".") !== "="
547
+ ) {
548
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Only IN (subquery) is allowed");
549
+ }
550
+ if (body.testexpr !== undefined) expression(body.testexpr, scope, clause);
551
+ const sub = nodeOf(body.subselect);
552
+ if (sub?.[0] !== "SelectStmt") fail(SqlValidationCodes.SQL_NOT_SINGLE_SELECT, "A subquery must be a SELECT");
553
+ selectStmt(sub[1], scope, false, false);
554
+ return;
555
+ }
556
+ default:
557
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, `${short(type)} is not allowed`);
558
+ }
559
+ }
560
+
561
+ function operatorExpression(body, scope, clause) {
562
+ const kind = asString(body.kind) ?? "";
563
+ const names = stringList(body.name);
564
+ if (names?.length !== 1) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Schema-qualified operators are not allowed");
565
+ const operator = names[0] ?? "";
566
+ const left = body.lexpr;
567
+ const right = body.rexpr;
568
+
569
+ const columnOf = (value) => (nodeOf(value)?.[0] === "ColumnRef" ? columnRef(value, scope, clause) : null);
570
+
571
+ switch (kind) {
572
+ case "AEXPR_OP": {
573
+ if (!COMPARISON_OPERATORS.has(operator) && !ARITHMETIC_OPERATORS.has(operator) && !LIKE_OPERATORS.has(operator)) {
574
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, `Operator ${short(operator)} is not allowed`);
575
+ }
576
+ if (left !== undefined) expression(left, scope, clause);
577
+ expression(right, scope, clause);
578
+ if (COMPARISON_OPERATORS.has(operator) || LIKE_OPERATORS.has(operator)) {
579
+ const leftColumn = left === undefined ? null : columnOf(left);
580
+ const rightColumn = columnOf(right);
581
+ if (leftColumn !== null)
582
+ comparedLiteral(right, LIKE_OPERATORS.has(operator) ? { ...leftColumn, allowedValues: null } : leftColumn, operator);
583
+ if (rightColumn !== null && left !== undefined) comparedLiteral(left, rightColumn, operator);
584
+ }
585
+ return;
586
+ }
587
+ case "AEXPR_IN": {
588
+ if (operator !== "=" && operator !== "<>") fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Unsupported IN operator");
589
+ expression(left, scope, clause);
590
+ const items = asArray(asObject(nodeOf(right)?.[1])?.items);
591
+ if (nodeOf(right)?.[0] !== "List" || items.length === 0 || items.length > 100)
592
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "IN needs a list of 1-100 values");
593
+ const column = columnOf(left);
594
+ for (const item of items) {
595
+ expression(item, scope, clause);
596
+ if (column !== null) comparedLiteral(item, column, "=");
597
+ }
598
+ return;
599
+ }
600
+ case "AEXPR_LIKE":
601
+ case "AEXPR_ILIKE": {
602
+ expression(left, scope, clause);
603
+ expression(right, scope, clause);
604
+ const column = columnOf(left);
605
+ if (column !== null) comparedLiteral(right, { ...column, allowedValues: null }, "~~");
606
+ return;
607
+ }
608
+ case "AEXPR_BETWEEN":
609
+ case "AEXPR_NOT_BETWEEN": {
610
+ expression(left, scope, clause);
611
+ const bounds = asArray(asObject(nodeOf(right)?.[1])?.items);
612
+ if (bounds.length !== 2) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "BETWEEN needs two bounds");
613
+ const column = columnOf(left);
614
+ for (const bound of bounds) {
615
+ expression(bound, scope, clause);
616
+ if (column !== null) comparedLiteral(bound, column, "<=");
617
+ }
618
+ return;
619
+ }
620
+ case "AEXPR_NULLIF":
621
+ case "AEXPR_DISTINCT":
622
+ case "AEXPR_NOT_DISTINCT":
623
+ expression(left, scope, clause);
624
+ expression(right, scope, clause);
625
+ return;
626
+ default:
627
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, `${short(kind)} expressions are not allowed`);
628
+ }
629
+ }
630
+
631
+ function functionCall(body, scope, clause) {
632
+ const names = stringList(body.funcname);
633
+ if (names === undefined || names.length === 0) fail(SqlValidationCodes.SQL_FUNCTION_NOT_ALLOWED, "Unsupported function call");
634
+ // pg_catalog.* only appears for SQL-syntax forms the parser itself produces: EXTRACT, AT TIME ZONE, TRIM.
635
+ const sqlSyntax = body.funcformat === "COERCE_SQL_SYNTAX" && names.length === 2 && names[0] === "pg_catalog";
636
+ if (names.length !== 1 && !sqlSyntax)
637
+ fail(SqlValidationCodes.SQL_FUNCTION_NOT_ALLOWED, "Schema-qualified functions are not allowed");
638
+ const name = (names[names.length - 1] ?? "").toLowerCase();
639
+ if (!policy.functions.has(name)) fail(SqlValidationCodes.SQL_FUNCTION_NOT_ALLOWED, `Function ${short(name)} is not allowed`);
640
+ if (body.agg_within_group === true || body.func_variadic === true)
641
+ fail(SqlValidationCodes.SQL_FUNCTION_NOT_ALLOWED, "WITHIN GROUP and VARIADIC are not allowed");
642
+ if (body.agg_star === true && name !== "count") fail(SqlValidationCodes.SQL_FUNCTION_NOT_ALLOWED, "Only count(*) may use *");
643
+ if (body.over !== undefined) {
644
+ if (!policy.allowWindowFunctions) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Window functions are not allowed");
645
+ const over = asObject(body.over) ?? nodeOf(body.over)?.[1] ?? {};
646
+ if (over.refname !== undefined || over.name !== undefined)
647
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Named windows are not allowed");
648
+ for (const part of asArray(over.partitionClause)) expression(part, scope, clause);
649
+ for (const order of asArray(over.orderClause)) sortBy(order, scope, null);
650
+ }
651
+ for (const arg of asArray(body.args)) expression(arg, scope, clause);
652
+ for (const order of asArray(body.agg_order)) sortBy(order, scope, null);
653
+ if (body.agg_filter !== undefined) expression(body.agg_filter, scope, clause);
654
+ }
655
+
656
+ function sortBy(value, scope, outputs, targetCount = 0) {
657
+ const node = nodeOf(value);
658
+ if (node?.[0] !== "SortBy") fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Unsupported ORDER BY item");
659
+ if (asArray(node[1].useOp).length > 0) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "ORDER BY USING is not allowed");
660
+ const key = node[1].node;
661
+ const ordinal = integerConst(key);
662
+ if (ordinal !== undefined && outputs !== null) {
663
+ if (ordinal < 1 || ordinal > targetCount)
664
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "ORDER BY position is out of range");
665
+ return;
666
+ }
667
+ // A bare name in ORDER BY refers to an output column first (PostgreSQL's rule); anything else is an input expression.
668
+ const ref = nodeOf(key);
669
+ const fields = ref?.[0] === "ColumnRef" ? stringList(ref[1].fields) : undefined;
670
+ if (outputs !== null && fields?.length === 1 && outputs.has(fields[0] ?? "")) return;
671
+ expression(key, scope, "ORDER BY");
672
+ }
673
+
674
+ function outputName(target) {
675
+ const name = asString(target.name);
676
+ if (name !== undefined) return name;
677
+ const node = nodeOf(target.val);
678
+ if (node?.[0] === "ColumnRef") return stringList(node[1].fields)?.at(-1);
679
+ if (node?.[0] === "FuncCall") return stringList(node[1].funcname)?.at(-1);
680
+ return undefined;
681
+ }
682
+
683
+ function limitValue(value, what, max) {
684
+ if (value === undefined) return undefined;
685
+ const number = integerConst(value);
686
+ if (number === undefined || number < 0 || number > max)
687
+ fail(SqlValidationCodes.SQL_LIMIT_INVALID, `${what} must be a whole number from 0 to ${String(max)}`);
688
+ return number;
689
+ }
690
+
691
+ /** Checks one SELECT and returns its output column names. */
692
+ function selectStmt(body, parent, top, outermost) {
693
+ if (body.intoClause !== undefined) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "SELECT INTO is not allowed");
694
+ if (asArray(body.lockingClause).length > 0)
695
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "FOR UPDATE / FOR SHARE are not allowed");
696
+ if (asArray(body.valuesLists).length > 0) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "VALUES lists are not allowed");
697
+ if (asArray(body.windowClause).length > 0) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "WINDOW clauses are not allowed");
698
+ if (body.limitOption === "LIMIT_OPTION_WITH_TIES")
699
+ fail(SqlValidationCodes.SQL_LIMIT_INVALID, "FETCH ... WITH TIES is not allowed");
700
+
701
+ const scope = { sources: new Map(), ctes: new Map(), parent };
702
+
703
+ const withClause = asObject(body.withClause) ?? nodeOf(body.withClause)?.[1];
704
+ if (withClause !== undefined) {
705
+ if (withClause.recursive === true) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "WITH RECURSIVE is not allowed");
706
+ for (const entry of asArray(withClause.ctes)) {
707
+ const cte = nodeOf(entry);
708
+ if (cte?.[0] !== "CommonTableExpr") fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Malformed WITH");
709
+ const query = nodeOf(cte[1].ctequery);
710
+ if (query?.[0] !== "SelectStmt") fail(SqlValidationCodes.SQL_NOT_SINGLE_SELECT, "WITH may only contain SELECT queries");
711
+ const name = asString(cte[1].ctename) ?? "";
712
+ // A WITH name may not reuse an allowed table's name: applications can then safely provide that
713
+ // table themselves as a CTE (a "virtual table") placed in front of the validated statement.
714
+ if (policy.tables.has(name))
715
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, `WITH name "${short(name)}" is the name of a table`);
716
+ if (scope.ctes.has(name)) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, `WITH name "${short(name)}" is used twice`);
717
+ // A WITH query sees the WITH queries before it and the enclosing scope (its FROM is not filled yet).
718
+ const outputs = selectStmt(query[1], scope, false, false);
719
+ const renamed = stringList(cte[1].aliascolnames);
720
+ scope.ctes.set(name, renamed !== undefined && renamed.length > 0 ? new Set(renamed) : outputs);
721
+ }
722
+ }
723
+
724
+ const op = asString(body.op) ?? "SETOP_NONE";
725
+ if (op !== "SETOP_NONE") {
726
+ if (!policy.allowSetOperations)
727
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "UNION, INTERSECT and EXCEPT are not allowed");
728
+ // Set-operation branches are SelectStmt bodies without the usual { SelectStmt: ... } wrapper.
729
+ const left = asObject(body.larg);
730
+ const right = asObject(body.rarg);
731
+ if (typeof left?.op !== "string" || typeof right?.op !== "string")
732
+ fail(SqlValidationCodes.SQL_NOT_SINGLE_SELECT, "Set operations must combine SELECTs");
733
+ const outputs = selectStmt(left, scope, top, false);
734
+ selectStmt(right, scope, top, false);
735
+ for (const order of asArray(body.sortClause)) sortBy(order, scope, outputs, outputs.size);
736
+ finishLimits(body, outermost);
737
+ return outputs;
738
+ }
739
+
740
+ const from = asArray(body.fromClause);
741
+ if (from.length > 1) fail(SqlValidationCodes.SQL_JOIN_NOT_ALLOWED, "Comma joins are not allowed; use JOIN ... ON");
742
+ for (const item of from) fromItem(item, scope);
743
+
744
+ const targets = asArray(body.targetList);
745
+ if (targets.length === 0) fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "SELECT needs at least one output column");
746
+ const outputs = new Set();
747
+ for (const target of targets) {
748
+ const resTarget = nodeOf(target);
749
+ if (resTarget?.[0] !== "ResTarget") fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "Unsupported output column");
750
+ expression(resTarget[1].val, scope, "SELECT");
751
+ const name = outputName(resTarget[1]);
752
+ if (name !== undefined) outputs.add(name);
753
+ }
754
+ if (body.whereClause !== undefined) expression(body.whereClause, scope, "WHERE");
755
+ for (const group of asArray(body.groupClause)) {
756
+ const ordinal = integerConst(group);
757
+ if (ordinal !== undefined) {
758
+ if (ordinal < 1 || ordinal > targets.length)
759
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "GROUP BY position is out of range");
760
+ continue;
761
+ }
762
+ if (nodeOf(group)?.[0] === "GroupingSet")
763
+ fail(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "ROLLUP, CUBE and GROUPING SETS are not allowed");
764
+ // PostgreSQL resolves a bare GROUP BY name to an input column before an output name, so an output
765
+ // name here could silently mean a hidden column. Ask for the position instead.
766
+ const groupNode = nodeOf(group);
767
+ const groupFields = groupNode?.[0] === "ColumnRef" ? stringList(groupNode[1].fields) : undefined;
768
+ const groupName = groupFields?.length === 1 ? (groupFields[0] ?? "") : undefined;
769
+ if (
770
+ groupName !== undefined &&
771
+ outputs.has(groupName) &&
772
+ ![...scope.sources.values()].some((source) => source.columns.has(groupName))
773
+ ) {
774
+ fail(
775
+ SqlValidationCodes.SQL_COLUMN_NOT_ALLOWED,
776
+ `GROUP BY cannot use the output name "${short(groupName)}"; use its position (GROUP BY 1) or repeat the expression`,
777
+ );
778
+ }
779
+ expression(group, scope, "GROUP BY");
780
+ }
781
+ if (body.havingClause !== undefined) expression(body.havingClause, scope, "HAVING");
782
+ for (const distinct of asArray(body.distinctClause)) {
783
+ // Plain DISTINCT is an empty node; DISTINCT ON lists expressions.
784
+ if (Object.keys(asObject(distinct) ?? {}).length > 0) expression(distinct, scope, "DISTINCT ON");
785
+ }
786
+ for (const order of asArray(body.sortClause)) sortBy(order, scope, outputs, targets.length);
787
+ finishLimits(body, outermost);
788
+ if (top && policy.requireAggregation) checkAggregation(body);
789
+ return outputs;
790
+ }
791
+
792
+ let topLimit = null;
793
+ function finishLimits(body, outermost) {
794
+ const count = limitValue(body.limitCount, "LIMIT", Number.MAX_SAFE_INTEGER);
795
+ limitValue(body.limitOffset, "OFFSET", policy.maxOffset);
796
+ if (outermost && count !== undefined) topLimit = { value: count, location: locationOf(nodeOf(body.limitCount)?.[1] ?? {}) };
797
+ }
798
+
799
+ function containsAggregate(value) {
800
+ const node = nodeOf(value);
801
+ if (node?.[0] === "FuncCall") {
802
+ const name = (stringList(node[1].funcname)?.at(-1) ?? "").toLowerCase();
803
+ if (policy.aggregates.has(name) && node[1].over === undefined) return true;
804
+ }
805
+ if (node?.[0] === "SubLink") return false;
806
+ const object = asObject(value);
807
+ const children =
808
+ node !== undefined
809
+ ? Object.values(node[1])
810
+ : Array.isArray(value)
811
+ ? asArray(value)
812
+ : object !== undefined
813
+ ? Object.values(object)
814
+ : [];
815
+ return children.some((child) => typeof child === "object" && child !== null && containsAggregate(child));
816
+ }
817
+
818
+ /** Every output column must be an aggregate or a GROUP BY key, so no individual rows are returned. */
819
+ function checkAggregation(body) {
820
+ const groups = asArray(body.groupClause);
821
+ const groupKeys = new Set(groups.map(structuralKey));
822
+ const groupOrdinals = new Set(groups.map(integerConst).filter((n) => n !== undefined));
823
+ asArray(body.targetList).forEach((target, index) => {
824
+ const value = nodeOf(target)?.[1].val;
825
+ if (containsAggregate(value) || groupKeys.has(structuralKey(value)) || groupOrdinals.has(index + 1)) return;
826
+ fail(SqlValidationCodes.SQL_AGGREGATION_REQUIRED, "Every output column must be an aggregate or a GROUP BY key");
827
+ });
828
+ }
829
+
830
+ selectStmt(select, null, true, true);
831
+ return { tables, columns, literals, paramRefs, topLimit };
832
+ }
833
+
834
+ /**
835
+ * Also has every field of SqlValidator.
836
+ * @typedef {Object} PostgresSqlValidator
837
+ * @property {"postgres"} dialect
838
+ * @property {SqlPolicy} policy
839
+ * @property {(sql: string) => Promise<SqlValidationOutcome>} validate - Validates one generated statement against the policy and rewrites it for execution: values compared with columns become $n bind parameters and the row limit is enforced. Never executes anything. Resolves to a rejection (never throws) for any statement that is not allowed.
840
+ */
841
+
842
+ // libpg-query is CommonJS: take parse from its default export.
843
+ const { parse } = libpgQuery;
844
+
845
+ const STRING_LITERAL = /^'(?:[^']|'')*'/;
846
+ const NUMBER_LITERAL = /^-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?/;
847
+
848
+ /** Parses and checks one statement; the statement must be exactly one SELECT. */
849
+ async function parseAndCheck(sql, policy, allowParams) {
850
+ const lexical = lexicalCheck(sql, allowParams ? policy.maxSqlChars + 200 : policy.maxSqlChars, allowParams);
851
+ if (!lexical.ok) return lexical;
852
+
853
+ let tree;
854
+ try {
855
+ tree = await parse(lexical.sql);
856
+ } catch {
857
+ // The parser's message quotes the offending token, so only a generic reason is returned.
858
+ return reject(SqlValidationCodes.SQL_PARSE_FAILED, "SQL could not be parsed as PostgreSQL");
859
+ }
860
+ const size = treeSize(tree);
861
+ if (size.nodes > policy.maxAstNodes || size.depth > policy.maxAstDepth) {
862
+ return reject(SqlValidationCodes.SQL_TOO_COMPLEX, "SQL is too complex");
863
+ }
864
+ const statements = asArray(asObject(tree)?.stmts);
865
+ if (statements.length !== 1) return reject(SqlValidationCodes.SQL_NOT_SINGLE_SELECT, "Exactly one statement is allowed");
866
+ const statement = nodeOf(asObject(statements[0])?.stmt);
867
+ if (statement?.[0] !== "SelectStmt")
868
+ return reject(SqlValidationCodes.SQL_NOT_SINGLE_SELECT, "Only SELECT statements are allowed");
869
+
870
+ try {
871
+ return { ok: true, sql: lexical.sql, check: checkStatement(statement[1], policy, { allowParams }) };
872
+ } catch (error) {
873
+ if (error instanceof StatementRejected) return reject(error.code, error.reason);
874
+ // Anything unexpected while walking the tree fails closed.
875
+ return reject(SqlValidationCodes.SQL_FEATURE_NOT_ALLOWED, "SQL could not be validated");
876
+ }
877
+ }
878
+
879
+ /**
880
+ * Rewrites the statement text at the parser's byte offsets: liftable literals become $1..$n (numbered in
881
+ * source order) and the top-level LIMIT is added or lowered to maxRows + 1.
882
+ */
883
+ function rewrite(sql, check, maxRows) {
884
+ const bytes = Buffer.from(sql, "utf8");
885
+ const edits = [];
886
+ const params = [];
887
+ const ordered = [...check.literals].sort((a, b) => a.location - b.location);
888
+ const seen = new Set();
889
+ for (const literal of ordered) {
890
+ if (seen.has(literal.location)) continue;
891
+ seen.add(literal.location);
892
+ const rest = bytes.subarray(literal.location).toString("utf8");
893
+ const match = (literal.kind === "string" ? STRING_LITERAL : NUMBER_LITERAL).exec(rest);
894
+ if (match === null || !literalText(match[0], literal)) return undefined;
895
+ params.push(literal.value);
896
+ edits.push({
897
+ start: literal.location,
898
+ end: literal.location + Buffer.byteLength(match[0], "utf8"),
899
+ text: `$${String(params.length)}`,
900
+ });
901
+ }
902
+
903
+ const cap = maxRows + 1;
904
+ let limit = cap;
905
+ let suffix = "";
906
+ if (check.topLimit === null) {
907
+ suffix = ` LIMIT ${String(cap)}`;
908
+ } else if (check.topLimit.value > maxRows) {
909
+ const location = check.topLimit.location;
910
+ if (location === undefined) return undefined;
911
+ const match = /^\d+/.exec(bytes.subarray(location).toString("utf8"));
912
+ if (match === null) return undefined;
913
+ edits.push({ start: location, end: location + match[0].length, text: String(cap) });
914
+ } else {
915
+ limit = check.topLimit.value;
916
+ }
917
+
918
+ edits.sort((a, b) => b.start - a.start);
919
+ let output = bytes;
920
+ for (const edit of edits) {
921
+ output = Buffer.concat([output.subarray(0, edit.start), Buffer.from(edit.text, "utf8"), output.subarray(edit.end)]);
922
+ }
923
+ return { sql: output.toString("utf8") + suffix, params, limit };
924
+ }
925
+
926
+ /** The literal's source text must spell exactly the value the parser reported. */
927
+ function literalText(text, literal) {
928
+ if (literal.kind === "string") return text.slice(1, -1).replaceAll("''", "'") === literal.value;
929
+ return Number(text) === Number(literal.value);
930
+ }
931
+
932
+ function sameSet(a, b) {
933
+ return a.size === b.size && [...a].every((value) => b.has(value));
934
+ }
935
+
936
+ /** PostgreSQL validator for one policy (see defineSqlPolicy). */
937
+ export function createPostgresSqlValidator(policy) {
938
+ // dialect is checked at runtime: the policy may come from untyped JavaScript.
939
+ if (!isSqlPolicy(policy) || policy.dialect !== "postgres") {
940
+ throw new AiServiceError(ErrorCodes.CONFIG_INVALID, "A PostgreSQL policy from defineSqlPolicy() is required");
941
+ }
942
+
943
+ async function validate(sql) {
944
+ if (typeof sql !== "string") return reject(SqlValidationCodes.SQL_EMPTY, "SQL must be a string");
945
+ const first = await parseAndCheck(sql, policy, false);
946
+ if (!first.ok) return first;
947
+
948
+ const rewritten = rewrite(first.sql, first.check, policy.maxRows);
949
+ if (rewritten === undefined) return reject(SqlValidationCodes.SQL_REWRITE_FAILED, "SQL could not be parameterised safely");
950
+
951
+ // Second pass over the exact text that will run.
952
+ const second = await parseAndCheck(rewritten.sql, policy, true);
953
+ if (!second.ok) return reject(SqlValidationCodes.SQL_REWRITE_FAILED, `Rewritten SQL failed validation (${second.code})`);
954
+ const expectedParams = new Set(rewritten.params.map((_, index) => index + 1));
955
+ if (
956
+ second.check.literals.length !== 0 ||
957
+ second.check.paramRefs.size !== expectedParams.size ||
958
+ ![...expectedParams].every((n) => second.check.paramRefs.has(n)) ||
959
+ second.check.topLimit?.value !== rewritten.limit ||
960
+ !sameSet(first.check.tables, second.check.tables) ||
961
+ !sameSet(first.check.columns, second.check.columns)
962
+ ) {
963
+ return reject(SqlValidationCodes.SQL_REWRITE_FAILED, "Rewritten SQL does not match the validated statement");
964
+ }
965
+
966
+ return {
967
+ ok: true,
968
+ query: brandValidatedQuery({
969
+ dialect: "postgres",
970
+ sql: rewritten.sql,
971
+ params: rewritten.params,
972
+ tables: [...first.check.tables].sort(),
973
+ columns: [...first.check.columns].sort(),
974
+ limit: rewritten.limit,
975
+ maxRows: policy.maxRows,
976
+ timeoutMs: policy.timeoutMs,
977
+ fingerprint: createHash("sha256").update(rewritten.sql).digest("hex"),
978
+ }),
979
+ };
980
+ }
981
+
982
+ return Object.freeze({ dialect: "postgres", policy, validate });
983
+ }