graphile-sql-expression-validator 0.3.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/index.d.ts CHANGED
@@ -1,21 +1,35 @@
1
- import type { Plugin } from 'graphile-build';
2
- export interface SqlExpressionValidatorOptions {
3
- allowedFunctions?: string[];
4
- allowedSchemas?: string[];
5
- maxExpressionLength?: number;
6
- allowOwnedSchemas?: boolean;
7
- getAdditionalAllowedSchemas?: (context: any) => Promise<string[]>;
8
- }
9
- export declare function parseAndValidateSqlExpression(expression: string, options?: SqlExpressionValidatorOptions): Promise<{
10
- valid: boolean;
11
- ast?: any;
12
- canonicalText?: string;
13
- error?: string;
14
- }>;
15
- export declare function validateAst(ast: any, options?: SqlExpressionValidatorOptions): Promise<{
16
- valid: boolean;
17
- canonicalText?: string;
18
- error?: string;
19
- }>;
20
- declare const SqlExpressionValidatorPlugin: Plugin;
21
- export default SqlExpressionValidatorPlugin;
1
+ /**
2
+ * SQL Expression Validator for PostGraphile v5
3
+ *
4
+ * Provides both standalone SQL expression validation utilities and a
5
+ * PostGraphile v5 plugin that validates `@sqlExpression` tagged columns
6
+ * in mutation inputs.
7
+ *
8
+ * @example Standalone validation
9
+ * ```typescript
10
+ * import { parseAndValidateSqlExpression } from 'graphile-sql-expression-validator';
11
+ *
12
+ * const result = await parseAndValidateSqlExpression('now()', {
13
+ * allowedFunctions: ['now', 'gen_random_uuid'],
14
+ * });
15
+ * if (result.valid) {
16
+ * console.log(result.canonicalText); // 'now()'
17
+ * }
18
+ * ```
19
+ *
20
+ * @example PostGraphile v5 preset
21
+ * ```typescript
22
+ * import { SqlExpressionValidatorPreset } from 'graphile-sql-expression-validator';
23
+ *
24
+ * const preset: GraphileConfig.Preset = {
25
+ * extends: [
26
+ * SqlExpressionValidatorPreset({
27
+ * allowedSchemas: ['app_public'],
28
+ * }),
29
+ * ],
30
+ * };
31
+ * ```
32
+ */
33
+ export { parseAndValidateSqlExpression, validateAst, DEFAULT_ALLOWED_FUNCTIONS } from './validator';
34
+ export type { SqlExpressionValidatorOptions, SqlExpressionValidationResult, AstValidationResult } from './validator';
35
+ export { createSqlExpressionValidatorPlugin, SqlExpressionValidatorPreset } from './plugin';
package/index.js CHANGED
@@ -1,345 +1,44 @@
1
1
  "use strict";
