@rebasepro/common 0.23.0 → 0.24.1-canary.g56af4a4

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.
Files changed (141) hide show
  1. package/dist/collections/CollectionRegistry.d.ts +72 -3
  2. package/dist/collections/CollectionRegistry.es.js +404 -0
  3. package/dist/collections/CollectionRegistry.es.js.map +1 -0
  4. package/dist/collections/auth-secrets.es.js +47 -0
  5. package/dist/collections/auth-secrets.es.js.map +1 -0
  6. package/dist/collections/default-collections.es.js +120 -0
  7. package/dist/collections/default-collections.es.js.map +1 -0
  8. package/dist/collections/engine-support.es.js +35 -0
  9. package/dist/collections/engine-support.es.js.map +1 -0
  10. package/dist/collections/field-access.d.ts +13 -0
  11. package/dist/collections/field-access.es.js +142 -0
  12. package/dist/collections/field-access.es.js.map +1 -0
  13. package/dist/collections/index.d.ts +1 -0
  14. package/dist/collections/soft-delete.es.js +34 -0
  15. package/dist/collections/soft-delete.es.js.map +1 -0
  16. package/dist/collections/unknown-field.d.ts +65 -0
  17. package/dist/collections/unknown-field.es.js +135 -0
  18. package/dist/collections/unknown-field.es.js.map +1 -0
  19. package/dist/data/buildRebaseData.d.ts +27 -2
  20. package/dist/data/buildRebaseData.es.js +1026 -0
  21. package/dist/data/buildRebaseData.es.js.map +1 -0
  22. package/dist/data/buildRoutedRebaseData.d.ts +6 -1
  23. package/dist/data/buildRoutedRebaseData.es.js +47 -0
  24. package/dist/data/buildRoutedRebaseData.es.js.map +1 -0
  25. package/dist/data/collection-accessor.d.ts +54 -0
  26. package/dist/data/collection-accessor.es.js +101 -0
  27. package/dist/data/collection-accessor.es.js.map +1 -0
  28. package/dist/data/cursor.d.ts +1 -1
  29. package/dist/data/cursor.es.js +166 -0
  30. package/dist/data/cursor.es.js.map +1 -0
  31. package/dist/data/filter-conditions.es.js +24 -0
  32. package/dist/data/filter-conditions.es.js.map +1 -0
  33. package/dist/data/filter-dialect.d.ts +3 -3
  34. package/dist/data/filter-dialect.es.js +786 -0
  35. package/dist/data/filter-dialect.es.js.map +1 -0
  36. package/dist/data/include-spec.d.ts +2 -0
  37. package/dist/data/include-spec.es.js +273 -0
  38. package/dist/data/include-spec.es.js.map +1 -0
  39. package/dist/data/paginate.d.ts +8 -1
  40. package/dist/data/paginate.es.js +181 -0
  41. package/dist/data/paginate.es.js.map +1 -0
  42. package/dist/data/query_builder.d.ts +52 -4
  43. package/dist/data/query_builder.es.js +151 -0
  44. package/dist/data/query_builder.es.js.map +1 -0
  45. package/dist/data/resolveDataSource.es.js +87 -0
  46. package/dist/data/resolveDataSource.es.js.map +1 -0
  47. package/dist/data/row-etag.d.ts +46 -0
  48. package/dist/data/row-etag.es.js +64 -0
  49. package/dist/data/row-etag.es.js.map +1 -0
  50. package/dist/data/sort-dialect.es.js +236 -0
  51. package/dist/data/sort-dialect.es.js.map +1 -0
  52. package/dist/index.d.ts +2 -0
  53. package/dist/index.es.js +56 -7235
  54. package/dist/table-classification.es.js +107 -0
  55. package/dist/table-classification.es.js.map +1 -0
  56. package/dist/util/auth-default-policies.es.js +184 -0
  57. package/dist/util/auth-default-policies.es.js.map +1 -0
  58. package/dist/util/builders.es.js +15 -0
  59. package/dist/util/builders.es.js.map +1 -0
  60. package/dist/util/callback-errors.es.js +164 -0
  61. package/dist/util/callback-errors.es.js.map +1 -0
  62. package/dist/util/callbacks.es.js +72 -0
  63. package/dist/util/callbacks.es.js.map +1 -0
  64. package/dist/util/collections.es.js +79 -0
  65. package/dist/util/collections.es.js.map +1 -0
  66. package/dist/util/common.es.js +7 -0
  67. package/dist/util/common.es.js.map +1 -0
  68. package/dist/util/conditions.es.js +100 -0
  69. package/dist/util/conditions.es.js.map +1 -0
  70. package/dist/util/copy.d.ts +33 -0
  71. package/dist/util/copy.es.js +74 -0
  72. package/dist/util/copy.es.js.map +1 -0
  73. package/dist/util/download-url-cache.d.ts +122 -0
  74. package/dist/util/download-url-cache.es.js +187 -0
  75. package/dist/util/download-url-cache.es.js.map +1 -0
  76. package/dist/util/email.es.js +36 -0
  77. package/dist/util/email.es.js.map +1 -0
  78. package/dist/util/entities.d.ts +27 -2
  79. package/dist/util/entities.es.js +328 -0
  80. package/dist/util/entities.es.js.map +1 -0
  81. package/dist/util/enums.d.ts +10 -1
  82. package/dist/util/enums.es.js +37 -0
  83. package/dist/util/enums.es.js.map +1 -0
  84. package/dist/util/identity.es.js +138 -0
  85. package/dist/util/identity.es.js.map +1 -0
  86. package/dist/util/index.d.ts +6 -0
  87. package/dist/util/internal-tables.d.ts +10 -0
  88. package/dist/util/internal-tables.es.js +202 -0
  89. package/dist/util/internal-tables.es.js.map +1 -0
  90. package/dist/util/junction-policies.es.js +273 -0
  91. package/dist/util/junction-policies.es.js.map +1 -0
  92. package/dist/util/paths.es.js +26 -0
  93. package/dist/util/paths.es.js.map +1 -0
  94. package/dist/util/permissions.es.js +108 -0
  95. package/dist/util/permissions.es.js.map +1 -0
  96. package/dist/util/pg-column-to-property.es.js +303 -0
  97. package/dist/util/pg-column-to-property.es.js.map +1 -0
  98. package/dist/util/policy/compileRulePolicies.d.ts +32 -0
  99. package/dist/util/policy/compileRulePolicies.es.js +43 -0
  100. package/dist/util/policy/compileRulePolicies.es.js.map +1 -0
  101. package/dist/util/policy/evaluatePolicy.es.js +104 -0
  102. package/dist/util/policy/evaluatePolicy.es.js.map +1 -0
  103. package/dist/util/policy/index.d.ts +1 -0
  104. package/dist/util/policy/policyToPostgres.d.ts +24 -0
  105. package/dist/util/policy/policyToPostgres.es.js +593 -0
  106. package/dist/util/policy/policyToPostgres.es.js.map +1 -0
  107. package/dist/util/policy/policyToSecurityRule.es.js +79 -0
  108. package/dist/util/policy/policyToSecurityRule.es.js.map +1 -0
  109. package/dist/util/policy/securityRuleToConditions.es.js +48 -0
  110. package/dist/util/policy/securityRuleToConditions.es.js.map +1 -0
  111. package/dist/util/policy/sqlToPolicy.es.js +326 -0
  112. package/dist/util/policy/sqlToPolicy.es.js.map +1 -0
  113. package/dist/util/relations.es.js +243 -0
  114. package/dist/util/relations.es.js.map +1 -0
  115. package/dist/util/resolutions.es.js +318 -0
  116. package/dist/util/resolutions.es.js.map +1 -0
  117. package/dist/util/resolve-relation.es.js +163 -0
  118. package/dist/util/resolve-relation.es.js.map +1 -0
  119. package/dist/util/resumable-upload-threshold.d.ts +15 -0
  120. package/dist/util/resumable-upload-threshold.es.js +20 -0
  121. package/dist/util/resumable-upload-threshold.es.js.map +1 -0
  122. package/dist/util/resumable-upload.d.ts +51 -0
  123. package/dist/util/resumable-upload.es.js +121 -0
  124. package/dist/util/resumable-upload.es.js.map +1 -0
  125. package/dist/util/sql-redaction.d.ts +21 -0
  126. package/dist/util/sql-redaction.es.js +107 -0
  127. package/dist/util/sql-redaction.es.js.map +1 -0
  128. package/dist/util/sql-rows.es.js +41 -0
  129. package/dist/util/sql-rows.es.js.map +1 -0
  130. package/dist/util/storage.d.ts +26 -4
  131. package/dist/util/storage.es.js +117 -0
  132. package/dist/util/storage.es.js.map +1 -0
  133. package/dist/util/string-column-length.es.js +31 -0
  134. package/dist/util/string-column-length.es.js.map +1 -0
  135. package/dist/util/tenant.es.js +201 -0
  136. package/dist/util/tenant.es.js.map +1 -0
  137. package/dist/util/untrusted-envelope.d.ts +25 -0
  138. package/dist/util/untrusted-envelope.es.js +40 -0
  139. package/dist/util/untrusted-envelope.es.js.map +1 -0
  140. package/package.json +5 -3
  141. package/dist/index.es.js.map +0 -1
