@rebasepro/common 0.8.0 → 0.9.1-canary.09aaf62

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 (65) hide show
  1. package/README.md +5 -5
  2. package/dist/collections/CollectionRegistry.d.ts +16 -16
  3. package/dist/collections/default-collections.d.ts +5 -1
  4. package/dist/data/buildRebaseData.d.ts +44 -3
  5. package/dist/data/buildRoutedRebaseData.d.ts +14 -9
  6. package/dist/data/filter-dialect.d.ts +18 -4
  7. package/dist/data/query_builder.d.ts +1 -1
  8. package/dist/data/resolveDataSource.d.ts +1 -1
  9. package/dist/data/sort-dialect.d.ts +41 -0
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.es.js +1236 -179
  12. package/dist/index.es.js.map +1 -1
  13. package/dist/util/auth-default-policies.d.ts +22 -0
  14. package/dist/util/builders.d.ts +19 -56
  15. package/dist/util/callbacks.d.ts +3 -3
  16. package/dist/util/collections.d.ts +4 -4
  17. package/dist/util/entities.d.ts +2 -2
  18. package/dist/util/filter-operator-resolution.d.ts +32 -0
  19. package/dist/util/identity.d.ts +83 -0
  20. package/dist/util/index.d.ts +4 -0
  21. package/dist/util/junction-policies.d.ts +108 -0
  22. package/dist/util/navigation_from_path.d.ts +4 -4
  23. package/dist/util/navigation_utils.d.ts +3 -3
  24. package/dist/util/parent_references_from_path.d.ts +2 -2
  25. package/dist/util/permissions.d.ts +6 -6
  26. package/dist/util/policy/evaluatePolicy.d.ts +8 -1
  27. package/dist/util/policy/index.d.ts +1 -0
  28. package/dist/util/policy/policyToPostgres.d.ts +14 -2
  29. package/dist/util/policy/sqlToPolicy.d.ts +24 -14
  30. package/dist/util/references.d.ts +2 -2
  31. package/dist/util/relations.d.ts +5 -5
  32. package/dist/util/resolutions.d.ts +2 -2
  33. package/package.json +7 -8
  34. package/src/collections/CollectionRegistry.ts +36 -36
  35. package/src/collections/default-collections.ts +2 -0
  36. package/src/data/buildRebaseData.ts +430 -60
  37. package/src/data/buildRoutedRebaseData.ts +22 -16
  38. package/src/data/filter-dialect.ts +151 -60
  39. package/src/data/query_builder.ts +11 -2
  40. package/src/data/resolveDataSource.ts +1 -1
  41. package/src/data/sort-dialect.ts +56 -0
  42. package/src/index.ts +1 -0
  43. package/src/util/auth-default-policies.ts +152 -0
  44. package/src/util/builders.ts +25 -99
  45. package/src/util/callbacks.ts +8 -8
  46. package/src/util/collections.ts +4 -4
  47. package/src/util/entities.ts +4 -4
  48. package/src/util/filter-operator-resolution.ts +81 -0
  49. package/src/util/identity.ts +166 -0
  50. package/src/util/index.ts +4 -0
  51. package/src/util/junction-policies.ts +353 -0
  52. package/src/util/navigation_from_path.ts +4 -4
  53. package/src/util/navigation_utils.ts +8 -8
  54. package/src/util/parent_references_from_path.ts +3 -3
  55. package/src/util/permissions.test.ts +2 -2
  56. package/src/util/permissions.ts +7 -7
  57. package/src/util/policy/evaluatePolicy.ts +26 -4
  58. package/src/util/policy/index.ts +1 -0
  59. package/src/util/policy/policyToPostgres.ts +123 -17
  60. package/src/util/policy/sqlToPolicy.ts +190 -13
  61. package/src/util/references.ts +2 -2
  62. package/src/util/relations.ts +12 -12
  63. package/src/util/resolutions.ts +5 -5
  64. package/dist/index.umd.js +0 -2901
  65. package/dist/index.umd.js.map +0 -1
