@pgxsinkit/contracts 0.2.4 → 0.2.6

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.
@@ -1,7 +1,7 @@
1
1
  import { and, eq, getTableName, or, sql, type AnyColumn, type SQL } from "drizzle-orm";
2
2
  import { PgDialect, pgPolicy, type AnyPgTable, type PgRole } from "drizzle-orm/pg-core";
3
3
 
4
- import { c, DENY_ALL, type JwtClaims } from "./config";
4
+ import { buildOwnershipShapeWhere, c, DENY_ALL, type JwtClaims } from "./config";
5
5
 
6
6
  // Render a typed fragment to inline-literal SQL text (CREATE POLICY DDL cannot carry `$n` binds).
7
7
  // The tier-② discipline for the text builders below: values enter as typed `${value}` interpolations
@@ -11,6 +11,28 @@ function renderInlineSql(fragment: SQL): string {
11
11
  return textDialect.sqlToQuery(fragment.inlineParams()).sql;
12
12
  }
13
13
 
14
+ // Walk a dotted claim path defensively (unverified claims may be any shape): anything that is not a
15
+ // plain object on the way down yields `undefined` rather than throwing. Shared by every Electric
16
+ // read-path mirror below — each family's mirror sits beside its own policies and reads exactly the
17
+ // claim the policy's SQL reads.
18
+ function readClaimsPath(claims: JwtClaims | null, path: string[]): unknown {
19
+ let current: unknown = claims;
20
+ for (const segment of path) {
21
+ if (typeof current !== "object" || current === null || Array.isArray(current)) {
22
+ return undefined;
23
+ }
24
+ current = (current as Record<string, unknown>)[segment];
25
+ }
26
+ return current;
27
+ }
28
+
29
+ // The JWT subject as the read path sees it: a non-empty `sub` string, else null (no subject → the
30
+ // mirrors deny). The RLS counterpart is `buildSubjectSqlText`, which reads the same claim in Postgres.
31
+ function readSubjectClaim(claims: JwtClaims | null): string | null {
32
+ const subject = readClaimsPath(claims, ["sub"]);
33
+ return typeof subject === "string" && subject.length > 0 ? subject : null;
34
+ }
35
+
14
36
  type SupabaseOwnerOrAdminPolicyKind = "select" | "insert" | "update" | "delete";
15
37
 
