graphile-sql-expression-validator 0.4.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/plugin.js ADDED
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+ /**
3
+ * PostGraphile v5 SQL Expression Validator Plugin
4
+ *
5
+ * Validates SQL expressions in mutation inputs for columns tagged with
6
+ * `@sqlExpression`. The plugin:
7
+ *
8
+ * 1. Hooks into mutation fields via GraphQLObjectType_fields_field
9
+ * 2. For each mutation whose pgCodec has `@sqlExpression` attributes:
10
+ * - Finds the text column's GraphQL name
11
+ * - Looks for a companion AST column (via @rawSqlAstField tag or `{name}_ast`)
12
+ * - Wraps the field's plan to add a sideEffect step that validates input
13
+ * - Throws on invalid SQL expressions (transaction rolls back)
14
+ *
15
+ * IMPORTANT: This plugin uses the per-field hook (GraphQLObjectType_fields_field)
16
+ * which provides `pgCodec` in scope. This ensures validation is ONLY applied to
17
+ * mutation fields whose associated table has @sqlExpression columns — not to
18
+ * unrelated mutations like signUp, login, etc.
19
+ *
20
+ * The plugin uses grafast's `sideEffect` step for validation rather than wrapping
21
+ * the resolver. In v5, mutation fields use plans and defining a GraphQL resolver
22
+ * on a plan-based field causes "Query planning error: expects a plan to be
23
+ * available; forbidden from defining a GraphQL resolver."
24
+ */
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.createSqlExpressionValidatorPlugin = createSqlExpressionValidatorPlugin;
27
+ exports.SqlExpressionValidatorPreset = SqlExpressionValidatorPreset;
28
+ require("graphile-build");
29
+ require("graphile-build-pg");
30
+ const grafast_1 = require("grafast");
31
+ const validator_1 = require("./validator");
32
+ // ─── Helpers ──────────────────────────────────────────────────────
33
+ /**
34
+ * Find all values for a key in a potentially nested mutation input object.
35
+ * Input is typically 1 level deep, but we traverse defensively to avoid
36
+ * silently skipping deeper/nested mutation payloads.
37
+ * Returns all matches to prevent bypasses via duplicate keys at different depths.
38
+ */
39
+ function findAllValues(input, key) {
40
+ const visited = new Set();
41
+ const results = [];
42
+ const stack = [
43
+ { node: input, depth: 0 }
44
+ ];
45
+ const maxDepth = 32;
46
+ while (stack.length > 0) {
47
+ const current = stack.pop();
48
+ const { node, depth } = current;
49
+ if (key in node) {
50
+ results.push(node[key]);
51
+ }
52
+ if (visited.has(node) || depth >= maxDepth) {
53
+ continue;
54
+ }
55
+ visited.add(node);
56
+ for (const value of Object.values(node)) {
57
+ if (value && typeof value === 'object') {
58
+ stack.push({
59
+ node: value,
60
+ depth: depth + 1
61
+ });
62
+ }
63
+ }
64
+ }
65
+ return results;
66
+ }
67
+ // ─── Plugin factory ───────────────────────────────────────────────
68
+ /**
69
+ * Creates the SQL Expression Validator PostGraphile v5 plugin.
70
+ *
71
+ * Options are pre-computed at build time (allowedFunctions lowercased
72
+ * into a Set) to avoid per-execution allocations.
73
+ *
74
+ * @param validatorOptions - Options for SQL expression validation.
75
+ * @returns GraphileConfig.Plugin
76
+ */
77
+ function createSqlExpressionValidatorPlugin(validatorOptions = {}) {
78
+ // Pre-compute at plugin creation time
79
+ const { allowedFunctions = validator_1.DEFAULT_ALLOWED_FUNCTIONS, allowedSchemas = [], maxExpressionLength = 10000 } = validatorOptions;
80
+ const precomputedOptions = {
81
+ allowedFunctions,
82
+ allowedSchemas,
83
+ maxExpressionLength
84
+ };
85
+ return {
86
+ name: 'SqlExpressionValidatorPlugin',
87
+ version: '2.0.0',
88
+ description: 'Validates SQL expressions in mutation inputs for @sqlExpression columns',
89
+ schema: {
90
+ hooks: {
91
+ GraphQLObjectType_fields_field(field, build, context) {
92
+ const { scope: { isRootMutation, pgCodec } } = context;
93
+ // Only process mutation fields
94
+ if (!isRootMutation) {
95
+ return field;
96
+ }
97
+ // Only process if this mutation's codec has attributes
98
+ if (!pgCodec ||
99
+ !('attributes' in pgCodec) ||
100
+ !pgCodec.attributes) {
101
+ return field;
102
+ }
103
+ const attrs = pgCodec.attributes;
104
+ // Find @sqlExpression columns on THIS mutation's codec only
105
+ const sqlExpressionColumns = [];
106
+ for (const [attrName, attr] of Object.entries(attrs)) {
107
+ const tags = attr.extensions?.tags;
108
+ if (!tags?.sqlExpression)
109
+ continue;
110
+ // Derive GraphQL field name via inflection
111
+ const gqlName = build.inflection.attribute({
112
+ attributeName: attrName,
113
+ codec: pgCodec
114
+ });
115
+ // Look for companion AST column
116
+ const rawSqlAstFieldTag = tags?.rawSqlAstField;
117
+ const astDbName = typeof rawSqlAstFieldTag === 'string' &&
118
+ rawSqlAstFieldTag.trim()
119
+ ? rawSqlAstFieldTag.trim()
120
+ : `${attrName}_ast`;
121
+ const astAttr = attrs[astDbName];
122
+ let astGqlName = null;
123
+ if (astAttr) {
124
+ astGqlName = build.inflection.attribute({
125
+ attributeName: astDbName,
126
+ codec: pgCodec
127
+ });
128
+ }
129
+ else if (typeof rawSqlAstFieldTag === 'string' &&
130
+ rawSqlAstFieldTag.trim()) {
131
+ const pgExt = pgCodec?.extensions?.pg;
132
+ throw new Error(`@rawSqlAstField points to missing column "${astDbName}" on ${pgExt?.schemaName ?? 'unknown'}.${pgExt?.name ?? 'unknown'}`);
133
+ }
134
+ sqlExpressionColumns.push({
135
+ attrName,
136
+ gqlName,
137
+ astGqlName
138
+ });
139
+ }
140
+ // If no @sqlExpression columns on this codec, pass through unchanged
141
+ if (sqlExpressionColumns.length === 0) {
142
+ return field;
143
+ }
144
+ // Wrap the plan function (NOT resolve) for v5 compatibility
145
+ if (!('plan' in field) || typeof field.plan !== 'function') {
146
+ return field;
147
+ }
148
+ const originalPlan = field.plan;
149
+ return {
150
+ ...field,
151
+ plan($parent, fieldArgs) {
152
+ // Get the input argument as a step
153
+ const $input = fieldArgs.get('input');
154
+ // Add a validation sideEffect step.
155
+ // $input is a grafast step, cast for type compatibility.
156
+ (0, grafast_1.sideEffect)($input, async (inputValue) => {
157
+ if (!inputValue ||
158
+ typeof inputValue !== 'object')
159
+ return;
160
+ const input = inputValue;
161
+ for (const col of sqlExpressionColumns) {
162
+ const { gqlName: textGqlName, astGqlName } = col;
163
+ const textValues = findAllValues(input, textGqlName);
164
+ const astValues = astGqlName
165
+ ? findAllValues(input, astGqlName)
166
+ : [];
167
+ // Validate all text inputs
168
+ for (const textValue of textValues) {
169
+ if (textValue !== undefined && textValue !== null) {
170
+ if (typeof textValue !== 'string') {
171
+ throw new Error(`SQL expression in ${textGqlName} must be a string, got ${typeof textValue}`);
172
+ }
173
+ const result = await (0, validator_1.parseAndValidateSqlExpression)(textValue, precomputedOptions);
174
+ if (!result.valid) {
175
+ throw new Error(`Invalid SQL expression in ${textGqlName}: ${result.error}`);
176
+ }
177
+ }
178
+ }
179
+ // Validate standalone AST inputs (only when text is absent)
180
+ if (textValues.length === 0 && astGqlName) {
181
+ for (const astValue of astValues) {
182
+ if (astValue !== undefined &&
183
+ astValue !== null) {
184
+ const result = (0, validator_1.validateAst)(astValue, precomputedOptions);
185
+ if (!result.valid) {
186
+ throw new Error(`Invalid SQL expression AST in ${astGqlName}: ${result.error}`);
187
+ }
188
+ }
189
+ }
190
+ }
191
+ }
192
+ });
193
+ // Call the original plan — the mutation proceeds normally.
194
+ // If the sideEffect throws, the transaction rolls back.
195
+ return originalPlan.call(this, $parent, fieldArgs);
196
+ }
197
+ };
198
+ }
199
+ }
200
+ }
201
+ };
202
+ }
203
+ // ─── Preset factory ───────────────────────────────────────────────
204
+ /**
205
+ * Creates a preset that includes the SQL expression validator plugin.
206
+ *
207
+ * @example
208
+ * ```typescript
209
+ * import { SqlExpressionValidatorPreset } from 'graphile-sql-expression-validator';
210
+ *
211
+ * const preset: GraphileConfig.Preset = {
212
+ * extends: [
213
+ * SqlExpressionValidatorPreset({
214
+ * allowedSchemas: ['app_public'],
215
+ * }),
216
+ * ],
217
+ * };
218
+ * ```
219
+ */
220
+ function SqlExpressionValidatorPreset(options = {}) {
221
+ return {
222
+ plugins: [createSqlExpressionValidatorPlugin(options)]
223
+ };
224
+ }
package/validator.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Core SQL expression validation utilities.
3
+ *
4
+ * Standalone functions with no PostGraphile dependency.
5
+ * Uses pgsql-parser to parse SQL expressions and pgsql-deparser to
6
+ * produce canonical text output.
7
+ *
8
+ * SECURITY: Uses an allowlist approach — only explicitly allowed AST
9
+ * node types are accepted. Any unknown or unrecognized node type is
10
+ * rejected. This is safer than a denylist because new/unknown node
11
+ * types are blocked by default.
12
+ */
13
+ export interface SqlExpressionValidatorOptions {
14
+ /** List of allowed unqualified function names (case-insensitive). */
15
+ allowedFunctions?: string[];
16
+ /** List of allowed schema names for schema-qualified function calls. */
17
+ allowedSchemas?: string[];
18
+ /** Maximum allowed expression length in characters. Defaults to 10000. */
19
+ maxExpressionLength?: number;
20
+ }
21
+ export interface SqlExpressionValidationResult {
22
+ valid: boolean;
23
+ ast?: Record<string, unknown>;
24
+ canonicalText?: string;
25
+ error?: string;
26
+ }
27
+ export interface AstValidationResult {
28
+ valid: boolean;
29
+ canonicalText?: string;
30
+ error?: string;
31
+ }
32
+ /**
33
+ * Default list of allowed unqualified function names.
34
+ * These are common PostgreSQL functions considered safe for use in
35
+ * SQL expression defaults.
36
+ *
37
+ * NOTE: `current_timestamp`, `current_date`, `current_time`, `localtime`,
38
+ * and `localtimestamp` are parsed as `SQLValueFunction` nodes by pgsql-parser,
39
+ * not as `FuncCall` nodes. They are handled via `ALLOWED_SVFOP` below.
40
+ *
41
+ * `setseed` is intentionally excluded — it makes `random()` predictable
42
+ * for the session, which is a security risk.
43
+ *
44
+ * `date_part` is included as a safe alternative to `EXTRACT(... FROM ...)`,
45
+ * which parses as `pg_catalog.extract` (a schema-qualified call that would
46
+ * require adding `pg_catalog` to allowedSchemas — too permissive).
47
+ */
48
+ export declare const DEFAULT_ALLOWED_FUNCTIONS: string[];
49
+ /**
50
+ * Parse and validate a SQL expression string.
51
+ *
52
+ * 1. Guards: non-empty string, under maxExpressionLength, no semicolons
53
+ * 2. Wraps in `SELECT (expression)` then parses with pgsql-parser
54
+ * 3. Extracts AST from the parse result
55
+ * 4. Recursively validates the AST against the allowlist
56
+ * 5. Deparses via pgsql-deparser to produce canonical text
57
+ *
58
+ * @param expression - The SQL expression string to validate.
59
+ * @param options - Validation options.
60
+ * @returns Validation result with canonical text and AST on success.
61
+ */
62
+ export declare function parseAndValidateSqlExpression(expression: string, options?: SqlExpressionValidatorOptions): Promise<SqlExpressionValidationResult>;
63
+ /**
64
+ * Validate an already-parsed AST.
65
+ *
66
+ * @param ast - The AST object to validate.
67
+ * @param options - Validation options.
68
+ * @returns Validation result with canonical text on success.
69
+ */
70
+ export declare function validateAst(ast: unknown, options?: SqlExpressionValidatorOptions): AstValidationResult;
package/validator.js ADDED
@@ -0,0 +1,396 @@
1
+ "use strict";
2
+ /**
3
+ * Core SQL expression validation utilities.
4
+ *
5
+ * Standalone functions with no PostGraphile dependency.
6
+ * Uses pgsql-parser to parse SQL expressions and pgsql-deparser to
7
+ * produce canonical text output.
8
+ *
9
+ * SECURITY: Uses an allowlist approach — only explicitly allowed AST
10
+ * node types are accepted. Any unknown or unrecognized node type is
11
+ * rejected. This is safer than a denylist because new/unknown node
12
+ * types are blocked by default.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.DEFAULT_ALLOWED_FUNCTIONS = void 0;
16
+ exports.parseAndValidateSqlExpression = parseAndValidateSqlExpression;
17
+ exports.validateAst = validateAst;
18
+ const pgsql_parser_1 = require("pgsql-parser");
19
+ const pgsql_deparser_1 = require("pgsql-deparser");
20
+ // ─── Constants ────────────────────────────────────────────────────
21
+ /**
22
+ * Default list of allowed unqualified function names.
23
+ * These are common PostgreSQL functions considered safe for use in
24
+ * SQL expression defaults.
25
+ *
26
+ * NOTE: `current_timestamp`, `current_date`, `current_time`, `localtime`,
27
+ * and `localtimestamp` are parsed as `SQLValueFunction` nodes by pgsql-parser,
28
+ * not as `FuncCall` nodes. They are handled via `ALLOWED_SVFOP` below.
29
+ *
30
+ * `setseed` is intentionally excluded — it makes `random()` predictable
31
+ * for the session, which is a security risk.
32
+ *
33
+ * `date_part` is included as a safe alternative to `EXTRACT(... FROM ...)`,
34
+ * which parses as `pg_catalog.extract` (a schema-qualified call that would
35
+ * require adding `pg_catalog` to allowedSchemas — too permissive).
36
+ */
37
+ exports.DEFAULT_ALLOWED_FUNCTIONS = [
38
+ 'uuid_generate_v4',
39
+ 'gen_random_uuid',
40
+ 'now',
41
+ 'clock_timestamp',
42
+ 'statement_timestamp',
43
+ 'transaction_timestamp',
44
+ 'timeofday',
45
+ 'random',
46
+ 'date_part'
47
+ ];
48
+ /**
49
+ * AST node types that are explicitly allowed in expressions.
50
+ * Any single-keyed object whose key is not in this set is rejected.
51
+ *
52
+ * This includes both expression-level nodes (A_Const, FuncCall, etc.)
53
+ * and structural/leaf nodes that pgsql-parser uses internally for
54
+ * value wrappers and identifiers (String, Integer, TypeName, etc.).
55
+ *
56
+ * Structural nodes only appear inside allowed parent nodes. Dangerous
57
+ * parents (ColumnRef, SubLink, etc.) are rejected before recursion
58
+ * reaches their children, so including structural types here is safe.
59
+ */
60
+ const ALLOWED_NODE_TYPES = new Set([
61
+ // Expression-level nodes (safe SQL expression constructs)
62
+ 'A_Const',
63
+ 'TypeCast',
64
+ 'A_Expr',
65
+ 'FuncCall',
66
+ 'CoalesceExpr',
67
+ 'NullTest',
68
+ 'BoolExpr',
69
+ 'CaseExpr',
70
+ 'CaseWhen',
71
+ 'MinMaxExpr',
72
+ 'SQLValueFunction',
73
+ 'A_ArrayExpr',
74
+ // Structural/leaf nodes (used within expression nodes for values/identifiers)
75
+ 'String',
76
+ 'Integer',
77
+ 'Float',
78
+ 'BitString',
79
+ 'Null',
80
+ 'TypeName',
81
+ // Value wrappers inside A_Const (pgsql-parser v17 format)
82
+ 'ival',
83
+ 'sval',
84
+ 'fval',
85
+ 'boolval',
86
+ 'bsval'
87
+ ]);
88
+ /**
89
+ * Safe SQLValueFunction.op values.
90
+ *
91
+ * pgsql-parser represents `current_timestamp`, `current_date`, etc.
92
+ * as `SQLValueFunction` nodes with an `op` field. Some values like
93
+ * `current_user` and `session_user` are dangerous (information disclosure)
94
+ * so we only allow the time-related ones.
95
+ */
96
+ const ALLOWED_SVFOP = new Set([
97
+ 'SVFOP_CURRENT_TIMESTAMP',
98
+ 'SVFOP_CURRENT_DATE',
99
+ 'SVFOP_CURRENT_TIME',
100
+ 'SVFOP_LOCALTIME',
101
+ 'SVFOP_LOCALTIMESTAMP'
102
+ ]);
103
+ /**
104
+ * PostgreSQL system catalog type casts that are forbidden in expressions.
105
+ * These OID-alias types can be used to probe the system catalog.
106
+ */
107
+ const FORBIDDEN_TYPE_CASTS = new Set([
108
+ 'regclass',
109
+ 'regtype',
110
+ 'regproc',
111
+ 'regprocedure',
112
+ 'regoper',
113
+ 'regoperator',
114
+ 'regnamespace',
115
+ 'regrole',
116
+ 'regconfig',
117
+ 'regdictionary'
118
+ ]);
119
+ const MAX_AST_DEPTH = 100;
120
+ const SQL_COMMENT_TOKENS = /--|\/\*|\*\//;
121
+ // ─── Internal helpers ─────────────────────────────────────────────
122
+ /**
123
+ * Extract the node type from a pgsql-parser AST node.
124
+ * AST nodes are objects with a single key representing the node type.
125
+ */
126
+ function getNodeType(node) {
127
+ const keys = Object.keys(node);
128
+ if (keys.length === 1)
129
+ return { type: keys[0], suspicious: false };
130
+ const astLikeKeys = keys.filter(k => /^[A-Z]/.test(k));
131
+ if (astLikeKeys.length > 0) {
132
+ return { type: null, suspicious: true };
133
+ }
134
+ return { type: null, suspicious: false };
135
+ }
136
+ function extractStringVal(n) {
137
+ if (typeof n === 'object' && n !== null) {
138
+ const rec = n;
139
+ const sval = rec.String?.sval;
140
+ if (typeof sval === 'string')
141
+ return sval;
142
+ if (typeof rec.str === 'string')
143
+ return rec.str;
144
+ }
145
+ return '';
146
+ }
147
+ /**
148
+ * Recursively validate an AST node against the allowlist rules.
149
+ * Uses mutable push/pop on path for performance.
150
+ */
151
+ function validateAstNode(node, allowedFunctions, allowedSchemas, path) {
152
+ if (path.length > MAX_AST_DEPTH) {
153
+ return {
154
+ valid: false,
155
+ error: `AST exceeds maximum depth of ${MAX_AST_DEPTH} at path: ${path.join('.')}`
156
+ };
157
+ }
158
+ if (node === null || node === undefined || typeof node !== 'object') {
159
+ return { valid: true };
160
+ }
161
+ const rec = node;
162
+ const { type: nodeType, suspicious } = getNodeType(rec);
163
+ // Multi-key AST nodes with uppercase keys are suspicious
164
+ if (suspicious) {
165
+ return {
166
+ valid: false,
167
+ error: `Suspicious multi-key AST node at path: ${path.join('.')}`
168
+ };
169
+ }
170
+ // Allowlist check: if this looks like a typed AST node, it must be allowed
171
+ if (nodeType !== null && !ALLOWED_NODE_TYPES.has(nodeType)) {
172
+ return {
173
+ valid: false,
174
+ error: `Disallowed node type "${nodeType}" at path: ${path.join('.')}`
175
+ };
176
+ }
177
+ // SQLValueFunction: check op is safe
178
+ if (nodeType === 'SQLValueFunction') {
179
+ const svf = rec.SQLValueFunction;
180
+ if (typeof svf === 'object' && svf !== null) {
181
+ const op = svf.op;
182
+ if (typeof op === 'string' && !ALLOWED_SVFOP.has(op)) {
183
+ return {
184
+ valid: false,
185
+ error: `Disallowed SQLValueFunction op "${op}" at path: ${path.join('.')}`
186
+ };
187
+ }
188
+ }
189
+ }
190
+ // TypeCast: check for forbidden system catalog types
191
+ if (nodeType === 'TypeCast') {
192
+ const typeCast = rec.TypeCast;
193
+ const typeName = typeCast?.typeName;
194
+ if (typeName?.names && Array.isArray(typeName.names)) {
195
+ const names = typeName.names
196
+ .map(extractStringVal)
197
+ .filter(Boolean);
198
+ const castType = names[names.length - 1]?.toLowerCase();
199
+ if (castType && FORBIDDEN_TYPE_CASTS.has(castType)) {
200
+ return {
201
+ valid: false,
202
+ error: `Forbidden type cast to "${castType}" — system catalog types are not allowed`
203
+ };
204
+ }
205
+ }
206
+ }
207
+ // FuncCall: validate function name and schema
208
+ if (nodeType === 'FuncCall') {
209
+ const funcCall = rec.FuncCall;
210
+ const funcName = funcCall?.funcname;
211
+ if (Array.isArray(funcName)) {
212
+ const names = funcName.map(extractStringVal);
213
+ const schemaName = names.length > 1 ? names[0] : null;
214
+ const functionName = names[names.length - 1];
215
+ if (schemaName) {
216
+ if (!allowedSchemas.has(schemaName.toLowerCase())) {
217
+ return {
218
+ valid: false,
219
+ error: `Function schema "${schemaName}" is not in the allowed schemas list`
220
+ };
221
+ }
222
+ // Also validate the function name when schema-qualified
223
+ if (!allowedFunctions.has(functionName.toLowerCase())) {
224
+ return {
225
+ valid: false,
226
+ error: `Function "${schemaName}.${functionName}" is not in the allowed functions list`
227
+ };
228
+ }
229
+ }
230
+ else {
231
+ if (!allowedFunctions.has(functionName.toLowerCase())) {
232
+ return {
233
+ valid: false,
234
+ error: `Function "${functionName}" is not in the allowed functions list`
235
+ };
236
+ }
237
+ }
238
+ }
239
+ }
240
+ // Recurse into children
241
+ for (const [key, value] of Object.entries(rec)) {
242
+ if (Array.isArray(value)) {
243
+ for (let i = 0; i < value.length; i++) {
244
+ path.push(key, String(i));
245
+ const result = validateAstNode(value[i], allowedFunctions, allowedSchemas, path);
246
+ path.pop();
247
+ path.pop();
248
+ if (!result.valid)
249
+ return result;
250
+ }
251
+ }
252
+ else if (value !== null && typeof value === 'object') {
253
+ path.push(key);
254
+ const result = validateAstNode(value, allowedFunctions, allowedSchemas, path);
255
+ path.pop();
256
+ if (!result.valid)
257
+ return result;
258
+ }
259
+ }
260
+ return { valid: true };
261
+ }
262
+ // ─── Public API ───────────────────────────────────────────────────
263
+ /**
264
+ * Parse and validate a SQL expression string.
265
+ *
266
+ * 1. Guards: non-empty string, under maxExpressionLength, no semicolons
267
+ * 2. Wraps in `SELECT (expression)` then parses with pgsql-parser
268
+ * 3. Extracts AST from the parse result
269
+ * 4. Recursively validates the AST against the allowlist
270
+ * 5. Deparses via pgsql-deparser to produce canonical text
271
+ *
272
+ * @param expression - The SQL expression string to validate.
273
+ * @param options - Validation options.
274
+ * @returns Validation result with canonical text and AST on success.
275
+ */
276
+ async function parseAndValidateSqlExpression(expression, options = {}) {
277
+ const { allowedFunctions = exports.DEFAULT_ALLOWED_FUNCTIONS, allowedSchemas = [], maxExpressionLength = 10000 } = options;
278
+ if (!expression || typeof expression !== 'string') {
279
+ return { valid: false, error: 'Expression must be a non-empty string' };
280
+ }
281
+ if (expression.length > maxExpressionLength) {
282
+ return {
283
+ valid: false,
284
+ error: `Expression exceeds maximum length of ${maxExpressionLength} characters`
285
+ };
286
+ }
287
+ if (expression.includes(';')) {
288
+ return {
289
+ valid: false,
290
+ error: 'Expression cannot contain semicolons (no stacked statements)'
291
+ };
292
+ }
293
+ if (SQL_COMMENT_TOKENS.test(expression)) {
294
+ return {
295
+ valid: false,
296
+ error: 'Expression cannot contain SQL comments'
297
+ };
298
+ }
299
+ const funcSet = new Set(allowedFunctions.map((f) => f.toLowerCase()));
300
+ const schemaSet = new Set(allowedSchemas.map((s) => s.toLowerCase()));
301
+ try {
302
+ const wrappedSql = `SELECT (${expression})`;
303
+ const parseResult = await (0, pgsql_parser_1.parse)(wrappedSql);
304
+ if (!parseResult ||
305
+ !parseResult.stmts ||
306
+ parseResult.stmts.length !== 1) {
307
+ return { valid: false, error: 'Failed to parse expression' };
308
+ }
309
+ const stmt = parseResult.stmts[0]?.stmt;
310
+ if (!stmt?.SelectStmt) {
311
+ return { valid: false, error: 'Unexpected parse result structure' };
312
+ }
313
+ const selectStmt = stmt.SelectStmt;
314
+ const DANGEROUS_SELECT_KEYS = [
315
+ 'fromClause', 'whereClause', 'larg', 'rarg', 'valuesLists',
316
+ 'intoClause', 'withClause', 'groupClause', 'havingClause',
317
+ 'windowClause', 'sortClause', 'limitOffset', 'limitCount',
318
+ 'lockingClause', 'distinctClause'
319
+ ];
320
+ for (const dangerousKey of DANGEROUS_SELECT_KEYS) {
321
+ if (selectStmt[dangerousKey] !== undefined) {
322
+ return {
323
+ valid: false,
324
+ error: `Expression contains disallowed SQL clause: ${dangerousKey}`
325
+ };
326
+ }
327
+ }
328
+ const targetList = selectStmt.targetList;
329
+ if (!targetList || targetList.length !== 1) {
330
+ return { valid: false, error: 'Expected single expression' };
331
+ }
332
+ const resTarget = targetList[0]?.ResTarget;
333
+ if (!resTarget || !resTarget.val) {
334
+ return {
335
+ valid: false,
336
+ error: 'Could not extract expression from parse result'
337
+ };
338
+ }
339
+ const expressionAst = resTarget.val;
340
+ const validationResult = validateAstNode(expressionAst, funcSet, schemaSet, []);
341
+ if (!validationResult.valid) {
342
+ return { valid: false, error: validationResult.error };
343
+ }
344
+ let canonicalText;
345
+ try {
346
+ canonicalText = (0, pgsql_deparser_1.deparseSync)([expressionAst]);
347
+ }
348
+ catch (deparseError) {
349
+ return {
350
+ valid: false,
351
+ error: `Failed to deparse expression: ${deparseError}`
352
+ };
353
+ }
354
+ return {
355
+ valid: true,
356
+ ast: expressionAst,
357
+ canonicalText
358
+ };
359
+ }
360
+ catch (e) {
361
+ const msg = e instanceof Error ? e.message : String(e);
362
+ return {
363
+ valid: false,
364
+ error: `Failed to parse SQL expression: ${msg}`
365
+ };
366
+ }
367
+ }
368
+ /**
369
+ * Validate an already-parsed AST.
370
+ *
371
+ * @param ast - The AST object to validate.
372
+ * @param options - Validation options.
373
+ * @returns Validation result with canonical text on success.
374
+ */
375
+ function validateAst(ast, options = {}) {
376
+ const { allowedFunctions = exports.DEFAULT_ALLOWED_FUNCTIONS, allowedSchemas = [] } = options;
377
+ if (!ast || typeof ast !== 'object') {
378
+ return { valid: false, error: 'AST must be a non-null object' };
379
+ }
380
+ const funcSet = new Set(allowedFunctions.map((f) => f.toLowerCase()));
381
+ const schemaSet = new Set(allowedSchemas.map((s) => s.toLowerCase()));
382
+ const validationResult = validateAstNode(ast, funcSet, schemaSet, []);
383
+ if (!validationResult.valid) {
384
+ return { valid: false, error: validationResult.error };
385
+ }
386
+ try {
387
+ const canonicalText = (0, pgsql_deparser_1.deparseSync)([ast]);
388
+ return { valid: true, canonicalText };
389
+ }
390
+ catch (deparseError) {
391
+ return {
392
+ valid: false,
393
+ error: `Failed to deparse AST: ${deparseError}`
394
+ };
395
+ }
396
+ }