@@ -0,0 +1,353 @@
1
+ import {
2
+ CollectionConfig,
3
+ PolicyExpression,
4
+ PolicyOperand,
5
+ Relation,
6
+ SecurityRule,
7
+ isPostgresCollectionConfig,
8
+ policy
9
+ } from "@rebasepro/types";
10
+ import { getPolicyOperations } from "@rebasepro/utils";
11
+ import { getTableName } from "./relations";
12
+ import { resolveCollectionRelations } from "./relations";
13
+ import { securityRuleToConditions } from "./policy/securityRuleToConditions";
14
+
15
+ /**
16
+ * RLS derivation for many-to-many junction tables.
17
+ *
18
+ * A `through` relation makes the generator create a table nobody declared as a
19
+ * collection — `posts_tags`, `user_roles`. Those tables used to be the one kind
20
+ * of generated table with **no** RLS at all: `rebase_user` holds full DML grants,
21
+ * so with the endpoints locked down, any signed-up user could still read or wipe
22
+ * every edge between them. There is also nowhere in the config to write rules
23
+ * for a junction, so the author could not even fix it by hand.
24
+ *
25
+ * The architecture here is that a junction's security is *derived*, never
26
+ * hand-written:
27
+ *
28
+ * 1. **Locked baseline.** The same server-or-admin `default_admin` grants every
29
+ * collection gets, so the invariant holds again: every table the generator
30
+ * creates is default-deny, and rules only broaden.
31
+ *
32
+ * 2. **Reads follow the endpoints.** An edge is visible iff *both* endpoint
33
+ * rows are visible — two correlated `EXISTS` subqueries. The subqueries run
34
+ * under the caller's role, so each endpoint's own RLS filters them: junction
35
+ * visibility delegates to the endpoints' policies, whatever they become,
36
+ * with nothing duplicated. A public blog keeps rendering its tags; a private
37
+ * CRM's edges are exactly as hidden as its rows.
38
+ *
39
+ * 3. **Writes follow the owning side's update rules.** Linking or unlinking an
40
+ * edge *is* an edit of the owning row — tagging a post is editing the post —
41
+ * so edge writes inherit the declaring collection's explicit permissive
42
+ * `update` rules, each wrapped in an `EXISTS` against the owning row. Where
43
+ * a rule cannot be embedded faithfully (see below) it is dropped, so the
44
+ * failure mode is always *too locked*, never open. Explicit **restrictive**
45
+ * update rules are inherited as restrictive junction rules; if one of them
46
+ * cannot be embedded, the whole derived write grant for that side is
47
+ * suppressed — granting without the author's gate would be looser than the
48
+ * parent itself.
49
+ *
50
+ * **Embeddability.** A parent rule is embedded by moving its condition inside
51
+ * `EXISTS (SELECT 1 FROM parent WHERE parent.pk = junction.fk AND <condition>)`.
52
+ * In that scope, `field` operands bind to the parent — which is what the author
53
+ * meant. But `outerField` operands and `{column}` placeholders in `raw` SQL bind
54
+ * to the RLS row, which is now the junction, not the parent the author wrote
55
+ * them against. So: `raw` anywhere disqualifies a rule; a top-level `outerField`
56
+ * (equivalent to `field` outside a subquery) is rewritten to `field`; an
57
+ * `outerField` inside a nested `existsIn` cannot be re-scoped and disqualifies
58
+ * the rule.
59
+ *
60
+ * Injected parent defaults are never inherited — the junction's own baseline
61
+ * already covers the server/admin plane, and an auth collection's restrictive
62
+ * `require_admin_write` gate exists to protect privileged parent *columns*,
63
+ * which an edge write cannot touch. Inheriting it would stop users managing
64
+ * e.g. their own interests through a `users_interests` junction for no gain.
65
+ *
66
+ * Everything flows through the shared naming machinery, so the Studio
67
+ * recognises these policies as generated instead of offering to "import" them.
68
+ */
69
+
70
+ /** One side of a junction: the collection and the FK column pointing at it. */
71
+ export interface JunctionEndpoint {
72
+ collection: CollectionConfig;
73
+ /** Junction column holding this endpoint's key. */
74
+ junctionColumn: string;
75
+ }
76
+
77
+ /** A collection that declares the `through` relation (owns the edge semantics). */
78
+ export interface JunctionDeclaringSide extends JunctionEndpoint {
79
+ relation: Relation;
80
+ }
81
+
82
+ export interface JunctionSpec {
83
+ /** Bare table name (schema stripped). */
84
+ table: string;
85
+ /** Schema the junction is created in — mirrors the CREATE TABLE path. */
86
+ schema: string;
87
+ /** The two endpoints, in [source, target] order of the first declaring relation. */
88
+ endpoints: [JunctionEndpoint, JunctionEndpoint];
89
+ /** Every collection that declares a relation through this table. */
90
+ declaringSides: JunctionDeclaringSide[];
91
+ }
92
+
93
+ // Mirrors auth-default-policies: the server context or an admin.
94
+ const SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(
95
+ policy.serverContext(),
96
+ policy.rolesOverlap(["admin"])
97
+ );
98
+
99
+ /**
100
+ * Walk every collection's resolved relations and aggregate the junction tables
101
+ * they declare. Two collections may declare the same junction from opposite
102
+ * sides (posts→tags and tags→posts through `posts_tags`); both become
103
+ * `declaringSides` of one spec, so derived write grants consider both.
104
+ */
105
+ export function resolveJunctionSpecs(collections: CollectionConfig[]): Map<string, JunctionSpec> {
106
+ const specs = new Map<string, JunctionSpec>();
107
+
108
+ for (const collection of collections) {
109
+ const resolved = resolveCollectionRelations(collection);
110
+ for (const relation of Object.values(resolved)) {
111
+ if (!relation.through) continue;
112
+
113
+ const targetCollection: CollectionConfig | undefined =
114
+ typeof relation.target === "function" ? relation.target() : undefined;
115
+ if (!targetCollection) continue;
116
+
117
+ const rawName = relation.through.table;
118
+ // The CREATE TABLE path strips a schema prefix from the name but
119
+ // still creates in "public"; the policies must target the same
120
+ // table, so mirror that behaviour exactly.
121
+ const table = rawName.includes(".") ? rawName.split(".").pop()! : rawName;
122
+ const schema = "public";
123
+
124
+ const source: JunctionDeclaringSide = {
125
+ collection,
126
+ junctionColumn: relation.through.sourceColumn,
127
+ relation
128
+ };
129
+ const target: JunctionEndpoint = {
130
+ collection: targetCollection,
131
+ junctionColumn: relation.through.targetColumn
132
+ };
133
+
134
+ const existing = specs.get(table);
135
+ if (!existing) {
136
+ specs.set(table, {
137
+ table,
138
+ schema,
139
+ endpoints: [source, target],
140
+ declaringSides: [source]
141
+ });
142
+ } else if (!existing.declaringSides.some(s => s.collection === collection)) {
143
+ existing.declaringSides.push(source);
144
+ }
145
+ }
146
+ }
147
+
148
+ return specs;
149
+ }
150
+
151
+ /**
152
+ * A synthetic CollectionConfig standing in for the junction during policy
153
+ * compilation and naming. Its two FK columns carry explicit `columnName`s so
154
+ * `outerField` operands resolve to the exact columns the CREATE TABLE emitted,
155
+ * whatever their casing.
156
+ */
157
+ export function getJunctionCollectionConfig(spec: JunctionSpec): CollectionConfig {
158
+ const properties: Record<string, unknown> = {};
159
+ for (const endpoint of spec.endpoints) {
160
+ properties[endpoint.junctionColumn] = {
161
+ type: "string",
162
+ columnName: endpoint.junctionColumn
163
+ };
164
+ }
165
+ return {
166
+ slug: spec.table,
167
+ name: spec.table,
168
+ table: spec.table,
169
+ schema: spec.schema,
170
+ properties
171
+ } as unknown as CollectionConfig;
172
+ }
173
+
174
+ /** The property marked as the row id (falls back to `id`). */
175
+ function getIdPropertyName(collection: CollectionConfig): string {
176
+ for (const [name, prop] of Object.entries(collection.properties ?? {})) {
177
+ if (prop && typeof prop === "object" && "isId" in prop && (prop as { isId?: unknown }).isId) {
178
+ return name;
179
+ }
180
+ }
181
+ return "id";
182
+ }
183
+
184
+ /** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */
185
+ function existsEndpoint(endpoint: JunctionEndpoint, extra?: PolicyExpression): PolicyExpression {
186
+ const correlation = policy.compare(
187
+ policy.field(getIdPropertyName(endpoint.collection)),
188
+ "eq",
189
+ policy.outerField(endpoint.junctionColumn)
190
+ );
191
+ return policy.existsIn({
192
+ collection: endpoint.collection.slug,
193
+ where: extra ? policy.and(correlation, extra) : correlation
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Whether a parent-rule expression keeps its meaning when moved inside the
199
+ * junction's `EXISTS` subquery — and the re-scoped copy if it does.
200
+ *
201
+ * Returns `null` when the rule cannot be embedded faithfully: `raw` SQL
202
+ * anywhere (its `{column}` placeholders would bind to the junction), or an
203
+ * `outerField` inside a nested `existsIn` (it would bind to the junction while
204
+ * the author meant the parent, and no operand can express "the middle scope").
205
+ * Top-level `outerField`s are rewritten to `field`, which is what they meant.
206
+ */
207
+ export function embedParentExpression(expr: PolicyExpression, depth = 0): PolicyExpression | null {
208
+ switch (expr.kind) {
209
+ case "raw":
210
+ return null;
211
+ case "and":
212
+ case "or": {
213
+ const parts: PolicyExpression[] = [];
214
+ for (const child of expr.operands) {
215
+ const embedded = embedParentExpression(child, depth);
216
+ if (!embedded) return null;
217
+ parts.push(embedded);
218
+ }
219
+ return expr.kind === "and" ? policy.and(...parts) : policy.or(...parts);
220
+ }
221
+ case "not": {
222
+ const embedded = embedParentExpression(expr.operand, depth);
223
+ return embedded ? policy.not(embedded) : null;
224
+ }
225
+ case "existsIn": {
226
+ const where = embedParentExpression(expr.where, depth + 1);
227
+ return where ? policy.existsIn({ collection: expr.collection, where }) : null;
228
+ }
229
+ case "compare": {
230
+ const left = embedOperand(expr.left, depth);
231
+ const right = embedOperand(expr.right, depth);
232
+ if (!left || !right) return null;
233
+ return { ...expr, left, right };
234
+ }
235
+ default:
236
+ // Leaf expressions with no field references (true, false,
237
+ // serverContext, authenticated, rolesOverlap, rolesContain) are
238
+ // position-independent.
239
+ return expr;
240
+ }
241
+ }
242
+
243
+ /** Re-scope an operand, or return `null` if its binding cannot be preserved. */
244
+ function embedOperand(operand: PolicyOperand, depth: number): PolicyOperand | null {
245
+ if (operand.kind === "outerField") {
246
+ // Outside a subquery, outerField ≡ field: the author meant their own
247
+ // row, which after embedding is the EXISTS's joined table → field.
248
+ if (depth === 0) return policy.field(operand.name);
249
+ // Inside the author's own existsIn it meant the parent row; after
250
+ // embedding it would bind to the junction. Not expressible.
251
+ return null;
252
+ }
253
+ return operand;
254
+ }
255
+
256
+ /** Does the rule cover the `update` operation? */
257
+ function coversUpdate(rule: SecurityRule): boolean {
258
+ return getPolicyOperations(rule).some(op => op === "update" || op === "all");
259
+ }
260
+
261
+ /**
262
+ * The full derived policy set for a junction table: the locked server/admin
263
+ * baseline, the endpoint-visibility read grant, inherited write grants, and
264
+ * inherited restrictive gates. Returns `[]` when every declaring collection set
265
+ * `disableDefaultPolicies` — the junction is then the author's to police, and
266
+ * stays locked (RLS is still enabled) until they write policies for it.
267
+ */
268
+ export function getJunctionSecurityRules(spec: JunctionSpec): SecurityRule[] {
269
+ if (spec.declaringSides.every(side => side.collection.disableDefaultPolicies)) {
270
+ return [];
271
+ }
272
+
273
+ const rules: SecurityRule[] = [];
274
+
275
+ // 1. Locked baseline — same shape and naming as every collection's.
276
+ rules.push({
277
+ name: `${spec.table}_default_admin_read`,
278
+ operations: ["select"],
279
+ condition: SERVER_OR_ADMIN_EXPR
280
+ });
281
+ rules.push({
282
+ name: `${spec.table}_default_admin_write`,
283
+ operations: ["insert", "update", "delete"],
284
+ condition: SERVER_OR_ADMIN_EXPR,
285
+ check: SERVER_OR_ADMIN_EXPR
286
+ });
287
+
288
+ // 2. Reads follow the endpoints: the edge is visible iff both rows are.
289
+ // The EXISTS subqueries run under the caller's role, so each endpoint's
290
+ // own RLS applies inside them — visibility is delegated, not copied.
291
+ rules.push({
292
+ name: `${spec.table}_default_edge_read`,
293
+ operations: ["select"],
294
+ condition: policy.and(
295
+ existsEndpoint(spec.endpoints[0]),
296
+ existsEndpoint(spec.endpoints[1])
297
+ )
298
+ });
299
+
300
+ // 3. Writes follow the owning side's explicit update rules.
301
+ const writeGrants: PolicyExpression[] = [];
302
+ for (const side of spec.declaringSides) {
303
+ const explicitRules = (isPostgresCollectionConfig(side.collection)
304
+ ? side.collection.securityRules
305
+ : undefined) ?? [];
306
+ const updateRules = explicitRules.filter(coversUpdate);
307
+
308
+ const permissive = updateRules.filter(r => r.mode !== "restrictive");
309
+ const restrictive = updateRules.filter(r => r.mode === "restrictive");
310
+
311
+ // Embed the restrictive gates first: if any of them cannot be carried
312
+ // over, granting writes from this side would be looser than the parent
313
+ // itself allows — so the whole side's grant is suppressed.
314
+ const embeddedGates: PolicyExpression[] = [];
315
+ let gatesEmbeddable = true;
316
+ for (const gate of restrictive) {
317
+ const using = securityRuleToConditions(gate).usingExpr;
318
+ const embedded = using ? embedParentExpression(using) : null;
319
+ if (!embedded) {
320
+ gatesEmbeddable = false;
321
+ break;
322
+ }
323
+ embeddedGates.push(embedded);
324
+ }
325
+ if (!gatesEmbeddable) continue;
326
+
327
+ const grants: PolicyExpression[] = [];
328
+ for (const rule of permissive) {
329
+ const using = securityRuleToConditions(rule).usingExpr;
330
+ const embedded = using ? embedParentExpression(using) : null;
331
+ if (embedded) grants.push(embedded);
332
+ }
333
+ if (grants.length === 0) continue;
334
+
335
+ // "May update the owning row": any permissive grant, AND every gate.
336
+ const condition = embeddedGates.length > 0
337
+ ? policy.and(policy.or(...grants), ...embeddedGates)
338
+ : policy.or(...grants);
339
+
340
+ writeGrants.push(existsEndpoint(side, condition));
341
+ }
342
+
343
+ if (writeGrants.length > 0) {
344
+ rules.push({
345
+ name: `${spec.table}_default_edge_write`,
346
+ operations: ["insert", "update", "delete"],
347
+ condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),
348
+ check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)
349
+ });
350
+ }
351
+
352
+ return rules;
353
+ }
@@ -1,4 +1,4 @@
1
- import { EntityCollection } from "@rebasepro/types";
1
+ import { CollectionConfig } from "@rebasepro/types";
2
2
  type EntityCustomView<M extends Record<string, unknown> = Record<string, unknown>> = { key: string; [key: string]: unknown };
3
3
  import { getCollectionPathsCombinations, removeInitialAndTrailingSlashes } from "./navigation_utils";
4
4
  import { getSubcollections } from "./resolutions";
@@ -13,7 +13,7 @@ export interface NavigationViewEntityInternal<M extends Record<string, unknown>>
13
13
  entityId: string | number;
14
14
  slug: string;
15
15
  path: string;
16
- parentCollection: EntityCollection<M>;
16
+ parentCollection: CollectionConfig<M>;
17
17
  }