2
+ /**
3
+ * SQL Expression Validator for PostGraphile v5
4
+ *
5
+ * Provides both standalone SQL expression validation utilities and a
6
+ * PostGraphile v5 plugin that validates `@sqlExpression` tagged columns
7
+ * in mutation inputs.
8
+ *
9
+ * @example Standalone validation
10
+ * ```typescript
11
+ * import { parseAndValidateSqlExpression } from 'graphile-sql-expression-validator';
12
+ *
13
+ * const result = await parseAndValidateSqlExpression('now()', {
14
+ * allowedFunctions: ['now', 'gen_random_uuid'],
15
+ * });
16
+ * if (result.valid) {
17
+ * console.log(result.canonicalText); // 'now()'
18
+ * }
19
+ * ```
20
+ *
21
+ * @example PostGraphile v5 preset
22
+ * ```typescript
23
+ * import { SqlExpressionValidatorPreset } from 'graphile-sql-expression-validator';
24
+ *
25
+ * const preset: GraphileConfig.Preset = {
26
+ * extends: [
27
+ * SqlExpressionValidatorPreset({
28
+ * allowedSchemas: ['app_public'],
29
+ * }),
30
+ * ],
31
+ * };
32
+ * ```
33
+ */
2
34
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseAndValidateSqlExpression = parseAndValidateSqlExpression;
4
- exports.validateAst = validateAst;
5
- const pgsql_parser_1 = require("pgsql-parser");
6
- const pgsql_deparser_1 = require("pgsql-deparser");
7
- const DEFAULT_ALLOWED_FUNCTIONS = [
8
- 'uuid_generate_v4',
9
- 'gen_random_uuid',
10
- 'now',
11
- 'current_timestamp',
12
- 'current_date',
13
- 'current_time',
14
- 'localtime',
15
- 'localtimestamp',
16
- 'clock_timestamp',
17
- 'statement_timestamp',
18
- 'transaction_timestamp',
19
- 'timeofday',
20
- 'random',
21
- 'setseed',
22
- ];
23
- const ALLOWED_NODE_TYPES = new Set([
24
- 'A_Const',
25
- 'TypeCast',
26
- 'A_Expr',
27
- 'FuncCall',
28
- 'CoalesceExpr',
29
- 'NullTest',
30
- 'BoolExpr',
31
- 'CaseExpr',
32
- 'CaseWhen',
33
- ]);
34
- const FORBIDDEN_NODE_TYPES = new Set([
35
- 'SelectStmt',
36
- 'InsertStmt',
37
- 'UpdateStmt',
38
- 'DeleteStmt',
39
- 'CreateStmt',
40
- 'AlterTableStmt',
41
- 'DropStmt',
42
- 'TruncateStmt',
43
- 'ColumnRef',
44
- 'SubLink',
45
- 'RangeVar',
46
- 'RangeSubselect',
47
- 'JoinExpr',
48
- 'FromExpr',
49
- ]);
50
- function getNodeType(node) {
51
- if (!node || typeof node !== 'object')
52
- return null;
53
- const keys = Object.keys(node);
54
- if (keys.length === 1)
55
- return keys[0];
56
- return null;
57
- }
58
- function validateAstNode(node, allowedFunctions, allowedSchemas, path = []) {
59
- if (!node || typeof node !== 'object') {
60
- return { valid: true };
61
- }
62
- const nodeType = getNodeType(node);
63
- if (nodeType && FORBIDDEN_NODE_TYPES.has(nodeType)) {
64
- return {
65
- valid: false,
66
- error: `Forbidden node type "${nodeType}" at path: ${path.join('.')}`,
67
- };
68
- }
69
- if (nodeType === 'FuncCall') {
70
- const funcCall = node.FuncCall;
71
- const funcName = funcCall?.funcname;
72
- if (Array.isArray(funcName)) {
73
- const names = funcName.map((n) => n.String?.sval || n.str || '');
74
- const schemaName = names.length > 1 ? names[0] : null;
75
- const functionName = names[names.length - 1];
76
- if (schemaName) {
77
- if (!allowedSchemas.includes(schemaName)) {
78
- return {
79
- valid: false,
80
- error: `Function schema "${schemaName}" is not in the allowed schemas list`,
81
- };
82
- }
83
- }
84
- else {
85
- if (!allowedFunctions.includes(functionName.toLowerCase())) {
86
- return {
87
- valid: false,
88
- error: `Function "${functionName}" is not in the allowed functions list`,
89
- };
90
- }
91
- }
92
- }
93
- }
94
- for (const [key, value] of Object.entries(node)) {
95
- if (Array.isArray(value)) {
96
- for (let i = 0; i < value.length; i++) {
97
- const result = validateAstNode(value[i], allowedFunctions, allowedSchemas, [...path, key, String(i)]);
98
- if (!result.valid)
99
- return result;
100
- }
101
- }
102
- else if (value && typeof value === 'object') {
103
- const result = validateAstNode(value, allowedFunctions, allowedSchemas, [
104
- ...path,
105
- key,
106
- ]);
107
- if (!result.valid)
108
- return result;
109
- }
110
- }
111
- return { valid: true };
112
- }
113
- async function parseAndValidateSqlExpression(expression, options = {}) {
114
- const { allowedFunctions = DEFAULT_ALLOWED_FUNCTIONS, allowedSchemas = [], maxExpressionLength = 10000, } = options;
115
- if (!expression || typeof expression !== 'string') {
116
- return { valid: false, error: 'Expression must be a non-empty string' };
117
- }
118
- if (expression.length > maxExpressionLength) {
119
- return {
120
- valid: false,
121
- error: `Expression exceeds maximum length of ${maxExpressionLength} characters`,
122
- };
123
- }
124
- if (expression.includes(';')) {
125
- return {
126
- valid: false,
127
- error: 'Expression cannot contain semicolons (no stacked statements)',
128
- };
129
- }
130
- try {
131
- const wrappedSql = `SELECT (${expression})`;
132
- const parseResult = await (0, pgsql_parser_1.parse)(wrappedSql);
133
- if (!parseResult ||
134
- !parseResult.stmts ||
135
- parseResult.stmts.length !== 1) {
136
- return { valid: false, error: 'Failed to parse expression' };
137
- }
138
- const stmt = parseResult.stmts[0]?.stmt;
139
- if (!stmt?.SelectStmt) {
140
- return { valid: false, error: 'Unexpected parse result structure' };
141
- }
142
- const targetList = stmt.SelectStmt.targetList;
143
- if (!targetList || targetList.length !== 1) {
144
- return { valid: false, error: 'Expected single expression' };
145
- }
146
- const resTarget = targetList[0]?.ResTarget;
147
- if (!resTarget || !resTarget.val) {
148
- return { valid: false, error: 'Could not extract expression from parse result' };
149
- }
150
- const expressionAst = resTarget.val;
151
- const validationResult = validateAstNode(expressionAst, allowedFunctions.map((f) => f.toLowerCase()), allowedSchemas);
152
- if (!validationResult.valid) {
153
- return { valid: false, error: validationResult.error };
154
- }
155
- let canonicalText;
156
- try {
157
- canonicalText = await (0, pgsql_deparser_1.deparse)([expressionAst]);
158
- }
159
- catch (deparseError) {
160
- return {
161
- valid: false,
162
- error: `Failed to deparse expression: ${deparseError}`,
163
- };
164
- }
165
- return {
166
- valid: true,
167
- ast: expressionAst,
168
- canonicalText,
169
- };
170
- }
171
- catch (parseError) {
172
- return {
173
- valid: false,
174
- error: `Failed to parse SQL expression: ${parseError.message || parseError}`,
175
- };
176
- }
177
- }
178
- async function validateAst(ast, options = {}) {
179
- const { allowedFunctions = DEFAULT_ALLOWED_FUNCTIONS, allowedSchemas = [] } = options;
180
- if (!ast || typeof ast !== 'object') {
181
- return { valid: false, error: 'AST must be a non-null object' };
182
- }
183
- const validationResult = validateAstNode(ast, allowedFunctions.map((f) => f.toLowerCase()), allowedSchemas);
184
- if (!validationResult.valid) {
185
- return { valid: false, error: validationResult.error };
186
- }
187
- try {
188
- const canonicalText = await (0, pgsql_deparser_1.deparse)([ast]);
189
- return { valid: true, canonicalText };
190
- }
191
- catch (deparseError) {
192
- return {
193
- valid: false,
194
- error: `Failed to deparse AST: ${deparseError}`,
195
- };
196
- }
197
- }
198
- const OWNED_SCHEMAS_CACHE_KEY = Symbol('sqlExpressionValidator.ownedSchemas');
199
- async function resolveEffectiveOptions(baseOptions, gqlContext) {
200
- const { allowedSchemas = [], allowOwnedSchemas = false, getAdditionalAllowedSchemas, ...rest } = baseOptions;
201
- const effectiveSchemas = [...allowedSchemas];
202
- if (allowOwnedSchemas && gqlContext?.pgClient) {
203
- let ownedSchemas = gqlContext[OWNED_SCHEMAS_CACHE_KEY];
204
- if (!ownedSchemas) {
205
- try {
206
- const result = await gqlContext.pgClient.query(`SELECT schema_name FROM metaschema_public.schema WHERE database_id = jwt_private.current_database_id()`);
207
- ownedSchemas = result.rows.map((row) => row.schema_name);
208
- gqlContext[OWNED_SCHEMAS_CACHE_KEY] = ownedSchemas;
209
- }
210
- catch (err) {
211
- ownedSchemas = [];
212
- }
213
- }
214
- effectiveSchemas.push(...ownedSchemas);
215
- }
216
- if (getAdditionalAllowedSchemas) {
217
- try {
218
- const additionalSchemas = await getAdditionalAllowedSchemas(gqlContext);
219
- effectiveSchemas.push(...additionalSchemas);
220
- }
221
- catch (err) {
222
- }
223
- }
224
- const uniqueSchemas = [...new Set(effectiveSchemas)];
225
- return {
226
- ...rest,
227
- allowedSchemas: uniqueSchemas,
228
- };
229
- }
230
- const SqlExpressionValidatorPlugin = (builder, options = {}) => {
231
- const validatorOptions = options.sqlExpressionValidator || {};
232
- builder.hook('GraphQLObjectType:fields:field', (field, build, context) => {
233
- const { scope: { isRootMutation, fieldName, pgFieldIntrospection: table }, } = context;
234
- if (!isRootMutation || !table) {
235
- return field;
236
- }
237
- const sqlExpressionColumns = build.pgIntrospectionResultsByKind.attribute
238
- .filter((attr) => attr.classId === table.id)
239
- .filter((attr) => attr.tags?.sqlExpression);
240
- if (sqlExpressionColumns.length === 0) {
241
- return field;
242
- }
243
- const defaultResolver = (obj) => obj[fieldName];
244
- const { resolve: oldResolve = defaultResolver, ...rest } = field;
245
- return {
246
- ...rest,
247
- async resolve(source, args, gqlContext, info) {
248
- const effectiveOptions = await resolveEffectiveOptions(validatorOptions, gqlContext);
249
- for (const attr of sqlExpressionColumns) {
250
- const textGqlName = build.inflection.column(attr);
251
- const rawSqlAstFieldTag = attr.tags?.rawSqlAstField;
252
- const astDbName = typeof rawSqlAstFieldTag === 'string' && rawSqlAstFieldTag.trim()
253
- ? rawSqlAstFieldTag.trim()
254
- : `${attr.name}_ast`;
255
- const astAttr = build.pgIntrospectionResultsByKind.attribute.find((a) => a.classId === table.id && a.name === astDbName);
256
- let astGqlName = null;
257
- if (astAttr) {
258
- astGqlName = build.inflection.column(astAttr);
259
- }
260
- else if (typeof rawSqlAstFieldTag === 'string' && rawSqlAstFieldTag.trim()) {
261
- throw new Error(`@rawSqlAstField points to missing column "${astDbName}" on ${table.namespaceName}.${table.name}`);
262
- }
263
- const inputPath = findInputPath(args, textGqlName);
264
- const astInputPath = astGqlName ? findInputPath(args, astGqlName) : null;
265
- if (inputPath) {
266
- const textValue = getNestedValue(args, inputPath);
267
- if (textValue !== undefined && textValue !== null) {
268
- const result = await parseAndValidateSqlExpression(textValue, effectiveOptions);
269
- if (!result.valid) {
270
- throw new Error(`Invalid SQL expression in ${textGqlName}: ${result.error}`);
271
- }
272
- setNestedValue(args, inputPath, result.canonicalText);
273
- if (astGqlName && (astInputPath || canSetAstColumn(args, inputPath, astGqlName))) {
274
- const astPath = astInputPath || replaceLastSegment(inputPath, astGqlName);
275
- setNestedValue(args, astPath, result.ast);
276
- }
277
- }
278
- }
279
- if (astInputPath && !inputPath && astGqlName) {
280
- const astValue = getNestedValue(args, astInputPath);
281
- if (astValue !== undefined && astValue !== null) {
282
- const result = await validateAst(astValue, effectiveOptions);
283
- if (!result.valid) {
284
- throw new Error(`Invalid SQL expression AST in ${astGqlName}: ${result.error}`);
285
- }
286
- const textPath = replaceLastSegment(astInputPath, textGqlName);
287
- if (canSetColumn(args, astInputPath, textGqlName)) {
288
- setNestedValue(args, textPath, result.canonicalText);
289
- }
290
- }
291
- }
292
- }
293
- return oldResolve(source, args, gqlContext, info);
294
- },
295
- };
296
- });
297
- };
298
- function findInputPath(obj, key, path = []) {
299
- if (!obj || typeof obj !== 'object')
300
- return null;
301
- for (const [k, v] of Object.entries(obj)) {
302
- if (k === key) {
303
- return [...path, k];
304
- }
305
- if (v && typeof v === 'object') {
306
- const result = findInputPath(v, key, [...path, k]);
307
- if (result)
308
- return result;
309
- }
310
- }
311
- return null;
312
- }
313
- function getNestedValue(obj, path) {
314
- let current = obj;
315
- for (const key of path) {
316
- if (current === null || current === undefined)
317
- return undefined;
318
- current = current[key];
319
- }
320
- return current;
321
- }
322
- function setNestedValue(obj, path, value) {
323
- let current = obj;
324
- for (let i = 0; i < path.length - 1; i++) {
325
- if (current[path[i]] === undefined) {
326
- current[path[i]] = {};
327
- }
328
- current = current[path[i]];
329
- }
330
- current[path[path.length - 1]] = value;
331
- }
332
- function replaceLastSegment(path, newSegment) {
333
- return [...path.slice(0, -1), newSegment];
334
- }
335
- function canSetAstColumn(args, textPath, astColumnName) {
336
- const parentPath = textPath.slice(0, -1);
337
- const parent = getNestedValue(args, parentPath);
338
- return parent && typeof parent === 'object';
339
- }
340
- function canSetColumn(args, astPath, columnName) {
341
- const parentPath = astPath.slice(0, -1);
342
- const parent = getNestedValue(args, parentPath);
343
- return parent && typeof parent === 'object';
344
- }
345
- exports.default = SqlExpressionValidatorPlugin;
35
+ exports.SqlExpressionValidatorPreset = exports.createSqlExpressionValidatorPlugin = exports.DEFAULT_ALLOWED_FUNCTIONS = exports.validateAst = exports.parseAndValidateSqlExpression = void 0;
36
+ // Standalone validation utilities
37
+ var validator_1 = require("./validator");
38
+ Object.defineProperty(exports, "parseAndValidateSqlExpression", { enumerable: true, get: function () { return validator_1.parseAndValidateSqlExpression; } });
39
+ Object.defineProperty(exports, "validateAst", { enumerable: true, get: function () { return validator_1.validateAst; } });
40
+ Object.defineProperty(exports, "DEFAULT_ALLOWED_FUNCTIONS", { enumerable: true, get: function () { return validator_1.DEFAULT_ALLOWED_FUNCTIONS; } });
41
+ // PostGraphile v5 plugin and preset
42
+ var plugin_1 = require("./plugin");
43
+ Object.defineProperty(exports, "createSqlExpressionValidatorPlugin", { enumerable: true, get: function () { return plugin_1.createSqlExpressionValidatorPlugin; } });
44
+ Object.defineProperty(exports, "SqlExpressionValidatorPreset", { enumerable: true, get: function () { return plugin_1.SqlExpressionValidatorPreset; } });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "graphile-sql-expression-validator",
3
- "version": "0.3.0",
4
- "description": "Graphile plugin for SQL expression validation and AST normalization",
3
+ "version": "2.2.0",
4
+ "description": "SQL expression validation for PostGraphile v5",
5
5
  "author": "Constructive <developers@constructive.io>",