16
38
  type SupabaseOwnerOrAdminPolicyShape = {
@@ -27,6 +49,8 @@ export type SupabaseOwnerOrAdminPredicateOptions = {
27
49
  ownerSqlColumn?: string;
28
50
  adminRoleName?: string;
29
51
  subjectCastType?: string;
52
+ /** Path to the roles array in the claims. Defaults to {@link adminRolesClaimPath}. */
53
+ adminRolesClaimPath?: readonly string[];
30
54
  };
31
55
 
32
56
  export type SupabaseOwnerOrAdminNativePoliciesOptions = {
@@ -37,6 +61,11 @@ export type SupabaseOwnerOrAdminNativePoliciesOptions = {
37
61
  adminRoleName?: string;
38
62
  /** SQL type the JWT subject is cast to before comparison (default "uuid"). */
39
63
  subjectCastType?: string;
64
+ /**
65
+ * Path to the roles array in the claims. Defaults to {@link adminRolesClaimPath}; pass the SAME value to
66
+ * {@link resolveOwnerOrAdminAccess} / {@link buildOwnerOrAdminShapeWhere} so both surfaces read one claim.
67
+ */
68
+ adminRolesClaimPath?: readonly string[];
40
69
  };
41
70
 
42
71
  const defaultOwnerSqlColumn = "owner_id";
@@ -44,6 +73,11 @@ const defaultOwnerPropertyKey = "ownerId";
44
73
  const defaultAuthenticatedRoleName = "authenticated";
45
74
  const defaultAdminRoleName = "admin";
46
75
  const defaultSubjectCastType = "uuid";
76
+ // The DEFAULT claim path the admin check reads — the single source for BOTH surfaces: the SQL `EXISTS`
77
+ // in `buildAdminRoleExistsSqlText` renders its `-> 'seg'` chain from this array, and the read-path mirror
78
+ // (`resolveOwnerOrAdminAccess`) walks the same segments in JS. Overridable per call via
79
+ // `adminRolesClaimPath` on either surface — pass the same value to both or they drift.
80
+ const adminRolesClaimPath = ["app_metadata", "roles"] as const;
47
81
 
48
82
  const ownerOrAdminPolicyShapes: SupabaseOwnerOrAdminPolicyShape[] = [
49
83
  {
@@ -124,23 +158,55 @@ function buildSubjectSqlText(subjectCastType: string): string {
124
158
  )::${subjectCastType}`;
125
159
  }
126
160
 
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 (
133
- SELECT 1
134
- FROM jsonb_array_elements_text(
135
- COALESCE(
136
- (
161
+ // The claim path the admin check walks, validated as plain identifiers (they are emitted into policy
162
+ // DDL). Mirrors `resolveGrantsClaimPath` in the grant-scope family below.
163
+ function resolveAdminRolesClaimPath(path: readonly string[] | undefined): string[] {
164
+ const segments = path && path.length > 0 ? [...path] : [...adminRolesClaimPath];
165
+ for (const segment of segments) {
166
+ assertIdentifier(segment, "adminRolesClaimPath segment");
167
+ }
168
+ return segments;
169
+ }
170
+
171
+ // The claim path as a jsonb `-> 'seg'` chain, one typed interpolation per segment (drizzle owns the
172
+ // quoting), so the SQL walks the SAME array the JS mirror walks — textual agreement is not enough.
173
+ function buildClaimPathChainSql(path: string[]): SQL {
174
+ return sql.join(
175
+ path.map((segment) => sql` -> ${segment}`),
176
+ sql``,
177
+ );
178
+ }
179
+
180
+ // An extracted claim as an ARRAY or nothing at all — the SQL twin of the mirrors' "an unverified claim
181
+ // of the wrong shape confers nothing". Absent/null already yields `[]`; the load-bearing case is a
182
+ // claim that is PRESENT but not an array (a token hook emitting `roles: "admin"` instead of
183
+ // `["admin"]`), which would otherwise reach `jsonb_array_elements(_text)` and raise "cannot extract
184
+ // elements from a scalar/object" — turning every governed write into an RLS execution ERROR instead of
185
+ // a clean deny. Wrapped here, a non-array claim behaves exactly like an absent one, so the policy
186
+ // reaches the same verdict as `resolveOwnerOrAdminAccess` / `resolveGrantScopeAccess`.
187
+ // The expression is repeated (Postgres has nowhere to bind it inside a policy predicate); it is a
188
+ // stable per-statement expression, so the planner evaluates it once, not per row.
189
+ function buildClaimArraySqlText(claimSqlText: string): string {
190
+ return `case jsonb_typeof(${claimSqlText}) when 'array' then ${claimSqlText} else '[]'::jsonb end`;
191
+ }
192
+
193
+ // The admin-bypass test: the roles array at `adminRolesClaimPath` (from the JWT claims) contains
194
+ // `adminRoleName`. No column reference and no recursion risk, so it is inlined as text (shared by the
195
+ // text builder and the native builder). The role value and the claim-path segments enter as typed
196
+ // interpolations (drizzle owns the escaping); the claim-extraction body is the allowed raw leaf, and it
197
+ // goes through {@link buildClaimArraySqlText} so a malformed `roles` denies instead of erroring.
198
+ function buildAdminRoleExistsSqlText(adminRoleName: string, claimPath: string[]): string {
199
+ const rolesClaim = renderInlineSql(sql`(
137
200
  coalesce(
138
201
  nullif(current_setting('request.jwt.claim', true), ''),
139
202
  nullif(current_setting('request.jwt.claims', true), '')
140
- )::jsonb -> 'app_metadata' -> 'roles'
141
- ),
142
- '[]'::jsonb
143
- )
203
+ )::jsonb${buildClaimPathChainSql(claimPath)}
204
+ )`);
205
+
206
+ return renderInlineSql(sql`EXISTS (
207
+ SELECT 1
208
+ FROM jsonb_array_elements_text(
209
+ ${sql.raw(buildClaimArraySqlText(rolesClaim))}
144
210
  ) AS assigned_role(role_name_value)
145
211
  WHERE assigned_role.role_name_value = ${adminRoleName}
146
212
  )`);
@@ -158,6 +224,7 @@ function normalizePredicateOptions(options: SupabaseOwnerOrAdminPredicateOptions
158
224
  ownerSqlColumn,
159
225
  adminRoleName,
160
226
  subjectCastType,
227
+ claimPath: resolveAdminRolesClaimPath(options.adminRolesClaimPath),
161
228
  };
162
229
  }
163
230
 
@@ -171,7 +238,7 @@ export function buildSupabaseOwnerOrAdminPredicateSqlText(options: SupabaseOwner
171
238
 
172
239
  return `
173
240
  ${normalized.ownerSqlColumn} = ${buildSubjectSqlText(normalized.subjectCastType)}
174
- OR ${buildAdminRoleExistsSqlText(normalized.adminRoleName)}
241
+ OR ${buildAdminRoleExistsSqlText(normalized.adminRoleName, normalized.claimPath)}
175
242
  `;
176
243
  }
177
244
 
@@ -181,7 +248,9 @@ export function buildSupabaseOwnerOrAdminPredicateSqlText(options: SupabaseOwner
181
248
  export function buildSupabaseOwnerOrAdminNativePolicies(options: SupabaseOwnerOrAdminNativePoliciesOptions) {
182
249
  const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;
183
250
  const subject = buildSubjectSql(options.subjectCastType ?? defaultSubjectCastType);
184
- const adminExists = sql.raw(buildAdminRoleExistsSqlText(adminRoleName));
251
+ const adminExists = sql.raw(
252
+ buildAdminRoleExistsSqlText(adminRoleName, resolveAdminRolesClaimPath(options.adminRolesClaimPath)),
253
+ );
185
254
  const predicate = or(eq(options.ownerColumn, subject), adminExists)!;
186
255
  const tableName = tableNameForColumn(options.ownerColumn, "ownerColumn");
187
256
 
@@ -204,6 +273,75 @@ export const supabaseOwnerOrAdminDefaults = {
204
273
  subjectCastType: defaultSubjectCastType,
205
274
  } as const;
206
275
 
276
+ // ---------------------------------------------------------------------------
277
+ // Electric read-path mirror of the owner-or-admin policies. Electric cannot read RLS, so the proxy has
278
+ // to reach the same verdict in JS, from the same claims: the policy's `OR` admin branch becomes "no
279
+ // filter at all" (every row streams), and its owner branch becomes the ownership shape `where`. One
280
+ // declaration — the owner column plus the admin role name — two enforcement surfaces, so a row can
281
+ // never be writable-but-unreadable (or the reverse).
282
+ //
283
+ // SELECT only, by construction: a shape `where` filters a read stream, so it mirrors the `select`
284
+ // policy. INSERT/UPDATE/DELETE remain the policies' business.
285
+ // ---------------------------------------------------------------------------
286
+
287
+ /**
288
+ * Claim-reading options for the read mirror; every field must match the value the policies were built
289
+ * with, or the two surfaces stop agreeing.
290
+ */
291
+ export type OwnerOrAdminAccessOptions = {
292
+ /** Role value (in `app_metadata.roles`) that bypasses ownership (default "admin"). */
293
+ adminRoleName?: string;
294
+ /** Path to the roles array in the claims. Defaults to {@link adminRolesClaimPath}. */
295
+ adminRolesClaimPath?: readonly string[];
296
+ };
297
+
298
+ /** The caller's standing on an owner-or-admin table, as resolved from the claims. */
299
+ export type OwnerOrAdminAccess = {
300
+ /** The caller holds the admin role — the policy's bypass branch; every row is visible. */
301
+ admin: boolean;
302
+ /** The JWT subject when it is a non-empty string, else null (no subject → nothing is visible). */
303
+ subject: string | null;
304
+ };
305
+
306
+ /**
307
+ * The caller's owner-or-admin standing, resolved from the JWT claims — the JS mirror of the policy's
308
+ * admin `EXISTS` and its subject comparison. `admin` is true when the roles array at
309
+ * `adminRolesClaimPath` (`app_metadata.roles` by default — the very array
310
+ * {@link buildSupabaseOwnerOrAdminNativePolicies} renders its `-> 'seg'` chain from, so the two surfaces
311
+ * read one declaration) contains `adminRoleName`; `subject` is the `sub` claim when it is a non-empty
312
+ * string, else null.
313
+ *
314
+ * Claims arrive unverified in shape, so this never throws: a missing/non-object claims bag, a
315
+ * non-array `roles`, or non-string members simply confer nothing.
316
+ */
317
+ export function resolveOwnerOrAdminAccess(
318
+ claims: JwtClaims | null,
319
+ options: OwnerOrAdminAccessOptions = {},
320
+ ): OwnerOrAdminAccess {
321
+ const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;
322
+ const roles = readClaimsPath(claims, resolveAdminRolesClaimPath(options.adminRolesClaimPath));
323
+ const admin = Array.isArray(roles) && roles.some((role) => typeof role === "string" && role === adminRoleName);
324
+
325
+ return { admin, subject: readSubjectClaim(claims) };
326
+ }
327
+
328
+ /**
329
+ * The Electric shape `where` for an owner-or-admin table — the read counterpart of
330
+ * {@link buildSupabaseOwnerOrAdminNativePolicies}, built from the same owner column. An admin gets
331
+ * `null` (no filter, every row — the policy's bypass branch); anyone else gets
332
+ * {@link buildOwnershipShapeWhere}, i.e. their own rows, or the {@link DENY_ALL} sentinel when there is
333
+ * no subject. Returning the sentinel *by reference* is what lets a `customWhere` built on this probe as
334
+ * claims-dependent (`isClaimsDependentRowFilter`).
335
+ */
336
+ export function buildOwnerOrAdminShapeWhere(
337
+ ownerColumn: AnyColumn,
338
+ claims: JwtClaims | null,
339
+ options: OwnerOrAdminAccessOptions = {},
340
+ ): SQL | null {
341
+ const access = resolveOwnerOrAdminAccess(claims, options);
342
+ return access.admin ? null : buildOwnershipShapeWhere(ownerColumn, access.subject);
343
+ }
344
+
207
345
  // ---------------------------------------------------------------------------
208
346
  // Membership-scoped policies (generic). A row belongs to a *container* and is
209
347
  // visible/writable through membership of that container — not just ownership.
@@ -223,6 +361,10 @@ export const supabaseOwnerOrAdminDefaults = {
223
361
  // and the `(select current_setting(...)::type)` JWT-subject expression (wrapped in a scalar subquery —
224
362
  // the Supabase per-statement-eval RLS perf idiom). Columns serialize qualified
225
363
  // (`"work_items"."workspace_id"`) — fine for Postgres RLS (the write path, unlike Electric's bare rule).
364
+ //
365
+ // The `select` half of this family is mirrored on the Electric read path by
366
+ // {@link buildMembershipShapeWhere}, built from the same column declarations — Electric cannot read
367
+ // RLS, so the two surfaces are generated from one declaration and must agree.
226
368
  // ---------------------------------------------------------------------------
227
369
 
228
370
  type MembershipPolicyKind = "select" | "insert" | "update" | "delete";
@@ -376,6 +518,58 @@ export function buildSupabaseMembershipNativePolicies(options: SupabaseMembershi
376
518
  });
377
519
  }
378
520
 
521
+ // ---------------------------------------------------------------------------
522
+ // Electric read-path mirror of the membership policies. Electric cannot read RLS, so the proxy must
523
+ // re-derive the same visible set in the shape `where`, from the SAME Drizzle columns the policies were
524
+ // built from — one declaration, two enforcement surfaces, so a row can never be readable-but-unwritable
525
+ // (or the reverse) through a rename or a typo.
526
+ //
527
+ // SELECT only, by construction: the mirror reproduces the family's `select` predicate — plain
528
+ // membership of the container. The owner/manager branches and the write-state gate are WRITE-side
529
+ // concerns (INSERT/UPDATE/DELETE) and are deliberately absent here; a shape `where` filters a read
530
+ // stream and has nothing to gate.
531
+ //
532
+ // The two surfaces render the SAME containment differently, on purpose:
533
+ // - RLS (`membershipMatch`) renders `= ANY(ARRAY(select …))` — the InitPlan/bitmap-index-scan
534
+ // discipline Postgres needs for a runtime-resolved set (see that function's comment).
535
+ // - Electric renders a plain `IN (subquery)`, because that is what Electric's shape `where` grammar
536
+ // accepts; there is no Postgres planner on this side to appease.
537
+ // Same columns, two dialects — that is exactly what the mirror is for.
538
+ // ---------------------------------------------------------------------------
539
+
540
+ /**
541
+ * The columns {@link buildMembershipShapeWhere} needs: the SELECT-relevant subset of
542
+ * {@link SupabaseMembershipPredicateColumns}. The write-only fields (owner, manager role, subject cast,
543
+ * write gate, policy role) are accepted but ignored, so the **same declaration object** you hand to
544
+ * {@link buildSupabaseMembershipNativePolicies} can be handed to the read mirror verbatim.
545
+ */
546
+ export type SupabaseMembershipShapeColumns = Pick<
547
+ SupabaseMembershipPredicateColumns,
548
+ "containerColumn" | "membershipTable" | "membershipContainerColumn" | "membershipSubjectColumn"
549
+ > &
550
+ Partial<SupabaseMembershipNativePoliciesOptions>;
551
+
552
+ /**
553
+ * The Electric shape `where` for a membership-scoped table — the read counterpart of the `select`
554
+ * policy in {@link buildSupabaseMembershipNativePolicies}: the row's container must be one the caller
555
+ * is a member of. Columns are referenced **bare** via {@link c} (Electric's grammar requires plain
556
+ * column refs) yet still through the real Drizzle column objects, so the reference is rename-safe; the
557
+ * subject rides as a typed interpolation and becomes a bound param once `buildRowFilterShape`
558
+ * serializes it (never a hand-escaped literal). The subquery is **self-contained** (uncorrelated) — it
559
+ * gets its own `FROM`, so the membership table's bare column names resolve to it.
560
+ *
561
+ * No subject → {@link DENY_ALL} (by reference, so a `customWhere` built on it probes claims-dependent),
562
+ * mirroring the policy, whose membership subquery matches nothing without a JWT sub.
563
+ */
564
+ export function buildMembershipShapeWhere(columns: SupabaseMembershipShapeColumns, claims: JwtClaims | null): SQL {
565
+ const subject = readSubjectClaim(claims);
566
+ if (subject === null) {
567
+ return DENY_ALL;
568
+ }
569
+
570
+ return sql`${c(columns.containerColumn)} in (select ${c(columns.membershipContainerColumn)} from ${columns.membershipTable} where ${c(columns.membershipSubjectColumn)} = ${subject})`;
571
+ }
572
+
379
573
  // ---------------------------------------------------------------------------
380
574
  // Grant-scope policies (generic). Authorization is carried IN THE JWT, not a DB
381
575
  // table: `app_metadata.authorization.grants` is an array of
@@ -395,16 +589,30 @@ export function buildSupabaseMembershipNativePolicies(options: SupabaseMembershi
395
589
  // regression-guard the InitPlan discipline (see the `rls-read-load` perf track);
396
590
  // never ship it.
397
591
  //
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.
592
+ // The same grant set is mirrored on the Electric read path by {@link resolveGrantScopeAccess}
593
+ // (or {@link resolveGrantScopeIds} for the id set alone) + {@link buildGrantScopeShapeWhere}: the proxy
594
+ // resolves the ids from the claims in JS and injects a literal `scope_col IN ('a','b')` — Electric
595
+ // cannot read RLS, so the two surfaces are generated from one declaration and must agree.
402
596
  // ---------------------------------------------------------------------------
403
597
 
404
598
  type GrantScopePolicyKind = "select" | "insert" | "update" | "delete";
405
599
 
406
600
  const defaultGrantsClaimPath = ["app_metadata", "authorization", "grants"] as const;
407
601
  const defaultGrantScopeCastType = "uuid";
602
+ // Scope kind a bypass grant must carry, on BOTH surfaces: the policy's `buildBypassExistsSqlText`
603
+ // inlines it and the read mirror's `resolveGrantScopeAccess` compares against it.
604
+ const defaultBypassScopeKind = "platform";
605
+
606
+ /**
607
+ * An unconditional bypass declaration: any grant whose `role` ∈ `roleValues` and whose `scope.kind` =
608
+ * `scopeKind` (default `"platform"`) confers access to every row — e.g. a platform-scoped
609
+ * `platform_admin`. Hand the SAME object to the policy builder and to
610
+ * {@link resolveGrantScopeAccess} / {@link buildGrantScopeAccessShapeWhere}.
611
+ */
612
+ export type GrantScopeBypassOptions = {
613
+ roleValues: string[];
614
+ scopeKind?: string;
615
+ };
408
616
 
409
617
  export type GrantScopeClaimOptions = {
410
618
  /** Value matched against each grant's `scope.kind` (e.g. "offering"). */
@@ -423,12 +631,13 @@ export type SupabaseGrantScopePredicateColumns = GrantScopeClaimOptions & {
423
631
  /** SQL type the extracted grant id is cast to before comparison (default "uuid"). */
424
632
  scopeCastType?: string;
425
633
  /**
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.
634
+ * Optional unconditional bypass ({@link GrantScopeBypassOptions}): any grant whose `role` ∈
635
+ * `bypass.roleValues` and whose `scope.kind` = `bypass.scopeKind` (default "platform") grants all
636
+ * rows — e.g. a platform-scoped `platform_admin`. The bypass is an **uncorrelated** EXISTS, so it
637
+ * stays InitPlan-hoisted in both the correct and naive forms. Its read-path twin is
638
+ * {@link buildGrantScopeAccessShapeWhere} (bypass → `null`, i.e. no shape filter at all).
430
639
  */
431
- bypass?: { roleValues: string[]; scopeKind?: string };
640
+ bypass?: GrantScopeBypassOptions;
432
641
  };
433
642
 
434
643
  export type SupabaseGrantScopeNativePoliciesOptions = SupabaseGrantScopePredicateColumns & {
@@ -452,19 +661,18 @@ function resolveGrantsClaimPath(path: readonly string[] | undefined): string[] {
452
661
  return segments;
453
662
  }
454
663
 
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.
664
+ // The grants array as a Postgres jsonb expression, guarded by {@link buildClaimArraySqlText} so
665
+ // `jsonb_array_elements` never errors: an absent, null, OR non-array grants claim all yield `[]`, i.e.
666
+ // no grants — the same "confers nothing" verdict `resolveGrantScopeAccess` reaches in JS. Shared by the
667
+ // scope predicate (both forms) and the bypass EXISTS. `#>` takes a text[] path; the segments are
668
+ // validated identifiers, so the `'{…}'` path literal is injection-safe.
458
669
  function buildGrantsArraySqlText(path: string[]): string {
459
- return `coalesce(
460
- (
670
+ return buildClaimArraySqlText(`(
461
671
  coalesce(
462
672
  nullif(current_setting('request.jwt.claim', true), ''),
463
673
  nullif(current_setting('request.jwt.claims', true), '')
464
674
  )::jsonb #> '{${path.join(",")}}'
465
- ),
466
- '[]'::jsonb
467
- )`;
675
+ )`);
468
676
  }