@@ -0,0 +1,273 @@
1
+ import { resolveCollectionRelations } from "./relations.es.js";
2
+ import { securityRuleToConditions } from "./policy/securityRuleToConditions.es.js";
3
+ import { JUNCTION_PIVOT_KEY, isManyToMany, isPostgresCollectionConfig, policy } from "@rebasepro/types";
4
+ import { getPolicyOperations } from "@rebasepro/utils";
5
+ //#region src/util/junction-policies.ts
6
+ var SERVER_OR_ADMIN_EXPR = policy.or(policy.serverContext(), policy.rolesOverlap(["admin"]));
7
+ /**
8
+ * Walk every collection's resolved relations and aggregate the junction tables
9
+ * they declare. Two collections may declare the same junction from opposite
10
+ * sides (posts→tags and tags→posts through `posts_tags`); both become
11
+ * `declaringSides` of one spec, so derived write grants consider both.
12
+ */
13
+ function resolveJunctionSpecs(collections) {
14
+ const specs = /* @__PURE__ */ new Map();
15
+ for (const collection of collections) {
16
+ const resolved = resolveCollectionRelations(collection);
17
+ for (const relation of Object.values(resolved)) {
18
+ if (!isManyToMany(relation)) continue;
19
+ const targetCollection = relation.target();
20
+ if (!targetCollection) continue;
21
+ const rawName = relation.through.table;
22
+ const table = rawName.includes(".") ? rawName.split(".").pop() : rawName;
23
+ const schema = "public";
24
+ const source = {
25
+ collection,
26
+ junctionColumn: relation.through.sourceColumn,
27
+ relation
28
+ };
29
+ const target = {
30
+ collection: targetCollection,
31
+ junctionColumn: relation.through.targetColumn
32
+ };
33
+ const existing = specs.get(table);
34
+ if (!existing) specs.set(table, {
35
+ table,
36
+ schema,
37
+ endpoints: [source, target],
38
+ declaringSides: [source],
39
+ properties: mergeJunctionPayload({}, relation.through.properties, table, collection)
40
+ });
41
+ else {
42
+ existing.properties = mergeJunctionPayload(existing.properties, relation.through.properties, table, collection);
43
+ if (!existing.declaringSides.some((s) => s.collection === collection)) existing.declaringSides.push(source);
44
+ }
45
+ }
46
+ }
47
+ return specs;
48
+ }
49
+ /**
50
+ * Fold one side's `through.properties` into the junction's, refusing a
51
+ * disagreement rather than picking a winner.
52
+ *
53
+ * Both ends of a link may declare it — `posts.tags` and `tags.posts` are one
54
+ * junction — and each end may name the payload. Only one table gets created, so
55
+ * two descriptions of `role` that are not the same description are a question
56
+ * with no correct answer: whichever won, one of the two collections would be
57
+ * writing through a column it does not think it has. Compared structurally, so
58
+ * two sides that spell the same property twice (the normal case, and the one
59
+ * the docs recommend) are fine.
60
+ */
61
+ function mergeJunctionPayload(into, incoming, table, collection) {
62
+ if (!incoming || Object.keys(incoming).length === 0) return into;
63
+ const merged = { ...into };
64
+ for (const [key, property] of Object.entries(incoming)) {
65
+ const already = merged[key];
66
+ if (already && JSON.stringify(already) !== JSON.stringify(property)) throw new Error(`The junction table "${table}" is declared from more than one side, and they disagree about the payload column "${key}": "${collection.slug ?? collection.name}" describes it differently than another declaring collection does. One table is created, so both \`through.properties\` blocks have to describe the same column — or only one side should declare it.`);
67
+ merged[key] = property;
68
+ }
69
+ return merged;
70
+ }
71
+ /**
72
+ * A synthetic CollectionConfig standing in for the junction during policy
73
+ * compilation and naming. Its two FK columns carry explicit `columnName`s so
74
+ * `outerField` operands resolve to the exact columns the CREATE TABLE emitted,
75
+ * whatever their casing.
76
+ *
77
+ * The payload columns are here too, exactly as authored. That is what lets one
78
+ * reading of a `Property` serve the junction as well as a collection: the
79
+ * schema planner plans these columns with the same function it plans a
80
+ * collection's with, and the write path validates a `_pivot` against them with
81
+ * the same validator a row's values go through. A second description of a
82
+ * payload column anywhere is a second description that can disagree.
83
+ */
84
+ function getJunctionCollectionConfig(spec) {
85
+ return buildJunctionCollectionConfig({
86
+ table: spec.table,
87
+ schema: spec.schema,
88
+ keyColumns: spec.endpoints.map((endpoint) => endpoint.junctionColumn),
89
+ properties: spec.properties
90
+ });
91
+ }
92
+ /**
93
+ * The same synthetic collection, reached from a resolved relation rather than
94
+ * from a spec.
95
+ *
96
+ * The spec is built by walking every collection, which the schema planner does
97
+ * once at boot and no request path can afford. A read or a write already holds
98
+ * the relation, and a relation's `through` carries the table, both key columns
99
+ * and the payload — everything the config is made of. One builder underneath
100
+ * both, so the shape the planner emitted columns from is the shape the write
101
+ * path validates a `_pivot` against and the read path strips it with.
102
+ */
103
+ function getJunctionConfigForRelation(through) {
104
+ return buildJunctionCollectionConfig({
105
+ table: through.table.includes(".") ? through.table.split(".").pop() : through.table,
106
+ schema: "public",
107
+ keyColumns: [through.sourceColumn, through.targetColumn],
108
+ properties: through.properties
109
+ });
110
+ }
111
+ function buildJunctionCollectionConfig(args) {
112
+ const properties = {};
113
+ for (const column of args.keyColumns) properties[column] = {
114
+ type: "string",
115
+ columnName: column
116
+ };
117
+ for (const [key, property] of Object.entries(args.properties)) {
118
+ if (key === JUNCTION_PIVOT_KEY || key in properties) continue;
119
+ properties[key] = property;
120
+ }
121
+ return {
122
+ slug: args.table,
123
+ name: args.table,
124
+ table: args.table,
125
+ schema: args.schema,
126
+ properties
127
+ };
128
+ }
129
+ /** The property marked as the row id (falls back to `id`). */
130
+ function getIdPropertyName(collection) {
131
+ for (const [name, prop] of Object.entries(collection.properties ?? {})) if (prop && typeof prop === "object" && "isId" in prop && prop.isId) return name;
132
+ return "id";
133
+ }
134
+ /** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */
135
+ function existsEndpoint(endpoint, extra) {
136
+ const correlation = policy.compare(policy.field(getIdPropertyName(endpoint.collection)), "eq", policy.outerField(endpoint.junctionColumn));
137
+ return policy.existsIn({
138
+ collection: endpoint.collection.slug,
139
+ where: extra ? policy.and(correlation, extra) : correlation
140
+ });
141
+ }
142
+ /**
143
+ * Whether a parent-rule expression keeps its meaning when moved inside the
144
+ * junction's `EXISTS` subquery — and the re-scoped copy if it does.
145
+ *
146
+ * Returns `null` when the rule cannot be embedded faithfully: `raw` SQL
147
+ * anywhere (its `{column}` placeholders would bind to the junction), or an
148
+ * `outerField` inside a nested `existsIn` (it would bind to the junction while
149
+ * the author meant the parent, and no operand can express "the middle scope").
150
+ * Top-level `outerField`s are rewritten to `field`, which is what they meant.
151
+ */
152
+ function embedParentExpression(expr, depth = 0) {
153
+ switch (expr.kind) {
154
+ case "raw": return null;
155
+ case "and":
156
+ case "or": {
157
+ const parts = [];
158
+ for (const child of expr.operands) {
159
+ const embedded = embedParentExpression(child, depth);
160
+ if (!embedded) return null;
161
+ parts.push(embedded);
162
+ }
163
+ return expr.kind === "and" ? policy.and(...parts) : policy.or(...parts);
164
+ }
165
+ case "not": {
166
+ const embedded = embedParentExpression(expr.operand, depth);
167
+ return embedded ? policy.not(embedded) : null;
168
+ }
169
+ case "existsIn": {
170
+ const where = embedParentExpression(expr.where, depth + 1);
171
+ return where ? policy.existsIn({
172
+ collection: expr.collection,
173
+ where
174
+ }) : null;
175
+ }
176
+ case "compare": {
177
+ const left = embedOperand(expr.left, depth);
178
+ const right = embedOperand(expr.right, depth);
179
+ if (!left || !right) return null;
180
+ return {
181
+ ...expr,
182
+ left,
183
+ right
184
+ };
185
+ }
186
+ default: return expr;
187
+ }
188
+ }
189
+ /** Re-scope an operand, or return `null` if its binding cannot be preserved. */
190
+ function embedOperand(operand, depth) {
191
+ if (operand.kind === "outerField") {
192
+ if (depth === 0) return policy.field(operand.name);
193
+ return null;
194
+ }
195
+ return operand;
196
+ }
197
+ /** Does the rule cover the `update` operation? */
198
+ function coversUpdate(rule) {
199
+ return getPolicyOperations(rule).some((op) => op === "update" || op === "all");
200
+ }
201
+ /**
202
+ * The full derived policy set for a junction table: the locked server/admin
203
+ * baseline, the endpoint-visibility read grant, inherited write grants, and
204
+ * inherited restrictive gates. Returns `[]` when every declaring collection set
205
+ * `disableDefaultPolicies` — the junction is then the author's to police, and
206
+ * stays locked (RLS is still enabled) until they write policies for it.
207
+ */
208
+ function getJunctionSecurityRules(spec) {
209
+ if (spec.declaringSides.every((side) => isPostgresCollectionConfig(side.collection) && side.collection.disableDefaultPolicies)) return [];
210
+ const rules = [];
211
+ rules.push({
212
+ name: `${spec.table}_default_admin_read`,
213
+ operations: ["select"],
214
+ condition: SERVER_OR_ADMIN_EXPR
215
+ });
216
+ rules.push({
217
+ name: `${spec.table}_default_admin_write`,
218
+ operations: [
219
+ "insert",
220
+ "update",
221
+ "delete"
222
+ ],
223
+ condition: SERVER_OR_ADMIN_EXPR,
224
+ check: SERVER_OR_ADMIN_EXPR
225
+ });
226
+ rules.push({
227
+ name: `${spec.table}_default_edge_read`,
228
+ operations: ["select"],
229
+ condition: policy.and(existsEndpoint(spec.endpoints[0]), existsEndpoint(spec.endpoints[1]))
230
+ });
231
+ const writeGrants = [];
232
+ for (const side of spec.declaringSides) {
233
+ const updateRules = ((isPostgresCollectionConfig(side.collection) ? side.collection.securityRules : void 0) ?? []).filter(coversUpdate);
234
+ const permissive = updateRules.filter((r) => r.mode !== "restrictive");
235
+ const restrictive = updateRules.filter((r) => r.mode === "restrictive");
236
+ const embeddedGates = [];
237
+ let gatesEmbeddable = true;
238
+ for (const gate of restrictive) {
239
+ const using = securityRuleToConditions(gate).usingExpr;
240
+ const embedded = using ? embedParentExpression(using) : null;
241
+ if (!embedded) {
242
+ gatesEmbeddable = false;
243
+ break;
244
+ }
245
+ embeddedGates.push(embedded);
246
+ }
247
+ if (!gatesEmbeddable) continue;
248
+ const grants = [];
249
+ for (const rule of permissive) {
250
+ const using = securityRuleToConditions(rule).usingExpr;
251
+ const embedded = using ? embedParentExpression(using) : null;
252
+ if (embedded) grants.push(embedded);
253
+ }
254
+ if (grants.length === 0) continue;
255
+ const condition = embeddedGates.length > 0 ? policy.and(policy.or(...grants), ...embeddedGates) : policy.or(...grants);
256
+ writeGrants.push(existsEndpoint(side, condition));
257
+ }
258
+ if (writeGrants.length > 0) rules.push({
259
+ name: `${spec.table}_default_edge_write`,
260
+ operations: [
261
+ "insert",
262
+ "update",
263
+ "delete"
264
+ ],
265
+ condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),
266
+ check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)
267
+ });
268
+ return rules;
269
+ }
270
+ //#endregion
271
+ export { embedParentExpression, getJunctionCollectionConfig, getJunctionConfigForRelation, getJunctionSecurityRules, resolveJunctionSpecs };
272
+
273
+ //# sourceMappingURL=junction-policies.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"junction-policies.es.js","names":[],"sources":["../../src/util/junction-policies.ts"],"sourcesContent":["import {\n CollectionConfig,\n JUNCTION_PIVOT_KEY,\n PolicyExpression,\n PolicyOperand,\n Properties,\n Property,\n Relation,\n SecurityRule,\n isPostgresCollectionConfig,\n policy\n} from \"@rebasepro/types\";\nimport { getPolicyOperations } from \"@rebasepro/utils\";\nimport { getTableName } from \"./relations\";\nimport { resolveCollectionRelations } from \"./relations\";\nimport { isManyToMany } from \"@rebasepro/types\";\nimport { securityRuleToConditions } from \"./policy/securityRuleToConditions\";\n\n/**\n * RLS derivation for many-to-many junction tables.\n *\n * A `through` relation makes the generator create a table nobody declared as a\n * collection — `posts_tags`, `user_roles`. Those tables used to be the one kind\n * of generated table with **no** RLS at all: `rebase_user` holds full DML grants,\n * so with the endpoints locked down, any signed-up user could still read or wipe\n * every edge between them. There is also nowhere in the config to write rules\n * for a junction, so the author could not even fix it by hand.\n *\n * The architecture here is that a junction's security is *derived*, never\n * hand-written:\n *\n * 1. **Locked baseline.** The same server-or-admin `default_admin` grants every\n * collection gets, so the invariant holds again: every table the generator\n * creates is default-deny, and rules only broaden.\n *\n * 2. **Reads follow the endpoints.** An edge is visible iff *both* endpoint\n * rows are visible — two correlated `EXISTS` subqueries. The subqueries run\n * under the caller's role, so each endpoint's own RLS filters them: junction\n * visibility delegates to the endpoints' policies, whatever they become,\n * with nothing duplicated. A public blog keeps rendering its tags; a private\n * CRM's edges are exactly as hidden as its rows.\n *\n * 3. **Writes follow the owning side's update rules.** Linking or unlinking an\n * edge *is* an edit of the owning row — tagging a post is editing the post —\n * so edge writes inherit the declaring collection's explicit permissive\n * `update` rules, each wrapped in an `EXISTS` against the owning row. Where\n * a rule cannot be embedded faithfully (see below) it is dropped, so the\n * failure mode is always *too locked*, never open. Explicit **restrictive**\n * update rules are inherited as restrictive junction rules; if one of them\n * cannot be embedded, the whole derived write grant for that side is\n * suppressed — granting without the author's gate would be looser than the\n * parent itself.\n *\n * **Embeddability.** A parent rule is embedded by moving its condition inside\n * `EXISTS (SELECT 1 FROM parent WHERE parent.pk = junction.fk AND <condition>)`.\n * In that scope, `field` operands bind to the parent — which is what the author\n * meant. But `outerField` operands and `{column}` placeholders in `raw` SQL bind\n * to the RLS row, which is now the junction, not the parent the author wrote\n * them against. So: `raw` anywhere disqualifies a rule; a top-level `outerField`\n * (equivalent to `field` outside a subquery) is rewritten to `field`; an\n * `outerField` inside a nested `existsIn` cannot be re-scoped and disqualifies\n * the rule.\n *\n * Injected parent defaults are never inherited — the junction's own baseline\n * already covers the server/admin plane, and an auth collection's restrictive\n * `require_admin_write` gate exists to protect privileged parent *columns*,\n * which an edge write cannot touch. Inheriting it would stop users managing\n * e.g. their own interests through a `users_interests` junction for no gain.\n *\n * Everything flows through the shared naming machinery, so the Studio\n * recognises these policies as generated instead of offering to \"import\" them.\n */\n\n/** One side of a junction: the collection and the FK column pointing at it. */\nexport interface JunctionEndpoint {\n collection: CollectionConfig;\n /** Junction column holding this endpoint's key. */\n junctionColumn: string;\n}\n\n/** A collection that declares the `through` relation (owns the edge semantics). */\nexport interface JunctionDeclaringSide extends JunctionEndpoint {\n relation: Relation;\n}\n\nexport interface JunctionSpec {\n /** Bare table name (schema stripped). */\n table: string;\n /** Schema the junction is created in — mirrors the CREATE TABLE path. */\n schema: string;\n /** The two endpoints, in [source, target] order of the first declaring relation. */\n endpoints: [JunctionEndpoint, JunctionEndpoint];\n /** Every collection that declares a relation through this table. */\n declaringSides: JunctionDeclaringSide[];\n /**\n * The junction's own columns beyond the two keys — `through.properties`,\n * merged across every declaring side. `{}` when there are none.\n *\n * See {@link ManyToManyRelation.through} for what they are; every side that\n * names a key has to describe the same column, which is checked when the\n * specs are resolved rather than left for `CREATE TABLE` to discover.\n */\n properties: Properties;\n}\n\n// Mirrors auth-default-policies: the server context or an admin.\nconst SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(\n policy.serverContext(),\n policy.rolesOverlap([\"admin\"])\n);\n\n/**\n * Walk every collection's resolved relations and aggregate the junction tables\n * they declare. Two collections may declare the same junction from opposite\n * sides (posts→tags and tags→posts through `posts_tags`); both become\n * `declaringSides` of one spec, so derived write grants consider both.\n */\nexport function resolveJunctionSpecs(collections: CollectionConfig[]): Map<string, JunctionSpec> {\n const specs = new Map<string, JunctionSpec>();\n\n for (const collection of collections) {\n const resolved = resolveCollectionRelations(collection);\n for (const relation of Object.values(resolved)) {\n // Narrowed rather than probed: only a many-to-many has a junction,\n // and only after narrowing is `through` guaranteed complete.\n if (!isManyToMany(relation)) continue;\n\n const targetCollection: CollectionConfig | undefined = relation.target();\n if (!targetCollection) continue;\n\n const rawName = relation.through.table;\n // The CREATE TABLE path strips a schema prefix from the name but\n // still creates in \"public\"; the policies must target the same\n // table, so mirror that behaviour exactly.\n const table = rawName.includes(\".\") ? rawName.split(\".\").pop()! : rawName;\n const schema = \"public\";\n\n const source: JunctionDeclaringSide = {\n collection,\n junctionColumn: relation.through.sourceColumn,\n relation\n };\n const target: JunctionEndpoint = {\n collection: targetCollection,\n junctionColumn: relation.through.targetColumn\n };\n\n const existing = specs.get(table);\n if (!existing) {\n specs.set(table, {\n table,\n schema,\n endpoints: [source, target],\n declaringSides: [source],\n properties: mergeJunctionPayload({}, relation.through.properties, table, collection)\n });\n } else {\n // Merged whether or not this side is new: the same collection\n // can reach one junction under two relation names, and the\n // columns each of them asks for all have to exist.\n existing.properties = mergeJunctionPayload(\n existing.properties, relation.through.properties, table, collection);\n if (!existing.declaringSides.some(s => s.collection === collection)) {\n existing.declaringSides.push(source);\n }\n }\n }\n }\n\n return specs;\n}\n\n/**\n * Fold one side's `through.properties` into the junction's, refusing a\n * disagreement rather than picking a winner.\n *\n * Both ends of a link may declare it — `posts.tags` and `tags.posts` are one\n * junction — and each end may name the payload. Only one table gets created, so\n * two descriptions of `role` that are not the same description are a question\n * with no correct answer: whichever won, one of the two collections would be\n * writing through a column it does not think it has. Compared structurally, so\n * two sides that spell the same property twice (the normal case, and the one\n * the docs recommend) are fine.\n */\nfunction mergeJunctionPayload(\n into: Properties,\n incoming: Properties | undefined,\n table: string,\n collection: CollectionConfig\n): Properties {\n if (!incoming || Object.keys(incoming).length === 0) return into;\n const merged: Properties = { ...into };\n for (const [key, property] of Object.entries(incoming)) {\n const already = merged[key as keyof Properties] as Property | undefined;\n if (already && JSON.stringify(already) !== JSON.stringify(property)) {\n throw new Error(\n `The junction table \"${table}\" is declared from more than one side, and they disagree ` +\n `about the payload column \"${key}\": \"${collection.slug ?? collection.name}\" describes it ` +\n \"differently than another declaring collection does. One table is created, so both \" +\n \"`through.properties` blocks have to describe the same column — or only one side should \" +\n \"declare it.\"\n );\n }\n (merged as Record<string, Property>)[key] = property as Property;\n }\n return merged;\n}\n\n/**\n * A synthetic CollectionConfig standing in for the junction during policy\n * compilation and naming. Its two FK columns carry explicit `columnName`s so\n * `outerField` operands resolve to the exact columns the CREATE TABLE emitted,\n * whatever their casing.\n *\n * The payload columns are here too, exactly as authored. That is what lets one\n * reading of a `Property` serve the junction as well as a collection: the\n * schema planner plans these columns with the same function it plans a\n * collection's with, and the write path validates a `_pivot` against them with\n * the same validator a row's values go through. A second description of a\n * payload column anywhere is a second description that can disagree.\n */\nexport function getJunctionCollectionConfig(spec: JunctionSpec): CollectionConfig {\n return buildJunctionCollectionConfig({\n table: spec.table,\n schema: spec.schema,\n keyColumns: spec.endpoints.map(endpoint => endpoint.junctionColumn),\n properties: spec.properties\n });\n}\n\n/**\n * The same synthetic collection, reached from a resolved relation rather than\n * from a spec.\n *\n * The spec is built by walking every collection, which the schema planner does\n * once at boot and no request path can afford. A read or a write already holds\n * the relation, and a relation's `through` carries the table, both key columns\n * and the payload — everything the config is made of. One builder underneath\n * both, so the shape the planner emitted columns from is the shape the write\n * path validates a `_pivot` against and the read path strips it with.\n */\nexport function getJunctionConfigForRelation(\n through: { table: string; sourceColumn: string; targetColumn: string; properties: Properties }\n): CollectionConfig {\n return buildJunctionCollectionConfig({\n // Junctions live in `public`; the CREATE TABLE path strips any schema\n // prefix from the name, so mirror that here rather than carrying it.\n table: through.table.includes(\".\") ? through.table.split(\".\").pop()! : through.table,\n schema: \"public\",\n keyColumns: [through.sourceColumn, through.targetColumn],\n properties: through.properties\n });\n}\n\nfunction buildJunctionCollectionConfig(args: {\n table: string;\n schema: string;\n keyColumns: string[];\n properties: Properties;\n}): CollectionConfig {\n const properties: Record<string, unknown> = {};\n for (const column of args.keyColumns) {\n properties[column] = { type: \"string\", columnName: column };\n }\n // After the keys, so a payload property that collides with a key column\n // cannot quietly replace it — `checkJunctionPayload` refuses that config at\n // boot, and this ordering means the key column survives if one gets past.\n for (const [key, property] of Object.entries(args.properties)) {\n if (key === JUNCTION_PIVOT_KEY || key in properties) continue;\n properties[key] = property;\n }\n return {\n slug: args.table,\n name: args.table,\n table: args.table,\n schema: args.schema,\n properties\n } as CollectionConfig;\n}\n\n/** The property marked as the row id (falls back to `id`). */\nfunction getIdPropertyName(collection: CollectionConfig): string {\n for (const [name, prop] of Object.entries(collection.properties ?? {})) {\n if (prop && typeof prop === \"object\" && \"isId\" in prop && (prop as { isId?: unknown }).isId) {\n return name;\n }\n }\n return \"id\";\n}\n\n/** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */\nfunction existsEndpoint(endpoint: JunctionEndpoint, extra?: PolicyExpression): PolicyExpression {\n const correlation = policy.compare(\n policy.field(getIdPropertyName(endpoint.collection)),\n \"eq\",\n policy.outerField(endpoint.junctionColumn)\n );\n return policy.existsIn({\n collection: endpoint.collection.slug,\n where: extra ? policy.and(correlation, extra) : correlation\n });\n}\n\n/**\n * Whether a parent-rule expression keeps its meaning when moved inside the\n * junction's `EXISTS` subquery — and the re-scoped copy if it does.\n *\n * Returns `null` when the rule cannot be embedded faithfully: `raw` SQL\n * anywhere (its `{column}` placeholders would bind to the junction), or an\n * `outerField` inside a nested `existsIn` (it would bind to the junction while\n * the author meant the parent, and no operand can express \"the middle scope\").\n * Top-level `outerField`s are rewritten to `field`, which is what they meant.\n */\nexport function embedParentExpression(expr: PolicyExpression, depth = 0): PolicyExpression | null {\n switch (expr.kind) {\n case \"raw\":\n return null;\n case \"and\":\n case \"or\": {\n const parts: PolicyExpression[] = [];\n for (const child of expr.operands) {\n const embedded = embedParentExpression(child, depth);\n if (!embedded) return null;\n parts.push(embedded);\n }\n return expr.kind === \"and\" ? policy.and(...parts) : policy.or(...parts);\n }\n case \"not\": {\n const embedded = embedParentExpression(expr.operand, depth);\n return embedded ? policy.not(embedded) : null;\n }\n case \"existsIn\": {\n const where = embedParentExpression(expr.where, depth + 1);\n return where ? policy.existsIn({ collection: expr.collection, where }) : null;\n }\n case \"compare\": {\n const left = embedOperand(expr.left, depth);\n const right = embedOperand(expr.right, depth);\n if (!left || !right) return null;\n return { ...expr, left, right };\n }\n default:\n // Leaf expressions with no field references (true, false,\n // serverContext, authenticated, rolesOverlap, rolesContain) are\n // position-independent.\n return expr;\n }\n}\n\n/** Re-scope an operand, or return `null` if its binding cannot be preserved. */\nfunction embedOperand(operand: PolicyOperand, depth: number): PolicyOperand | null {\n if (operand.kind === \"outerField\") {\n // Outside a subquery, outerField ≡ field: the author meant their own\n // row, which after embedding is the EXISTS's joined table → field.\n if (depth === 0) return policy.field(operand.name);\n // Inside the author's own existsIn it meant the parent row; after\n // embedding it would bind to the junction. Not expressible.\n return null;\n }\n return operand;\n}\n\n/** Does the rule cover the `update` operation? */\nfunction coversUpdate(rule: SecurityRule): boolean {\n return getPolicyOperations(rule).some(op => op === \"update\" || op === \"all\");\n}\n\n/**\n * The full derived policy set for a junction table: the locked server/admin\n * baseline, the endpoint-visibility read grant, inherited write grants, and\n * inherited restrictive gates. Returns `[]` when every declaring collection set\n * `disableDefaultPolicies` — the junction is then the author's to police, and\n * stays locked (RLS is still enabled) until they write policies for it.\n */\nexport function getJunctionSecurityRules(spec: JunctionSpec): SecurityRule[] {\n if (spec.declaringSides.every(side => isPostgresCollectionConfig(side.collection) && side.collection.disableDefaultPolicies)) {\n return [];\n }\n\n const rules: SecurityRule[] = [];\n\n // 1. Locked baseline — same shape and naming as every collection's.\n rules.push({\n name: `${spec.table}_default_admin_read`,\n operations: [\"select\"],\n condition: SERVER_OR_ADMIN_EXPR\n });\n rules.push({\n name: `${spec.table}_default_admin_write`,\n operations: [\"insert\", \"update\", \"delete\"],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n });\n\n // 2. Reads follow the endpoints: the edge is visible iff both rows are.\n // The EXISTS subqueries run under the caller's role, so each endpoint's\n // own RLS applies inside them — visibility is delegated, not copied.\n rules.push({\n name: `${spec.table}_default_edge_read`,\n operations: [\"select\"],\n condition: policy.and(\n existsEndpoint(spec.endpoints[0]),\n existsEndpoint(spec.endpoints[1])\n )\n });\n\n // 3. Writes follow the owning side's explicit update rules.\n const writeGrants: PolicyExpression[] = [];\n for (const side of spec.declaringSides) {\n const explicitRules = (isPostgresCollectionConfig(side.collection)\n ? side.collection.securityRules\n : undefined) ?? [];\n const updateRules = explicitRules.filter(coversUpdate);\n\n const permissive = updateRules.filter(r => r.mode !== \"restrictive\");\n const restrictive = updateRules.filter(r => r.mode === \"restrictive\");\n\n // Embed the restrictive gates first: if any of them cannot be carried\n // over, granting writes from this side would be looser than the parent\n // itself allows — so the whole side's grant is suppressed.\n const embeddedGates: PolicyExpression[] = [];\n let gatesEmbeddable = true;\n for (const gate of restrictive) {\n const using = securityRuleToConditions(gate).usingExpr;\n const embedded = using ? embedParentExpression(using) : null;\n if (!embedded) {\n gatesEmbeddable = false;\n break;\n }\n embeddedGates.push(embedded);\n }\n if (!gatesEmbeddable) continue;\n\n const grants: PolicyExpression[] = [];\n for (const rule of permissive) {\n const using = securityRuleToConditions(rule).usingExpr;\n const embedded = using ? embedParentExpression(using) : null;\n if (embedded) grants.push(embedded);\n }\n if (grants.length === 0) continue;\n\n // \"May update the owning row\": any permissive grant, AND every gate.\n const condition = embeddedGates.length > 0\n ? policy.and(policy.or(...grants), ...embeddedGates)\n : policy.or(...grants);\n\n writeGrants.push(existsEndpoint(side, condition));\n }\n\n if (writeGrants.length > 0) {\n rules.push({\n name: `${spec.table}_default_edge_write`,\n operations: [\"insert\", \"update\", \"delete\"],\n condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),\n check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)\n });\n }\n\n return rules;\n}\n"],"mappings":";;;;;AA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ClB;GACJ;GACA,cAAc,KAAK,QAAQ;EAC/B;EACA,IAAI,CAAC,iBAAiB;EAEtB,MAAM,SAA6B,CAAC;EACpC,KAAK,MAAM,QAAQ,YAAY;GAC3B,MAAM,QAAQ,yBAAyB,IAAI,CAAC,CAAC;GAC7C,MAAM,WAAW,QAAQ,sBAAsB,KAAK,IAAI;GACxD,IAAI,UAAU,OAAO,KAAK,QAAQ;EACtC;EACA,IAAI,OAAO,WAAW,GAAG;EAGzB,MAAM,YAAY,cAAc,SAAS,IACnC,OAAO,IAAI,OAAO,GAAG,GAAG,MAAM,GAAG,GAAG,aAAa,IACjD,OAAO,GAAG,GAAG,MAAM;EAEzB,YAAY,KAAK,eAAe,MAAM,SAAS,CAAC;CACpD;CAEA,IAAI,YAAY,SAAS,GACrB,MAAM,KAAK;EACP,MAAM,GAAG,KAAK,MAAM;EACpB,YAAY;GAAC;GAAU;GAAU;EAAQ;EACzC,WAAW,YAAY,WAAW,IAAI,YAAY,KAAK,OAAO,GAAG,GAAG,WAAW;EAC/E,OAAO,YAAY,WAAW,IAAI,YAAY,KAAK,OAAO,GAAG,GAAG,WAAW;CAC/E,CAAC;CAGL,OAAO;AACX"}
@@ -0,0 +1,26 @@
1
+ //#region src/util/paths.ts
2
+ var COLLECTION_PATH_SEPARATOR = "::";
3
+ /**
4
+ * Remove the entity ids from a given path
5
+ * `products/B44RG6APH/locales` => `products::locales`
6
+ * @param path
7
+ */
8
+ function stripCollectionPath(path) {
9
+ return segmentsToStrippedPath(fullPathToCollectionSegments(path));
10
+ }
11
+ function segmentsToStrippedPath(paths) {
12
+ if (paths.length === 1) return paths[0];
13
+ return paths.reduce((a, b) => `${a}${COLLECTION_PATH_SEPARATOR}${b}`);
14
+ }
15
+ /**
16
+ * Extract the collection path routes
17
+ * `products/B44RG6APH/locales` => [`products`, `locales`]
18
+ * @param path
19
+ */
20
+ function fullPathToCollectionSegments(path) {
21
+ return path.split("/").filter((e, i) => i % 2 === 0);
22
+ }
23
+ //#endregion
24
+ export { COLLECTION_PATH_SEPARATOR, fullPathToCollectionSegments, segmentsToStrippedPath, stripCollectionPath };
25
+
26
+ //# sourceMappingURL=paths.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paths.es.js","names":[],"sources":["../../src/util/paths.ts"],"sourcesContent":["export const COLLECTION_PATH_SEPARATOR = \"::\";\n\n/**\n * Remove the entity ids from a given path\n * `products/B44RG6APH/locales` => `products::locales`\n * @param path\n */\nexport function stripCollectionPath(path: string): string {\n return segmentsToStrippedPath(fullPathToCollectionSegments(path));\n}\n\nexport function segmentsToStrippedPath(paths: string[]) {\n if (paths.length === 1)\n return paths[0];\n return paths.reduce((a, b) => `${a}${COLLECTION_PATH_SEPARATOR}${b}`);\n}\n\n/**\n * Extract the collection path routes\n * `products/B44RG6APH/locales` => [`products`, `locales`]\n * @param path\n */\nexport function fullPathToCollectionSegments(path: string): string[] {\n return path\n .split(\"/\")\n .filter((e, i) => i % 2 === 0);\n}\n"],"mappings":";AAAA,IAAa,4BAA4B;;;;;;AAOzC,SAAgB,oBAAoB,MAAsB;CACtD,OAAO,uBAAuB,6BAA6B,IAAI,CAAC;AACpE;AAEA,SAAgB,uBAAuB,OAAiB;CACpD,IAAI,MAAM,WAAW,GACjB,OAAO,MAAM;CACjB,OAAO,MAAM,QAAQ,GAAG,MAAM,GAAG,IAAI,4BAA4B,GAAG;AACxE;;;;;;AAOA,SAAgB,6BAA6B,MAAwB;CACjE,OAAO,KACF,MAAM,GAAG,CAAC,CACV,QAAQ,GAAG,MAAM,IAAI,MAAM,CAAC;AACrC"}
@@ -0,0 +1,108 @@
1
+ import { securityRuleToConditions } from "./policy/securityRuleToConditions.es.js";
2
+ import { evaluatePolicy } from "./policy/evaluatePolicy.es.js";
3
+ //#region src/util/permissions.ts
4
+ /** Combine clause results with AND under three-valued (Kleene) logic. */
5
+ function kleeneAnd(values) {
6
+ if (values.some((v) => v === false)) return false;
7
+ if (values.some((v) => v === "unknown")) return "unknown";
8
+ return true;
9
+ }
10
+ /** The operations a rule covers, mirroring the Postgres generator's resolution. */
11
+ function ruleOperations(rule) {
12
+ return rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? "all"];
13
+ }
14
+ function ruleApplies(rule, targetOperation) {
15
+ const ops = ruleOperations(rule);
16
+ return ops.includes(targetOperation) || ops.includes("all");
17
+ }
18
+ /**
19
+ * Evaluate a single rule for one operation, returning a tri-state.
20
+ *
21
+ * A `null` clause (the rule contributes no condition for a required clause)
22
+ * denies — matching Postgres, which emits `USING (false)` / `WITH CHECK (false)`
23
+ * in that case. USING applies to SELECT/UPDATE/DELETE; WITH CHECK to
24
+ * INSERT/UPDATE; both must pass for UPDATE.
25
+ */
26
+ function evaluateRuleForOperation(rule, ctx, targetOperation, clauses = "both") {
27
+ const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
28
+ const clause = (expr) => expr === null ? false : evaluatePolicy(expr, ctx);
29
+ const needsUsing = targetOperation !== "insert" && clauses !== "withCheck";
30
+ const needsWithCheck = (targetOperation === "insert" || targetOperation === "update") && clauses !== "using";
31
+ const results = [];
32
+ if (needsUsing) results.push(clause(usingExpr));
33
+ if (needsWithCheck) results.push(clause(withCheckExpr));
34
+ return kleeneAnd(results);
35
+ }
36
+ function resolveTriState(value, onUnknown) {
37
+ if (value === "unknown") return onUnknown === "allow";
38
+ return value;
39
+ }
40
+ /**
41
+ * Decide whether an operation is permitted for a user on a (possibly null) row,
42
+ * by evaluating the collection's security rules with the shared policy model —
43
+ * the same model compiled to Postgres RLS DDL, so the decision matches database
44
+ * enforcement for every non-raw rule.
45
+ *
46
+ * Engine-independent by design. `securityRules` are a declaration about the
47
+ * data, not about Postgres: the engine decides *who* enforces them (Postgres
48
+ * compiles them to RLS DDL, a document driver applies them in-process), never
49
+ * *whether* they hold. Gating this function on the engine's `supportsRLS`
50
+ * capability is what made every `{ onUnknown: "deny" }` call site in the Mongo
51
+ * driver return `true` before it evaluated anything — and it did so only for
52
+ * collections that spelled their engine out, so declaring `engine: "mongodb"`
53
+ * was what switched authorization off.
54
+ *
55
+ * @param options.onUnknown how to treat rules that cannot be decided
56
+ * client-side (raw SQL, or row predicates with no row). Defaults to `"allow"`
57
+ * for optimistic UI gating; enforcement callers should pass `"deny"`.
58
+ * @param options.clauses which half of each rule to evaluate. See
59
+ * {@link PolicyClauses}; defaults to `"both"`.
60
+ */
61
+ function checkOperation(collection, authContext, entity, targetOperation, options) {
62
+ const onUnknown = options?.onUnknown ?? "allow";
63
+ const clauses = options?.clauses ?? "both";
64
+ const securityRules = collection.securityRules;
65
+ if (!securityRules || securityRules.length === 0) return true;
66
+ const applicableRules = securityRules.filter((r) => ruleApplies(r, targetOperation));
67
+ if (applicableRules.length === 0) return false;
68
+ const ctx = {
69
+ uid: authContext.user?.uid,
70
+ roles: authContext.user?.roles ?? [],
71
+ isAnonymous: authContext.user?.isAnonymous === true,
72
+ entity
73
+ };
74
+ let grantedByPermissive = false;
75
+ let deniedByRestrictive = false;
76
+ let hasPermissive = false;
77
+ for (const rule of applicableRules) {
78
+ const mode = rule.mode || "permissive";
79
+ const passed = resolveTriState(evaluateRuleForOperation(rule, ctx, targetOperation, clauses), onUnknown);
80
+ if (mode === "restrictive") {
81
+ if (!passed) {
82
+ deniedByRestrictive = true;
83
+ break;
84
+ }
85
+ } else {
86
+ hasPermissive = true;
87
+ if (passed) grantedByPermissive = true;
88
+ }
89
+ }
90
+ if (deniedByRestrictive) return false;
91
+ return hasPermissive ? grantedByPermissive : false;
92
+ }
93
+ function canReadCollection(collection, authContext) {
94
+ return checkOperation(collection, authContext, null, "select");
95
+ }
96
+ function canEditEntity(collection, authContext, path, entity) {
97
+ return checkOperation(collection, authContext, entity, "update");
98
+ }
99
+ function canCreateEntity(collection, authContext, path, entity) {
100
+ return checkOperation(collection, authContext, entity, "insert");
101
+ }
102
+ function canDeleteEntity(collection, authContext, path, entity) {
103
+ return checkOperation(collection, authContext, entity, "delete");
104
+ }
105
+ //#endregion
106
+ export { canCreateEntity, canDeleteEntity, canEditEntity, canReadCollection, checkOperation };
107
+
108
+ //# sourceMappingURL=permissions.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permissions.es.js","names":[],"sources":["../../src/util/permissions.ts"],"sourcesContent":["import { AuthState, Entity, CollectionConfig, SecurityOperation, SecurityRule, User } from \"@rebasepro/types\";\nimport { securityRuleToConditions } from \"./policy/securityRuleToConditions\";\nimport { evaluatePolicy, PolicyEvalContext, TriState } from \"./policy/evaluatePolicy\";\n\n/**\n * Minimal auth context for permission checking.\n * Only requires the user object — avoids forcing callers to construct\n * a full AuthController just to check permissions.\n *\n * An alias, not a second definition: {@link AuthState} in `@rebasepro/types` is\n * the same shape and is what `dynamicProps` and the JSON-Logic condition context\n * now take, so declaring it twice would be the `WhereFilterOp` mistake again —\n * two copies that agree only by luck.\n */\nexport type AuthContext<USER extends User = User> = AuthState<USER>;\n\n/**\n * How to resolve a policy result that cannot be decided client-side (a raw-SQL\n * escape-hatch rule, or a row-column reference with no row in hand).\n *\n * - `\"allow\"` (default): optimistic — used for admin-UI gating, where Postgres\n * remains the authoritative gate and hiding a working action is worse than\n * showing one the server may reject.\n * - `\"deny\"`: fail-closed — used by real enforcement callers (e.g. a driver\n * applying policies in-process), so an undecidable rule never silently allows.\n */\nexport type UnknownResolution = \"allow\" | \"deny\";\n\n/**\n * Which half of a rule to evaluate.\n *\n * Postgres evaluates `USING` against the row as it is *now* and `WITH CHECK`\n * against the row as it *will be*, both inside the transaction. A driver\n * enforcing an update in-process has two different rows in hand and therefore\n * needs to ask the two questions separately — asking one question about one row\n * either checks the new values against the old row's ownership or the reverse.\n *\n * - `\"both\"` (default): what a single-row decision means (`USING ∧ WITH CHECK`).\n * - `\"using\"`: the read/target clause only — ask it about the stored row.\n * - `\"withCheck\"`: the write clause only — ask it about the row being written.\n *\n * Rule *selection* is unaffected: the target operation still decides which rules\n * apply, so `\"using\"` on an `update` evaluates the update rules' USING clause,\n * not the delete rules'.\n */\nexport type PolicyClauses = \"both\" | \"using\" | \"withCheck\";\n\nexport interface CheckOperationOptions {\n onUnknown?: UnknownResolution;\n clauses?: PolicyClauses;\n}\n\n/** Combine clause results with AND under three-valued (Kleene) logic. */\nfunction kleeneAnd(values: TriState[]): TriState {\n if (values.some(v => v === false)) return false;\n if (values.some(v => v === \"unknown\")) return \"unknown\";\n return true;\n}\n\n/** The operations a rule covers, mirroring the Postgres generator's resolution. */\nfunction ruleOperations(rule: SecurityRule): readonly SecurityOperation[] {\n return rule.operations && rule.operations.length > 0\n ? rule.operations\n : [rule.operation ?? \"all\"];\n}\n\nfunction ruleApplies(rule: SecurityRule, targetOperation: SecurityOperation): boolean {\n const ops = ruleOperations(rule);\n return ops.includes(targetOperation) || ops.includes(\"all\");\n}\n\n/**\n * Evaluate a single rule for one operation, returning a tri-state.\n *\n * A `null` clause (the rule contributes no condition for a required clause)\n * denies — matching Postgres, which emits `USING (false)` / `WITH CHECK (false)`\n * in that case. USING applies to SELECT/UPDATE/DELETE; WITH CHECK to\n * INSERT/UPDATE; both must pass for UPDATE.\n */\nfunction evaluateRuleForOperation(\n rule: SecurityRule,\n ctx: PolicyEvalContext,\n targetOperation: SecurityOperation,\n clauses: PolicyClauses = \"both\"\n): TriState {\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n const clause = (expr: typeof usingExpr): TriState => expr === null ? false : evaluatePolicy(expr, ctx);\n\n const needsUsing = targetOperation !== \"insert\" && clauses !== \"withCheck\";\n const needsWithCheck = (targetOperation === \"insert\" || targetOperation === \"update\") && clauses !== \"using\";\n\n const results: TriState[] = [];\n if (needsUsing) results.push(clause(usingExpr));\n if (needsWithCheck) results.push(clause(withCheckExpr));\n return kleeneAnd(results);\n}\n\nfunction resolveTriState(value: TriState, onUnknown: UnknownResolution): boolean {\n if (value === \"unknown\") return onUnknown === \"allow\";\n return value;\n}\n\n/**\n * Decide whether an operation is permitted for a user on a (possibly null) row,\n * by evaluating the collection's security rules with the shared policy model —\n * the same model compiled to Postgres RLS DDL, so the decision matches database\n * enforcement for every non-raw rule.\n *\n * Engine-independent by design. `securityRules` are a declaration about the\n * data, not about Postgres: the engine decides *who* enforces them (Postgres\n * compiles them to RLS DDL, a document driver applies them in-process), never\n * *whether* they hold. Gating this function on the engine's `supportsRLS`\n * capability is what made every `{ onUnknown: \"deny\" }` call site in the Mongo\n * driver return `true` before it evaluated anything — and it did so only for\n * collections that spelled their engine out, so declaring `engine: \"mongodb\"`\n * was what switched authorization off.\n *\n * @param options.onUnknown how to treat rules that cannot be decided\n * client-side (raw SQL, or row predicates with no row). Defaults to `\"allow\"`\n * for optimistic UI gating; enforcement callers should pass `\"deny\"`.\n * @param options.clauses which half of each rule to evaluate. See\n * {@link PolicyClauses}; defaults to `\"both\"`.\n */\nexport function checkOperation<M extends Record<string, unknown>, USER extends User>(\n collection: CollectionConfig<M>,\n authContext: AuthContext<USER>,\n entity: Entity<M> | null,\n targetOperation: SecurityOperation,\n options?: CheckOperationOptions\n): boolean {\n const onUnknown = options?.onUnknown ?? \"allow\";\n const clauses = options?.clauses ?? \"both\";\n const securityRules = collection.securityRules;\n if (!securityRules || securityRules.length === 0) {\n return true;\n }\n\n const applicableRules = securityRules.filter((r: SecurityRule) => ruleApplies(r, targetOperation));\n if (applicableRules.length === 0) return false;\n\n const ctx: PolicyEvalContext = {\n uid: authContext.user?.uid,\n roles: authContext.user?.roles ?? [],\n // What `policy.registered()` reads. Left out, every guest was an\n // account here: a document driver let a guest read, write and delete\n // the rows `registered()` withholds, whatever user it was handed.\n isAnonymous: authContext.user?.isAnonymous === true,\n entity\n };\n\n let grantedByPermissive = false;\n let deniedByRestrictive = false;\n let hasPermissive = false;\n\n for (const rule of applicableRules) {\n const mode = rule.mode || \"permissive\";\n const passed = resolveTriState(evaluateRuleForOperation(rule, ctx, targetOperation, clauses), onUnknown);\n\n if (mode === \"restrictive\") {\n if (!passed) {\n deniedByRestrictive = true;\n break;\n }\n } else {\n hasPermissive = true;\n if (passed) grantedByPermissive = true;\n }\n }\n\n if (deniedByRestrictive) return false;\n return hasPermissive ? grantedByPermissive : false;\n}\n\nexport function canReadCollection<M extends Record<string, unknown>, USER extends User>\n (\n collection: CollectionConfig<M>,\n authContext: AuthContext<USER>\n ): boolean {\n return checkOperation(collection, authContext, null, \"select\");\n}\n\nexport function canEditEntity<M extends Record<string, unknown>, USER extends User>\n (\n collection: CollectionConfig<M>,\n authContext: AuthContext<USER>,\n path: string,\n entity: Entity<M> | null\n ): boolean {\n return checkOperation(collection, authContext, entity, \"update\");\n}\n\nexport function canCreateEntity<M extends Record<string, unknown>, USER extends User>\n (\n collection: CollectionConfig<M>,\n authContext: AuthContext<USER>,\n path: string,\n entity: Entity<M> | null\n ): boolean {\n return checkOperation(collection, authContext, entity, \"insert\");\n}\n\nexport function canDeleteEntity<M extends Record<string, unknown>, USER extends User>\n (\n collection: CollectionConfig<M>,\n authContext: AuthContext<USER>,\n path: string,\n entity: Entity<M> | null\n ): boolean {\n return checkOperation(collection, authContext, entity, \"delete\");\n}\n"],"mappings":";;;;AAqDA,SAAS,UAAU,QAA8B;CAC7C,IAAI,OAAO,MAAK,MAAK,MAAM,KAAK,GAAG,OAAO;CAC1C,IAAI,OAAO,MAAK,MAAK,MAAM,SAAS,GAAG,OAAO;CAC9C,OAAO;AACX;;AAGA,SAAS,eAAe,MAAkD;CACtE,OAAO,KAAK,cAAc,KAAK,WAAW,SAAS,IAC7C,KAAK,aACL,CAAC,KAAK,aAAa,KAAK;AAClC;AAEA,SAAS,YAAY,MAAoB,iBAA6C;CAClF,MAAM,MAAM,eAAe,IAAI;CAC/B,OAAO,IAAI,SAAS,eAAe,KAAK,IAAI,SAAS,KAAK;AAC9D;;;;;;;;;AAUA,SAAS,yBACL,MACA,KACA,iBACA,UAAyB,QACjB;CACR,MAAM,EAAE,WAAW,kBAAkB,yBAAyB,IAAI;CAClE,MAAM,UAAU,SAAqC,SAAS,OAAO,QAAQ,eAAe,MAAM,GAAG;CAErG,MAAM,aAAa,oBAAoB,YAAY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