@pgxsinkit/contracts 0.1.32 → 0.1.36

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 (44) hide show
  1. package/README.md +13 -0
  2. package/dist/apply-strategy.d.ts +35 -0
  3. package/dist/apply-strategy.d.ts.map +1 -0
  4. package/dist/config.d.ts +210 -32
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/convergence-model.d.ts +106 -0
  7. package/dist/convergence-model.d.ts.map +1 -0
  8. package/dist/fingerprint.d.ts +136 -0
  9. package/dist/fingerprint.d.ts.map +1 -0
  10. package/dist/index.d.ts +7 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +5222 -3494
  13. package/dist/index.js.map +37 -30
  14. package/dist/mutation.d.ts +78 -0
  15. package/dist/mutation.d.ts.map +1 -1
  16. package/dist/projection.d.ts +88 -0
  17. package/dist/projection.d.ts.map +1 -0
  18. package/dist/registry-diff.d.ts +50 -0
  19. package/dist/registry-diff.d.ts.map +1 -0
  20. package/dist/registry.d.ts +253 -2
  21. package/dist/registry.d.ts.map +1 -1
  22. package/dist/runtime.d.ts +21 -1
  23. package/dist/runtime.d.ts.map +1 -1
  24. package/dist/sql-defaults.d.ts +27 -0
  25. package/dist/sql-defaults.d.ts.map +1 -0
  26. package/dist/sql-identifier.d.ts +26 -0
  27. package/dist/sql-identifier.d.ts.map +1 -0
  28. package/dist/supabase-rls.d.ts +99 -3
  29. package/dist/supabase-rls.d.ts.map +1 -1
  30. package/package.json +8 -3
  31. package/skills/registry-authoring/SKILL.md +376 -0
  32. package/src/apply-strategy.ts +124 -0
  33. package/src/config.ts +254 -106
  34. package/src/convergence-model.ts +190 -0
  35. package/src/fingerprint.ts +265 -0
  36. package/src/index.ts +7 -0
  37. package/src/mutation.ts +94 -2
  38. package/src/projection.ts +150 -0
  39. package/src/registry-diff.ts +215 -0
  40. package/src/registry.ts +751 -23
  41. package/src/runtime.ts +21 -1
  42. package/src/sql-defaults.ts +29 -0
  43. package/src/sql-identifier.ts +130 -0
  44. package/src/supabase-rls.ts +515 -37
@@ -1,5 +1,15 @@
1
- import { sql } from "drizzle-orm";
2
- import { pgPolicy, type PgRole } from "drizzle-orm/pg-core";
1
+ import { and, eq, getTableName, or, sql, type AnyColumn, type SQL } from "drizzle-orm";
2
+ import { PgDialect, pgPolicy, type AnyPgTable, type PgRole } from "drizzle-orm/pg-core";
3
+
4
+ import { c, DENY_ALL, type JwtClaims } from "./config";
5
+
6
+ // Render a typed fragment to inline-literal SQL text (CREATE POLICY DDL cannot carry `$n` binds).
7
+ // The tier-② discipline for the text builders below: values enter as typed `${value}` interpolations
8
+ // and drizzle owns the escaping; only the claim-extraction leaves stay raw text.
9
+ const textDialect = new PgDialect();
10
+ function renderInlineSql(fragment: SQL): string {
11
+ return textDialect.sqlToQuery(fragment.inlineParams()).sql;
12
+ }
3
13
 
4
14
  type SupabaseOwnerOrAdminPolicyKind = "select" | "insert" | "update" | "delete";
5
15
 
@@ -9,15 +19,24 @@ type SupabaseOwnerOrAdminPolicyShape = {
9
19
  withCheck: boolean;
10
20
  };
11
21
 
22
+ // Options for the raw predicate *text* builder (`buildSupabaseOwnerOrAdminPredicateSqlText`) — the
23
+ // documented escape hatch that returns the predicate as a SQL string (for a hand-written trigger or
24
+ // migration). It takes a column *name* because text has no column object. The native policy builder
25
+ // below takes a real Drizzle column instead.
12
26
  export type SupabaseOwnerOrAdminPredicateOptions = {
13
27
  ownerSqlColumn?: string;
14
28
  adminRoleName?: string;
15
29
  subjectCastType?: string;
16
30
  };
17
31
 