18
18
 
19
19
  export interface NavigationViewCollectionInternal<M extends Record<string, unknown>> {
@@ -21,7 +21,7 @@ export interface NavigationViewCollectionInternal<M extends Record<string, unkno
21
21
  id: string;
22
22
  slug: string;
23
23
  path: string;
24
- collection: EntityCollection<M>;
24
+ collection: CollectionConfig<M>;
25
25
  }
26
26
 
27
27
  export interface NavigationViewEntityCustomInternal<M extends Record<string, unknown>> {
@@ -34,7 +34,7 @@ export interface NavigationViewEntityCustomInternal<M extends Record<string, unk
34
34
 
35
35
  export function getNavigationEntriesFromPath(props: {
36
36
  path: string,
37
- collections: EntityCollection[] | undefined,
37
+ collections: CollectionConfig[] | undefined,
38
38
  currentFullPath?: string,
39
39
  contextEntityViews?: EntityCustomView[]
40
40
  }): NavigationViewInternal[] {
@@ -1,4 +1,4 @@
1
- import { EntityCollection } from "@rebasepro/types";
1
+ import { CollectionConfig } from "@rebasepro/types";
2
2
 
3
3
  import { getSubcollections } from "./resolutions";
4
4
 
@@ -33,13 +33,13 @@ export function getLastSegment(path: string) {
33
33
  return cleanPath;
34
34
  }
35
35
 
36
- export function resolveCollectionPathIds(path: string, allCollections: EntityCollection[]): string {
36
+ export function resolveCollectionPathIds(path: string, allCollections: CollectionConfig[]): string {
37
37
  let remainingPath = removeInitialAndTrailingSlashes(path);
38
38
  if (!remainingPath) {
39
39
  return "";
40
40
  }
41
41
 
42
- let currentCollections: EntityCollection[] | undefined = allCollections;
42
+ let currentCollections: CollectionConfig[] | undefined = allCollections;
43
43
  const resolvedPathParts: string[] = [];
44
44
 
45
45
  while (remainingPath.length > 0) {
@@ -53,7 +53,7 @@ export function resolveCollectionPathIds(path: string, allCollections: EntityCol
53
53
 
54
54
  let foundMatch = false;
55
55
  // Sort potential matches by length descending to prioritize longer matches (e.g., "a/b" over "a")
56
- const potentialMatches: { col: EntityCollection; match: string; }[] = currentCollections
56
+ const potentialMatches: { col: CollectionConfig; match: string; }[] = currentCollections
57
57
  .flatMap(col => [{
58
58
  col,
59
59
  match: col.slug
@@ -76,7 +76,7 @@ export function resolveCollectionPathIds(path: string, allCollections: EntityCol
76
76
  break; // Path ends with a collection segment
77
77
  }
78
78
 
79
- // The next segment must be an entity ID
79
+ // The next segment must be a entity ID
80
80
  const idSeparatorIndex = remainingPath.indexOf("/");
81
81
  let entityId: string | number;
82
82
  if (idSeparatorIndex > -1) {
@@ -87,7 +87,7 @@ export function resolveCollectionPathIds(path: string, allCollections: EntityCol
87
87
  // but handle it defensively: assume the rest is the ID
88
88
  entityId = remainingPath;
89
89
  remainingPath = "";
90
- console.warn(`resolveCollectionPathIds: Path seems to end with an entity ID "${entityId}" instead of a collection segment in original path "${path}". This might indicate an invalid input path.`);
90
+ console.warn(`resolveCollectionPathIds: Path seems to end with a entity ID "${entityId}" instead of a collection segment in original path "${path}". This might indicate an invalid input path.`);
91
91
  // Even if it ends here, we still need to push the ID
92
92
  }
93
93
 
@@ -123,7 +123,7 @@ export function resolveCollectionPathIds(path: string, allCollections: EntityCol
123
123
  * @param slugOrPath
124
124
  * @param collections
125
125
  */
126
- export function getCollectionBySlugWithin(slugOrPath: string, collections: EntityCollection[]): EntityCollection | undefined {
126
+ export function getCollectionBySlugWithin(slugOrPath: string, collections: CollectionConfig[]): CollectionConfig | undefined {
127
127
 
128
128
  const subpaths = removeInitialAndTrailingSlashes(slugOrPath).split("/");
129
129
  if (subpaths.length % 2 === 0) {
@@ -131,7 +131,7 @@ export function getCollectionBySlugWithin(slugOrPath: string, collections: Entit
131
131
  }
132
132
 
133
133
  const subpathCombinations = getCollectionPathsCombinations(subpaths);
134
- let result: EntityCollection | undefined;
134
+ let result: CollectionConfig | undefined;
135
135
  for (let i = 0; i < subpathCombinations.length; i++) {
136
136
  const subpathCombination = subpathCombinations[i];
137
137
  const navigationEntry = collections && collections
@@ -1,10 +1,10 @@
1
- import { EntityCollection, EntityReference } from "@rebasepro/types";
1
+ import { CollectionConfig, EntityReference } from "@rebasepro/types";
2
2
  import { getCollectionPathsCombinations, removeInitialAndTrailingSlashes } from "./navigation_utils";
3
3
  import { getSubcollections } from "./resolutions";
4
4
 
5
5
  export function getParentReferencesFromPath(props: {
6
6
  path: string,
7
- collections: EntityCollection[] | undefined,
7
+ collections: CollectionConfig[] | undefined,
8
8
  currentFullPath?: string,
9
9
  }): EntityReference[] {
10
10
 
@@ -21,7 +21,7 @@ export function getParentReferencesFromPath(props: {
21
21
  for (let i = 0; i < subpathCombinations.length; i++) {
22
22
  const subpathCombination = subpathCombinations[i];
23
23
 
24
- const collection: EntityCollection | undefined = collections && collections.find((entry) => entry.slug === subpathCombination);
24
+ const collection: CollectionConfig | undefined = collections && collections.find((entry) => entry.slug === subpathCombination);
25
25
 
26
26
  // If we find a collection, we add the reference and continue
27
27
  if (collection) {
@@ -1,5 +1,5 @@
1
1
  import { canCreateEntity, canEditEntity, canDeleteEntity, canReadCollection } from "./permissions";
2
- import { EntityCollection, AuthController, Entity, User, SecurityRule } from "@rebasepro/types";
2
+ import { CollectionConfig, AuthController, Entity, User, SecurityRule } from "@rebasepro/types";
3
3
 
4
4
  describe("Permissions Evaluator", () => {
5
5
 
@@ -46,7 +46,7 @@ describe("Permissions Evaluator", () => {
46
46
  user: null
47
47
  };
48
48
 
49
- const createMockCollection = (rules?: SecurityRule[]): EntityCollection => ({
49
+ const createMockCollection = (rules?: SecurityRule[]): CollectionConfig => ({
50
50
  slug: "test",
51
51
  name: "Test",
52
52
  table: "test",
@@ -1,4 +1,4 @@
1
- import { Entity, EntityCollection, getDataSourceCapabilities, SecurityOperation, SecurityRule, User } from "@rebasepro/types";
1
+ import { Entity, CollectionConfig, getDataSourceCapabilities, SecurityOperation, SecurityRule, User } from "@rebasepro/types";
2
2
  import { securityRuleToConditions } from "./policy/securityRuleToConditions";
3
3
  import { evaluatePolicy, PolicyEvalContext, TriState } from "./policy/evaluatePolicy";
4
4
 
@@ -35,7 +35,7 @@ function kleeneAnd(values: TriState[]): TriState {
35
35
  }
36
36
 
37
37
  /** The operations a rule covers, mirroring the Postgres generator's resolution. */
38
- function ruleOperations(rule: SecurityRule): SecurityOperation[] {
38
+ function ruleOperations(rule: SecurityRule): readonly SecurityOperation[] {
39
39
  return rule.operations && rule.operations.length > 0
40
40
  ? rule.operations
41
41
  : [rule.operation ?? "all"];
@@ -83,7 +83,7 @@ function resolveTriState(value: TriState, onUnknown: UnknownResolution): boolean
83
83
  * for optimistic UI gating; enforcement callers should pass `"deny"`.
84
84
  */
85
85
  export function checkOperation<M extends Record<string, unknown>, USER extends User>(
86
- collection: EntityCollection<M>,
86
+ collection: CollectionConfig<M>,
87
87
  authContext: AuthContext<USER>,
88
88
  entity: Entity<M> | null,
89
89
  targetOperation: SecurityOperation,
@@ -129,7 +129,7 @@ export function checkOperation<M extends Record<string, unknown>, USER extends U
129
129
 
130
130
  export function canReadCollection<M extends Record<string, unknown>, USER extends User>
131
131
  (
132
- collection: EntityCollection<M>,
132
+ collection: CollectionConfig<M>,
133
133
  authContext: AuthContext<USER>
134
134
  ): boolean {
135
135
  return checkOperation(collection, authContext, null, "select");
@@ -137,7 +137,7 @@ export function canReadCollection<M extends Record<string, unknown>, USER extend
137
137
 
138
138
  export function canEditEntity<M extends Record<string, unknown>, USER extends User>
139
139
  (
140
- collection: EntityCollection<M>,
140
+ collection: CollectionConfig<M>,
141
141
  authContext: AuthContext<USER>,
142
142
  path: string,
143
143
  entity: Entity<M> | null
@@ -147,7 +147,7 @@ export function canEditEntity<M extends Record<string, unknown>, USER extends Us
147
147
 
148
148
  export function canCreateEntity<M extends Record<string, unknown>, USER extends User>
149
149
  (
150
- collection: EntityCollection<M>,
150
+ collection: CollectionConfig<M>,
151
151
  authContext: AuthContext<USER>,
152
152
  path: string,
153
153
  entity: Entity<M> | null
@@ -157,7 +157,7 @@ export function canCreateEntity<M extends Record<string, unknown>, USER extends
157
157
 
158
158
  export function canDeleteEntity<M extends Record<string, unknown>, USER extends User>
159
159
  (
160
- collection: EntityCollection<M>,
160
+ collection: CollectionConfig<M>,
161
161
  authContext: AuthContext<USER>,
162
162
  path: string,
163
163
  entity: Entity<M> | null
@@ -1,4 +1,4 @@
1
- import { Entity, PolicyCompareOperator, PolicyExpression, PolicyOperand } from "@rebasepro/types";
1
+ import { ANONYMOUS_USER_ID, Entity, PolicyCompareOperator, PolicyExpression, PolicyOperand } from "@rebasepro/types";
2
2
 
3
3
  /**
4
4
  * Result of evaluating a policy client-side. `"unknown"` means the expression
@@ -15,7 +15,14 @@ export type TriState = boolean | "unknown";
15
15
  * being evaluated (or none, for collection-level gating).
16
16
  */
17
17
  export interface PolicyEvalContext {
18
- /** The current user's id, or null/undefined when unauthenticated. */
18
+ /**
19
+ * The current user's id, or null/undefined when no user is signed in.
20
+ *
21
+ * Null here means *anonymous visitor*, not "server context" — a client is
22
+ * never the server context. `authUid` operands therefore resolve to
23
+ * {@link ANONYMOUS_USER_ID} rather than `null`, matching the `auth.uid()`
24
+ * the database would see for the same request.
25
+ */
19
26
  uid?: string | null;
20
27
  /** The current user's application roles. */
21
28
  roles?: string[];
@@ -54,7 +61,15 @@ export function evaluatePolicy(expr: PolicyExpression, ctx: PolicyEvalContext):
54
61
  return expr.roles.every(r => r === "public" || userRoles.includes(r));
55
62
  }
56
63
  case "authenticated":
57
- return ctx.uid != null;
64
+ return ctx.uid != null && ctx.uid !== ANONYMOUS_USER_ID;
65
+ case "serverContext":
66
+ // A client is never the server context. Postgres decides this by
67
+ // `auth.uid() IS NULL`, which a client request can never produce:
68
+ // the driver substitutes ANONYMOUS_USER_ID for a missing id.
69
+ return false;
70
+ case "existsIn":
71
+ // A membership subquery cannot be run client-side — server-authoritative.
72
+ return "unknown";
58
73
  case "raw":
59
74
  // Arbitrary SQL cannot be evaluated client-side — never guess.
60
75
  return "unknown";
@@ -89,13 +104,20 @@ function resolveOperand(operand: PolicyOperand, ctx: PolicyEvalContext): Resolve
89
104
  case "literal":
90
105
  return { known: true, value: operand.value };
91
106
  case "authUid":
92
- return { known: true, value: ctx.uid ?? null };
107
+ // The sentinel, not null: `auth.uid()` is never NULL for a request
108
+ // that came from a client, so comparing against null here would
109
+ // disagree with the database on exactly the rules that test for it
110
+ // (e.g. `auth.uid() <> 'anonymous'`).
111
+ return { known: true, value: ctx.uid ?? ANONYMOUS_USER_ID };
93
112
  case "authRoles":
94
113
  return { known: true, value: ctx.roles ?? [] };
95
114
  case "field":
96
115
  // Can't resolve a row column without the row.
97
116
  if (!ctx.entity) return { known: false };
98
117
  return { known: true, value: ctx.entity.values[operand.name] };
118
+ case "outerField":
119
+ // Only meaningful inside an `existsIn` subquery (server-authoritative).
120
+ return { known: false };
99
121
  }
100
122
  }
101
123
 
@@ -1,3 +1,4 @@
1
1
  export * from "./securityRuleToConditions";
2
+ export * from "./sqlToPolicy";
2
3
  export * from "./policyToPostgres";
3
4
  export * from "./evaluatePolicy";