6
6
  "homepage": "https://github.com/constructive-io/constructive",
7
7
  "license": "MIT",
@@ -10,11 +10,11 @@
10
10
  "types": "index.d.ts",
11
11
  "scripts": {
12
12
  "clean": "makage clean",
13
- "prepack": "pnpm run build",
13
+ "prepack": "npm run build",
14
14
  "build": "makage build",
15
15
  "build:dev": "makage build --dev",
16
16
  "lint": "eslint . --fix",
17
- "test": "jest --passWithNoTests",
17
+ "test": "jest",
18
18
  "test:watch": "jest --watch"
19
19
  },
20
20
  "publishConfig": {
@@ -41,15 +41,20 @@
41
41
  "bugs": {
42
42
  "url": "https://github.com/constructive-io/constructive/issues"
43
43
  },
44
- "devDependencies": {
45
- "makage": "^0.1.10",
46
- "ts-jest": "^29.4.6"
47
- },
48
44
  "dependencies": {
49
- "graphile-build": "^4.14.1",
50
- "graphql": "15.10.1",
51
45
  "pgsql-deparser": "^17.17.2",
52
46
  "pgsql-parser": "^17.9.11"
53
47
  },
54
- "gitHead": "481b3a50b4eec2da6b376c4cd1868065e1e28edb"
48
+ "peerDependencies": {
49
+ "grafast": "^1.0.0-rc.7",
50
+ "graphile-build": "^5.0.0-rc.4",
51
+ "graphile-build-pg": "^5.0.0-rc.5",
52
+ "graphile-config": "^1.0.0-rc.5",
53
+ "graphql": "^16.9.0"
54
+ },
55
+ "devDependencies": {
56
+ "@types/node": "^22.19.1",
57
+ "makage": "^0.1.10"
58
+ },
59
+ "gitHead": "b758178b808ce0bf451e86c0bd7e92079155db7c"
55
60
  }
