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