@zenstackhq/plugin-policy 3.5.6 → 3.6.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/dist/index.cjs +1374 -1948
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -21
- package/dist/index.d.mts +34 -0
- package/dist/index.mjs +1421 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +12 -11
- package/dist/index.d.ts +0 -27
- package/dist/index.js +0 -1971
- package/dist/index.js.map +0 -1
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1421 @@
|
|
|
1
|
+
import { CRUD, KyselyUtils, ORMError, ORMErrorReason, QueryUtils, RejectedByPolicyReason, SchemaUtils, getCrudDialect } from "@zenstackhq/orm";
|
|
2
|
+
import { invariant } from "@zenstackhq/common-helpers";
|
|
3
|
+
import { AliasNode, AndNode, BinaryOperationNode, ColumnNode, DeleteQueryNode, ExpressionWrapper, FromNode, FunctionNode, IdentifierNode, InsertQueryNode, OperationNodeTransformer, OperatorNode, OrNode, ParensNode, PrimitiveValueListNode, RawNode, ReferenceNode, ReturningNode, SelectAllNode, SelectQueryNode, SelectionNode, TableNode, UnaryOperationNode, UpdateQueryNode, ValueListNode, ValueNode, ValuesNode, WhereNode, expressionBuilder, sql } from "kysely";
|
|
4
|
+
import { ExpressionUtils } from "@zenstackhq/orm/schema";
|
|
5
|
+
import { match } from "ts-pattern";
|
|
6
|
+
//#region src/column-collector.ts
|
|
7
|
+
/**
|
|
8
|
+
* Collects all column names from a query.
|
|
9
|
+
*/
|
|
10
|
+
var ColumnCollector = class extends KyselyUtils.DefaultOperationNodeVisitor {
|
|
11
|
+
columns = [];
|
|
12
|
+
collect(node) {
|
|
13
|
+
this.columns = [];
|
|
14
|
+
this.visitNode(node);
|
|
15
|
+
return this.columns;
|
|
16
|
+
}
|
|
17
|
+
visitColumn(node) {
|
|
18
|
+
if (!this.columns.includes(node.column.name)) this.columns.push(node.column.name);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/expression-evaluator.ts
|
|
23
|
+
/**
|
|
24
|
+
* Utility for evaluating a ZModel expression into a JavaScript value.
|
|
25
|
+
*/
|
|
26
|
+
var ExpressionEvaluator = class {
|
|
27
|
+
evaluate(expression, context) {
|
|
28
|
+
return match(expression).when(ExpressionUtils.isArray, (expr) => this.evaluateArray(expr, context)).when(ExpressionUtils.isBinary, (expr) => this.evaluateBinary(expr, context)).when(ExpressionUtils.isField, (expr) => this.evaluateField(expr, context)).when(ExpressionUtils.isLiteral, (expr) => this.evaluateLiteral(expr)).when(ExpressionUtils.isMember, (expr) => this.evaluateMember(expr, context)).when(ExpressionUtils.isUnary, (expr) => this.evaluateUnary(expr, context)).when(ExpressionUtils.isCall, (expr) => this.evaluateCall(expr, context)).when(ExpressionUtils.isBinding, (expr) => this.evaluateBinding(expr, context)).when(ExpressionUtils.isThis, () => context.thisValue).when(ExpressionUtils.isNull, () => null).exhaustive() ?? null;
|
|
29
|
+
}
|
|
30
|
+
evaluateCall(expr, context) {
|
|
31
|
+
if (expr.function === "auth") return context.auth;
|
|
32
|
+
else if (expr.function === "currentModel") return context.thisType;
|
|
33
|
+
else if (expr.function === "currentOperation") return context.operation;
|
|
34
|
+
else throw new Error(`Unsupported call expression function: ${expr.function}`);
|
|
35
|
+
}
|
|
36
|
+
evaluateUnary(expr, context) {
|
|
37
|
+
return match(expr.op).with("!", () => !this.evaluate(expr.operand, context)).exhaustive();
|
|
38
|
+
}
|
|
39
|
+
evaluateMember(expr, context) {
|
|
40
|
+
let val = this.evaluate(expr.receiver, context);
|
|
41
|
+
for (const member of expr.members) val = val?.[member];
|
|
42
|
+
return val;
|
|
43
|
+
}
|
|
44
|
+
evaluateLiteral(expr) {
|
|
45
|
+
return expr.value;
|
|
46
|
+
}
|
|
47
|
+
evaluateField(expr, context) {
|
|
48
|
+
if (context.bindingScope && expr.field in context.bindingScope) return context.bindingScope[expr.field];
|
|
49
|
+
return context.thisValue?.[expr.field];
|
|
50
|
+
}
|
|
51
|
+
evaluateArray(expr, context) {
|
|
52
|
+
return expr.items.map((item) => this.evaluate(item, context));
|
|
53
|
+
}
|
|
54
|
+
evaluateBinary(expr, context) {
|
|
55
|
+
if (expr.op === "?" || expr.op === "!" || expr.op === "^") return this.evaluateCollectionPredicate(expr, context);
|
|
56
|
+
const left = this.evaluate(expr.left, context);
|
|
57
|
+
const right = this.evaluate(expr.right, context);
|
|
58
|
+
if (!["==", "!="].includes(expr.op) && (left === null || right === null)) return null;
|
|
59
|
+
return match(expr.op).with("==", () => left === right).with("!=", () => left !== right).with(">", () => left > right).with(">=", () => left >= right).with("<", () => left < right).with("<=", () => left <= right).with("&&", () => left && right).with("||", () => left || right).with("in", () => {
|
|
60
|
+
const _right = right ?? [];
|
|
61
|
+
invariant(Array.isArray(_right), "expected array for \"in\" operator");
|
|
62
|
+
return _right.includes(left);
|
|
63
|
+
}).exhaustive();
|
|
64
|
+
}
|
|
65
|
+
evaluateCollectionPredicate(expr, context) {
|
|
66
|
+
const op = expr.op;
|
|
67
|
+
invariant(op === "?" || op === "!" || op === "^", "expected \"?\" or \"!\" or \"^\" operator");
|
|
68
|
+
const left = this.evaluate(expr.left, context);
|
|
69
|
+
if (left === null || left === void 0) return null;
|
|
70
|
+
invariant(Array.isArray(left), "expected array");
|
|
71
|
+
return match(op).with("?", () => left.some((item) => this.evaluate(expr.right, {
|
|
72
|
+
...context,
|
|
73
|
+
thisValue: item,
|
|
74
|
+
bindingScope: expr.binding ? {
|
|
75
|
+
...context.bindingScope ?? {},
|
|
76
|
+
[expr.binding]: item
|
|
77
|
+
} : context.bindingScope
|
|
78
|
+
}))).with("!", () => left.every((item) => this.evaluate(expr.right, {
|
|
79
|
+
...context,
|
|
80
|
+
thisValue: item,
|
|
81
|
+
bindingScope: expr.binding ? {
|
|
82
|
+
...context.bindingScope ?? {},
|
|
83
|
+
[expr.binding]: item
|
|
84
|
+
} : context.bindingScope
|
|
85
|
+
}))).with("^", () => !left.some((item) => this.evaluate(expr.right, {
|
|
86
|
+
...context,
|
|
87
|
+
thisValue: item,
|
|
88
|
+
bindingScope: expr.binding ? {
|
|
89
|
+
...context.bindingScope ?? {},
|
|
90
|
+
[expr.binding]: item
|
|
91
|
+
} : context.bindingScope
|
|
92
|
+
}))).exhaustive();
|
|
93
|
+
}
|
|
94
|
+
evaluateBinding(expr, context) {
|
|
95
|
+
if (!context.bindingScope || !(expr.name in context.bindingScope)) throw new Error(`Unresolved binding: ${expr.name}`);
|
|
96
|
+
return context.bindingScope[expr.name];
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/types.ts
|
|
101
|
+
/**
|
|
102
|
+
* Operators allowed for collection predicate expressions.
|
|
103
|
+
*/
|
|
104
|
+
const CollectionPredicateOperator = [
|
|
105
|
+
"?",
|
|
106
|
+
"!",
|
|
107
|
+
"^"
|
|
108
|
+
];
|
|
109
|
+
//#endregion
|
|
110
|
+
//#region src/utils.ts
|
|
111
|
+
/**
|
|
112
|
+
* Creates a `true` value node.
|
|
113
|
+
*/
|
|
114
|
+
function trueNode(dialect) {
|
|
115
|
+
return ValueNode.createImmediate(dialect.transformInput(true, "Boolean", false));
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Creates a `false` value node.
|
|
119
|
+
*/
|
|
120
|
+
function falseNode(dialect) {
|
|
121
|
+
return ValueNode.createImmediate(dialect.transformInput(false, "Boolean", false));
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Checks if a node is a truthy value node.
|
|
125
|
+
*/
|
|
126
|
+
function isTrueNode(node) {
|
|
127
|
+
return ValueNode.is(node) && (node.value === true || node.value === 1);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Checks if a node is a falsy value node.
|
|
131
|
+
*/
|
|
132
|
+
function isFalseNode(node) {
|
|
133
|
+
return ValueNode.is(node) && (node.value === false || node.value === 0);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Builds a logical conjunction of a list of nodes.
|
|
137
|
+
*/
|
|
138
|
+
function conjunction(dialect, nodes) {
|
|
139
|
+
if (nodes.length === 0) return trueNode(dialect);
|
|
140
|
+
if (nodes.length === 1) return nodes[0];
|
|
141
|
+
if (nodes.some(isFalseNode)) return falseNode(dialect);
|
|
142
|
+
const items = nodes.filter((n) => !isTrueNode(n));
|
|
143
|
+
if (items.length === 0) return trueNode(dialect);
|
|
144
|
+
return items.reduce((acc, node) => AndNode.create(wrapParensIf(acc, OrNode.is), wrapParensIf(node, OrNode.is)));
|
|
145
|
+
}
|
|
146
|
+
function disjunction(dialect, nodes) {
|
|
147
|
+
if (nodes.length === 0) return falseNode(dialect);
|
|
148
|
+
if (nodes.length === 1) return nodes[0];
|
|
149
|
+
if (nodes.some(isTrueNode)) return trueNode(dialect);
|
|
150
|
+
const items = nodes.filter((n) => !isFalseNode(n));
|
|
151
|
+
if (items.length === 0) return falseNode(dialect);
|
|
152
|
+
return items.reduce((acc, node) => OrNode.create(wrapParensIf(acc, AndNode.is), wrapParensIf(node, AndNode.is)));
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Negates a logical expression.
|
|
156
|
+
*/
|
|
157
|
+
function logicalNot(dialect, node) {
|
|
158
|
+
if (isTrueNode(node)) return falseNode(dialect);
|
|
159
|
+
if (isFalseNode(node)) return trueNode(dialect);
|
|
160
|
+
return UnaryOperationNode.create(OperatorNode.create("not"), wrapParensIf(node, (n) => AndNode.is(n) || OrNode.is(n)));
|
|
161
|
+
}
|
|
162
|
+
function wrapParensIf(node, predicate) {
|
|
163
|
+
return predicate(node) ? ParensNode.create(node) : node;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Builds an expression node that checks if a node is false.
|
|
167
|
+
*/
|
|
168
|
+
function buildIsFalse(node, dialect) {
|
|
169
|
+
if (isFalseNode(node)) return trueNode(dialect);
|
|
170
|
+
else if (isTrueNode(node)) return falseNode(dialect);
|
|
171
|
+
return BinaryOperationNode.create(FunctionNode.create("coalesce", [node, falseNode(dialect)]), OperatorNode.create("="), falseNode(dialect));
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Gets the table name from a node.
|
|
175
|
+
*/
|
|
176
|
+
function getTableName(node) {
|
|
177
|
+
if (!node) return node;
|
|
178
|
+
if (TableNode.is(node)) return node.table.identifier.name;
|
|
179
|
+
else if (AliasNode.is(node)) return getTableName(node.node);
|
|
180
|
+
else if (ReferenceNode.is(node) && node.table) return getTableName(node.table);
|
|
181
|
+
}
|
|
182
|
+
function isBeforeInvocation(expr) {
|
|
183
|
+
return ExpressionUtils.isCall(expr) && expr.function === "before";
|
|
184
|
+
}
|
|
185
|
+
function createRejectedByPolicyError(model, reason, message) {
|
|
186
|
+
const err = new ORMError(ORMErrorReason.REJECTED_BY_POLICY, message ?? "operation is rejected by access policies");
|
|
187
|
+
err.rejectedByPolicyReason = reason;
|
|
188
|
+
err.model = model;
|
|
189
|
+
return err;
|
|
190
|
+
}
|
|
191
|
+
function createUnsupportedError(message) {
|
|
192
|
+
return new ORMError(ORMErrorReason.NOT_SUPPORTED, message);
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region \0@oxc-project+runtime@0.124.0/helpers/decorateMetadata.js
|
|
196
|
+
function __decorateMetadata(k, v) {
|
|
197
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
198
|
+
}
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region \0@oxc-project+runtime@0.124.0/helpers/decorate.js
|
|
201
|
+
function __decorate(decorators, target, key, desc) {
|
|
202
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
203
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
204
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
205
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
206
|
+
}
|
|
207
|
+
//#endregion
|
|
208
|
+
//#region src/expression-transformer.ts
|
|
209
|
+
const expressionHandlers = /* @__PURE__ */ new Map();
|
|
210
|
+
function expr(kind) {
|
|
211
|
+
return function(_target, _propertyKey, descriptor) {
|
|
212
|
+
if (!expressionHandlers.get(kind)) expressionHandlers.set(kind, descriptor);
|
|
213
|
+
return descriptor;
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Utility for transforming a ZModel expression into a Kysely OperationNode.
|
|
218
|
+
*/
|
|
219
|
+
var ExpressionTransformer = class {
|
|
220
|
+
dialect;
|
|
221
|
+
eb = expressionBuilder();
|
|
222
|
+
constructor(client) {
|
|
223
|
+
this.client = client;
|
|
224
|
+
this.dialect = getCrudDialect(this.schema, this.clientOptions);
|
|
225
|
+
}
|
|
226
|
+
get schema() {
|
|
227
|
+
return this.client.$schema;
|
|
228
|
+
}
|
|
229
|
+
get clientOptions() {
|
|
230
|
+
return this.client.$options;
|
|
231
|
+
}
|
|
232
|
+
get auth() {
|
|
233
|
+
return this.client.$auth;
|
|
234
|
+
}
|
|
235
|
+
get authType() {
|
|
236
|
+
if (!this.schema.authType) invariant(false, "Schema does not have an \"authType\" specified");
|
|
237
|
+
return this.schema.authType;
|
|
238
|
+
}
|
|
239
|
+
transform(expression, context) {
|
|
240
|
+
const handler = expressionHandlers.get(expression.kind);
|
|
241
|
+
if (!handler) throw new Error(`Unsupported expression kind: ${expression.kind}`);
|
|
242
|
+
const result = handler.value.call(this, expression, context);
|
|
243
|
+
invariant("kind" in result, `expression handler must return an OperationNode: transforming ${expression.kind}`);
|
|
244
|
+
return result;
|
|
245
|
+
}
|
|
246
|
+
_literal(expr) {
|
|
247
|
+
return this.transformValue(expr.value, typeof expr.value === "string" ? "String" : typeof expr.value === "boolean" ? "Boolean" : "Int");
|
|
248
|
+
}
|
|
249
|
+
_array(expr, context) {
|
|
250
|
+
return this.dialect.buildArrayValue(expr.items.map((item) => new ExpressionWrapper(this.transform(item, context))), expr.type).toOperationNode();
|
|
251
|
+
}
|
|
252
|
+
_field(expr, context) {
|
|
253
|
+
if (context.contextValue) {
|
|
254
|
+
const fieldDef = QueryUtils.requireField(this.schema, context.modelOrType, expr.field);
|
|
255
|
+
return this.transformValue(context.contextValue[expr.field], fieldDef.type);
|
|
256
|
+
}
|
|
257
|
+
const fieldDef = QueryUtils.requireField(this.schema, context.modelOrType, expr.field);
|
|
258
|
+
if (!fieldDef.relation) return this.createColumnRef(expr.field, context);
|
|
259
|
+
else {
|
|
260
|
+
const { memberFilter, memberSelect, ...restContext } = context;
|
|
261
|
+
const relation = this.transformRelationAccess(expr.field, fieldDef.type, restContext);
|
|
262
|
+
return {
|
|
263
|
+
...relation,
|
|
264
|
+
where: this.mergeWhere(relation.where, memberFilter),
|
|
265
|
+
selections: memberSelect ? [memberSelect] : relation.selections
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
mergeWhere(where, memberFilter) {
|
|
270
|
+
if (!where) return WhereNode.create(memberFilter ?? trueNode(this.dialect));
|
|
271
|
+
if (!memberFilter) return where;
|
|
272
|
+
return WhereNode.create(conjunction(this.dialect, [where.where, memberFilter]));
|
|
273
|
+
}
|
|
274
|
+
_null() {
|
|
275
|
+
return ValueNode.createImmediate(null);
|
|
276
|
+
}
|
|
277
|
+
_binary(expr, context) {
|
|
278
|
+
if (expr.op === "&&") return conjunction(this.dialect, [this.transform(expr.left, context), this.transform(expr.right, context)]);
|
|
279
|
+
else if (expr.op === "||") return disjunction(this.dialect, [this.transform(expr.left, context), this.transform(expr.right, context)]);
|
|
280
|
+
if (this.isAuthCall(expr.left) || this.isAuthCall(expr.right)) return this.transformAuthBinary(expr, context);
|
|
281
|
+
const op = expr.op;
|
|
282
|
+
if (op === "?" || op === "!" || op === "^") return this.transformCollectionPredicate(expr, context);
|
|
283
|
+
const { normalizedLeft, normalizedRight } = this.normalizeBinaryOperationOperands(expr, context);
|
|
284
|
+
const left = this.transform(normalizedLeft, context);
|
|
285
|
+
const right = this.transform(normalizedRight, context);
|
|
286
|
+
if (op === "in") if (this.isNullNode(left)) return this.transformValue(false, "Boolean");
|
|
287
|
+
else if (ValueListNode.is(right)) return BinaryOperationNode.create(left, OperatorNode.create("in"), right);
|
|
288
|
+
else return BinaryOperationNode.create(left, OperatorNode.create("="), FunctionNode.create("any", [right]));
|
|
289
|
+
if (this.isNullNode(right)) return this.transformNullCheck(left, expr.op);
|
|
290
|
+
else if (this.isNullNode(left)) return this.transformNullCheck(right, expr.op);
|
|
291
|
+
else {
|
|
292
|
+
const leftFieldDef = this.getFieldDefFromFieldRef(normalizedLeft, context);
|
|
293
|
+
const rightFieldDef = this.getFieldDefFromFieldRef(normalizedRight, context);
|
|
294
|
+
const sqlOp = op === "==" ? "=" : op;
|
|
295
|
+
return this.dialect.buildComparison(new ExpressionWrapper(left), leftFieldDef, sqlOp, new ExpressionWrapper(right), rightFieldDef).toOperationNode();
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
transformNullCheck(expr, operator) {
|
|
299
|
+
if (operator === "==" || operator === "!=") if (ValueNode.is(expr)) if (expr.value === null) return operator === "==" ? trueNode(this.dialect) : falseNode(this.dialect);
|
|
300
|
+
else return operator === "==" ? falseNode(this.dialect) : trueNode(this.dialect);
|
|
301
|
+
else return operator === "==" ? BinaryOperationNode.create(expr, OperatorNode.create("is"), ValueNode.createImmediate(null)) : BinaryOperationNode.create(expr, OperatorNode.create("is not"), ValueNode.createImmediate(null));
|
|
302
|
+
else return ValueNode.createImmediate(null);
|
|
303
|
+
}
|
|
304
|
+
normalizeBinaryOperationOperands(expr, context) {
|
|
305
|
+
if (context.contextValue) return {
|
|
306
|
+
normalizedLeft: expr.left,
|
|
307
|
+
normalizedRight: expr.right
|
|
308
|
+
};
|
|
309
|
+
let normalizedLeft = expr.left;
|
|
310
|
+
if (this.isRelationField(expr.left, context)) {
|
|
311
|
+
invariant(ExpressionUtils.isNull(expr.right), "only null comparison is supported for relation field");
|
|
312
|
+
const leftRelDef = this.getFieldDefFromFieldRef(expr.left, context);
|
|
313
|
+
invariant(leftRelDef, "failed to get relation field definition");
|
|
314
|
+
const idFields = QueryUtils.requireIdFields(this.schema, leftRelDef.type);
|
|
315
|
+
normalizedLeft = this.makeOrAppendMember(normalizedLeft, idFields[0]);
|
|
316
|
+
}
|
|
317
|
+
let normalizedRight = expr.right;
|
|
318
|
+
if (this.isRelationField(expr.right, context)) {
|
|
319
|
+
invariant(ExpressionUtils.isNull(expr.left), "only null comparison is supported for relation field");
|
|
320
|
+
const rightRelDef = this.getFieldDefFromFieldRef(expr.right, context);
|
|
321
|
+
invariant(rightRelDef, "failed to get relation field definition");
|
|
322
|
+
const idFields = QueryUtils.requireIdFields(this.schema, rightRelDef.type);
|
|
323
|
+
normalizedRight = this.makeOrAppendMember(normalizedRight, idFields[0]);
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
normalizedLeft,
|
|
327
|
+
normalizedRight
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
transformCollectionPredicate(expr, context) {
|
|
331
|
+
this.ensureCollectionPredicateOperator(expr.op);
|
|
332
|
+
if (this.isAuthMember(expr.left) || context.contextValue) {
|
|
333
|
+
invariant(ExpressionUtils.isMember(expr.left) || ExpressionUtils.isField(expr.left), "expected member or field expression");
|
|
334
|
+
const receiver = new ExpressionEvaluator().evaluate(expr.left, {
|
|
335
|
+
thisValue: context.contextValue,
|
|
336
|
+
auth: this.auth,
|
|
337
|
+
bindingScope: this.getEvaluationBindingScope(context.bindingScope),
|
|
338
|
+
operation: context.operation,
|
|
339
|
+
thisType: context.thisType
|
|
340
|
+
});
|
|
341
|
+
const baseType = this.isAuthMember(expr.left) ? this.authType : context.modelOrType;
|
|
342
|
+
const memberType = this.getMemberType(baseType, expr.left);
|
|
343
|
+
return this.transformValueCollectionPredicate(receiver, expr, {
|
|
344
|
+
...context,
|
|
345
|
+
modelOrType: memberType
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
invariant(ExpressionUtils.isField(expr.left) || ExpressionUtils.isMember(expr.left), "left operand must be field or member access");
|
|
349
|
+
let newContextModel;
|
|
350
|
+
const fieldDef = this.getFieldDefFromFieldRef(expr.left, context);
|
|
351
|
+
if (fieldDef) {
|
|
352
|
+
invariant(fieldDef.relation, `field is not a relation: ${JSON.stringify(expr.left)}`);
|
|
353
|
+
newContextModel = fieldDef.type;
|
|
354
|
+
} else {
|
|
355
|
+
invariant(ExpressionUtils.isMember(expr.left) && (ExpressionUtils.isField(expr.left.receiver) || ExpressionUtils.isBinding(expr.left.receiver)), "left operand must be member access with field receiver");
|
|
356
|
+
if (ExpressionUtils.isField(expr.left.receiver)) newContextModel = QueryUtils.requireField(this.schema, context.modelOrType, expr.left.receiver.field).type;
|
|
357
|
+
else newContextModel = this.requireBindingScope(expr.left.receiver, context).type;
|
|
358
|
+
for (const member of expr.left.members) newContextModel = QueryUtils.requireField(this.schema, newContextModel, member).type;
|
|
359
|
+
}
|
|
360
|
+
const bindingScope = expr.binding ? {
|
|
361
|
+
...context.bindingScope ?? {},
|
|
362
|
+
[expr.binding]: {
|
|
363
|
+
type: newContextModel,
|
|
364
|
+
alias: newContextModel
|
|
365
|
+
}
|
|
366
|
+
} : context.bindingScope;
|
|
367
|
+
let predicateFilter = this.transform(expr.right, {
|
|
368
|
+
...context,
|
|
369
|
+
modelOrType: newContextModel,
|
|
370
|
+
alias: void 0,
|
|
371
|
+
bindingScope
|
|
372
|
+
});
|
|
373
|
+
if (expr.op === "!") predicateFilter = logicalNot(this.dialect, predicateFilter);
|
|
374
|
+
const count = FunctionNode.create("count", [ValueNode.createImmediate(1)]);
|
|
375
|
+
const predicateResult = match(expr.op).with("?", () => BinaryOperationNode.create(count, OperatorNode.create(">"), ValueNode.createImmediate(0))).with("!", () => BinaryOperationNode.create(count, OperatorNode.create("="), ValueNode.createImmediate(0))).with("^", () => BinaryOperationNode.create(count, OperatorNode.create("="), ValueNode.createImmediate(0))).exhaustive();
|
|
376
|
+
return this.transform(expr.left, {
|
|
377
|
+
...context,
|
|
378
|
+
memberSelect: SelectionNode.create(AliasNode.create(predicateResult, IdentifierNode.create("_"))),
|
|
379
|
+
memberFilter: predicateFilter
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
ensureCollectionPredicateOperator(op) {
|
|
383
|
+
invariant(CollectionPredicateOperator.includes(op), "expected \"?\" or \"!\" or \"^\" operator");
|
|
384
|
+
}
|
|
385
|
+
transformValueCollectionPredicate(receiver, expr, context) {
|
|
386
|
+
if (!receiver) return ValueNode.createImmediate(null);
|
|
387
|
+
this.ensureCollectionPredicateOperator(expr.op);
|
|
388
|
+
if (!new SchemaUtils.MatchingExpressionVisitor((e) => ExpressionUtils.isThis(e)).find(expr.right)) {
|
|
389
|
+
const value = new ExpressionEvaluator().evaluate(expr, {
|
|
390
|
+
auth: this.auth,
|
|
391
|
+
thisValue: context.contextValue,
|
|
392
|
+
bindingScope: this.getEvaluationBindingScope(context.bindingScope),
|
|
393
|
+
operation: context.operation,
|
|
394
|
+
thisType: context.thisType
|
|
395
|
+
});
|
|
396
|
+
return this.transformValue(value, "Boolean");
|
|
397
|
+
} else {
|
|
398
|
+
invariant(Array.isArray(receiver), "array value is expected");
|
|
399
|
+
const components = receiver.map((item) => {
|
|
400
|
+
const bindingScope = expr.binding ? {
|
|
401
|
+
...context.bindingScope ?? {},
|
|
402
|
+
[expr.binding]: {
|
|
403
|
+
type: context.modelOrType,
|
|
404
|
+
alias: context.thisAlias ?? context.modelOrType,
|
|
405
|
+
value: item
|
|
406
|
+
}
|
|
407
|
+
} : context.bindingScope;
|
|
408
|
+
return this.transform(expr.right, {
|
|
409
|
+
operation: context.operation,
|
|
410
|
+
thisType: context.thisType,
|
|
411
|
+
thisAlias: context.thisAlias,
|
|
412
|
+
modelOrType: context.modelOrType,
|
|
413
|
+
contextValue: item,
|
|
414
|
+
bindingScope
|
|
415
|
+
});
|
|
416
|
+
});
|
|
417
|
+
return match(expr.op).with("?", () => disjunction(this.dialect, components)).with("!", () => conjunction(this.dialect, components)).with("^", () => logicalNot(this.dialect, disjunction(this.dialect, components))).exhaustive();
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
getMemberType(receiverType, expr) {
|
|
421
|
+
if (ExpressionUtils.isField(expr)) return QueryUtils.requireField(this.schema, receiverType, expr.field).type;
|
|
422
|
+
else {
|
|
423
|
+
let currType = receiverType;
|
|
424
|
+
for (const member of expr.members) currType = QueryUtils.requireField(this.schema, currType, member).type;
|
|
425
|
+
return currType;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
transformAuthBinary(expr, context) {
|
|
429
|
+
if (expr.op !== "==" && expr.op !== "!=") throw createUnsupportedError(`Unsupported operator for \`auth()\` in policy of model "${context.modelOrType}": ${expr.op}`);
|
|
430
|
+
let authExpr;
|
|
431
|
+
let other;
|
|
432
|
+
if (this.isAuthCall(expr.left)) {
|
|
433
|
+
authExpr = expr.left;
|
|
434
|
+
other = expr.right;
|
|
435
|
+
} else {
|
|
436
|
+
authExpr = expr.right;
|
|
437
|
+
other = expr.left;
|
|
438
|
+
}
|
|
439
|
+
if (ExpressionUtils.isNull(other)) return this.transformValue(expr.op === "==" ? !this.auth : !!this.auth, "Boolean");
|
|
440
|
+
else {
|
|
441
|
+
const authModel = QueryUtils.getModel(this.schema, this.authType);
|
|
442
|
+
if (!authModel) throw createUnsupportedError(`Unsupported use of \`auth()\` in policy of model "${context.modelOrType}", comparing with \`auth()\` is only possible when auth type is a model`);
|
|
443
|
+
const idFields = Object.values(authModel.fields).filter((f) => f.id).map((f) => f.name);
|
|
444
|
+
invariant(idFields.length > 0, "auth type model must have at least one id field");
|
|
445
|
+
const conditions = idFields.map((fieldName) => ExpressionUtils.binary(ExpressionUtils.member(authExpr, [fieldName]), "==", this.makeOrAppendMember(other, fieldName)));
|
|
446
|
+
let result = this.buildAnd(conditions);
|
|
447
|
+
if (expr.op === "!=") result = this.buildLogicalNot(result);
|
|
448
|
+
return this.transform(result, context);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
makeOrAppendMember(other, fieldName) {
|
|
452
|
+
if (ExpressionUtils.isMember(other)) return ExpressionUtils.member(other.receiver, [...other.members, fieldName]);
|
|
453
|
+
else return ExpressionUtils.member(other, [fieldName]);
|
|
454
|
+
}
|
|
455
|
+
transformValue(value, type) {
|
|
456
|
+
if (value === true) return trueNode(this.dialect);
|
|
457
|
+
else if (value === false) return falseNode(this.dialect);
|
|
458
|
+
else if (Array.isArray(value)) return this.dialect.buildArrayValue(value.map((v) => new ExpressionWrapper(this.transformValue(v, type))), type).toOperationNode();
|
|
459
|
+
else {
|
|
460
|
+
const transformed = this.dialect.transformInput(value, type, false) ?? null;
|
|
461
|
+
if (typeof transformed !== "string") return ValueNode.createImmediate(transformed);
|
|
462
|
+
else return ValueNode.create(transformed);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
_unary(expr, context) {
|
|
466
|
+
invariant(expr.op === "!", "only \"!\" operator is supported");
|
|
467
|
+
return logicalNot(this.dialect, this.transform(expr.operand, context));
|
|
468
|
+
}
|
|
469
|
+
_call(expr, context) {
|
|
470
|
+
return this.transformCall(expr, context).toOperationNode();
|
|
471
|
+
}
|
|
472
|
+
transformCall(expr, context) {
|
|
473
|
+
const func = this.getFunctionImpl(expr.function);
|
|
474
|
+
if (!func) throw createUnsupportedError(`Function not implemented: ${expr.function}`);
|
|
475
|
+
return func(this.eb, (expr.args ?? []).map((arg) => this.transformCallArg(arg, context)), {
|
|
476
|
+
client: this.client,
|
|
477
|
+
dialect: this.dialect,
|
|
478
|
+
model: context.modelOrType,
|
|
479
|
+
modelAlias: context.alias ?? context.modelOrType,
|
|
480
|
+
operation: context.operation
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
getFunctionImpl(functionName) {
|
|
484
|
+
let func = this.clientOptions.functions?.[functionName];
|
|
485
|
+
if (!func) {
|
|
486
|
+
for (const plugin of this.clientOptions.plugins ?? []) if (plugin.functions?.[functionName]) {
|
|
487
|
+
func = plugin.functions[functionName];
|
|
488
|
+
break;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
return func;
|
|
492
|
+
}
|
|
493
|
+
transformCallArg(arg, context) {
|
|
494
|
+
if (ExpressionUtils.isField(arg)) return this.eb.ref(arg.field);
|
|
495
|
+
else return new ExpressionWrapper(this.transform(arg, context));
|
|
496
|
+
}
|
|
497
|
+
_member(expr, context) {
|
|
498
|
+
if (ExpressionUtils.isBinding(expr.receiver)) {
|
|
499
|
+
const scope = this.requireBindingScope(expr.receiver, context);
|
|
500
|
+
if (scope.value !== void 0) return this.valueMemberAccess(scope.value, expr, scope.type);
|
|
501
|
+
}
|
|
502
|
+
if (this.isAuthCall(expr.receiver)) return this.valueMemberAccess(this.auth, expr, this.authType);
|
|
503
|
+
if (isBeforeInvocation(expr.receiver)) {
|
|
504
|
+
invariant(context.operation === "post-update", "before() can only be used in post-update policy");
|
|
505
|
+
invariant(expr.members.length === 1, "before() can only be followed by a scalar field access");
|
|
506
|
+
return ReferenceNode.create(ColumnNode.create(expr.members[0]), TableNode.create("$before"));
|
|
507
|
+
}
|
|
508
|
+
invariant(ExpressionUtils.isField(expr.receiver) || ExpressionUtils.isThis(expr.receiver) || ExpressionUtils.isBinding(expr.receiver), "expect receiver to be field expression, collection predicate binding, or \"this\"");
|
|
509
|
+
let members = expr.members;
|
|
510
|
+
let receiver;
|
|
511
|
+
let startType;
|
|
512
|
+
const { memberFilter, memberSelect, ...restContext } = context;
|
|
513
|
+
if (ExpressionUtils.isThis(expr.receiver)) if (expr.members.length === 1) return this._field(ExpressionUtils.field(expr.members[0]), {
|
|
514
|
+
...context,
|
|
515
|
+
alias: context.thisAlias,
|
|
516
|
+
modelOrType: context.thisType,
|
|
517
|
+
thisType: context.thisType,
|
|
518
|
+
contextValue: void 0
|
|
519
|
+
});
|
|
520
|
+
else {
|
|
521
|
+
const firstMemberFieldDef = QueryUtils.requireField(this.schema, context.thisType, expr.members[0]);
|
|
522
|
+
receiver = this.transformRelationAccess(expr.members[0], firstMemberFieldDef.type, restContext);
|
|
523
|
+
members = expr.members.slice(1);
|
|
524
|
+
startType = firstMemberFieldDef.type;
|
|
525
|
+
}
|
|
526
|
+
else if (ExpressionUtils.isBinding(expr.receiver)) if (expr.members.length === 1) {
|
|
527
|
+
const bindingScope = this.requireBindingScope(expr.receiver, context);
|
|
528
|
+
return this._field(ExpressionUtils.field(expr.members[0]), {
|
|
529
|
+
...context,
|
|
530
|
+
modelOrType: bindingScope.type,
|
|
531
|
+
alias: bindingScope.alias,
|
|
532
|
+
thisType: context.thisType,
|
|
533
|
+
contextValue: void 0
|
|
534
|
+
});
|
|
535
|
+
} else {
|
|
536
|
+
const bindingScope = this.requireBindingScope(expr.receiver, context);
|
|
537
|
+
const firstMemberFieldDef = QueryUtils.requireField(this.schema, bindingScope.type, expr.members[0]);
|
|
538
|
+
receiver = this.transformRelationAccess(expr.members[0], firstMemberFieldDef.type, {
|
|
539
|
+
...restContext,
|
|
540
|
+
modelOrType: bindingScope.type,
|
|
541
|
+
alias: bindingScope.alias
|
|
542
|
+
});
|
|
543
|
+
members = expr.members.slice(1);
|
|
544
|
+
startType = firstMemberFieldDef.type;
|
|
545
|
+
}
|
|
546
|
+
else receiver = this.transform(expr.receiver, restContext);
|
|
547
|
+
invariant(SelectQueryNode.is(receiver), "expected receiver to be select query");
|
|
548
|
+
if (startType === void 0) if (ExpressionUtils.isField(expr.receiver)) startType = QueryUtils.requireField(this.schema, context.modelOrType, expr.receiver.field).type;
|
|
549
|
+
else startType = context.thisType;
|
|
550
|
+
const memberFields = [];
|
|
551
|
+
let currType = startType;
|
|
552
|
+
for (const member of members) {
|
|
553
|
+
const fieldDef = QueryUtils.requireField(this.schema, currType, member);
|
|
554
|
+
memberFields.push({
|
|
555
|
+
fieldDef,
|
|
556
|
+
fromModel: currType
|
|
557
|
+
});
|
|
558
|
+
currType = fieldDef.type;
|
|
559
|
+
}
|
|
560
|
+
let currNode = void 0;
|
|
561
|
+
for (let i = members.length - 1; i >= 0; i--) {
|
|
562
|
+
const member = members[i];
|
|
563
|
+
const { fieldDef, fromModel } = memberFields[i];
|
|
564
|
+
if (fieldDef.relation) {
|
|
565
|
+
const relation = this.transformRelationAccess(member, fieldDef.type, {
|
|
566
|
+
...restContext,
|
|
567
|
+
modelOrType: fromModel,
|
|
568
|
+
alias: void 0
|
|
569
|
+
});
|
|
570
|
+
if (currNode) currNode = {
|
|
571
|
+
...relation,
|
|
572
|
+
selections: [SelectionNode.create(AliasNode.create(currNode, IdentifierNode.create(members[i + 1])))]
|
|
573
|
+
};
|
|
574
|
+
else currNode = {
|
|
575
|
+
...relation,
|
|
576
|
+
where: this.mergeWhere(relation.where, memberFilter),
|
|
577
|
+
selections: memberSelect ? [memberSelect] : relation.selections
|
|
578
|
+
};
|
|
579
|
+
} else {
|
|
580
|
+
invariant(i === members.length - 1, "plain field access must be the last segment");
|
|
581
|
+
invariant(!currNode, "plain field access must be the last segment");
|
|
582
|
+
currNode = ColumnNode.create(member);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
return {
|
|
586
|
+
...receiver,
|
|
587
|
+
selections: [SelectionNode.create(AliasNode.create(currNode, IdentifierNode.create("_")))]
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
requireBindingScope(expr, context) {
|
|
591
|
+
const binding = context.bindingScope?.[expr.name];
|
|
592
|
+
invariant(binding, `binding not found: ${expr.name}`);
|
|
593
|
+
return binding;
|
|
594
|
+
}
|
|
595
|
+
valueMemberAccess(receiver, expr, receiverType) {
|
|
596
|
+
if (!receiver) return ValueNode.createImmediate(null);
|
|
597
|
+
invariant(expr.members.length > 0, "member expression must have at least one member");
|
|
598
|
+
let curr = receiver;
|
|
599
|
+
let currType = receiverType;
|
|
600
|
+
for (let i = 0; i < expr.members.length; i++) {
|
|
601
|
+
const field = expr.members[i];
|
|
602
|
+
curr = curr?.[field];
|
|
603
|
+
if (curr === void 0) {
|
|
604
|
+
curr = ValueNode.createImmediate(null);
|
|
605
|
+
break;
|
|
606
|
+
}
|
|
607
|
+
currType = QueryUtils.requireField(this.schema, currType, field).type;
|
|
608
|
+
if (i === expr.members.length - 1) curr = this.transformValue(curr, currType);
|
|
609
|
+
}
|
|
610
|
+
return curr;
|
|
611
|
+
}
|
|
612
|
+
transformRelationAccess(field, relationModel, context) {
|
|
613
|
+
const m2m = QueryUtils.getManyToManyRelation(this.schema, context.modelOrType, field);
|
|
614
|
+
if (m2m) return this.transformManyToManyRelationAccess(m2m, context);
|
|
615
|
+
const fromModel = context.modelOrType;
|
|
616
|
+
const relationFieldDef = QueryUtils.requireField(this.schema, fromModel, field);
|
|
617
|
+
const { keyPairs, ownedByModel } = QueryUtils.getRelationForeignKeyFieldPairs(this.schema, fromModel, field);
|
|
618
|
+
let condition;
|
|
619
|
+
if (ownedByModel) condition = conjunction(this.dialect, keyPairs.map(({ fk, pk }) => {
|
|
620
|
+
let fkRef = ReferenceNode.create(ColumnNode.create(fk), TableNode.create(context.alias ?? fromModel));
|
|
621
|
+
if (relationFieldDef.originModel && relationFieldDef.originModel !== fromModel) fkRef = this.buildDelegateBaseFieldSelect(fromModel, context.alias ?? fromModel, fk, relationFieldDef.originModel);
|
|
622
|
+
return BinaryOperationNode.create(fkRef, OperatorNode.create("="), ReferenceNode.create(ColumnNode.create(pk), TableNode.create(relationModel)));
|
|
623
|
+
}));
|
|
624
|
+
else condition = conjunction(this.dialect, keyPairs.map(({ fk, pk }) => BinaryOperationNode.create(ReferenceNode.create(ColumnNode.create(pk), TableNode.create(context.alias ?? fromModel)), OperatorNode.create("="), ReferenceNode.create(ColumnNode.create(fk), TableNode.create(relationModel)))));
|
|
625
|
+
return {
|
|
626
|
+
kind: "SelectQueryNode",
|
|
627
|
+
from: FromNode.create([TableNode.create(relationModel)]),
|
|
628
|
+
where: WhereNode.create(condition)
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
transformManyToManyRelationAccess(m2m, context) {
|
|
632
|
+
return expressionBuilder().selectFrom(m2m.otherModel).innerJoin(m2m.joinTable, (join) => join.onRef(`${m2m.otherModel}.${m2m.otherPKName}`, "=", `${m2m.joinTable}.${m2m.otherFkName}`).onRef(`${m2m.joinTable}.${m2m.parentFkName}`, "=", `${context.alias ?? context.modelOrType}.${m2m.parentPKName}`)).toOperationNode();
|
|
633
|
+
}
|
|
634
|
+
createColumnRef(column, context) {
|
|
635
|
+
const tableName = context.alias ?? context.modelOrType;
|
|
636
|
+
if (context.operation === "create") return ReferenceNode.create(ColumnNode.create(column), TableNode.create(tableName));
|
|
637
|
+
const fieldDef = QueryUtils.requireField(this.schema, context.modelOrType, column);
|
|
638
|
+
if (!fieldDef.originModel || fieldDef.originModel === context.modelOrType) return ReferenceNode.create(ColumnNode.create(column), TableNode.create(tableName));
|
|
639
|
+
return this.buildDelegateBaseFieldSelect(context.modelOrType, tableName, column, fieldDef.originModel);
|
|
640
|
+
}
|
|
641
|
+
getEvaluationBindingScope(scope) {
|
|
642
|
+
if (!scope) return;
|
|
643
|
+
const result = {};
|
|
644
|
+
for (const [key, value] of Object.entries(scope)) if (value.value !== void 0) result[key] = value.value;
|
|
645
|
+
return Object.keys(result).length > 0 ? result : void 0;
|
|
646
|
+
}
|
|
647
|
+
buildDelegateBaseFieldSelect(model, modelAlias, field, baseModel) {
|
|
648
|
+
const idFields = QueryUtils.requireIdFields(this.client.$schema, model);
|
|
649
|
+
return {
|
|
650
|
+
kind: "SelectQueryNode",
|
|
651
|
+
from: FromNode.create([TableNode.create(baseModel)]),
|
|
652
|
+
selections: [SelectionNode.create(ReferenceNode.create(ColumnNode.create(field), TableNode.create(baseModel)))],
|
|
653
|
+
where: WhereNode.create(conjunction(this.dialect, idFields.map((idField) => BinaryOperationNode.create(ReferenceNode.create(ColumnNode.create(idField), TableNode.create(baseModel)), OperatorNode.create("="), ReferenceNode.create(ColumnNode.create(idField), TableNode.create(modelAlias))))))
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
isAuthCall(value) {
|
|
657
|
+
return ExpressionUtils.isCall(value) && value.function === "auth";
|
|
658
|
+
}
|
|
659
|
+
isAuthMember(expr) {
|
|
660
|
+
return ExpressionUtils.isMember(expr) && this.isAuthCall(expr.receiver);
|
|
661
|
+
}
|
|
662
|
+
isNullNode(node) {
|
|
663
|
+
return ValueNode.is(node) && node.value === null;
|
|
664
|
+
}
|
|
665
|
+
buildLogicalNot(result) {
|
|
666
|
+
return ExpressionUtils.unary("!", result);
|
|
667
|
+
}
|
|
668
|
+
buildAnd(conditions) {
|
|
669
|
+
if (conditions.length === 0) return ExpressionUtils.literal(true);
|
|
670
|
+
else if (conditions.length === 1) return conditions[0];
|
|
671
|
+
else return conditions.reduce((acc, condition) => ExpressionUtils.binary(acc, "&&", condition));
|
|
672
|
+
}
|
|
673
|
+
isRelationField(expr, context) {
|
|
674
|
+
return !!this.getFieldDefFromFieldRef(expr, context)?.relation;
|
|
675
|
+
}
|
|
676
|
+
getFieldDefFromFieldRef(expr, context) {
|
|
677
|
+
const model = ExpressionUtils.isMember(expr) && ExpressionUtils.isThis(expr.receiver) ? context.thisType : context.modelOrType;
|
|
678
|
+
if (ExpressionUtils.isField(expr)) return QueryUtils.getField(this.schema, model, expr.field);
|
|
679
|
+
else if (ExpressionUtils.isMember(expr) && expr.members.length === 1 && ExpressionUtils.isThis(expr.receiver)) return QueryUtils.getField(this.schema, model, expr.members[0]);
|
|
680
|
+
else if (ExpressionUtils.isMember(expr) && ExpressionUtils.isField(expr.receiver)) {
|
|
681
|
+
const receiverDef = QueryUtils.getField(this.schema, model, expr.receiver.field);
|
|
682
|
+
if (!receiverDef?.relation) return void 0;
|
|
683
|
+
let currModel = receiverDef.type;
|
|
684
|
+
for (let i = 0; i < expr.members.length - 1; i++) {
|
|
685
|
+
const hopDef = QueryUtils.getField(this.schema, currModel, expr.members[i]);
|
|
686
|
+
if (!hopDef?.relation) return void 0;
|
|
687
|
+
currModel = hopDef.type;
|
|
688
|
+
}
|
|
689
|
+
return QueryUtils.getField(this.schema, currModel, expr.members[expr.members.length - 1]);
|
|
690
|
+
} else return;
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
__decorate([
|
|
694
|
+
expr("literal"),
|
|
695
|
+
__decorateMetadata("design:type", Function),
|
|
696
|
+
__decorateMetadata("design:paramtypes", [Object]),
|
|
697
|
+
__decorateMetadata("design:returntype", void 0)
|
|
698
|
+
], ExpressionTransformer.prototype, "_literal", null);
|
|
699
|
+
__decorate([
|
|
700
|
+
expr("array"),
|
|
701
|
+
__decorateMetadata("design:type", Function),
|
|
702
|
+
__decorateMetadata("design:paramtypes", [Object, Object]),
|
|
703
|
+
__decorateMetadata("design:returntype", void 0)
|
|
704
|
+
], ExpressionTransformer.prototype, "_array", null);
|
|
705
|
+
__decorate([
|
|
706
|
+
expr("field"),
|
|
707
|
+
__decorateMetadata("design:type", Function),
|
|
708
|
+
__decorateMetadata("design:paramtypes", [Object, Object]),
|
|
709
|
+
__decorateMetadata("design:returntype", void 0)
|
|
710
|
+
], ExpressionTransformer.prototype, "_field", null);
|
|
711
|
+
__decorate([
|
|
712
|
+
expr("null"),
|
|
713
|
+
__decorateMetadata("design:type", Function),
|
|
714
|
+
__decorateMetadata("design:paramtypes", []),
|
|
715
|
+
__decorateMetadata("design:returntype", void 0)
|
|
716
|
+
], ExpressionTransformer.prototype, "_null", null);
|
|
717
|
+
__decorate([
|
|
718
|
+
expr("binary"),
|
|
719
|
+
__decorateMetadata("design:type", Function),
|
|
720
|
+
__decorateMetadata("design:paramtypes", [Object, Object]),
|
|
721
|
+
__decorateMetadata("design:returntype", void 0)
|
|
722
|
+
], ExpressionTransformer.prototype, "_binary", null);
|
|
723
|
+
__decorate([
|
|
724
|
+
expr("unary"),
|
|
725
|
+
__decorateMetadata("design:type", Function),
|
|
726
|
+
__decorateMetadata("design:paramtypes", [Object, Object]),
|
|
727
|
+
__decorateMetadata("design:returntype", void 0)
|
|
728
|
+
], ExpressionTransformer.prototype, "_unary", null);
|
|
729
|
+
__decorate([
|
|
730
|
+
expr("call"),
|
|
731
|
+
__decorateMetadata("design:type", Function),
|
|
732
|
+
__decorateMetadata("design:paramtypes", [Object, Object]),
|
|
733
|
+
__decorateMetadata("design:returntype", void 0)
|
|
734
|
+
], ExpressionTransformer.prototype, "_call", null);
|
|
735
|
+
__decorate([
|
|
736
|
+
expr("member"),
|
|
737
|
+
__decorateMetadata("design:type", Function),
|
|
738
|
+
__decorateMetadata("design:paramtypes", [Object, Object]),
|
|
739
|
+
__decorateMetadata("design:returntype", void 0)
|
|
740
|
+
], ExpressionTransformer.prototype, "_member", null);
|
|
741
|
+
//#endregion
|
|
742
|
+
//#region src/policy-handler.ts
|
|
743
|
+
var PolicyHandler = class extends OperationNodeTransformer {
|
|
744
|
+
dialect;
|
|
745
|
+
eb = expressionBuilder();
|
|
746
|
+
constructor(client, options = {}) {
|
|
747
|
+
super();
|
|
748
|
+
this.client = client;
|
|
749
|
+
this.options = options;
|
|
750
|
+
this.dialect = getCrudDialect(this.client.$schema, this.client.$options);
|
|
751
|
+
}
|
|
752
|
+
async handle(node, proceed) {
|
|
753
|
+
if (!this.isCrudQueryNode(node)) {
|
|
754
|
+
if (this.options.dangerouslyAllowRawSql && RawNode.is(node)) return proceed(node);
|
|
755
|
+
throw createRejectedByPolicyError(void 0, RejectedByPolicyReason.OTHER, "non-CRUD queries are not allowed");
|
|
756
|
+
}
|
|
757
|
+
if (!this.isMutationQueryNode(node)) return proceed(this.transformNode(node));
|
|
758
|
+
const { mutationModel } = this.getMutationModel(node);
|
|
759
|
+
this.tryRejectNonexistentModel(mutationModel);
|
|
760
|
+
if (InsertQueryNode.is(node)) await this.preCreateCheck(mutationModel, node, proceed);
|
|
761
|
+
if (UpdateQueryNode.is(node)) await this.preUpdateCheck(mutationModel, node, proceed);
|
|
762
|
+
const needsPostUpdateCheck = UpdateQueryNode.is(node) && this.hasPostUpdatePolicies(mutationModel);
|
|
763
|
+
let beforeUpdateInfo;
|
|
764
|
+
if (needsPostUpdateCheck) beforeUpdateInfo = await this.loadBeforeUpdateEntities(mutationModel, node.where, proceed, !this.dialect.supportsReturning);
|
|
765
|
+
const result = await proceed(this.transformNode(node));
|
|
766
|
+
if ((result.numAffectedRows ?? 0) > 0 && needsPostUpdateCheck) await this.postUpdateCheck(mutationModel, beforeUpdateInfo, result, proceed);
|
|
767
|
+
if (!node.returning || this.onlyReturningId(node)) return this.postProcessMutationResult(result, node);
|
|
768
|
+
else {
|
|
769
|
+
const readBackResult = await this.processReadBack(node, result, proceed);
|
|
770
|
+
if (readBackResult.rows.length !== result.rows.length) throw createRejectedByPolicyError(mutationModel, RejectedByPolicyReason.CANNOT_READ_BACK, "result is not allowed to be read back");
|
|
771
|
+
return readBackResult;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
async preCreateCheck(mutationModel, node, proceed) {
|
|
775
|
+
const isManyToManyJoinTable = this.isManyToManyJoinTable(mutationModel);
|
|
776
|
+
let needCheckPreCreate = true;
|
|
777
|
+
if (!isManyToManyJoinTable) {
|
|
778
|
+
const constCondition = this.tryGetConstantPolicy(mutationModel, "create");
|
|
779
|
+
if (constCondition === true) needCheckPreCreate = false;
|
|
780
|
+
else if (constCondition === false) throw createRejectedByPolicyError(mutationModel, RejectedByPolicyReason.NO_ACCESS);
|
|
781
|
+
}
|
|
782
|
+
if (needCheckPreCreate) await this.enforcePreCreatePolicy(node, mutationModel, isManyToManyJoinTable, proceed);
|
|
783
|
+
}
|
|
784
|
+
async preUpdateCheck(mutationModel, node, proceed) {
|
|
785
|
+
const fieldUpdatePolicies = (node.updates?.map((u) => ColumnNode.is(u.column) ? u.column.column.name : void 0).filter((f) => !!f) ?? []).map((f) => this.buildFieldPolicyFilter(mutationModel, f, "update"));
|
|
786
|
+
const fieldLevelFilter = conjunction(this.dialect, fieldUpdatePolicies);
|
|
787
|
+
if (isTrueNode(fieldLevelFilter)) return;
|
|
788
|
+
const modelLevelFilter = this.buildPolicyFilter(mutationModel, void 0, "update");
|
|
789
|
+
const updateFilter = conjunction(this.dialect, [modelLevelFilter, node.where?.where ?? trueNode(this.dialect)]);
|
|
790
|
+
if ((await proceed(this.eb.selectFrom(mutationModel).select((eb) => eb.fn.coalesce(eb.fn.sum(this.dialect.castInt(new ExpressionWrapper(logicalNot(this.dialect, fieldLevelFilter)))), eb.lit(0)).as("$filteredCount")).where(() => new ExpressionWrapper(updateFilter)).toOperationNode())).rows[0].$filteredCount > 0) throw createRejectedByPolicyError(mutationModel, RejectedByPolicyReason.NO_ACCESS, "some rows cannot be updated due to field policies");
|
|
791
|
+
}
|
|
792
|
+
async postUpdateCheck(model, beforeUpdateInfo, updateResult, proceed) {
|
|
793
|
+
let postUpdateRows;
|
|
794
|
+
if (this.dialect.supportsReturning) postUpdateRows = updateResult.rows;
|
|
795
|
+
else {
|
|
796
|
+
invariant(beforeUpdateInfo, "beforeUpdateInfo must be defined for dialects not supporting returning");
|
|
797
|
+
const idConditions = this.buildIdConditions(model, beforeUpdateInfo.rows);
|
|
798
|
+
const idFields = QueryUtils.requireIdFields(this.client.$schema, model);
|
|
799
|
+
postUpdateRows = (await proceed({
|
|
800
|
+
kind: "SelectQueryNode",
|
|
801
|
+
from: FromNode.create([TableNode.create(model)]),
|
|
802
|
+
where: WhereNode.create(idConditions),
|
|
803
|
+
selections: idFields.map((field) => SelectionNode.create(ColumnNode.create(field)))
|
|
804
|
+
})).rows;
|
|
805
|
+
}
|
|
806
|
+
if (beforeUpdateInfo) {
|
|
807
|
+
if (beforeUpdateInfo.rows.length !== postUpdateRows.length) throw createRejectedByPolicyError(model, RejectedByPolicyReason.OTHER, "Before-update and after-update rows do not match. If you have post-update policies on a model, updating id fields is not supported.");
|
|
808
|
+
const idFields = QueryUtils.requireIdFields(this.client.$schema, model);
|
|
809
|
+
for (const postRow of postUpdateRows) if (!beforeUpdateInfo.rows.find((r) => idFields.every((f) => r[f] === postRow[f]))) throw createRejectedByPolicyError(model, RejectedByPolicyReason.OTHER, "Before-update and after-update rows do not match. If you have post-update policies on a model, updating id fields is not supported.");
|
|
810
|
+
}
|
|
811
|
+
const idConditions = this.buildIdConditions(model, postUpdateRows);
|
|
812
|
+
const postUpdateFilter = this.buildPolicyFilter(model, void 0, "post-update");
|
|
813
|
+
const eb = expressionBuilder();
|
|
814
|
+
const needsBeforeUpdateJoin = !!beforeUpdateInfo?.fields;
|
|
815
|
+
let beforeUpdateTable = void 0;
|
|
816
|
+
if (needsBeforeUpdateJoin) {
|
|
817
|
+
const fieldDefs = beforeUpdateInfo.fields.map((name) => QueryUtils.requireField(this.client.$schema, model, name));
|
|
818
|
+
const rows = beforeUpdateInfo.rows.map((r) => beforeUpdateInfo.fields.map((f) => r[f]));
|
|
819
|
+
beforeUpdateTable = this.dialect.buildValuesTableSelect(fieldDefs, rows).toOperationNode();
|
|
820
|
+
}
|
|
821
|
+
if (!(await proceed(eb.selectFrom(model).select(() => [eb(eb.fn("COUNT", [eb.lit(1)]), "=", Number(updateResult.numAffectedRows ?? 0)).as("$condition")]).where(() => new ExpressionWrapper(conjunction(this.dialect, [idConditions, postUpdateFilter]))).$if(needsBeforeUpdateJoin, (qb) => qb.leftJoin(() => new ExpressionWrapper(beforeUpdateTable).as("$before"), (join) => {
|
|
822
|
+
return QueryUtils.requireIdFields(this.client.$schema, model).reduce((acc, f) => acc.onRef(`${model}.${f}`, "=", `$before.${f}`), join);
|
|
823
|
+
})).toOperationNode())).rows[0]?.$condition) throw createRejectedByPolicyError(model, RejectedByPolicyReason.NO_ACCESS, "some or all updated rows failed to pass post-update policy check");
|
|
824
|
+
}
|
|
825
|
+
transformSelectQuery(node) {
|
|
826
|
+
if (!node.from) return super.transformSelectQuery(node);
|
|
827
|
+
this.tryRejectNonexistingTables(node.from.froms);
|
|
828
|
+
let result = super.transformSelectQuery(node);
|
|
829
|
+
if (node.from.froms.some((table) => {
|
|
830
|
+
const extractedTable = this.extractTableName(table);
|
|
831
|
+
if (extractedTable) return this.hasFieldLevelPolicies(extractedTable.model, "read");
|
|
832
|
+
else return false;
|
|
833
|
+
})) {
|
|
834
|
+
const updatedFroms = [];
|
|
835
|
+
for (const table of result.from.froms) {
|
|
836
|
+
const extractedTable = this.extractTableName(table);
|
|
837
|
+
if (extractedTable?.model && QueryUtils.getModel(this.client.$schema, extractedTable.model)) {
|
|
838
|
+
const { query } = this.createSelectAllFieldsWithPolicies(extractedTable.model, extractedTable.alias, "read");
|
|
839
|
+
updatedFroms.push(query);
|
|
840
|
+
} else updatedFroms.push(table);
|
|
841
|
+
}
|
|
842
|
+
result = {
|
|
843
|
+
...result,
|
|
844
|
+
from: FromNode.create(updatedFroms)
|
|
845
|
+
};
|
|
846
|
+
} else {
|
|
847
|
+
let whereNode = result.where;
|
|
848
|
+
const policyFilter = this.createPolicyFilterForFrom(result.from);
|
|
849
|
+
if (policyFilter && !isTrueNode(policyFilter)) whereNode = WhereNode.create(whereNode?.where ? conjunction(this.dialect, [whereNode.where, policyFilter]) : policyFilter);
|
|
850
|
+
result = {
|
|
851
|
+
...result,
|
|
852
|
+
where: whereNode
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
return result;
|
|
856
|
+
}
|
|
857
|
+
transformJoin(node) {
|
|
858
|
+
const table = this.extractTableName(node.table);
|
|
859
|
+
if (!table) return super.transformJoin(node);
|
|
860
|
+
this.tryRejectNonexistentModel(table.model);
|
|
861
|
+
if (!QueryUtils.getModel(this.client.$schema, table.model)) return super.transformJoin(node);
|
|
862
|
+
const result = super.transformJoin(node);
|
|
863
|
+
const { hasPolicies, query: nestedQuery } = this.createSelectAllFieldsWithPolicies(table.model, table.alias, "read");
|
|
864
|
+
if (!hasPolicies) return result;
|
|
865
|
+
return {
|
|
866
|
+
...result,
|
|
867
|
+
table: nestedQuery
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
transformInsertQuery(node) {
|
|
871
|
+
let processedNode = node;
|
|
872
|
+
let onConflict = node.onConflict;
|
|
873
|
+
if (onConflict?.updates) {
|
|
874
|
+
const { mutationModel, alias } = this.getMutationModel(node);
|
|
875
|
+
const filter = this.buildPolicyFilter(mutationModel, alias, "update");
|
|
876
|
+
if (onConflict.updateWhere) onConflict = {
|
|
877
|
+
...onConflict,
|
|
878
|
+
updateWhere: WhereNode.create(conjunction(this.dialect, [onConflict.updateWhere.where, filter]))
|
|
879
|
+
};
|
|
880
|
+
else onConflict = {
|
|
881
|
+
...onConflict,
|
|
882
|
+
updateWhere: WhereNode.create(filter)
|
|
883
|
+
};
|
|
884
|
+
processedNode = {
|
|
885
|
+
...node,
|
|
886
|
+
onConflict
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
let onDuplicateKey = node.onDuplicateKey;
|
|
890
|
+
if (onDuplicateKey?.updates) {
|
|
891
|
+
const { mutationModel } = this.getMutationModel(node);
|
|
892
|
+
const filterWithTableRef = this.buildPolicyFilter(mutationModel, void 0, "update");
|
|
893
|
+
const filter = this.stripTableReferences(filterWithTableRef, mutationModel);
|
|
894
|
+
const wrappedUpdates = onDuplicateKey.updates.map((update) => {
|
|
895
|
+
const columnName = ColumnNode.is(update.column) ? update.column.column.name : void 0;
|
|
896
|
+
if (!columnName) return update;
|
|
897
|
+
const wrappedValue = sql`IF(${new ExpressionWrapper(filter)}, ${new ExpressionWrapper(update.value)}, ${sql.ref(columnName)})`.toOperationNode();
|
|
898
|
+
return {
|
|
899
|
+
...update,
|
|
900
|
+
value: wrappedValue
|
|
901
|
+
};
|
|
902
|
+
});
|
|
903
|
+
onDuplicateKey = {
|
|
904
|
+
...onDuplicateKey,
|
|
905
|
+
updates: wrappedUpdates
|
|
906
|
+
};
|
|
907
|
+
processedNode = {
|
|
908
|
+
...processedNode,
|
|
909
|
+
onDuplicateKey
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
const result = super.transformInsertQuery(processedNode);
|
|
913
|
+
let returning = result.returning;
|
|
914
|
+
if (returning) {
|
|
915
|
+
const { mutationModel } = this.getMutationModel(node);
|
|
916
|
+
const idFields = QueryUtils.requireIdFields(this.client.$schema, mutationModel);
|
|
917
|
+
returning = ReturningNode.create(idFields.map((f) => SelectionNode.create(ColumnNode.create(f))));
|
|
918
|
+
}
|
|
919
|
+
return {
|
|
920
|
+
...result,
|
|
921
|
+
returning
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
transformUpdateQuery(node) {
|
|
925
|
+
const result = super.transformUpdateQuery(node);
|
|
926
|
+
const { mutationModel, alias } = this.getMutationModel(node);
|
|
927
|
+
let filter = this.buildPolicyFilter(mutationModel, alias, "update");
|
|
928
|
+
if (node.from) {
|
|
929
|
+
this.tryRejectNonexistingTables(node.from.froms);
|
|
930
|
+
const joinFilter = this.createPolicyFilterForFrom(node.from);
|
|
931
|
+
if (joinFilter) filter = conjunction(this.dialect, [filter, joinFilter]);
|
|
932
|
+
}
|
|
933
|
+
let returning = result.returning;
|
|
934
|
+
if (this.dialect.supportsReturning && (returning || this.hasPostUpdatePolicies(mutationModel))) {
|
|
935
|
+
const idFields = QueryUtils.requireIdFields(this.client.$schema, mutationModel);
|
|
936
|
+
returning = ReturningNode.create(idFields.map((f) => SelectionNode.create(ColumnNode.create(f))));
|
|
937
|
+
}
|
|
938
|
+
return {
|
|
939
|
+
...result,
|
|
940
|
+
where: WhereNode.create(result.where ? conjunction(this.dialect, [result.where.where, filter]) : filter),
|
|
941
|
+
returning
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
transformDeleteQuery(node) {
|
|
945
|
+
const result = super.transformDeleteQuery(node);
|
|
946
|
+
const { mutationModel, alias } = this.getMutationModel(node);
|
|
947
|
+
let filter = this.buildPolicyFilter(mutationModel, alias, "delete");
|
|
948
|
+
if (node.using) {
|
|
949
|
+
this.tryRejectNonexistingTables(node.using.tables);
|
|
950
|
+
const joinFilter = this.createPolicyFilterForTables(node.using.tables);
|
|
951
|
+
if (joinFilter) filter = conjunction(this.dialect, [filter, joinFilter]);
|
|
952
|
+
}
|
|
953
|
+
return {
|
|
954
|
+
...result,
|
|
955
|
+
where: WhereNode.create(result.where ? conjunction(this.dialect, [result.where.where, filter]) : filter)
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
async loadBeforeUpdateEntities(model, where, proceed, forceLoad = false) {
|
|
959
|
+
const beforeUpdateAccessFields = this.getFieldsAccessForBeforeUpdatePolicies(model);
|
|
960
|
+
if (!forceLoad && (!beforeUpdateAccessFields || beforeUpdateAccessFields.length === 0)) return;
|
|
961
|
+
const policyFilter = this.buildPolicyFilter(model, model, "update");
|
|
962
|
+
const combinedFilter = where ? conjunction(this.dialect, [where.where, policyFilter]) : policyFilter;
|
|
963
|
+
const selections = beforeUpdateAccessFields ?? QueryUtils.requireIdFields(this.client.$schema, model);
|
|
964
|
+
return {
|
|
965
|
+
fields: beforeUpdateAccessFields,
|
|
966
|
+
rows: (await proceed({
|
|
967
|
+
kind: "SelectQueryNode",
|
|
968
|
+
from: FromNode.create([TableNode.create(model)]),
|
|
969
|
+
where: WhereNode.create(combinedFilter),
|
|
970
|
+
selections: selections.map((f) => SelectionNode.create(ColumnNode.create(f)))
|
|
971
|
+
})).rows
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
getFieldsAccessForBeforeUpdatePolicies(model) {
|
|
975
|
+
const policies = this.getModelPolicies(model, "post-update");
|
|
976
|
+
if (policies.length === 0) return;
|
|
977
|
+
const fields = /* @__PURE__ */ new Set();
|
|
978
|
+
const fieldCollector = new class extends SchemaUtils.ExpressionVisitor {
|
|
979
|
+
visitMember(e) {
|
|
980
|
+
if (isBeforeInvocation(e.receiver)) {
|
|
981
|
+
invariant(e.members.length === 1, "before() can only be followed by a scalar field access");
|
|
982
|
+
fields.add(e.members[0]);
|
|
983
|
+
}
|
|
984
|
+
super.visitMember(e);
|
|
985
|
+
}
|
|
986
|
+
}();
|
|
987
|
+
for (const policy of policies) fieldCollector.visit(policy.condition);
|
|
988
|
+
if (fields.size === 0) return;
|
|
989
|
+
QueryUtils.requireIdFields(this.client.$schema, model).forEach((f) => fields.add(f));
|
|
990
|
+
return Array.from(fields).sort();
|
|
991
|
+
}
|
|
992
|
+
hasPostUpdatePolicies(model) {
|
|
993
|
+
return this.getModelPolicies(model, "post-update").length > 0;
|
|
994
|
+
}
|
|
995
|
+
createSelectAllFieldsWithPolicies(model, alias, operation) {
|
|
996
|
+
let hasPolicies = false;
|
|
997
|
+
const modelDef = QueryUtils.requireModel(this.client.$schema, model);
|
|
998
|
+
let selections = [];
|
|
999
|
+
for (const fieldDef of Object.values(modelDef.fields).filter((f) => !f.relation && !f.computed && !f.originModel)) {
|
|
1000
|
+
const { hasPolicies: fieldHasPolicies, selection } = this.createFieldSelectionWithPolicy(model, fieldDef.name, operation);
|
|
1001
|
+
hasPolicies = hasPolicies || fieldHasPolicies;
|
|
1002
|
+
selections.push(selection);
|
|
1003
|
+
}
|
|
1004
|
+
if (!hasPolicies) selections = [SelectionNode.create(SelectAllNode.create())];
|
|
1005
|
+
const modelPolicyFilter = this.buildPolicyFilter(model, model, operation);
|
|
1006
|
+
if (!isTrueNode(modelPolicyFilter)) hasPolicies = true;
|
|
1007
|
+
const nestedQuery = {
|
|
1008
|
+
kind: "SelectQueryNode",
|
|
1009
|
+
from: FromNode.create([TableNode.create(model)]),
|
|
1010
|
+
where: isTrueNode(modelPolicyFilter) ? void 0 : WhereNode.create(modelPolicyFilter),
|
|
1011
|
+
selections
|
|
1012
|
+
};
|
|
1013
|
+
return {
|
|
1014
|
+
hasPolicies,
|
|
1015
|
+
query: AliasNode.create(ParensNode.create(nestedQuery), IdentifierNode.create(alias ?? model))
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
createFieldSelectionWithPolicy(model, field, operation) {
|
|
1019
|
+
const filter = this.buildFieldPolicyFilter(model, field, operation);
|
|
1020
|
+
if (isTrueNode(filter)) return {
|
|
1021
|
+
hasPolicies: false,
|
|
1022
|
+
selection: SelectionNode.create(ColumnNode.create(field))
|
|
1023
|
+
};
|
|
1024
|
+
const eb = expressionBuilder();
|
|
1025
|
+
const selection = eb.case().when(new ExpressionWrapper(filter)).then(eb.ref(field)).else(null).end().as(field).toOperationNode();
|
|
1026
|
+
return {
|
|
1027
|
+
hasPolicies: true,
|
|
1028
|
+
selection: SelectionNode.create(selection)
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
hasFieldLevelPolicies(model, operation) {
|
|
1032
|
+
const modelDef = QueryUtils.getModel(this.client.$schema, model);
|
|
1033
|
+
if (!modelDef) return false;
|
|
1034
|
+
return Object.keys(modelDef.fields).some((field) => this.getFieldPolicies(model, field, operation).length > 0);
|
|
1035
|
+
}
|
|
1036
|
+
buildFieldPolicyFilter(model, field, operation) {
|
|
1037
|
+
const policies = this.getFieldPolicies(model, field, operation);
|
|
1038
|
+
const allows = policies.filter((policy) => policy.kind === "allow").map((policy) => this.compilePolicyCondition(model, model, operation, policy));
|
|
1039
|
+
const denies = policies.filter((policy) => policy.kind === "deny").map((policy) => this.compilePolicyCondition(model, model, operation, policy));
|
|
1040
|
+
let combinedPolicy;
|
|
1041
|
+
if (allows.length === 0) combinedPolicy = trueNode(this.dialect);
|
|
1042
|
+
else combinedPolicy = disjunction(this.dialect, allows);
|
|
1043
|
+
if (denies.length !== 0) {
|
|
1044
|
+
const combinedDenies = conjunction(this.dialect, denies.map((d) => buildIsFalse(d, this.dialect)));
|
|
1045
|
+
combinedPolicy = conjunction(this.dialect, [combinedPolicy, combinedDenies]);
|
|
1046
|
+
}
|
|
1047
|
+
return combinedPolicy;
|
|
1048
|
+
}
|
|
1049
|
+
onlyReturningId(node) {
|
|
1050
|
+
if (!node.returning) return true;
|
|
1051
|
+
const { mutationModel } = this.getMutationModel(node);
|
|
1052
|
+
const idFields = QueryUtils.requireIdFields(this.client.$schema, mutationModel);
|
|
1053
|
+
if (node.returning.selections.some((s) => SelectAllNode.is(s.selection))) {
|
|
1054
|
+
const modelDef = QueryUtils.requireModel(this.client.$schema, mutationModel);
|
|
1055
|
+
if (Object.keys(modelDef.fields).some((f) => !idFields.includes(f))) return false;
|
|
1056
|
+
else return true;
|
|
1057
|
+
}
|
|
1058
|
+
return new ColumnCollector().collect(node.returning).every((c) => idFields.includes(c));
|
|
1059
|
+
}
|
|
1060
|
+
async enforcePreCreatePolicy(node, mutationModel, isManyToManyJoinTable, proceed) {
|
|
1061
|
+
const fields = node.columns?.map((c) => c.column.name) ?? [];
|
|
1062
|
+
const valueRows = node.values ? this.unwrapCreateValueRows(node.values, mutationModel, fields, isManyToManyJoinTable) : [[]];
|
|
1063
|
+
for (const values of valueRows) if (isManyToManyJoinTable) await this.enforcePreCreatePolicyForManyToManyJoinTable(mutationModel, fields, values.map((v) => v.node), proceed);
|
|
1064
|
+
else await this.enforcePreCreatePolicyForOne(mutationModel, fields, values.map((v) => v.node), proceed);
|
|
1065
|
+
}
|
|
1066
|
+
async enforcePreCreatePolicyForManyToManyJoinTable(tableName, fields, values, proceed) {
|
|
1067
|
+
const m2m = this.resolveManyToManyJoinTable(tableName);
|
|
1068
|
+
invariant(m2m);
|
|
1069
|
+
invariant(fields.includes("A") && fields.includes("B"), "many-to-many join table must have A and B fk fields");
|
|
1070
|
+
const aNode = values[fields.indexOf("A")];
|
|
1071
|
+
const bNode = values[fields.indexOf("B")];
|
|
1072
|
+
invariant(ValueNode.is(aNode) && ValueNode.is(bNode), "A and B values must be ValueNode");
|
|
1073
|
+
const aValue = aNode.value;
|
|
1074
|
+
const bValue = bNode.value;
|
|
1075
|
+
invariant(aValue !== null && aValue !== void 0, "A value cannot be null or undefined");
|
|
1076
|
+
invariant(bValue !== null && bValue !== void 0, "B value cannot be null or undefined");
|
|
1077
|
+
const eb = expressionBuilder();
|
|
1078
|
+
const filterA = this.buildPolicyFilter(m2m.firstModel, void 0, "update");
|
|
1079
|
+
const queryA = eb.selectFrom(m2m.firstModel).where(eb(eb.ref(`${m2m.firstModel}.${m2m.firstIdField}`), "=", aValue)).select(() => new ExpressionWrapper(filterA).as("_"));
|
|
1080
|
+
const filterB = this.buildPolicyFilter(m2m.secondModel, void 0, "update");
|
|
1081
|
+
const queryB = eb.selectFrom(m2m.secondModel).where(eb(eb.ref(`${m2m.secondModel}.${m2m.secondIdField}`), "=", bValue)).select(() => new ExpressionWrapper(filterB).as("_"));
|
|
1082
|
+
const result = await proceed({
|
|
1083
|
+
kind: "SelectQueryNode",
|
|
1084
|
+
selections: [SelectionNode.create(AliasNode.create(queryA.toOperationNode(), IdentifierNode.create("$conditionA"))), SelectionNode.create(AliasNode.create(queryB.toOperationNode(), IdentifierNode.create("$conditionB")))]
|
|
1085
|
+
});
|
|
1086
|
+
if (!result.rows[0]?.$conditionA) throw createRejectedByPolicyError(m2m.firstModel, RejectedByPolicyReason.CANNOT_READ_BACK, `many-to-many relation participant model "${m2m.firstModel}" not updatable`);
|
|
1087
|
+
if (!result.rows[0]?.$conditionB) throw createRejectedByPolicyError(m2m.secondModel, RejectedByPolicyReason.NO_ACCESS, `many-to-many relation participant model "${m2m.secondModel}" not updatable`);
|
|
1088
|
+
}
|
|
1089
|
+
async enforcePreCreatePolicyForOne(model, fields, values, proceed) {
|
|
1090
|
+
const allFields = QueryUtils.getModelFields(this.client.$schema, model, { inherited: true });
|
|
1091
|
+
const allValues = [];
|
|
1092
|
+
for (const def of allFields) {
|
|
1093
|
+
const index = fields.indexOf(def.name);
|
|
1094
|
+
if (index >= 0) allValues.push(new ExpressionWrapper(values[index]));
|
|
1095
|
+
else allValues.push(this.eb.lit(null));
|
|
1096
|
+
}
|
|
1097
|
+
const valuesTable = this.dialect.buildValuesTableSelect(allFields, [allValues]);
|
|
1098
|
+
const filter = this.buildPolicyFilter(model, void 0, "create");
|
|
1099
|
+
if (!(await proceed(this.eb.selectFrom(valuesTable.as(model)).select(this.eb(this.eb.fn.count(this.eb.lit(1)), ">", 0).as("$condition")).where(() => new ExpressionWrapper(filter)).toOperationNode())).rows[0]?.$condition) throw createRejectedByPolicyError(model, RejectedByPolicyReason.NO_ACCESS);
|
|
1100
|
+
}
|
|
1101
|
+
unwrapCreateValueRows(node, model, fields, isManyToManyJoinTable) {
|
|
1102
|
+
if (ValuesNode.is(node)) return node.values.map((v) => this.unwrapCreateValueRow(v.values, model, fields, isManyToManyJoinTable));
|
|
1103
|
+
else if (PrimitiveValueListNode.is(node)) return [this.unwrapCreateValueRow(node.values, model, fields, isManyToManyJoinTable)];
|
|
1104
|
+
else invariant(false, `Unexpected node kind: ${node.kind} for unwrapping create values`);
|
|
1105
|
+
}
|
|
1106
|
+
unwrapCreateValueRow(data, model, fields, isImplicitManyToManyJoinTable) {
|
|
1107
|
+
invariant(data.length === fields.length, "data length must match fields length");
|
|
1108
|
+
const result = [];
|
|
1109
|
+
for (let i = 0; i < data.length; i++) {
|
|
1110
|
+
const item = data[i];
|
|
1111
|
+
if (typeof item === "object" && item && "kind" in item) {
|
|
1112
|
+
if (item.kind === "DefaultInsertValueNode") {
|
|
1113
|
+
result.push({
|
|
1114
|
+
node: ValueNode.create(null),
|
|
1115
|
+
raw: null
|
|
1116
|
+
});
|
|
1117
|
+
continue;
|
|
1118
|
+
}
|
|
1119
|
+
const fieldDef = QueryUtils.requireField(this.client.$schema, model, fields[i]);
|
|
1120
|
+
invariant(item.kind === "ValueNode", "expecting a ValueNode");
|
|
1121
|
+
result.push({
|
|
1122
|
+
node: ValueNode.create(this.dialect.transformInput(item.value, fieldDef.type, !!fieldDef.array)),
|
|
1123
|
+
raw: item.value
|
|
1124
|
+
});
|
|
1125
|
+
} else {
|
|
1126
|
+
let value = item;
|
|
1127
|
+
if (!isImplicitManyToManyJoinTable) {
|
|
1128
|
+
const fieldDef = QueryUtils.requireField(this.client.$schema, model, fields[i]);
|
|
1129
|
+
value = this.dialect.transformInput(item, fieldDef.type, !!fieldDef.array);
|
|
1130
|
+
}
|
|
1131
|
+
if (Array.isArray(value)) {
|
|
1132
|
+
const fieldDef = QueryUtils.requireField(this.client.$schema, model, fields[i]);
|
|
1133
|
+
result.push({
|
|
1134
|
+
node: this.dialect.buildArrayValue(value, fieldDef.type).toOperationNode(),
|
|
1135
|
+
raw: value
|
|
1136
|
+
});
|
|
1137
|
+
} else result.push({
|
|
1138
|
+
node: ValueNode.create(value),
|
|
1139
|
+
raw: value
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
return result;
|
|
1144
|
+
}
|
|
1145
|
+
tryGetConstantPolicy(model, operation) {
|
|
1146
|
+
const policies = this.getModelPolicies(model, operation);
|
|
1147
|
+
if (!policies.some((p) => p.kind === "allow")) return false;
|
|
1148
|
+
else if (policies.some((p) => p.kind === "deny" && this.isTrueExpr(p.condition))) return false;
|
|
1149
|
+
else if (!policies.some((p) => p.kind === "deny") && policies.some((p) => p.kind === "allow" && this.isTrueExpr(p.condition))) return true;
|
|
1150
|
+
else return;
|
|
1151
|
+
}
|
|
1152
|
+
isTrueExpr(expr) {
|
|
1153
|
+
return ExpressionUtils.isLiteral(expr) && expr.value === true;
|
|
1154
|
+
}
|
|
1155
|
+
async processReadBack(node, result, proceed) {
|
|
1156
|
+
if (result.rows.length === 0) return result;
|
|
1157
|
+
if (!this.isMutationQueryNode(node) || !node.returning) return result;
|
|
1158
|
+
const { mutationModel } = this.getMutationModel(node);
|
|
1159
|
+
const idConditions = this.buildIdConditions(mutationModel, result.rows);
|
|
1160
|
+
const policyFilter = this.buildPolicyFilter(mutationModel, void 0, "read");
|
|
1161
|
+
return await proceed({
|
|
1162
|
+
kind: "SelectQueryNode",
|
|
1163
|
+
from: FromNode.create([TableNode.create(mutationModel)]),
|
|
1164
|
+
where: WhereNode.create(conjunction(this.dialect, [idConditions, policyFilter])),
|
|
1165
|
+
selections: node.returning.selections
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
buildIdConditions(table, rows) {
|
|
1169
|
+
const idFields = QueryUtils.requireIdFields(this.client.$schema, table);
|
|
1170
|
+
return disjunction(this.dialect, rows.map((row) => conjunction(this.dialect, idFields.map((field) => BinaryOperationNode.create(ReferenceNode.create(ColumnNode.create(field), TableNode.create(table)), OperatorNode.create("="), ValueNode.create(row[field]))))));
|
|
1171
|
+
}
|
|
1172
|
+
getMutationModel(node) {
|
|
1173
|
+
const r = match(node).when(InsertQueryNode.is, (node) => ({
|
|
1174
|
+
mutationModel: getTableName(node.into),
|
|
1175
|
+
alias: void 0
|
|
1176
|
+
})).when(UpdateQueryNode.is, (node) => {
|
|
1177
|
+
if (!node.table) invariant(false, "Update query must have a table");
|
|
1178
|
+
const r = this.extractTableName(node.table);
|
|
1179
|
+
return r ? {
|
|
1180
|
+
mutationModel: r.model,
|
|
1181
|
+
alias: r.alias
|
|
1182
|
+
} : void 0;
|
|
1183
|
+
}).when(DeleteQueryNode.is, (node) => {
|
|
1184
|
+
if (node.from.froms.length !== 1) throw createUnsupportedError("Only one from table is supported for delete");
|
|
1185
|
+
const r = this.extractTableName(node.from.froms[0]);
|
|
1186
|
+
return r ? {
|
|
1187
|
+
mutationModel: r.model,
|
|
1188
|
+
alias: r.alias
|
|
1189
|
+
} : void 0;
|
|
1190
|
+
}).exhaustive();
|
|
1191
|
+
if (!r) invariant(false, `Unable to get table name for query node: ${node}`);
|
|
1192
|
+
return r;
|
|
1193
|
+
}
|
|
1194
|
+
isCrudQueryNode(node) {
|
|
1195
|
+
return SelectQueryNode.is(node) || InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node);
|
|
1196
|
+
}
|
|
1197
|
+
isMutationQueryNode(node) {
|
|
1198
|
+
return InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node);
|
|
1199
|
+
}
|
|
1200
|
+
buildPolicyFilter(model, alias, operation) {
|
|
1201
|
+
const m2mFilter = this.getModelPolicyFilterForManyToManyJoinTable(model, alias, operation);
|
|
1202
|
+
if (m2mFilter) return m2mFilter;
|
|
1203
|
+
const policies = this.getModelPolicies(model, operation);
|
|
1204
|
+
const allows = policies.filter((policy) => policy.kind === "allow").map((policy) => this.compilePolicyCondition(model, alias, operation, policy));
|
|
1205
|
+
const denies = policies.filter((policy) => policy.kind === "deny").map((policy) => this.compilePolicyCondition(model, alias, operation, policy));
|
|
1206
|
+
let combinedPolicy;
|
|
1207
|
+
if (allows.length === 0) if (operation === "post-update") combinedPolicy = trueNode(this.dialect);
|
|
1208
|
+
else combinedPolicy = falseNode(this.dialect);
|
|
1209
|
+
else combinedPolicy = disjunction(this.dialect, allows);
|
|
1210
|
+
if (denies.length !== 0) {
|
|
1211
|
+
const combinedDenies = conjunction(this.dialect, denies.map((d) => buildIsFalse(d, this.dialect)));
|
|
1212
|
+
combinedPolicy = conjunction(this.dialect, [combinedPolicy, combinedDenies]);
|
|
1213
|
+
}
|
|
1214
|
+
return combinedPolicy;
|
|
1215
|
+
}
|
|
1216
|
+
extractTableName(node) {
|
|
1217
|
+
if (TableNode.is(node)) return { model: node.table.identifier.name };
|
|
1218
|
+
if (AliasNode.is(node)) {
|
|
1219
|
+
const inner = this.extractTableName(node.node);
|
|
1220
|
+
if (!inner) return;
|
|
1221
|
+
return {
|
|
1222
|
+
model: inner.model,
|
|
1223
|
+
alias: IdentifierNode.is(node.alias) ? node.alias.name : void 0
|
|
1224
|
+
};
|
|
1225
|
+
} else return;
|
|
1226
|
+
}
|
|
1227
|
+
createPolicyFilterForFrom(node) {
|
|
1228
|
+
if (!node) return;
|
|
1229
|
+
return this.createPolicyFilterForTables(node.froms);
|
|
1230
|
+
}
|
|
1231
|
+
createPolicyFilterForTables(tables) {
|
|
1232
|
+
return tables.reduce((acc, table) => {
|
|
1233
|
+
const extractResult = this.extractTableName(table);
|
|
1234
|
+
if (extractResult) {
|
|
1235
|
+
const { model, alias } = extractResult;
|
|
1236
|
+
const filter = this.buildPolicyFilter(model, alias, "read");
|
|
1237
|
+
return acc ? conjunction(this.dialect, [acc, filter]) : filter;
|
|
1238
|
+
}
|
|
1239
|
+
return acc;
|
|
1240
|
+
}, void 0);
|
|
1241
|
+
}
|
|
1242
|
+
compilePolicyCondition(model, alias, operation, policy) {
|
|
1243
|
+
return new ExpressionTransformer(this.client).transform(policy.condition, {
|
|
1244
|
+
modelOrType: model,
|
|
1245
|
+
thisType: model,
|
|
1246
|
+
thisAlias: alias,
|
|
1247
|
+
alias,
|
|
1248
|
+
operation
|
|
1249
|
+
});
|
|
1250
|
+
}
|
|
1251
|
+
getModelPolicies(model, operation) {
|
|
1252
|
+
const modelDef = QueryUtils.requireModel(this.client.$schema, model);
|
|
1253
|
+
const result = [];
|
|
1254
|
+
const extractOperations = (expr) => {
|
|
1255
|
+
invariant(ExpressionUtils.isLiteral(expr), "expecting a literal");
|
|
1256
|
+
invariant(typeof expr.value === "string", "expecting a string literal");
|
|
1257
|
+
return expr.value.split(",").filter((v) => !!v).map((v) => v.trim());
|
|
1258
|
+
};
|
|
1259
|
+
if (modelDef.attributes) result.push(...modelDef.attributes.filter((attr) => attr.name === "@@allow" || attr.name === "@@deny").map((attr) => ({
|
|
1260
|
+
kind: attr.name === "@@allow" ? "allow" : "deny",
|
|
1261
|
+
operations: extractOperations(attr.args[0].value),
|
|
1262
|
+
condition: attr.args[1].value
|
|
1263
|
+
})).filter((policy) => operation !== "post-update" && policy.operations.includes("all") || policy.operations.includes(operation)));
|
|
1264
|
+
return result;
|
|
1265
|
+
}
|
|
1266
|
+
getFieldPolicies(model, field, operation) {
|
|
1267
|
+
const fieldDef = QueryUtils.requireField(this.client.$schema, model, field);
|
|
1268
|
+
const result = [];
|
|
1269
|
+
const extractOperations = (expr) => {
|
|
1270
|
+
invariant(ExpressionUtils.isLiteral(expr), "expecting a literal");
|
|
1271
|
+
invariant(typeof expr.value === "string", "expecting a string literal");
|
|
1272
|
+
return expr.value.split(",").filter((v) => !!v).map((v) => v.trim());
|
|
1273
|
+
};
|
|
1274
|
+
if (fieldDef.attributes) result.push(...fieldDef.attributes.filter((attr) => attr.name === "@allow" || attr.name === "@deny").map((attr) => ({
|
|
1275
|
+
kind: attr.name === "@allow" ? "allow" : "deny",
|
|
1276
|
+
operations: extractOperations(attr.args[0].value),
|
|
1277
|
+
condition: attr.args[1].value
|
|
1278
|
+
})).filter((policy) => policy.operations.includes("all") || policy.operations.includes(operation)));
|
|
1279
|
+
return result;
|
|
1280
|
+
}
|
|
1281
|
+
resolveManyToManyJoinTable(tableName) {
|
|
1282
|
+
for (const model of Object.values(this.client.$schema.models)) for (const field of Object.values(model.fields)) {
|
|
1283
|
+
const m2m = QueryUtils.getManyToManyRelation(this.client.$schema, model.name, field.name);
|
|
1284
|
+
if (m2m?.joinTable === tableName) {
|
|
1285
|
+
const sortedRecord = [{
|
|
1286
|
+
model: model.name,
|
|
1287
|
+
field: field.name
|
|
1288
|
+
}, {
|
|
1289
|
+
model: m2m.otherModel,
|
|
1290
|
+
field: m2m.otherField
|
|
1291
|
+
}].sort(this.manyToManySorter);
|
|
1292
|
+
const firstIdFields = QueryUtils.requireIdFields(this.client.$schema, sortedRecord[0].model);
|
|
1293
|
+
const secondIdFields = QueryUtils.requireIdFields(this.client.$schema, sortedRecord[1].model);
|
|
1294
|
+
invariant(firstIdFields.length === 1 && secondIdFields.length === 1, "only single-field id is supported for implicit many-to-many join table");
|
|
1295
|
+
return {
|
|
1296
|
+
firstModel: sortedRecord[0].model,
|
|
1297
|
+
firstField: sortedRecord[0].field,
|
|
1298
|
+
firstIdField: firstIdFields[0],
|
|
1299
|
+
secondModel: sortedRecord[1].model,
|
|
1300
|
+
secondField: sortedRecord[1].field,
|
|
1301
|
+
secondIdField: secondIdFields[0]
|
|
1302
|
+
};
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
manyToManySorter(a, b) {
|
|
1307
|
+
return a.model !== b.model ? a.model.localeCompare(b.model) : a.field.localeCompare(b.field);
|
|
1308
|
+
}
|
|
1309
|
+
isManyToManyJoinTable(tableName) {
|
|
1310
|
+
return !!this.resolveManyToManyJoinTable(tableName);
|
|
1311
|
+
}
|
|
1312
|
+
getModelPolicyFilterForManyToManyJoinTable(tableName, alias, operation) {
|
|
1313
|
+
const m2m = this.resolveManyToManyJoinTable(tableName);
|
|
1314
|
+
if (!m2m) return;
|
|
1315
|
+
const checkForOperation = operation === "read" ? "read" : "update";
|
|
1316
|
+
const joinTable = alias ?? tableName;
|
|
1317
|
+
const aQuery = this.eb.selectFrom(m2m.firstModel).whereRef(`${m2m.firstModel}.${m2m.firstIdField}`, "=", `${joinTable}.A`).select(() => new ExpressionWrapper(this.buildPolicyFilter(m2m.firstModel, void 0, checkForOperation)).as("$conditionA"));
|
|
1318
|
+
const bQuery = this.eb.selectFrom(m2m.secondModel).whereRef(`${m2m.secondModel}.${m2m.secondIdField}`, "=", `${joinTable}.B`).select(() => new ExpressionWrapper(this.buildPolicyFilter(m2m.secondModel, void 0, checkForOperation)).as("$conditionB"));
|
|
1319
|
+
return this.eb.and([aQuery, bQuery]).toOperationNode();
|
|
1320
|
+
}
|
|
1321
|
+
tryRejectNonexistentModel(model) {
|
|
1322
|
+
if (!QueryUtils.hasModel(this.client.$schema, model) && !this.isManyToManyJoinTable(model)) throw createRejectedByPolicyError(model, RejectedByPolicyReason.NO_ACCESS);
|
|
1323
|
+
}
|
|
1324
|
+
tryRejectNonexistingTables(tables) {
|
|
1325
|
+
for (const table of tables) {
|
|
1326
|
+
const extractResult = this.extractTableName(table);
|
|
1327
|
+
if (extractResult) this.tryRejectNonexistentModel(extractResult.model);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
postProcessMutationResult(result, node) {
|
|
1331
|
+
if (node.returning) return result;
|
|
1332
|
+
else return {
|
|
1333
|
+
...result,
|
|
1334
|
+
rows: [],
|
|
1335
|
+
numAffectedRows: result.numAffectedRows ?? BigInt(result.rows.length)
|
|
1336
|
+
};
|
|
1337
|
+
}
|
|
1338
|
+
stripTableReferences(node, modelName) {
|
|
1339
|
+
return new TableReferenceStripper().strip(node, modelName);
|
|
1340
|
+
}
|
|
1341
|
+
};
|
|
1342
|
+
var TableReferenceStripper = class extends OperationNodeTransformer {
|
|
1343
|
+
tableName = "";
|
|
1344
|
+
strip(node, tableName) {
|
|
1345
|
+
this.tableName = tableName;
|
|
1346
|
+
return this.transformNode(node);
|
|
1347
|
+
}
|
|
1348
|
+
transformReference(node) {
|
|
1349
|
+
if (ColumnNode.is(node.column) && node.table?.table.identifier.name === this.tableName) return ReferenceNode.create(this.transformNode(node.column));
|
|
1350
|
+
return super.transformReference(node);
|
|
1351
|
+
}
|
|
1352
|
+
};
|
|
1353
|
+
//#endregion
|
|
1354
|
+
//#region src/functions.ts
|
|
1355
|
+
/**
|
|
1356
|
+
* Relation checker implementation.
|
|
1357
|
+
*/
|
|
1358
|
+
const check = (eb, args, { client, model, modelAlias, operation }) => {
|
|
1359
|
+
invariant(args.length === 1 || args.length === 2, "\"check\" function requires 1 or 2 arguments");
|
|
1360
|
+
const arg1Node = args[0].toOperationNode();
|
|
1361
|
+
const arg2Node = args.length === 2 ? args[1].toOperationNode() : void 0;
|
|
1362
|
+
if (arg2Node) {
|
|
1363
|
+
invariant(ValueNode.is(arg2Node) && typeof arg2Node.value === "string", "\"operation\" parameter must be a string literal when provided");
|
|
1364
|
+
invariant(CRUD.includes(arg2Node.value), "\"operation\" parameter must be one of \"create\", \"read\", \"update\", \"delete\"");
|
|
1365
|
+
}
|
|
1366
|
+
const fieldName = QueryUtils.extractFieldName(arg1Node);
|
|
1367
|
+
invariant(fieldName, "Failed to extract field name from the first argument of \"check\" function");
|
|
1368
|
+
const fieldDef = QueryUtils.requireField(client.$schema, model, fieldName);
|
|
1369
|
+
invariant(fieldDef.relation, `Field "${fieldName}" is not a relation field in model "${model}"`);
|
|
1370
|
+
invariant(!fieldDef.array, `Field "${fieldName}" is a to-many relation, which is not supported by "check"`);
|
|
1371
|
+
const relationModel = fieldDef.type;
|
|
1372
|
+
const joinConditions = [];
|
|
1373
|
+
const fkInfo = QueryUtils.getRelationForeignKeyFieldPairs(client.$schema, model, fieldName);
|
|
1374
|
+
const idFields = QueryUtils.requireIdFields(client.$schema, model);
|
|
1375
|
+
const buildBaseSelect = (baseModel, field) => {
|
|
1376
|
+
return eb.selectFrom(baseModel).select(field).where(eb.and(idFields.map((idField) => eb(eb.ref(`${fieldDef.originModel}.${idField}`), "=", eb.ref(`${modelAlias}.${idField}`)))));
|
|
1377
|
+
};
|
|
1378
|
+
if (fkInfo.ownedByModel) joinConditions.push(...fkInfo.keyPairs.map(({ fk, pk }) => {
|
|
1379
|
+
let fkRef;
|
|
1380
|
+
if (fieldDef.originModel && fieldDef.originModel !== model) fkRef = buildBaseSelect(fieldDef.originModel, fk);
|
|
1381
|
+
else fkRef = eb.ref(`${modelAlias}.${fk}`);
|
|
1382
|
+
return eb(fkRef, "=", eb.ref(`${relationModel}.${pk}`));
|
|
1383
|
+
}));
|
|
1384
|
+
else joinConditions.push(...fkInfo.keyPairs.map(({ fk, pk }) => {
|
|
1385
|
+
let pkRef;
|
|
1386
|
+
if (fieldDef.originModel && fieldDef.originModel !== model) pkRef = buildBaseSelect(fieldDef.originModel, pk);
|
|
1387
|
+
else pkRef = eb.ref(`${modelAlias}.${pk}`);
|
|
1388
|
+
return eb(pkRef, "=", eb.ref(`${relationModel}.${fk}`));
|
|
1389
|
+
}));
|
|
1390
|
+
const joinCondition = joinConditions.length === 1 ? joinConditions[0] : eb.and(joinConditions);
|
|
1391
|
+
const policyHandler = new PolicyHandler(client);
|
|
1392
|
+
const op = arg2Node ? arg2Node.value : operation;
|
|
1393
|
+
const policyCondition = policyHandler.buildPolicyFilter(relationModel, void 0, op);
|
|
1394
|
+
return eb.selectFrom(eb.selectFrom(relationModel).where(joinCondition).select(new ExpressionWrapper(policyCondition).as("$condition")).as("$sub")).selectAll();
|
|
1395
|
+
};
|
|
1396
|
+
//#endregion
|
|
1397
|
+
//#region src/plugin.ts
|
|
1398
|
+
var PolicyPlugin = class {
|
|
1399
|
+
constructor(options = {}) {
|
|
1400
|
+
this.options = options;
|
|
1401
|
+
}
|
|
1402
|
+
get id() {
|
|
1403
|
+
return "policy";
|
|
1404
|
+
}
|
|
1405
|
+
get name() {
|
|
1406
|
+
return "Access Policy";
|
|
1407
|
+
}
|
|
1408
|
+
get description() {
|
|
1409
|
+
return "Enforces access policies defined in the schema.";
|
|
1410
|
+
}
|
|
1411
|
+
get functions() {
|
|
1412
|
+
return { check };
|
|
1413
|
+
}
|
|
1414
|
+
onKyselyQuery({ query, client, proceed }) {
|
|
1415
|
+
return new PolicyHandler(client, this.options).handle(query, proceed);
|
|
1416
|
+
}
|
|
1417
|
+
};
|
|
1418
|
+
//#endregion
|
|
1419
|
+
export { PolicyPlugin };
|
|
1420
|
+
|
|
1421
|
+
//# sourceMappingURL=index.mjs.map
|