@rebasepro/common 0.17.3 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +4 -0
  2. package/dist/collections/CollectionRegistry.d.ts +1 -1
  3. package/dist/collections/default-collections.d.ts +15 -84
  4. package/dist/data/buildRebaseData.d.ts +1 -1
  5. package/dist/data/filter-dialect.d.ts +11 -0
  6. package/dist/data/sort-dialect.d.ts +15 -3
  7. package/dist/index.es.js +375 -63
  8. package/dist/index.es.js.map +1 -1
  9. package/dist/util/builders.d.ts +69 -24
  10. package/dist/util/callback-errors.d.ts +77 -0
  11. package/dist/util/callback-errors.test.d.ts +1 -0
  12. package/dist/util/index.d.ts +1 -0
  13. package/dist/util/policy/evaluatePolicy.d.ts +6 -0
  14. package/dist/util/relations.d.ts +41 -0
  15. package/dist/util/table-name.test.d.ts +1 -0
  16. package/package.json +26 -22
  17. package/src/collections/CollectionRegistry.ts +0 -485
  18. package/src/collections/default-collections.ts +0 -109
  19. package/src/collections/index.ts +0 -2
  20. package/src/data/buildRebaseData.ts +0 -816
  21. package/src/data/buildRoutedRebaseData.ts +0 -103
  22. package/src/data/filter-conditions.ts +0 -46
  23. package/src/data/filter-dialect.ts +0 -737
  24. package/src/data/paginate.ts +0 -334
  25. package/src/data/query_builder.ts +0 -176
  26. package/src/data/resolveDataSource.ts +0 -135
  27. package/src/data/sort-dialect.ts +0 -237
  28. package/src/index.ts +0 -11
  29. package/src/table-classification.ts +0 -109
  30. package/src/types/json-logic-js.d.ts +0 -8
  31. package/src/util/auth-default-policies.ts +0 -215
  32. package/src/util/builders.ts +0 -82
  33. package/src/util/callbacks.ts +0 -122
  34. package/src/util/collections.ts +0 -117
  35. package/src/util/common.ts +0 -2
  36. package/src/util/conditions.ts +0 -168
  37. package/src/util/email.ts +0 -32
  38. package/src/util/entities.ts +0 -282
  39. package/src/util/enums.ts +0 -26
  40. package/src/util/identity.ts +0 -202
  41. package/src/util/index.ts +0 -21
  42. package/src/util/internal-tables.test.ts +0 -188
  43. package/src/util/internal-tables.ts +0 -197
  44. package/src/util/junction-policies.ts +0 -355
  45. package/src/util/paths.ts +0 -27
  46. package/src/util/permissions.test.ts +0 -866
  47. package/src/util/permissions.ts +0 -206
  48. package/src/util/pg-column-to-property.ts +0 -377
  49. package/src/util/policy/evaluatePolicy.ts +0 -194
  50. package/src/util/policy/index.ts +0 -4
  51. package/src/util/policy/policyToPostgres.ts +0 -263
  52. package/src/util/policy/securityRuleToConditions.ts +0 -67
  53. package/src/util/policy/sqlToPolicy.ts +0 -422
  54. package/src/util/relations.ts +0 -236
  55. package/src/util/resolutions.ts +0 -534
  56. package/src/util/resolve-relation.ts +0 -243
  57. package/src/util/storage.ts +0 -177
  58. package/src/util/string-column-length.ts +0 -31
