@rebasepro/common 0.9.1-canary.fd3754b → 0.10.0

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.
@@ -0,0 +1,152 @@
1
+ import { CollectionConfig, SecurityRule, SecurityOperation, AuthCollectionConfig, PolicyExpression, isPostgresCollectionConfig, policy } from "@rebasepro/types";
2
+ import { getTableName } from "./relations";
3
+
4
+ /**
5
+ * Default RLS policies injected by the schema generator.
6
+ *
7
+ * Rebase's enforcement model is unified: authenticated (user-context) requests
8
+ * run under the restricted `rebase_user` role, so Postgres RLS binds *every*
9
+ * statement — reads and writes. A collection's `securityRules` are the whole
10
+ * authorization model. The server context (auth flows, migrations,
11
+ * `dataAsAdmin`) runs as the owner and bypasses RLS.
12
+ *
13
+ * Because RLS default-denies, every collection is **locked by default**: with
14
+ * no rules, only the server context and admins can touch it. The generator
15
+ * injects that safe baseline:
16
+ *
17
+ * **For every collection**
18
+ * 1. A permissive **server-or-admin SELECT** grant.
19
+ * 2. A permissive **server-or-admin write** grant (insert/update/delete).
20
+ *
21
+ * Author `securityRules` are permissive and OR together, so explicit rules only
22
+ * *broaden* access from this locked baseline (e.g. "users read/write their own
23
+ * rows").
24
+ *
25
+ * **For auth collections additionally**
26
+ * 3. A permissive **self SELECT** grant (`id = auth.uid()`), so users can read
27
+ * their own row (profile, session bootstrap) without every app re-declaring
28
+ * it.
29
+ * 4. A **restrictive** admin write gate. Restrictive policies are AND'd with
30
+ * every other policy, so a write is rejected unless the caller is an admin
31
+ * (or the server context) — even if the author also wrote a permissive rule
32
+ * such as "a user may edit their own row". Without this, a permissive owner
33
+ * rule would let a user change their own `roles`.
34
+ *
35
+ * The server context is recognised as `auth.uid() IS NULL` (`policy.serverContext()`)
36
+ * — the built-in flows that run without a user (signup, migrations) set no user
37
+ * GUC — which also lets the owner connection satisfy these policies even under
38
+ * FORCE RLS. A *user* request never reaches that state: an anonymous one carries
39
+ * `ANONYMOUS_USER_ID`, precisely so it cannot pass for the server here.
40
+ *
41
+ * Opt out with `disableDefaultPolicies: true` to take full responsibility for
42
+ * the collection's RLS.
43
+ */
44
+ // Expressed structurally (not as raw SQL) so the admin UI can evaluate it
45
+ // exactly — the framework's most security-critical policies must be reflected
46
+ // precisely, not left as un-evaluable raw clauses. Compiles to
47
+ // `auth.uid() IS NULL OR (string_to_array(auth.roles(), ',') && ARRAY['admin'])`.
48
+ //
49
+ // `serverContext()`, emphatically not `not(authenticated())`: the server arm of
50
+ // this grant must match the server context and nothing else. Anonymous visitors
51
+ // are not signed in either, so a negated `authenticated()` would hand them the
52
+ // server-or-admin grant on every collection's default policy.
53
+ const SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(
54
+ policy.serverContext(),
55
+ policy.rolesOverlap(["admin"])
56
+ );
57
+
58
+ /** Write operations that must be admin-gated by default on auth collections. */
59
+ const DEFAULT_GUARDED_OPS: SecurityOperation[] = ["insert", "update", "delete"];
60
+
61
+ /** Whether a collection is flagged as an authentication collection. */
62
+ function isAuthCollection(collection: CollectionConfig): boolean {
63
+ const auth = collection.auth;
64
+ return auth === true || (typeof auth === "object" && (auth as AuthCollectionConfig)?.enabled === true);
65
+ }
66
+
67
+ /** The property marked as the row id (falls back to `id`). */
68
+ function getIdPropertyName(collection: CollectionConfig): string {
69
+ for (const [name, prop] of Object.entries(collection.properties ?? {})) {
70
+ if (prop && typeof prop === "object" && "isId" in prop && (prop as { isId?: unknown }).isId) {
71
+ return name;
72
+ }
73
+ }
74
+ return "id";
75
+ }
76
+
77
+ /**
78
+ * Returns the security rules that should be applied to a collection: the
79
+ * author's explicit `securityRules` plus the framework defaults described in
80
+ * the module doc (baseline server/admin read for all collections; self-read
81
+ * and the admin write gate for auth collections).
82
+ *
83
+ * Collections that opt out via `disableDefaultPolicies` are returned unchanged.
84
+ */
85
+ export function getEffectiveSecurityRules(collection: CollectionConfig): SecurityRule[] {
86
+ const explicit = [...((isPostgresCollectionConfig(collection) ? collection.securityRules : undefined) ?? [])];
87
+
88
+ if (collection.disableDefaultPolicies) {
89
+ return explicit;
90
+ }
91
+
92
+ const tableName = getTableName(collection);
93
+ const injected: SecurityRule[] = [];
94
+
95
+ // Baseline read + write: the server context and admins can always operate.
96
+ // RLS default-denies under the user role, so without these a rule-less
97
+ // collection would be locked to everyone — including the admin studio.
98
+ // Author rules are permissive and broaden access from here.
99
+ injected.push({
100
+ name: `${tableName}_default_admin_read`,
101
+ operations: ["select"],
102
+ condition: SERVER_OR_ADMIN_EXPR
103
+ });
104
+ injected.push({
105
+ name: `${tableName}_default_admin_write`,
106
+ operations: [...DEFAULT_GUARDED_OPS],
107
+ condition: SERVER_OR_ADMIN_EXPR,
108
+ check: SERVER_OR_ADMIN_EXPR
109
+ });
110
+
111
+ if (isAuthCollection(collection)) {
112
+ // Self-read: a user can always read their own row.
113
+ injected.push({
114
+ name: `${tableName}_default_self_read`,
115
+ operations: ["select"],
116
+ condition: policy.compare(policy.field(getIdPropertyName(collection)), "eq", policy.authUid())
117
+ });
118
+
119
+ // Restrictive gate: AND'd with all other policies, so no permissive rule
120
+ // (e.g. an owner "edit your own row" rule) can let a non-admin change
121
+ // privileged columns like `roles`.
122
+ injected.push({
123
+ name: `${tableName}_require_admin_write`,
124
+ mode: "restrictive",
125
+ operations: [...DEFAULT_GUARDED_OPS],
126
+ condition: SERVER_OR_ADMIN_EXPR,
127
+ check: SERVER_OR_ADMIN_EXPR
128
+ });
129
+ }
130
+
131
+ return [...explicit, ...injected];
132
+ }
133
+
134
+ /**
135
+ * The framework defaults that {@link getEffectiveSecurityRules} would add to a
136
+ * collection, without the author's own rules.
137
+ *
138
+ * These policies appear in the database under names the author never wrote, and
139
+ * a permissive policy ORs with every other permissive policy — so someone
140
+ * reading their `securityRules` and then the real ACL sees more access than they
141
+ * declared. Dropping them by hand does nothing either: `db push` is declarative,
142
+ * so the next push asserts them again. Callers use this to say, in the generated
143
+ * DDL, which policies are injected and how to take them off.
144
+ */
145
+ export function getInjectedSecurityRules(collection: CollectionConfig): SecurityRule[] {
146
+ if (collection.disableDefaultPolicies) return [];
147
+
148
+ const explicitCount = ((isPostgresCollectionConfig(collection) ? collection.securityRules : undefined) ?? []).length;
149
+ // getEffectiveSecurityRules appends the defaults after the author's rules,
150
+ // so everything past the author's count is injected.
151
+ return getEffectiveSecurityRules(collection).slice(explicitCount);
152
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Row identity: the address of a row, and how to derive it.
3
+ *
4
+ * Postgres has no `id`. A row is identified by its primary key — one or more
5
+ * columns, with any names and any types. `id` is something we synthesize on top
6
+ * of that: a single string token, because the admin needs *one* value it can put
7
+ * in a URL (`/products/1:::2`), use as a cache key, and hang a relation ref off.
8
+ *
9
+ * That token is an address, not data. It is derived from the row's columns and
10
+ * never stored in them — a row is exactly its columns, with their real types.
11
+ * Writing the address back into the row is what used to rename primary keys
12
+ * (`sku` → `id`) and restringify them (`42` → `"42"`) on the way out.
13
+ *
14
+ * These live in `common` because both sides need them and must agree exactly:
15
+ * the driver parses an incoming address back into key columns, and the admin
16
+ * derives the address from a row it was served.
17
+ */
18
+
19
+ /**
20
+ * A primary-key column: its name, the type it round-trips as, and whether it is
21
+ * a UUID (which is a string despite sometimes being described as an id "number").
22
+ */
23
+ export interface PrimaryKeyInfo {
24
+ fieldName: string;
25
+ type: "string" | "number";
26
+ isUUID?: boolean;
27
+ }
28
+
29
+ /** Separator between the parts of a composite address. */
30
+ export const COMPOSITE_ID_SEPARATOR = ":::";
31
+
32
+ /**
33
+ * Derive a row's address from its key columns.
34
+ *
35
+ * Single key → the value as a string. Composite → each part joined by
36
+ * {@link COMPOSITE_ID_SEPARATOR}, in primary-key order, which is what
37
+ * {@link parseIdValues} expects to invert.
38
+ */
39
+ export function buildCompositeId(values: Record<string, unknown>, primaryKeys: PrimaryKeyInfo[]): string {
40
+ if (primaryKeys.length === 0) {
41
+ return "";
42
+ }
43
+ if (primaryKeys.length === 1) {
44
+ return String(values[primaryKeys[0].fieldName] ?? "");
45
+ }
46
+ return primaryKeys.map(pk => String(values[pk.fieldName] ?? "")).join(COMPOSITE_ID_SEPARATOR);
47
+ }
48
+
49
+ /**
50
+ * Invert {@link buildCompositeId}: turn an address back into key columns, each
51
+ * coerced to the type its column actually round-trips as.
52
+ *
53
+ * This is the boundary where a URL segment becomes a query parameter, so a
54
+ * malformed address must throw rather than silently produce a query that
55
+ * matches the wrong row (or none).
56
+ */
57
+ export function parseIdValues(idValue: string | number, primaryKeys: PrimaryKeyInfo[]): Record<string, string | number> {
58
+ const result: Record<string, string | number> = {};
59
+
60
+ if (primaryKeys.length === 0) {
61
+ return result;
62
+ }
63
+
64
+ if (primaryKeys.length === 1) {
65
+ const pk = primaryKeys[0];
66
+ if (pk.type === "number" && !pk.isUUID) {
67
+ const parsed = typeof idValue === "number" ? idValue : parseInt(String(idValue), 10);
68
+ if (isNaN(parsed)) {
69
+ throw new Error(`Invalid numeric ID: ${idValue}`);
70
+ }
71
+ result[pk.fieldName] = parsed;
72
+ } else {
73
+ result[pk.fieldName] = String(idValue);
74
+ }
75
+ return result;
76
+ }
77
+
78
+ // Composite key
79
+ const parts = String(idValue).split(COMPOSITE_ID_SEPARATOR);
80
+ if (parts.length !== primaryKeys.length) {
81
+ throw new Error(`Composite ID parts mismatch. Expected ${primaryKeys.length}, got ${parts.length} for ID: ${idValue}`);
82
+ }
83
+
84
+ for (let i = 0; i < primaryKeys.length; i++) {
85
+ const pk = primaryKeys[i];
86
+ const val = parts[i];
87
+ if (pk.type === "number" && !pk.isUUID) {
88
+ const parsed = parseInt(val, 10);
89
+ if (isNaN(parsed)) {
90
+ throw new Error(`Invalid numeric ID component: ${val}`);
91
+ }
92
+ result[pk.fieldName] = parsed;
93
+ } else {
94
+ result[pk.fieldName] = val;
95
+ }
96
+ }
97
+
98
+ return result;
99
+ }
100
+
101
+ /**
102
+ * The primary keys of a collection, as declared by its properties.
103
+ *
104
+ * This is the only tier both sides can read, because it is the only one written
105
+ * in the config: the postgres driver can also infer keys from the Drizzle
106
+ * schema, which the browser never sees and is never sent — the admin compiles
107
+ * the collection files into its own bundle rather than being served them. A key
108
+ * that lives only in the Drizzle schema is therefore invisible here, and the
109
+ * server says so at boot (`warnOnKeysTheAdminCannotResolve`) naming the `isId`
110
+ * to add.
111
+ *
112
+ * Returns an empty array when a collection declares none, which callers must
113
+ * treat as "not addressable" rather than defaulting to `id`: guessing a key
114
+ * that is not the real one produces confidently wrong addresses.
115
+ */
116
+ export function getDeclaredPrimaryKeys(collection: {
117
+ properties?: Record<string, unknown>;
118
+ }): PrimaryKeyInfo[] {
119
+ const properties = collection.properties;
120
+ if (!properties) return [];
121
+
122
+ const keys: PrimaryKeyInfo[] = [];
123
+ for (const [fieldName, propRaw] of Object.entries(properties)) {
124
+ const prop = propRaw as { type?: string; isId?: unknown } | undefined;
125
+ if (!prop || typeof prop !== "object") continue;
126
+ if (!("isId" in prop) || !prop.isId) continue;
127
+ keys.push({
128
+ fieldName,
129
+ type: prop.type === "number" ? "number" : "string",
130
+ isUUID: prop.isId === "uuid"
131
+ });
132
+ }
133
+ return keys;
134
+ }
135
+
136
+ /**
137
+ * The keys to address a collection's rows with, resolved the way the driver
138
+ * resolves them — minus the tier the browser cannot reach.
139
+ *
140
+ * The postgres driver tries, in order: properties marked `isId`; the primary
141
+ * keys of the Drizzle schema; and finally a column literally named `id`. Only
142
+ * the first and last are visible in a `CollectionConfig`, which is what both
143
+ * sides share.
144
+ *
145
+ * So the two agree except on a collection that declares no `isId` and whose key
146
+ * is known only to Drizzle. There, the driver reads the real key, and this
147
+ * either resolves nothing (reported to the console by the caller) or — if the
148
+ * table happens to have an unrelated `id` property — resolves `id`, which is
149
+ * the wrong key and cannot be detected from here: the addresses look right and
150
+ * route wrong. Only the config can settle it, so the server names both cases
151
+ * at boot (`warnOnKeysTheAdminCannotResolve`) with the `isId` to add.
152
+ */
153
+ export function resolvePrimaryKeys(collection: {
154
+ properties?: Record<string, unknown>;
155
+ }): PrimaryKeyInfo[] {
156
+ const declared = getDeclaredPrimaryKeys(collection);
157
+ if (declared.length > 0) return declared;
158
+
159
+ const idProp = collection.properties?.id as { type?: string } | undefined;
160
+ if (idProp && typeof idProp === "object") {
161
+ return [{ fieldName: "id",
162
+ type: idProp.type === "number" ? "number" : "string" }];
163
+ }
164
+
165
+ return [];
166
+ }
package/src/util/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from "./collections";
2
2
  export * from "./common";
3
3
  export * from "./entities";
4
+ export * from "./identity";
4
5
  export * from "./enums";
5
6
  export * from "./paths";
6
7
  export * from "./resolutions";
@@ -13,6 +14,8 @@ export * from "./builders";
13
14
  export * from "./storage";
14
15
  export * from "./callbacks";
15
16
  export * from "./relations";
17
+ export * from "./auth-default-policies";
18
+ export * from "./junction-policies";
16
19
  export * from "./conditions";
17
20
  export * from "./navigation_utils";
18
21
  export * from "./filter-operator-resolution";
@@ -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
+ }