package/plugin.d.ts ADDED
@@ -0,0 +1,54 @@
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 type { GraphileConfig } from 'graphile-config';
25
+ import 'graphile-build';
26
+ import 'graphile-build-pg';
27
+ import type { SqlExpressionValidatorOptions } from './validator';
28
+ /**
29
+ * Creates the SQL Expression Validator PostGraphile v5 plugin.
30
+ *
31
+ * Options are pre-computed at build time (allowedFunctions lowercased
32
+ * into a Set) to avoid per-execution allocations.
33
+ *
34
+ * @param validatorOptions - Options for SQL expression validation.
35
+ * @returns GraphileConfig.Plugin
36
+ */
37
+ export declare function createSqlExpressionValidatorPlugin(validatorOptions?: SqlExpressionValidatorOptions): GraphileConfig.Plugin;
38
+ /**
39
+ * Creates a preset that includes the SQL expression validator plugin.
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * import { SqlExpressionValidatorPreset } from 'graphile-sql-expression-validator';
44
+ *
45
+ * const preset: GraphileConfig.Preset = {
46
+ * extends: [
47
+ * SqlExpressionValidatorPreset({
48
+ * allowedSchemas: ['app_public'],
49
+ * }),
50
+ * ],
51
+ * };
52
+ * ```
53
+ */
54
+ export declare function SqlExpressionValidatorPreset(options?: SqlExpressionValidatorOptions): GraphileConfig.Preset;