469
677
 
470
678
  function buildRoleInListSqlText(roleValues: string[]): string {
@@ -486,8 +694,8 @@ function resolveGrantScopeIdField(options: GrantScopeClaimOptions): string {
486
694
  }
487
695
 
488
696
  // 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";
697
+ function buildBypassExistsSqlText(bypass: GrantScopeBypassOptions, grantsText: string): string {
698
+ const scopeKind = bypass.scopeKind ?? defaultBypassScopeKind;
491
699
  return `exists (
492
700
  select 1
493
701
  from jsonb_array_elements(${grantsText}) as bypass_grant
@@ -547,21 +755,15 @@ export function buildSupabaseGrantScopeNativePolicies(options: SupabaseGrantScop
547
755
  // ---------------------------------------------------------------------------
548
756
  // Electric read-path mirror of the grant-scope policy. Electric cannot read RLS, so the proxy must
549
757
  // 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,
758
+ // `where`. These helpers are the read-path counterpart to the policy above — one declaration,
551
759
  // two enforcement surfaces, derived from the same grant data so they cannot drift.
760
+ //
761
+ // The policy's OR bypass branch has a mirror too: {@link resolveGrantScopeAccess} reports it and
762
+ // {@link buildGrantScopeAccessShapeWhere} turns it into `null` — no shape filter at all, every row
763
+ // streams — exactly as the `exists (…)` OR-branch makes the scope test irrelevant on the write side.
764
+ // Without it a bypass grant would be enforced on writes yet invisible on reads.
552
765
  // ---------------------------------------------------------------------------
553
766
 
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
767
  /**
566
768
  * The set of scope ids the caller can see, resolved from the JWT grants — the JS mirror of the
567
769
  * grant-scope RLS subquery. Returns a de-duplicated list (empty → no rows visible).
@@ -617,3 +819,89 @@ export function buildGrantScopeShapeWhere(scopeColumn: AnyColumn, ids: string[])
617
819
  sql`, `,
618
820
  )})`;
619
821
  }
822
+
823
+ /** The full grant-scope declaration the read mirror needs: the claim options plus the optional bypass. */
824
+ export type GrantScopeAccessOptions = GrantScopeClaimOptions & {
825
+ /** The same {@link GrantScopeBypassOptions} handed to {@link buildSupabaseGrantScopeNativePolicies}. */
826
+ bypass?: GrantScopeBypassOptions;
827
+ };
828
+
829
+ /** The caller's standing on a grant-scope table, as resolved from the claims. */
830
+ export type GrantScopeAccess = {
831
+ /** A bypass grant is present — the policy's OR branch; every row is visible. */
832
+ bypass: boolean;
833
+ /** The de-duplicated scope ids the caller can see (empty → no rows, absent a bypass). */
834
+ ids: string[];
835
+ };
836
+
837
+ // The JS mirror of `buildBypassExistsSqlText`: a grant whose `role` is one of `bypass.roleValues` and
838
+ // whose `scope.kind` is `bypass.scopeKind` (defaulting to the same `defaultBypassScopeKind` the SQL
839
+ // inlines). Claims arrive unverified in shape, so nothing here throws — a non-array grants claim, a
840
+ // non-object grant, or a missing `scope` simply confers nothing.
841
+ function hasGrantScopeBypass(claims: JwtClaims | null, options: GrantScopeAccessOptions): boolean {
842
+ const bypass = options.bypass;
843
+ if (!bypass) {
844
+ return false;
845
+ }
846
+
847
+ const grants = readClaimsPath(claims, resolveGrantsClaimPath(options.grantsClaimPath));
848
+ if (!Array.isArray(grants)) {
849
+ return false;
850
+ }
851
+
852
+ const scopeKind = bypass.scopeKind ?? defaultBypassScopeKind;
853
+ const roleValues = new Set(bypass.roleValues);
854
+
855
+ for (const grant of grants) {
856
+ if (typeof grant !== "object" || grant === null) {
857
+ continue;
858
+ }
859
+ const record = grant as Record<string, unknown>;
860
+ if (!roleValues.has(String(record["role"]))) {
861
+ continue;
862
+ }
863
+ const scope = record["scope"];
864
+ if (typeof scope !== "object" || scope === null) {
865
+ continue;
866
+ }
867
+ if ((scope as Record<string, unknown>)["kind"] === scopeKind) {
868
+ return true;
869
+ }
870
+ }
871
+
872
+ return false;
873
+ }
874
+
875
+ /**
876
+ * The caller's grant-scope standing, resolved from the JWT grants — the JS mirror of the whole policy
877
+ * predicate, both branches: `ids` is {@link resolveGrantScopeIds} (the scope-set subquery) and `bypass`
878
+ * mirrors the policy's OR `exists (…)` branch. One declaration, two enforcement surfaces: pass the SAME
879
+ * options object you gave {@link buildSupabaseGrantScopeNativePolicies} and a bypass grant cannot be
880
+ * enforced on writes yet invisible on reads.
881
+ *
882
+ * Never throws on malformed claims (they reach a `customWhere` unverified in shape) — a wrong shape
883
+ * simply confers nothing. A malformed `grantsClaimPath`/`scopeIdField` **option** is still a loud error.
884
+ */
885
+ export function resolveGrantScopeAccess(claims: JwtClaims | null, options: GrantScopeAccessOptions): GrantScopeAccess {
886
+ return {
887
+ bypass: hasGrantScopeBypass(claims, options),
888
+ ids: resolveGrantScopeIds(claims, options),
889
+ };
890
+ }
891
+
892
+ /**
893
+ * The Electric shape `where` for a grant-scope table, bypass included — the read counterpart of the
894
+ * `select` policy in {@link buildSupabaseGrantScopeNativePolicies}, from the same declaration. A caller
895
+ * holding a bypass grant gets `null` (no filter, every row — the policy's OR branch); anyone else gets
896
+ * {@link buildGrantScopeShapeWhere} over their resolved ids, i.e. the {@link DENY_ALL} sentinel *by
897
+ * reference* when the set is empty (which is what lets a `customWhere` built on this probe as
898
+ * claims-dependent). Use {@link buildGrantScopeShapeWhere} directly only when there is no bypass to mirror.
899
+ */
900
+ export function buildGrantScopeAccessShapeWhere(
901
+ scopeColumn: AnyColumn,
902
+ claims: JwtClaims | null,
903
+ options: GrantScopeAccessOptions,
904
+ ): SQL | null {
905
+ const access = resolveGrantScopeAccess(claims, options);
906
+ return access.bypass ? null : buildGrantScopeShapeWhere(scopeColumn, access.ids);
907
+ }