@@ -1,355 +0,0 @@
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 { isManyToMany } from "@rebasepro/types";
14
- import { securityRuleToConditions } from "./policy/securityRuleToConditions";
15
-
16
- /**
17
- * RLS derivation for many-to-many junction tables.
18
- *
19
- * A `through` relation makes the generator create a table nobody declared as a
20
- * collection — `posts_tags`, `user_roles`. Those tables used to be the one kind
21
- * of generated table with **no** RLS at all: `rebase_user` holds full DML grants,
22
- * so with the endpoints locked down, any signed-up user could still read or wipe
23
- * every edge between them. There is also nowhere in the config to write rules
24
- * for a junction, so the author could not even fix it by hand.
25
- *
26
- * The architecture here is that a junction's security is *derived*, never
27
- * hand-written:
28
- *
29
- * 1. **Locked baseline.** The same server-or-admin `default_admin` grants every
30
- * collection gets, so the invariant holds again: every table the generator
31
- * creates is default-deny, and rules only broaden.
32
- *
33
- * 2. **Reads follow the endpoints.** An edge is visible iff *both* endpoint
34
- * rows are visible — two correlated `EXISTS` subqueries. The subqueries run
35
- * under the caller's role, so each endpoint's own RLS filters them: junction
36
- * visibility delegates to the endpoints' policies, whatever they become,
37
- * with nothing duplicated. A public blog keeps rendering its tags; a private
38
- * CRM's edges are exactly as hidden as its rows.
39
- *
40
- * 3. **Writes follow the owning side's update rules.** Linking or unlinking an
41
- * edge *is* an edit of the owning row — tagging a post is editing the post —
42
- * so edge writes inherit the declaring collection's explicit permissive
43
- * `update` rules, each wrapped in an `EXISTS` against the owning row. Where
44
- * a rule cannot be embedded faithfully (see below) it is dropped, so the
45
- * failure mode is always *too locked*, never open. Explicit **restrictive**
46
- * update rules are inherited as restrictive junction rules; if one of them
47
- * cannot be embedded, the whole derived write grant for that side is
48
- * suppressed — granting without the author's gate would be looser than the
49
- * parent itself.
50
- *
51
- * **Embeddability.** A parent rule is embedded by moving its condition inside
52
- * `EXISTS (SELECT 1 FROM parent WHERE parent.pk = junction.fk AND <condition>)`.
53
- * In that scope, `field` operands bind to the parent — which is what the author
54
- * meant. But `outerField` operands and `{column}` placeholders in `raw` SQL bind
55
- * to the RLS row, which is now the junction, not the parent the author wrote
56
- * them against. So: `raw` anywhere disqualifies a rule; a top-level `outerField`
57
- * (equivalent to `field` outside a subquery) is rewritten to `field`; an
58
- * `outerField` inside a nested `existsIn` cannot be re-scoped and disqualifies
59
- * the rule.
60
- *
61
- * Injected parent defaults are never inherited — the junction's own baseline
62
- * already covers the server/admin plane, and an auth collection's restrictive
63
- * `require_admin_write` gate exists to protect privileged parent *columns*,
64
- * which an edge write cannot touch. Inheriting it would stop users managing
65
- * e.g. their own interests through a `users_interests` junction for no gain.
66
- *
67
- * Everything flows through the shared naming machinery, so the Studio
68
- * recognises these policies as generated instead of offering to "import" them.
69
- */
70
-
71
- /** One side of a junction: the collection and the FK column pointing at it. */
72
- export interface JunctionEndpoint {
73
- collection: CollectionConfig;
74
- /** Junction column holding this endpoint's key. */
75
- junctionColumn: string;
76
- }
77
-
78
- /** A collection that declares the `through` relation (owns the edge semantics). */
79
- export interface JunctionDeclaringSide extends JunctionEndpoint {
80
- relation: Relation;
81
- }
82
-
83
- export interface JunctionSpec {
84
- /** Bare table name (schema stripped). */
85
- table: string;
86
- /** Schema the junction is created in — mirrors the CREATE TABLE path. */
87
- schema: string;
88
- /** The two endpoints, in [source, target] order of the first declaring relation. */
89
- endpoints: [JunctionEndpoint, JunctionEndpoint];
90
- /** Every collection that declares a relation through this table. */
91
- declaringSides: JunctionDeclaringSide[];
92
- }
93
-
94
- // Mirrors auth-default-policies: the server context or an admin.
95
- const SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(
96
- policy.serverContext(),
97
- policy.rolesOverlap(["admin"])
98
- );
99
-
100
- /**
101
- * Walk every collection's resolved relations and aggregate the junction tables
102
- * they declare. Two collections may declare the same junction from opposite
103
- * sides (posts→tags and tags→posts through `posts_tags`); both become
104
- * `declaringSides` of one spec, so derived write grants consider both.
105
- */
106
- export function resolveJunctionSpecs(collections: CollectionConfig[]): Map<string, JunctionSpec> {
107
- const specs = new Map<string, JunctionSpec>();
108
-
109
- for (const collection of collections) {
110
- const resolved = resolveCollectionRelations(collection);
111
- for (const relation of Object.values(resolved)) {
112
- // Narrowed rather than probed: only a many-to-many has a junction,
113
- // and only after narrowing is `through` guaranteed complete.
114
- if (!isManyToMany(relation)) continue;
115
-
116
- const targetCollection: CollectionConfig | undefined = relation.target();
117
- if (!targetCollection) continue;
118
-
119
- const rawName = relation.through.table;
120
- // The CREATE TABLE path strips a schema prefix from the name but
121
- // still creates in "public"; the policies must target the same
122
- // table, so mirror that behaviour exactly.
123
- const table = rawName.includes(".") ? rawName.split(".").pop()! : rawName;
124
- const schema = "public";
125
-
126
- const source: JunctionDeclaringSide = {
127
- collection,
128
- junctionColumn: relation.through.sourceColumn,
129
- relation
130
- };
131
- const target: JunctionEndpoint = {
132
- collection: targetCollection,
133
- junctionColumn: relation.through.targetColumn
134
- };
135
-
136
- const existing = specs.get(table);
137
- if (!existing) {
138
- specs.set(table, {
139
- table,
140
- schema,
141
- endpoints: [source, target],
142
- declaringSides: [source]
143
- });
144
- } else if (!existing.declaringSides.some(s => s.collection === collection)) {
145
- existing.declaringSides.push(source);
146
- }
147
- }
148
- }
149
-
150
- return specs;
151
- }
152
-
153
- /**
154
- * A synthetic CollectionConfig standing in for the junction during policy
155
- * compilation and naming. Its two FK columns carry explicit `columnName`s so
156
- * `outerField` operands resolve to the exact columns the CREATE TABLE emitted,
157
- * whatever their casing.
158
- */
159
- export function getJunctionCollectionConfig(spec: JunctionSpec): CollectionConfig {
160
- const properties: Record<string, unknown> = {};
161
- for (const endpoint of spec.endpoints) {
162
- properties[endpoint.junctionColumn] = {
163
- type: "string",
164
- columnName: endpoint.junctionColumn
165
- };
166
- }
167
- return {
168
- slug: spec.table,
169
- name: spec.table,
170
- table: spec.table,
171
- schema: spec.schema,
172
- properties
173
- } as unknown as CollectionConfig;
174
- }
175
-
176
- /** The property marked as the row id (falls back to `id`). */
177
- function getIdPropertyName(collection: CollectionConfig): string {
178
- for (const [name, prop] of Object.entries(collection.properties ?? {})) {
179
- if (prop && typeof prop === "object" && "isId" in prop && (prop as { isId?: unknown }).isId) {
180
- return name;
181
- }
182
- }
183
- return "id";
184
- }
185
-
186
- /** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */
187
- function existsEndpoint(endpoint: JunctionEndpoint, extra?: PolicyExpression): PolicyExpression {
188
- const correlation = policy.compare(
189
- policy.field(getIdPropertyName(endpoint.collection)),
190
- "eq",
191
- policy.outerField(endpoint.junctionColumn)
192
- );
193
- return policy.existsIn({
194
- collection: endpoint.collection.slug,
195
- where: extra ? policy.and(correlation, extra) : correlation
196
- });
197
- }
198
-
199
- /**
200
- * Whether a parent-rule expression keeps its meaning when moved inside the
201
- * junction's `EXISTS` subquery — and the re-scoped copy if it does.
202
- *
203
- * Returns `null` when the rule cannot be embedded faithfully: `raw` SQL
204
- * anywhere (its `{column}` placeholders would bind to the junction), or an
205
- * `outerField` inside a nested `existsIn` (it would bind to the junction while
206
- * the author meant the parent, and no operand can express "the middle scope").
207
- * Top-level `outerField`s are rewritten to `field`, which is what they meant.
208
- */
209
- export function embedParentExpression(expr: PolicyExpression, depth = 0): PolicyExpression | null {
210
- switch (expr.kind) {
211
- case "raw":
212
- return null;
213
- case "and":
214
- case "or": {
215
- const parts: PolicyExpression[] = [];
216
- for (const child of expr.operands) {
217
- const embedded = embedParentExpression(child, depth);
218
- if (!embedded) return null;
219
- parts.push(embedded);
220
- }
221
- return expr.kind === "and" ? policy.and(...parts) : policy.or(...parts);
222
- }
223
- case "not": {
224
- const embedded = embedParentExpression(expr.operand, depth);
225
- return embedded ? policy.not(embedded) : null;
226
- }
227
- case "existsIn": {
228
- const where = embedParentExpression(expr.where, depth + 1);
229
- return where ? policy.existsIn({ collection: expr.collection, where }) : null;
230
- }
231
- case "compare": {
232
- const left = embedOperand(expr.left, depth);
233
- const right = embedOperand(expr.right, depth);
234
- if (!left || !right) return null;
235
- return { ...expr, left, right };
236
- }
237
- default:
238
- // Leaf expressions with no field references (true, false,
239
- // serverContext, authenticated, rolesOverlap, rolesContain) are
240
- // position-independent.
241
- return expr;
242
- }
243
- }
244
-
245
- /** Re-scope an operand, or return `null` if its binding cannot be preserved. */
246
- function embedOperand(operand: PolicyOperand, depth: number): PolicyOperand | null {
247
- if (operand.kind === "outerField") {
248
- // Outside a subquery, outerField ≡ field: the author meant their own
249
- // row, which after embedding is the EXISTS's joined table → field.
250
- if (depth === 0) return policy.field(operand.name);
251
- // Inside the author's own existsIn it meant the parent row; after
252
- // embedding it would bind to the junction. Not expressible.
253
- return null;
254
- }
255
- return operand;
256
- }
257
-
258
- /** Does the rule cover the `update` operation? */
259
- function coversUpdate(rule: SecurityRule): boolean {
260
- return getPolicyOperations(rule).some(op => op === "update" || op === "all");
261
- }
262
-
263
- /**
264
- * The full derived policy set for a junction table: the locked server/admin
265
- * baseline, the endpoint-visibility read grant, inherited write grants, and
266
- * inherited restrictive gates. Returns `[]` when every declaring collection set
267
- * `disableDefaultPolicies` — the junction is then the author's to police, and
268
- * stays locked (RLS is still enabled) until they write policies for it.
269
- */
270
- export function getJunctionSecurityRules(spec: JunctionSpec): SecurityRule[] {
271
- if (spec.declaringSides.every(side => isPostgresCollectionConfig(side.collection) && side.collection.disableDefaultPolicies)) {
272
- return [];
273
- }
274
-
275
- const rules: SecurityRule[] = [];
276
-
277
- // 1. Locked baseline — same shape and naming as every collection's.
278
- rules.push({
279
- name: `${spec.table}_default_admin_read`,
280
- operations: ["select"],
281
- condition: SERVER_OR_ADMIN_EXPR
282
- });
283
- rules.push({
284
- name: `${spec.table}_default_admin_write`,
285
- operations: ["insert", "update", "delete"],
286
- condition: SERVER_OR_ADMIN_EXPR,
287
- check: SERVER_OR_ADMIN_EXPR
288
- });
289
-
290
- // 2. Reads follow the endpoints: the edge is visible iff both rows are.
291
- // The EXISTS subqueries run under the caller's role, so each endpoint's
292
- // own RLS applies inside them — visibility is delegated, not copied.
293
- rules.push({
294
- name: `${spec.table}_default_edge_read`,
295
- operations: ["select"],
296
- condition: policy.and(
297
- existsEndpoint(spec.endpoints[0]),
298
- existsEndpoint(spec.endpoints[1])
299
- )
300
- });
301
-
302
- // 3. Writes follow the owning side's explicit update rules.
303
- const writeGrants: PolicyExpression[] = [];
304
- for (const side of spec.declaringSides) {
305
- const explicitRules = (isPostgresCollectionConfig(side.collection)
306
- ? side.collection.securityRules
307
- : undefined) ?? [];
308
- const updateRules = explicitRules.filter(coversUpdate);
309
-
310
- const permissive = updateRules.filter(r => r.mode !== "restrictive");
311
- const restrictive = updateRules.filter(r => r.mode === "restrictive");
312
-
313
- // Embed the restrictive gates first: if any of them cannot be carried
314
- // over, granting writes from this side would be looser than the parent
315
- // itself allows — so the whole side's grant is suppressed.
316
- const embeddedGates: PolicyExpression[] = [];
317
- let gatesEmbeddable = true;
318
- for (const gate of restrictive) {
319
- const using = securityRuleToConditions(gate).usingExpr;
320
- const embedded = using ? embedParentExpression(using) : null;
321
- if (!embedded) {
322
- gatesEmbeddable = false;
323
- break;
324
- }
325
- embeddedGates.push(embedded);
326
- }
327
- if (!gatesEmbeddable) continue;
328
-
329
- const grants: PolicyExpression[] = [];
330
- for (const rule of permissive) {
331
- const using = securityRuleToConditions(rule).usingExpr;
332
- const embedded = using ? embedParentExpression(using) : null;
333
- if (embedded) grants.push(embedded);
334
- }
335
- if (grants.length === 0) continue;
336
-
337
- // "May update the owning row": any permissive grant, AND every gate.
338
- const condition = embeddedGates.length > 0
339
- ? policy.and(policy.or(...grants), ...embeddedGates)
340
- : policy.or(...grants);
341
-
342
- writeGrants.push(existsEndpoint(side, condition));
343
- }
344
-
345
- if (writeGrants.length > 0) {
346
- rules.push({
347
- name: `${spec.table}_default_edge_write`,
348
- operations: ["insert", "update", "delete"],
349
- condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),
350
- check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)
351
- });
352
- }
353
-
354
- return rules;
355
- }
package/src/util/paths.ts DELETED
@@ -1,27 +0,0 @@
1
- export const COLLECTION_PATH_SEPARATOR = "::";
2
-
3
- /**
4
- * Remove the entity ids from a given path
5
- * `products/B44RG6APH/locales` => `products::locales`
6
- * @param path
7
- */
8
- export function stripCollectionPath(path: string): string {
9
- return segmentsToStrippedPath(fullPathToCollectionSegments(path));
10
- }
11
-
12
- export function segmentsToStrippedPath(paths: string[]) {
13
- if (paths.length === 1)
14
- return paths[0];
15
- return paths.reduce((a, b) => `${a}${COLLECTION_PATH_SEPARATOR}${b}`);
16
- }
17
-
18
- /**
19
- * Extract the collection path routes
20
- * `products/B44RG6APH/locales` => [`products`, `locales`]
21
- * @param path
22
- */
23
- export function fullPathToCollectionSegments(path: string): string[] {
24
- return path
25
- .split("/")
26
- .filter((e, i) => i % 2 === 0);
27
- }