18
- export type SupabaseOwnerOrAdminNativePoliciesOptions = SupabaseOwnerOrAdminPredicateOptions & {
19
- tableName: string;
32
+ export type SupabaseOwnerOrAdminNativePoliciesOptions = {
33
+ /** Owner column on the governed row (e.g. `authors.ownerId`). The governed table name is derived from it. */
34
+ ownerColumn: AnyColumn;
20
35
  role: PgRole;
36
+ /** Role value (in `app_metadata.roles`) that bypasses ownership (default "admin"). */
37
+ adminRoleName?: string;
38
+ /** SQL type the JWT subject is cast to before comparison (default "uuid"). */
39
+ subjectCastType?: string;
21
40
  };
22
41
 
23
42
  const defaultOwnerSqlColumn = "owner_id";
@@ -61,46 +80,56 @@ function assertTypeName(value: string, label: string): void {
61
80
  }
62
81
  }
63
82
 
64
- function escapeSqlLiteral(value: string): string {
65
- return value.replace(/'/g, "''");
66
- }
67
-
68
83
  function buildOwnerOrAdminPolicyName(tableName: string, command: SupabaseOwnerOrAdminPolicyKind) {
69
84
  return `${tableName}_${command}_owner_or_admin`;
70
85
  }
71
86
 
72
- function normalizePredicateOptions(options: SupabaseOwnerOrAdminPredicateOptions = {}) {
73
- const ownerSqlColumn = options.ownerSqlColumn ?? defaultOwnerSqlColumn;
74
- const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;
75
- const subjectCastType = options.subjectCastType ?? defaultSubjectCastType;
87
+ // ---------------------------------------------------------------------------
88
+ // Shared predicate leaves (used by both policy families). RLS is the *write* path
89
+ // (Postgres), so columns may serialize qualified — unlike the Electric read `where`,
90
+ // which needs bare columns. The only bits that stay raw `sql` are genuinely-Postgres
91
+ // expressions with no Drizzle operator: the JWT-subject `(select current_setting(...)::type)`
92
+ // and the admin-roles `EXISTS`. Literal values use `eq(col, value).inlineParams()` so the
93
+ // value is inlined into the DDL — a bare `$n` is something `CREATE POLICY` cannot carry.
94
+ // ---------------------------------------------------------------------------
76
95
 
77
- assertIdentifier(ownerSqlColumn, "ownerSqlColumn");
78
- assertTypeName(subjectCastType, "subjectCastType");
79
-
80
- return {
81
- ownerSqlColumn,
82
- adminRoleName,
83
- subjectCastType,
84
- };
96
+ // The governed table name (for policy identifiers) derived from a built Drizzle column, so renaming
97
+ // the table renames its policies. Columns built inside `defineSyncTable`'s `extras` callback carry
98
+ // their `.table` — which is where these builders are meant to be called (the table object does not
99
+ // yet exist when its own `policies:` array would be built).
100
+ function tableNameForColumn(column: AnyColumn, label: string): string {
101
+ const table = (column as { table?: AnyPgTable }).table;
102
+ if (!table) {
103
+ throw new Error(
104
+ `${label} must be a built Drizzle column carrying its table — call this builder inside defineSyncTable's \`extras\` callback`,
105
+ );
106
+ }
107
+ return getTableName(table);
85
108
  }
86
109
 
87
- function toPredicateOptions(options: SupabaseOwnerOrAdminPredicateOptions): SupabaseOwnerOrAdminPredicateOptions {
88
- return {
89
- ...(options.ownerSqlColumn !== undefined ? { ownerSqlColumn: options.ownerSqlColumn } : {}),
90
- ...(options.adminRoleName !== undefined ? { adminRoleName: options.adminRoleName } : {}),
91
- ...(options.subjectCastType !== undefined ? { subjectCastType: options.subjectCastType } : {}),
92
- };
110
+ // The JWT subject as a Postgres expression (irreducibly raw: `current_setting` + cast). Used as the
111
+ // right-hand side of `eq(ownerColumn, subject)` — eq splices an SQL fragment verbatim (no bound
112
+ // param), so the DDL carries the literal expression, not a `$n` CREATE POLICY cannot bind. Wrapped in
113
+ // a scalar subquery — the Supabase RLS performance idiom: the stable `current_setting` expression is
114
+ // evaluated once per statement (InitPlan), not once per row.
115
+ function buildSubjectSql(subjectCastType: string): SQL {
116
+ assertTypeName(subjectCastType, "subjectCastType");
117
+ return sql.raw(`(select ${buildSubjectSqlText(subjectCastType)})`);
93
118
  }
94
119
 
95
- export function buildSupabaseOwnerOrAdminPredicateSqlText(options: SupabaseOwnerOrAdminPredicateOptions = {}): string {
96
- const normalized = normalizePredicateOptions(options);
97
-
98
- return `
99
- ${normalized.ownerSqlColumn} = coalesce(
120
+ function buildSubjectSqlText(subjectCastType: string): string {
121
+ return `coalesce(
100
122
  nullif(current_setting('request.jwt.claim.sub', true), ''),
101
123
  (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')
102
- )::${normalized.subjectCastType}
103
- OR EXISTS (
124
+ )::${subjectCastType}`;
125
+ }
126
+
127
+ // The admin-bypass test: `app_metadata.roles` (from the JWT claims) contains `adminRoleName`. No
128
+ // column reference and no recursion risk, so it is inlined as text (shared by the text builder and
129
+ // the native builder). The role value enters as a typed interpolation (drizzle owns the escaping);
130
+ // the claim-extraction body is the allowed raw leaf.
131
+ function buildAdminRoleExistsSqlText(adminRoleName: string): string {
132
+ return renderInlineSql(sql`EXISTS (
104
133
  SELECT 1
105
134
  FROM jsonb_array_elements_text(
106
135
  COALESCE(
@@ -113,16 +142,51 @@ export function buildSupabaseOwnerOrAdminPredicateSqlText(options: SupabaseOwner
113
142
  '[]'::jsonb
114
143
  )
115
144
  ) AS assigned_role(role_name_value)
116
- WHERE assigned_role.role_name_value = '${escapeSqlLiteral(normalized.adminRoleName)}'
117
- )
145
+ WHERE assigned_role.role_name_value = ${adminRoleName}
146
+ )`);
147
+ }
148
+
149
+ function normalizePredicateOptions(options: SupabaseOwnerOrAdminPredicateOptions = {}) {
150
+ const ownerSqlColumn = options.ownerSqlColumn ?? defaultOwnerSqlColumn;
151
+ const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;
152
+ const subjectCastType = options.subjectCastType ?? defaultSubjectCastType;
153
+
154
+ assertIdentifier(ownerSqlColumn, "ownerSqlColumn");
155
+ assertTypeName(subjectCastType, "subjectCastType");
156
+
157
+ return {
158
+ ownerSqlColumn,
159
+ adminRoleName,
160
+ subjectCastType,
161
+ };
162
+ }
163
+
164
+ /**
165
+ * The owner-or-admin predicate as raw SQL **text** — the escape hatch for when you need the predicate
166
+ * as a string (a hand-written trigger, a manual migration). For attaching RLS to a Drizzle table,
167
+ * prefer `buildSupabaseOwnerOrAdminNativePolicies`, which takes the real column and is rename-tracked.
168
+ */
169
+ export function buildSupabaseOwnerOrAdminPredicateSqlText(options: SupabaseOwnerOrAdminPredicateOptions = {}): string {
170
+ const normalized = normalizePredicateOptions(options);
171
+
172
+ return `
173
+ ${normalized.ownerSqlColumn} = ${buildSubjectSqlText(normalized.subjectCastType)}
174
+ OR ${buildAdminRoleExistsSqlText(normalized.adminRoleName)}
118
175
  `;
119
176
  }
120
177
 
178
+ // owner-or-admin predicate built from the real Drizzle column: `eq(ownerColumn, subject)` (qualified,
179
+ // rename-tracked) OR the raw admin-roles EXISTS (no column, no Drizzle operator). The single boolean
180
+ // is `or(...)`.
121
181
  export function buildSupabaseOwnerOrAdminNativePolicies(options: SupabaseOwnerOrAdminNativePoliciesOptions) {
122
- const predicate = sql.raw(buildSupabaseOwnerOrAdminPredicateSqlText(toPredicateOptions(options)));
182
+ const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;
183
+ const subject = buildSubjectSql(options.subjectCastType ?? defaultSubjectCastType);
184
+ const adminExists = sql.raw(buildAdminRoleExistsSqlText(adminRoleName));
185
+ const predicate = or(eq(options.ownerColumn, subject), adminExists)!;
186
+ const tableName = tableNameForColumn(options.ownerColumn, "ownerColumn");
123
187
 
124
188
  return ownerOrAdminPolicyShapes.map((shape) =>
125
- pgPolicy(buildOwnerOrAdminPolicyName(options.tableName, shape.command), {
189
+ pgPolicy(buildOwnerOrAdminPolicyName(tableName, shape.command), {
126
190
  as: "permissive",
127
191
  for: shape.command,
128
192
  to: options.role,
@@ -139,3 +203,417 @@ export const supabaseOwnerOrAdminDefaults = {
139
203
  adminRoleName: defaultAdminRoleName,
140
204
  subjectCastType: defaultSubjectCastType,
141
205
  } as const;
206
+
207
+ // ---------------------------------------------------------------------------
208
+ // Membership-scoped policies (generic). A row belongs to a *container* and is
209
+ // visible/writable through membership of that container — not just ownership.
210
+ // This is the readwrite counterpart to a membership row-filter: every member of
211
+ // the container may read the row (fan-out to non-owners); only the owner may
212
+ // create it (as themselves) and edit it, while a container *manager* may moderate
213
+ // any row. Domain-agnostic: the container, membership table, and manager role are
214
+ // all parameters.
215
+ //
216
+ // The container, membership, and owner references are **real Drizzle columns/tables**
217
+ // (not name strings), so the policy tracks the schema — a column or table rename is a
218
+ // compile error, and the governed table name is *derived* from the container column
219
+ // (no redundant `tableName` to drift). Predicate structure is built with Drizzle
220
+ // operators (`and`/`or`/`eq`, with `.inlineParams()` on the `'manager'` / `false` literals so
221
+ // they inline instead of becoming a `$n` CREATE POLICY cannot carry); only the irreducibly-Postgres
222
+ // leaves stay `sql`: the `IN (subquery)` containment (Drizzle's `inArray` cannot wrap a raw subquery)
223
+ // and the `(select current_setting(...)::type)` JWT-subject expression (wrapped in a scalar subquery —
224
+ // the Supabase per-statement-eval RLS perf idiom). Columns serialize qualified
225
+ // (`"work_items"."workspace_id"`) — fine for Postgres RLS (the write path, unlike Electric's bare rule).
226
+ // ---------------------------------------------------------------------------
227
+
228
+ type MembershipPolicyKind = "select" | "insert" | "update" | "delete";
229
+
230
+ export type SupabaseMembershipPredicateColumns = {
231
+ /** Column on the governed row naming its container (e.g. `workItems.workspaceId`). */
232
+ containerColumn: AnyColumn;
233
+ /** Membership link table (e.g. the `workspace_members` table). */
234
+ membershipTable: AnyPgTable;
235
+ /** Container column on the membership link table (e.g. `workspaceMembers.workspaceId`). */
236
+ membershipContainerColumn: AnyColumn;
237
+ /** Subject (member) column on the membership link table, compared to the JWT sub. */
238
+ membershipSubjectColumn: AnyColumn;
239
+ /** Owner column on the governed row (e.g. `workItems.ownerId`). */
240
+ ownerColumn: AnyColumn;
241
+ /** Optional role column on the membership link enabling manager moderation. */
242
+ managerRoleColumn?: AnyColumn;
243
+ /** Role value that grants moderation (default "manager"); only used with managerRoleColumn. */
244
+ managerRoleValue?: string;
245
+ /** SQL type the JWT subject is cast to before comparison (default "uuid"). */
246
+ subjectCastType?: string;
247
+ };
248
+
249
+ // Optional write-state gate (generic). When supplied, INSERT and UPDATE are additionally gated on
250
+ // mutable state: a *locked* container admits writes only from a manager (e.g. a frozen discussion
251
+ // thread), and a *muted* member may not write at all. SELECT and DELETE are unaffected — reads and
252
+ // moderation deletes still flow. Domain-agnostic: the container/lock and membership/mute columns are
253
+ // parameters. Requires managerRoleColumn (managers bypass the lock).
254
+ export type SupabaseMembershipWriteGateColumns = {
255
+ /** Container table holding the lock flag (e.g. the `workspaces` table). */
256
+ containerTable: AnyPgTable;
257
+ /** PK column on the container table the governed row's container column references (e.g. `workspaces.id`). */
258
+ containerPkColumn: AnyColumn;
259
+ /** Boolean column on the container table; when true, only a manager may write (e.g. `workspaces.locked`). */
260
+ containerLockColumn: AnyColumn;
261
+ /** Boolean column on the membership table; when true, that member may not write (e.g. `workspaceMembers.muted`). */
262
+ membershipMutedColumn: AnyColumn;
263
+ };
264
+
265
+ export type SupabaseMembershipNativePoliciesOptions = SupabaseMembershipPredicateColumns & {
266
+ role: PgRole;
267
+ /** Optional write-state gate applied to INSERT and UPDATE only. */
268
+ writeGate?: SupabaseMembershipWriteGateColumns;
269
+ };
270
+
271
+ const defaultManagerRoleValue = "manager";
272
+
273
+ const membershipPolicyShapes: { command: MembershipPolicyKind; using: boolean; withCheck: boolean }[] = [
274
+ { command: "select", using: true, withCheck: false },
275
+ { command: "insert", using: false, withCheck: true },
276
+ { command: "update", using: true, withCheck: true },
277
+ { command: "delete", using: true, withCheck: false },
278
+ ];
279
+
280
+ type NormalizedMembershipColumns = SupabaseMembershipPredicateColumns & {
281
+ managerRoleValue: string;
282
+ subjectCastType: string;
283
+ };
284
+
285
+ function normalizeMembershipColumns(options: SupabaseMembershipPredicateColumns): NormalizedMembershipColumns {
286
+ return {
287
+ ...options,
288
+ managerRoleValue: options.managerRoleValue ?? defaultManagerRoleValue,
289
+ subjectCastType: options.subjectCastType ?? defaultSubjectCastType,
290
+ };
291
+ }
292
+
293
+ // Containment form (not a correlated EXISTS): the governed row's container column must be in the set
294
+ // of containers the subject belongs to. Two reasons it is `= ANY(ARRAY(subquery))` and not
295
+ // `IN (subquery)`, both load-bearing:
296
+ // 1. Correctness — the subquery stays uncorrelated (its `WHERE` references only the subject), so the
297
+ // membership table's same-named column can't shadow the outer container column. A correlated
298
+ // `EXISTS (… WHERE m.container = container …)` would collapse the correlation.
299
+ // 2. Performance — for a runtime-resolved set (the subject comes from `current_setting`, opaque to
300
+ // the planner) `IN (subquery)` is costed as a hashed semi-join → **sequential scan** of the
301
+ // governed table; `= ANY(ARRAY(subquery))` materializes the set once (InitPlan) and the
302
+ // ScalarArrayOp drives a **bitmap index scan**. At scale that is ~25-45× faster (the rls-read
303
+ // perf track proves it). `inArray` can't wrap a raw subquery, so this stays `sql`.
304
+ function membershipMatch(cols: NormalizedMembershipColumns, subject: SQL, requireManager: boolean): SQL {
305
+ const subjectIsMember = eq(cols.membershipSubjectColumn, subject);
306
+ const where =
307
+ requireManager && cols.managerRoleColumn
308
+ ? and(subjectIsMember, eq(cols.managerRoleColumn, cols.managerRoleValue).inlineParams())!
309
+ : subjectIsMember;
310
+
311
+ return sql`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${where}))`;
312
+ }
313
+
314
+ /** owner-or-manager predicate (edit / moderate). */
315
+ function ownerOrManager(cols: NormalizedMembershipColumns, subject: SQL): SQL {
316
+ const owner = eq(cols.ownerColumn, subject);
317
+ return cols.managerRoleColumn ? or(owner, membershipMatch(cols, subject, true))! : owner;
318
+ }
319
+
320
+ // write-state gate: ((container not locked) OR caller is a manager) AND caller's membership not muted.
321
+ // Same `= ANY(ARRAY(subquery))` containment discipline as membershipMatch (uncorrelated set, index-scan
322
+ // friendly), so the container/membership tables can reuse their own column names without shadowing the
323
+ // governed row's container column.
324
+ function membershipWriteGate(
325
+ cols: NormalizedMembershipColumns,
326
+ gate: SupabaseMembershipWriteGateColumns,
327
+ subject: SQL,
328
+ ): SQL {
329
+ const unlocked = sql`${cols.containerColumn} = any(array(select ${gate.containerPkColumn} from ${gate.containerTable} where ${eq(gate.containerLockColumn, false).inlineParams()}))`;
330
+ const notMuted = sql`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${and(eq(cols.membershipSubjectColumn, subject), eq(gate.membershipMutedColumn, false).inlineParams())}))`;
331
+ return and(or(unlocked, membershipMatch(cols, subject, true))!, notMuted)!;
332
+ }
333
+
334
+ export function buildSupabaseMembershipNativePolicies(options: SupabaseMembershipNativePoliciesOptions) {
335
+ const cols = normalizeMembershipColumns(options);
336
+ const subject = buildSubjectSql(cols.subjectCastType);
337
+ const tableName = tableNameForColumn(cols.containerColumn, "containerColumn");
338
+
339
+ const memberPredicate = membershipMatch(cols, subject, false);
340
+ const ownerAndMember = and(eq(cols.ownerColumn, subject), memberPredicate)!;
341
+ const ownerOrManagerPredicate = ownerOrManager(cols, subject);
342
+
343
+ let writeGateClause: SQL | null = null;
344
+ if (options.writeGate) {
345
+ if (!cols.managerRoleColumn) {
346
+ throw new Error("writeGate requires managerRoleColumn so a manager can write into a locked container");
347
+ }
348
+ writeGateClause = membershipWriteGate(cols, options.writeGate, subject);
349
+ }
350
+
351
+ const gatedForWrite = (base: SQL): SQL => (writeGateClause ? and(base, writeGateClause)! : base);
352
+
353
+ const predicateFor = (command: MembershipPolicyKind): SQL => {
354
+ switch (command) {
355
+ case "select":
356
+ return memberPredicate;
357
+ case "insert":
358
+ return gatedForWrite(ownerAndMember);
359
+ case "update":
360
+ return gatedForWrite(ownerOrManagerPredicate);
361
+ case "delete":
362
+ return ownerOrManagerPredicate;
363
+ }
364
+ };
365
+
366
+ return membershipPolicyShapes.map((shape) => {
367
+ const predicate = predicateFor(shape.command);
368
+
369
+ return pgPolicy(`${tableName}_${shape.command}_membership`, {
370
+ as: "permissive",
371
+ for: shape.command,
372
+ to: options.role,
373
+ ...(shape.using ? { using: predicate } : {}),
374
+ ...(shape.withCheck ? { withCheck: predicate } : {}),
375
+ });
376
+ });
377
+ }
378
+
379
+ // ---------------------------------------------------------------------------
380
+ // Grant-scope policies (generic). Authorization is carried IN THE JWT, not a DB
381
+ // table: `app_metadata.authorization.grants` is an array of
382
+ // `{ role, scope: { kind, <kind>Id } }` minted into the token. A row is visible
383
+ // when its scope column (e.g. `offering_id`) appears among the caller's grants for
384
+ // one of the accepting roles. Because the grant set lives in the token, the
385
+ // predicate needs NO join — it parses the claims jsonb and tests set membership.
386
+ //
387
+ // Two forms, deliberately:
388
+ // - default (InitPlan-correct): an **uncorrelated** `scope_col IN (SELECT …
389
+ // jsonb_array_elements(claims) …)`. The subquery never references the outer row,
390
+ // so the planner hoists it to an InitPlan and the JWT is parsed **once per
391
+ // statement**.
392
+ // - `naive: true` (the cliff): a **correlated** `EXISTS (… WHERE (g->…->>id) =
393
+ // scope_col)`. Referencing the outer row forces per-row re-evaluation — the JWT
394
+ // is re-parsed for **every row scanned**. It exists only to demonstrate and
395
+ // regression-guard the InitPlan discipline (see the `rls-read-load` perf track);
396
+ // never ship it.
397
+ //
398
+ // The same grant set is mirrored on the Electric read path by {@link resolveGrantScopeIds}
399
+ // + {@link buildGrantScopeShapeWhere}: the proxy resolves the ids from the claims in JS
400
+ // and injects a literal `scope_col IN ('a','b')` — Electric cannot read RLS, so the two
401
+ // surfaces are generated from one declaration and must agree.
402
+ // ---------------------------------------------------------------------------
403
+
404
+ type GrantScopePolicyKind = "select" | "insert" | "update" | "delete";
405
+
406
+ const defaultGrantsClaimPath = ["app_metadata", "authorization", "grants"] as const;
407
+ const defaultGrantScopeCastType = "uuid";
408
+
409
+ export type GrantScopeClaimOptions = {
410
+ /** Value matched against each grant's `scope.kind` (e.g. "offering"). */
411
+ scopeKind: string;
412
+ /** Grant `role` values that confer access (e.g. ["teacher", "assistant"]). */
413
+ roleValues: string[];
414
+ /** Field within `scope` holding the id (e.g. "offeringId"). Defaults to `${scopeKind}Id`. */
415
+ scopeIdField?: string;
416
+ /** Path to the grants array in the claims. Defaults to `app_metadata.authorization.grants`. */
417
+ grantsClaimPath?: string[];
418
+ };
419
+
420
+ export type SupabaseGrantScopePredicateColumns = GrantScopeClaimOptions & {
421
+ /** Column on the governed row naming its scope (e.g. `offerings.id` reference column). Table name is derived from it. */
422
+ scopeColumn: AnyColumn;
423
+ /** SQL type the extracted grant id is cast to before comparison (default "uuid"). */
424
+ scopeCastType?: string;
425
+ /**
426
+ * Optional unconditional bypass: any grant whose `role` ∈ `bypass.roleValues` and whose
427
+ * `scope.kind` = `bypass.scopeKind` (default "platform") grants all rows — e.g. a
428
+ * platform-scoped `platform_admin`. The bypass is an **uncorrelated** EXISTS, so it stays
429
+ * InitPlan-hoisted in both the correct and naive forms.
430
+ */
431
+ bypass?: { roleValues: string[]; scopeKind?: string };
432
+ };
433
+
434
+ export type SupabaseGrantScopeNativePoliciesOptions = SupabaseGrantScopePredicateColumns & {
435
+ role: PgRole;
436
+ /** Emit the deliberately-naive per-row correlated form (cliff demo / regression guard only). */
437
+ naive?: boolean;
438
+ };
439
+
440
+ const grantScopePolicyShapes: { command: GrantScopePolicyKind; using: boolean; withCheck: boolean }[] = [
441
+ { command: "select", using: true, withCheck: false },
442
+ { command: "insert", using: false, withCheck: true },
443
+ { command: "update", using: true, withCheck: true },
444
+ { command: "delete", using: true, withCheck: false },
445
+ ];
446
+
447
+ function resolveGrantsClaimPath(path: readonly string[] | undefined): string[] {
448
+ const segments = path && path.length > 0 ? [...path] : [...defaultGrantsClaimPath];
449
+ for (const segment of segments) {
450
+ assertIdentifier(segment, "grantsClaimPath segment");
451
+ }
452
+ return segments;
453
+ }
454
+
455
+ // The grants array as a Postgres jsonb expression, defaulting to `[]` when absent so
456
+ // `jsonb_array_elements` never errors. `#>` takes a text[] path; the segments are validated
457
+ // identifiers, so the `'{…}'` path literal is injection-safe.
458
+ function buildGrantsArraySqlText(path: string[]): string {
459
+ return `coalesce(
460
+ (
461
+ coalesce(
462
+ nullif(current_setting('request.jwt.claim', true), ''),
463
+ nullif(current_setting('request.jwt.claims', true), '')
464
+ )::jsonb #> '{${path.join(",")}}'
465
+ ),
466
+ '[]'::jsonb
467
+ )`;
468
+ }
469
+
470
+ function buildRoleInListSqlText(roleValues: string[]): string {
471
+ if (roleValues.length === 0) {
472
+ throw new Error("grant-scope policy requires at least one role value");
473
+ }
474
+ return renderInlineSql(
475
+ sql.join(
476
+ roleValues.map((role) => sql`${role}`),
477
+ sql`, `,
478
+ ),
479
+ );
480
+ }
481
+
482
+ function resolveGrantScopeIdField(options: GrantScopeClaimOptions): string {
483
+ const field = options.scopeIdField ?? `${options.scopeKind}Id`;
484
+ assertIdentifier(field, "scopeIdField");
485
+ return field;
486
+ }
487
+
488
+ // Uncorrelated bypass test (never references the governed row), so it is InitPlan-hoisted in both forms.
489
+ function buildBypassExistsSqlText(bypass: { roleValues: string[]; scopeKind?: string }, grantsText: string): string {
490
+ const scopeKind = bypass.scopeKind ?? "platform";
491
+ return `exists (
492
+ select 1
493
+ from jsonb_array_elements(${grantsText}) as bypass_grant
494
+ where bypass_grant -> 'scope' ->> 'kind' = ${renderInlineSql(sql`${scopeKind}`)}
495
+ and bypass_grant ->> 'role' in (${buildRoleInListSqlText(bypass.roleValues)})
496
+ )`;
497
+ }
498
+
499
+ function buildGrantScopePredicate(options: SupabaseGrantScopeNativePoliciesOptions): SQL {
500
+ const scopeKind = options.scopeKind;
501
+ assertIdentifier(scopeKind, "scopeKind");
502
+ const scopeIdField = resolveGrantScopeIdField(options);
503
+ const castType = options.scopeCastType ?? defaultGrantScopeCastType;
504
+ assertTypeName(castType, "scopeCastType");
505
+ const grantsText = buildGrantsArraySqlText(resolveGrantsClaimPath(options.grantsClaimPath));
506
+ const roleIn = buildRoleInListSqlText(options.roleValues);
507
+ const kindMatch = `grant_elem -> 'scope' ->> 'kind' = ${renderInlineSql(sql`${scopeKind}`)} and grant_elem ->> 'role' in (${roleIn})`;
508
+ const idExpr = `(grant_elem -> 'scope' ->> ${renderInlineSql(sql`${scopeIdField}`)})::${castType}`;
509
+
510
+ // Correct: uncorrelated `= ANY(ARRAY(select …))` → the grant set materializes once (InitPlan, JWT
511
+ // parsed once) and the ScalarArrayOp drives a bitmap index scan on the scope column — ~25-45× faster
512
+ // at scale than `IN (select …)`, which the planner costs as a hashed semi-join → sequential scan (the
513
+ // rls-read perf track proves both). Naive: correlated `EXISTS` referencing the governed scope column →
514
+ // re-evaluated per row (JWT parsed per row). The column object is spliced so it serializes qualified —
515
+ // valid CREATE POLICY DDL on the write path.
516
+ const base = options.naive
517
+ ? sql`exists (select 1 from jsonb_array_elements(${sql.raw(grantsText)}) as grant_elem where ${sql.raw(kindMatch)} and ${sql.raw(idExpr)} = ${options.scopeColumn})`
518
+ : sql`${options.scopeColumn} = any(array(select ${sql.raw(idExpr)} from jsonb_array_elements(${sql.raw(grantsText)}) as grant_elem where ${sql.raw(kindMatch)}))`;
519
+
520
+ if (!options.bypass) {
521
+ return base;
522
+ }
523
+ return or(base, sql.raw(buildBypassExistsSqlText(options.bypass, grantsText)))!;
524
+ }
525
+
526
+ /**
527
+ * Native Drizzle RLS policies for a JWT-resident grant set (see the section comment). Pass the real
528
+ * scope column; the governed table name is derived from it. By default the predicate is the
529
+ * InitPlan-correct uncorrelated `IN (subquery)`; pass `naive: true` for the correlated cliff variant.
530
+ */
531
+ export function buildSupabaseGrantScopeNativePolicies(options: SupabaseGrantScopeNativePoliciesOptions) {
532
+ const predicate = buildGrantScopePredicate(options);
533
+ const tableName = tableNameForColumn(options.scopeColumn, "scopeColumn");
534
+ const suffix = options.naive ? "grant_scope_naive" : "grant_scope";
535
+
536
+ return grantScopePolicyShapes.map((shape) =>
537
+ pgPolicy(`${tableName}_${shape.command}_${suffix}`, {
538
+ as: "permissive",
539
+ for: shape.command,
540
+ to: options.role,
541
+ ...(shape.using ? { using: predicate } : {}),
542
+ ...(shape.withCheck ? { withCheck: predicate } : {}),
543
+ }),
544
+ );
545
+ }
546
+
547
+ // ---------------------------------------------------------------------------
548
+ // Electric read-path mirror of the grant-scope policy. Electric cannot read RLS, so the proxy must
549
+ // resolve the same visible scope-id set from the claims in JS and inject a literal `IN (…)` shape
550
+ // `where`. These two helpers are the read-path counterpart to the policy above — one declaration,
551
+ // two enforcement surfaces, derived from the same grant data so they cannot drift.
552
+ // ---------------------------------------------------------------------------
553
+
554
+ function readClaimsPath(claims: JwtClaims | null, path: string[]): unknown {
555
+ let current: unknown = claims;
556
+ for (const segment of path) {
557
+ if (typeof current !== "object" || current === null || Array.isArray(current)) {
558
+ return undefined;
559
+ }
560
+ current = (current as Record<string, unknown>)[segment];
561
+ }
562
+ return current;
563
+ }
564
+
565
+ /**
566
+ * The set of scope ids the caller can see, resolved from the JWT grants — the JS mirror of the
567
+ * grant-scope RLS subquery. Returns a de-duplicated list (empty → no rows visible).
568
+ */
569
+ export function resolveGrantScopeIds(claims: JwtClaims | null, options: GrantScopeClaimOptions): string[] {
570
+ const grants = readClaimsPath(claims, resolveGrantsClaimPath(options.grantsClaimPath));
571
+ if (!Array.isArray(grants)) {
572
+ return [];
573
+ }
574
+
575
+ const scopeIdField = resolveGrantScopeIdField(options);
576
+ const roleValues = new Set(options.roleValues);
577
+ const ids = new Set<string>();
578
+
579
+ for (const grant of grants) {
580
+ if (typeof grant !== "object" || grant === null) {
581
+ continue;
582
+ }
583
+ const record = grant as Record<string, unknown>;
584
+ if (!roleValues.has(String(record["role"]))) {
585
+ continue;
586
+ }
587
+ const scope = record["scope"];
588
+ if (typeof scope !== "object" || scope === null) {
589
+ continue;
590
+ }
591
+ const scopeRecord = scope as Record<string, unknown>;
592
+ if (scopeRecord["kind"] !== options.scopeKind) {
593
+ continue;
594
+ }
595
+ const id = scopeRecord[scopeIdField];
596
+ if (typeof id === "string" && id.length > 0) {
597
+ ids.add(id);
598
+ }
599
+ }
600
+
601
+ return [...ids];
602
+ }
603
+
604
+ /**
605
+ * The Electric shape `where` for a grant-scope table: an `IN (…)` over the resolved ids (what the
606
+ * proxy injects). Takes the real Drizzle scope column — referenced bare via `c()` (Electric's grammar
607
+ * requires bare columns), so the reference is rename-safe — and returns a typed fragment whose ids
608
+ * are **bound params** once `buildRowFilterShape` serializes it (never hand-escaped literals). An
609
+ * empty id set denies all rows ({@link DENY_ALL}), mirroring the policy returning no rows.
610
+ */
611
+ export function buildGrantScopeShapeWhere(scopeColumn: AnyColumn, ids: string[]): SQL {
612
+ if (ids.length === 0) {
613
+ return DENY_ALL;
614
+ }
615
+ return sql`${c(scopeColumn)} in (${sql.join(
616
+ ids.map((id) => sql`${id}`),
617
+ sql`, `,
618
+ )})`;
619
+ }