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/README.md +19 -107
- package/esm/index.d.ts +35 -21
- package/esm/index.js +36 -341
- package/esm/plugin.d.ts +54 -0
- package/esm/plugin.js +220 -0
- package/esm/validator.d.ts +70 -0
- package/esm/validator.js +391 -0
- package/index.d.ts +35 -21
- package/index.js +42 -343
- package/package.json +16 -11
- package/plugin.d.ts +54 -0
- package/plugin.js +224 -0
- package/validator.d.ts +70 -0
- package/validator.js +396 -0
package/README.md
CHANGED
|
@@ -1,127 +1,39 @@
|
|
|
1
1
|
# graphile-sql-expression-validator
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
SQL expression validation and normalization for PostGraphile v5.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
```sh
|
|
8
|
-
npm install graphile-sql-expression-validator
|
|
9
|
-
```
|
|
5
|
+
Validates SQL expressions against a configurable allowlist of functions and schemas, preventing injection of dangerous SQL constructs while allowing safe default expressions.
|
|
10
6
|
|
|
11
7
|
## Usage
|
|
12
8
|
|
|
13
|
-
###
|
|
14
|
-
|
|
15
|
-
Tag columns that contain SQL expressions with `@sqlExpression`:
|
|
16
|
-
|
|
17
|
-
```sql
|
|
18
|
-
COMMENT ON COLUMN metaschema_public.field.default_value IS E'@sqlExpression';
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
The plugin will automatically look for a companion `*_ast` column (e.g., `default_value_ast`) to store the parsed AST.
|
|
22
|
-
|
|
23
|
-
#### Custom AST Field Name
|
|
24
|
-
|
|
25
|
-
By default, the plugin looks for a companion column named `<column>_ast`. You can override this with `@rawSqlAstField`:
|
|
26
|
-
|
|
27
|
-
```sql
|
|
28
|
-
-- Use a custom AST column name
|
|
29
|
-
COMMENT ON COLUMN metaschema_public.field.default_value IS E'@sqlExpression\n@rawSqlAstField my_custom_ast_column';
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
If `@rawSqlAstField` points to a non-existent column, the plugin will throw an error. If not specified, it falls back to the `<column>_ast` convention (and silently skips AST storage if that column doesn't exist).
|
|
33
|
-
|
|
34
|
-
### Plugin Configuration
|
|
35
|
-
|
|
36
|
-
```typescript
|
|
37
|
-
import SqlExpressionValidatorPlugin from 'graphile-sql-expression-validator';
|
|
38
|
-
|
|
39
|
-
const postgraphileOptions = {
|
|
40
|
-
appendPlugins: [SqlExpressionValidatorPlugin],
|
|
41
|
-
graphileBuildOptions: {
|
|
42
|
-
sqlExpressionValidator: {
|
|
43
|
-
// Optional: Additional allowed functions beyond defaults
|
|
44
|
-
allowedFunctions: ['my_custom_function'],
|
|
45
|
-
// Optional: Allowed schema names for schema-qualified functions
|
|
46
|
-
allowedSchemas: ['my_schema'],
|
|
47
|
-
// Optional: Maximum expression length (default: 10000)
|
|
48
|
-
maxExpressionLength: 5000,
|
|
49
|
-
// Optional: Auto-allow schemas owned by the current database
|
|
50
|
-
// Queries: SELECT schema_name FROM metaschema_public.schema
|
|
51
|
-
// WHERE database_id = jwt_private.current_database_id()
|
|
52
|
-
allowOwnedSchemas: true,
|
|
53
|
-
// Optional: Custom hook for dynamic schema resolution
|
|
54
|
-
getAdditionalAllowedSchemas: async (context) => {
|
|
55
|
-
// Return additional allowed schemas based on request context
|
|
56
|
-
return ['dynamic_schema'];
|
|
57
|
-
},
|
|
58
|
-
},
|
|
59
|
-
},
|
|
60
|
-
};
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
## How It Works
|
|
64
|
-
|
|
65
|
-
1. **On mutation input**, the plugin detects fields tagged with `@sqlExpression`
|
|
66
|
-
2. **If text is provided**: Parses the SQL expression, validates the AST, and stores both the canonical text and AST
|
|
67
|
-
3. **If AST is provided**: Validates the AST and deparses to canonical text
|
|
68
|
-
4. **Validation includes**:
|
|
69
|
-
- Node type allowlist (constants, casts, operators, function calls)
|
|
70
|
-
- Function name allowlist for unqualified functions
|
|
71
|
-
- Schema allowlist for schema-qualified functions
|
|
72
|
-
- Rejection of dangerous constructs (subqueries, DDL, DML, column references)
|
|
73
|
-
|
|
74
|
-
## Default Allowed Functions
|
|
75
|
-
|
|
76
|
-
- `uuid_generate_v4`
|
|
77
|
-
- `gen_random_uuid`
|
|
78
|
-
- `now`
|
|
79
|
-
- `current_timestamp`
|
|
80
|
-
- `current_date`
|
|
81
|
-
- `current_time`
|
|
82
|
-
- `localtime`
|
|
83
|
-
- `localtimestamp`
|
|
84
|
-
- `clock_timestamp`
|
|
85
|
-
- `statement_timestamp`
|
|
86
|
-
- `transaction_timestamp`
|
|
87
|
-
- `timeofday`
|
|
88
|
-
- `random`
|
|
89
|
-
- `setseed`
|
|
90
|
-
|
|
91
|
-
## API
|
|
92
|
-
|
|
93
|
-
### `parseAndValidateSqlExpression(expression, options)`
|
|
94
|
-
|
|
95
|
-
Parse and validate a SQL expression string.
|
|
9
|
+
### Standalone Validation
|
|
96
10
|
|
|
97
11
|
```typescript
|
|
98
12
|
import { parseAndValidateSqlExpression } from 'graphile-sql-expression-validator';
|
|
99
13
|
|
|
100
|
-
const result = parseAndValidateSqlExpression('
|
|
101
|
-
|
|
14
|
+
const result = await parseAndValidateSqlExpression('now()', {
|
|
15
|
+
allowedFunctions: ['now', 'gen_random_uuid'],
|
|
16
|
+
});
|
|
102
17
|
|
|
103
|
-
|
|
104
|
-
//
|
|
18
|
+
if (result.valid) {
|
|
19
|
+
console.log(result.canonicalText); // 'now()'
|
|
20
|
+
}
|
|
105
21
|
```
|
|
106
22
|
|
|
107
|
-
###
|
|
108
|
-
|
|
109
|
-
Validate an existing AST and get canonical text.
|
|
23
|
+
### PostGraphile v5 Preset
|
|
110
24
|
|
|
111
25
|
```typescript
|
|
112
|
-
import {
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
|
|
26
|
+
import { SqlExpressionValidatorPreset } from 'graphile-sql-expression-validator';
|
|
27
|
+
|
|
28
|
+
const preset: GraphileConfig.Preset = {
|
|
29
|
+
extends: [
|
|
30
|
+
SqlExpressionValidatorPreset({
|
|
31
|
+
allowedSchemas: ['app_public'],
|
|
32
|
+
}),
|
|
33
|
+
],
|
|
34
|
+
};
|
|
116
35
|
```
|
|
117
36
|
|
|
118
|
-
## Security Notes
|
|
119
|
-
|
|
120
|
-
- This plugin provides defense-in-depth at the GraphQL layer
|
|
121
|
-
- It does not replace database-level security measures
|
|
122
|
-
- Superuser/admin paths that bypass GraphQL are not protected
|
|
123
|
-
- Always use RLS and proper database permissions as the primary security layer
|
|
124
|
-
|
|
125
37
|
---
|
|
126
38
|
|
|
127
39
|
## Education and Tutorials
|
package/esm/index.d.ts
CHANGED
|
@@ -1,21 +1,35 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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/esm/index.js
CHANGED
|
@@ -1,341 +1,36 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
]
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
'DropStmt',
|
|
38
|
-
'TruncateStmt',
|
|
39
|
-
'ColumnRef',
|
|
40
|
-
'SubLink',
|
|
41
|
-
'RangeVar',
|
|
42
|
-
'RangeSubselect',
|
|
43
|
-
'JoinExpr',
|
|
44
|
-
'FromExpr',
|
|
45
|
-
]);
|
|
46
|
-
function getNodeType(node) {
|
|
47
|
-
if (!node || typeof node !== 'object')
|
|
48
|
-
return null;
|
|
49
|
-
const keys = Object.keys(node);
|
|
50
|
-
if (keys.length === 1)
|
|
51
|
-
return keys[0];
|
|
52
|
-
return null;
|
|
53
|
-
}
|
|
54
|
-
function validateAstNode(node, allowedFunctions, allowedSchemas, path = []) {
|
|
55
|
-
if (!node || typeof node !== 'object') {
|
|
56
|
-
return { valid: true };
|
|
57
|
-
}
|
|
58
|
-
const nodeType = getNodeType(node);
|
|
59
|
-
if (nodeType && FORBIDDEN_NODE_TYPES.has(nodeType)) {
|
|
60
|
-
return {
|
|
61
|
-
valid: false,
|
|
62
|
-
error: `Forbidden node type "${nodeType}" at path: ${path.join('.')}`,
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
if (nodeType === 'FuncCall') {
|
|
66
|
-
const funcCall = node.FuncCall;
|
|
67
|
-
const funcName = funcCall?.funcname;
|
|
68
|
-
if (Array.isArray(funcName)) {
|
|
69
|
-
const names = funcName.map((n) => n.String?.sval || n.str || '');
|
|
70
|
-
const schemaName = names.length > 1 ? names[0] : null;
|
|
71
|
-
const functionName = names[names.length - 1];
|
|
72
|
-
if (schemaName) {
|
|
73
|
-
if (!allowedSchemas.includes(schemaName)) {
|
|
74
|
-
return {
|
|
75
|
-
valid: false,
|
|
76
|
-
error: `Function schema "${schemaName}" is not in the allowed schemas list`,
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
else {
|
|
81
|
-
if (!allowedFunctions.includes(functionName.toLowerCase())) {
|
|
82
|
-
return {
|
|
83
|
-
valid: false,
|
|
84
|
-
error: `Function "${functionName}" is not in the allowed functions list`,
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
for (const [key, value] of Object.entries(node)) {
|
|
91
|
-
if (Array.isArray(value)) {
|
|
92
|
-
for (let i = 0; i < value.length; i++) {
|
|
93
|
-
const result = validateAstNode(value[i], allowedFunctions, allowedSchemas, [...path, key, String(i)]);
|
|
94
|
-
if (!result.valid)
|
|
95
|
-
return result;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
else if (value && typeof value === 'object') {
|
|
99
|
-
const result = validateAstNode(value, allowedFunctions, allowedSchemas, [
|
|
100
|
-
...path,
|
|
101
|
-
key,
|
|
102
|
-
]);
|
|
103
|
-
if (!result.valid)
|
|
104
|
-
return result;
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
return { valid: true };
|
|
108
|
-
}
|
|
109
|
-
export async function parseAndValidateSqlExpression(expression, options = {}) {
|
|
110
|
-
const { allowedFunctions = DEFAULT_ALLOWED_FUNCTIONS, allowedSchemas = [], maxExpressionLength = 10000, } = options;
|
|
111
|
-
if (!expression || typeof expression !== 'string') {
|
|
112
|
-
return { valid: false, error: 'Expression must be a non-empty string' };
|
|
113
|
-
}
|
|
114
|
-
if (expression.length > maxExpressionLength) {
|
|
115
|
-
return {
|
|
116
|
-
valid: false,
|
|
117
|
-
error: `Expression exceeds maximum length of ${maxExpressionLength} characters`,
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
if (expression.includes(';')) {
|
|
121
|
-
return {
|
|
122
|
-
valid: false,
|
|
123
|
-
error: 'Expression cannot contain semicolons (no stacked statements)',
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
try {
|
|
127
|
-
const wrappedSql = `SELECT (${expression})`;
|
|
128
|
-
const parseResult = await parse(wrappedSql);
|
|
129
|
-
if (!parseResult ||
|
|
130
|
-
!parseResult.stmts ||
|
|
131
|
-
parseResult.stmts.length !== 1) {
|
|
132
|
-
return { valid: false, error: 'Failed to parse expression' };
|
|
133
|
-
}
|
|
134
|
-
const stmt = parseResult.stmts[0]?.stmt;
|
|
135
|
-
if (!stmt?.SelectStmt) {
|
|
136
|
-
return { valid: false, error: 'Unexpected parse result structure' };
|
|
137
|
-
}
|
|
138
|
-
const targetList = stmt.SelectStmt.targetList;
|
|
139
|
-
if (!targetList || targetList.length !== 1) {
|
|
140
|
-
return { valid: false, error: 'Expected single expression' };
|
|
141
|
-
}
|
|
142
|
-
const resTarget = targetList[0]?.ResTarget;
|
|
143
|
-
if (!resTarget || !resTarget.val) {
|
|
144
|
-
return { valid: false, error: 'Could not extract expression from parse result' };
|
|
145
|
-
}
|
|
146
|
-
const expressionAst = resTarget.val;
|
|
147
|
-
const validationResult = validateAstNode(expressionAst, allowedFunctions.map((f) => f.toLowerCase()), allowedSchemas);
|
|
148
|
-
if (!validationResult.valid) {
|
|
149
|
-
return { valid: false, error: validationResult.error };
|
|
150
|
-
}
|
|
151
|
-
let canonicalText;
|
|
152
|
-
try {
|
|
153
|
-
canonicalText = await deparse([expressionAst]);
|
|
154
|
-
}
|
|
155
|
-
catch (deparseError) {
|
|
156
|
-
return {
|
|
157
|
-
valid: false,
|
|
158
|
-
error: `Failed to deparse expression: ${deparseError}`,
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
return {
|
|
162
|
-
valid: true,
|
|
163
|
-
ast: expressionAst,
|
|
164
|
-
canonicalText,
|
|
165
|
-
};
|
|
166
|
-
}
|
|
167
|
-
catch (parseError) {
|
|
168
|
-
return {
|
|
169
|
-
valid: false,
|
|
170
|
-
error: `Failed to parse SQL expression: ${parseError.message || parseError}`,
|
|
171
|
-
};
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
export async function validateAst(ast, options = {}) {
|
|
175
|
-
const { allowedFunctions = DEFAULT_ALLOWED_FUNCTIONS, allowedSchemas = [] } = options;
|
|
176
|
-
if (!ast || typeof ast !== 'object') {
|
|
177
|
-
return { valid: false, error: 'AST must be a non-null object' };
|
|
178
|
-
}
|
|
179
|
-
const validationResult = validateAstNode(ast, allowedFunctions.map((f) => f.toLowerCase()), allowedSchemas);
|
|
180
|
-
if (!validationResult.valid) {
|
|
181
|
-
return { valid: false, error: validationResult.error };
|
|
182
|
-
}
|
|
183
|
-
try {
|
|
184
|
-
const canonicalText = await deparse([ast]);
|
|
185
|
-
return { valid: true, canonicalText };
|
|
186
|
-
}
|
|
187
|
-
catch (deparseError) {
|
|
188
|
-
return {
|
|
189
|
-
valid: false,
|
|
190
|
-
error: `Failed to deparse AST: ${deparseError}`,
|
|
191
|
-
};
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
const OWNED_SCHEMAS_CACHE_KEY = Symbol('sqlExpressionValidator.ownedSchemas');
|
|
195
|
-
async function resolveEffectiveOptions(baseOptions, gqlContext) {
|
|
196
|
-
const { allowedSchemas = [], allowOwnedSchemas = false, getAdditionalAllowedSchemas, ...rest } = baseOptions;
|
|
197
|
-
const effectiveSchemas = [...allowedSchemas];
|
|
198
|
-
if (allowOwnedSchemas && gqlContext?.pgClient) {
|
|
199
|
-
let ownedSchemas = gqlContext[OWNED_SCHEMAS_CACHE_KEY];
|
|
200
|
-
if (!ownedSchemas) {
|
|
201
|
-
try {
|
|
202
|
-
const result = await gqlContext.pgClient.query(`SELECT schema_name FROM metaschema_public.schema WHERE database_id = jwt_private.current_database_id()`);
|
|
203
|
-
ownedSchemas = result.rows.map((row) => row.schema_name);
|
|
204
|
-
gqlContext[OWNED_SCHEMAS_CACHE_KEY] = ownedSchemas;
|
|
205
|
-
}
|
|
206
|
-
catch (err) {
|
|
207
|
-
ownedSchemas = [];
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
effectiveSchemas.push(...ownedSchemas);
|
|
211
|
-
}
|
|
212
|
-
if (getAdditionalAllowedSchemas) {
|
|
213
|
-
try {
|
|
214
|
-
const additionalSchemas = await getAdditionalAllowedSchemas(gqlContext);
|
|
215
|
-
effectiveSchemas.push(...additionalSchemas);
|
|
216
|
-
}
|
|
217
|
-
catch (err) {
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
const uniqueSchemas = [...new Set(effectiveSchemas)];
|
|
221
|
-
return {
|
|
222
|
-
...rest,
|
|
223
|
-
allowedSchemas: uniqueSchemas,
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
const SqlExpressionValidatorPlugin = (builder, options = {}) => {
|
|
227
|
-
const validatorOptions = options.sqlExpressionValidator || {};
|
|
228
|
-
builder.hook('GraphQLObjectType:fields:field', (field, build, context) => {
|
|
229
|
-
const { scope: { isRootMutation, fieldName, pgFieldIntrospection: table }, } = context;
|
|
230
|
-
if (!isRootMutation || !table) {
|
|
231
|
-
return field;
|
|
232
|
-
}
|
|
233
|
-
const sqlExpressionColumns = build.pgIntrospectionResultsByKind.attribute
|
|
234
|
-
.filter((attr) => attr.classId === table.id)
|
|
235
|
-
.filter((attr) => attr.tags?.sqlExpression);
|
|
236
|
-
if (sqlExpressionColumns.length === 0) {
|
|
237
|
-
return field;
|
|
238
|
-
}
|
|
239
|
-
const defaultResolver = (obj) => obj[fieldName];
|
|
240
|
-
const { resolve: oldResolve = defaultResolver, ...rest } = field;
|
|
241
|
-
return {
|
|
242
|
-
...rest,
|
|
243
|
-
async resolve(source, args, gqlContext, info) {
|
|
244
|
-
const effectiveOptions = await resolveEffectiveOptions(validatorOptions, gqlContext);
|
|
245
|
-
for (const attr of sqlExpressionColumns) {
|
|
246
|
-
const textGqlName = build.inflection.column(attr);
|
|
247
|
-
const rawSqlAstFieldTag = attr.tags?.rawSqlAstField;
|
|
248
|
-
const astDbName = typeof rawSqlAstFieldTag === 'string' && rawSqlAstFieldTag.trim()
|
|
249
|
-
? rawSqlAstFieldTag.trim()
|
|
250
|
-
: `${attr.name}_ast`;
|
|
251
|
-
const astAttr = build.pgIntrospectionResultsByKind.attribute.find((a) => a.classId === table.id && a.name === astDbName);
|
|
252
|
-
let astGqlName = null;
|
|
253
|
-
if (astAttr) {
|
|
254
|
-
astGqlName = build.inflection.column(astAttr);
|
|
255
|
-
}
|
|
256
|
-
else if (typeof rawSqlAstFieldTag === 'string' && rawSqlAstFieldTag.trim()) {
|
|
257
|
-
throw new Error(`@rawSqlAstField points to missing column "${astDbName}" on ${table.namespaceName}.${table.name}`);
|
|
258
|
-
}
|
|
259
|
-
const inputPath = findInputPath(args, textGqlName);
|
|
260
|
-
const astInputPath = astGqlName ? findInputPath(args, astGqlName) : null;
|
|
261
|
-
if (inputPath) {
|
|
262
|
-
const textValue = getNestedValue(args, inputPath);
|
|
263
|
-
if (textValue !== undefined && textValue !== null) {
|
|
264
|
-
const result = await parseAndValidateSqlExpression(textValue, effectiveOptions);
|
|
265
|
-
if (!result.valid) {
|
|
266
|
-
throw new Error(`Invalid SQL expression in ${textGqlName}: ${result.error}`);
|
|
267
|
-
}
|
|
268
|
-
setNestedValue(args, inputPath, result.canonicalText);
|
|
269
|
-
if (astGqlName && (astInputPath || canSetAstColumn(args, inputPath, astGqlName))) {
|
|
270
|
-
const astPath = astInputPath || replaceLastSegment(inputPath, astGqlName);
|
|
271
|
-
setNestedValue(args, astPath, result.ast);
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
if (astInputPath && !inputPath && astGqlName) {
|
|
276
|
-
const astValue = getNestedValue(args, astInputPath);
|
|
277
|
-
if (astValue !== undefined && astValue !== null) {
|
|
278
|
-
const result = await validateAst(astValue, effectiveOptions);
|
|
279
|
-
if (!result.valid) {
|
|
280
|
-
throw new Error(`Invalid SQL expression AST in ${astGqlName}: ${result.error}`);
|
|
281
|
-
}
|
|
282
|
-
const textPath = replaceLastSegment(astInputPath, textGqlName);
|
|
283
|
-
if (canSetColumn(args, astInputPath, textGqlName)) {
|
|
284
|
-
setNestedValue(args, textPath, result.canonicalText);
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
return oldResolve(source, args, gqlContext, info);
|
|
290
|
-
},
|
|
291
|
-
};
|
|
292
|
-
});
|
|
293
|
-
};
|
|
294
|
-
function findInputPath(obj, key, path = []) {
|
|
295
|
-
if (!obj || typeof obj !== 'object')
|
|
296
|
-
return null;
|
|
297
|
-
for (const [k, v] of Object.entries(obj)) {
|
|
298
|
-
if (k === key) {
|
|
299
|
-
return [...path, k];
|
|
300
|
-
}
|
|
301
|
-
if (v && typeof v === 'object') {
|
|
302
|
-
const result = findInputPath(v, key, [...path, k]);
|
|
303
|
-
if (result)
|
|
304
|
-
return result;
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
return null;
|
|
308
|
-
}
|
|
309
|
-
function getNestedValue(obj, path) {
|
|
310
|
-
let current = obj;
|
|
311
|
-
for (const key of path) {
|
|
312
|
-
if (current === null || current === undefined)
|
|
313
|
-
return undefined;
|
|
314
|
-
current = current[key];
|
|
315
|
-
}
|
|
316
|
-
return current;
|
|
317
|
-
}
|
|
318
|
-
function setNestedValue(obj, path, value) {
|
|
319
|
-
let current = obj;
|
|
320
|
-
for (let i = 0; i < path.length - 1; i++) {
|
|
321
|
-
if (current[path[i]] === undefined) {
|
|
322
|
-
current[path[i]] = {};
|
|
323
|
-
}
|
|
324
|
-
current = current[path[i]];
|
|
325
|
-
}
|
|
326
|
-
current[path[path.length - 1]] = value;
|
|
327
|
-
}
|
|
328
|
-
function replaceLastSegment(path, newSegment) {
|
|
329
|
-
return [...path.slice(0, -1), newSegment];
|
|
330
|
-
}
|
|
331
|
-
function canSetAstColumn(args, textPath, astColumnName) {
|
|
332
|
-
const parentPath = textPath.slice(0, -1);
|
|
333
|
-
const parent = getNestedValue(args, parentPath);
|
|
334
|
-
return parent && typeof parent === 'object';
|
|
335
|
-
}
|
|
336
|
-
function canSetColumn(args, astPath, columnName) {
|
|
337
|
-
const parentPath = astPath.slice(0, -1);
|
|
338
|
-
const parent = getNestedValue(args, parentPath);
|
|
339
|
-
return parent && typeof parent === 'object';
|
|
340
|
-
}
|
|
341
|
-
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
|
+
// Standalone validation utilities
|
|
34
|
+
export { parseAndValidateSqlExpression, validateAst, DEFAULT_ALLOWED_FUNCTIONS } from './validator';
|
|
35
|
+
// PostGraphile v5 plugin and preset
|
|
36
|
+
export { createSqlExpressionValidatorPlugin, SqlExpressionValidatorPreset } from './plugin';
|
package/esm/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;
|