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