@pgxsinkit/contracts 0.2.7 → 0.3.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.
@@ -1,7 +1,8 @@
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 { buildOwnershipShapeWhere, c, DENY_ALL, type JwtClaims } from "./config";
4
+ import { buildOwnershipShapePredicate, DENY_ALL_PREDICATE, type JwtClaims } from "./config";
5
+ import { p, type Predicate } from "./predicate";
5
6
 
6
7
  // Render a typed fragment to inline-literal SQL text (CREATE POLICY DDL cannot carry `$n` binds).
7
8
  // The tier-② discipline for the text builders below: values enter as typed `${value}` interpolations
@@ -12,8 +13,8 @@ function renderInlineSql(fragment: SQL): string {
12
13
  }
13
14
 
14
15
  // 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
16
+ // plain object on the way down yields `undefined` rather than throwing. Shared by every read-path
17
+ // predicate mirror below — each family's mirror sits beside its own policies and reads exactly the
17
18
  // claim the policy's SQL reads.
18
19
  function readClaimsPath(claims: JwtClaims | null, path: string[]): unknown {
19
20
  let current: unknown = claims;
@@ -63,7 +64,7 @@ export type SupabaseOwnerOrAdminNativePoliciesOptions = {
63
64
  subjectCastType?: string;
64
65
  /**
65
66
  * 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
+ * {@link resolveOwnerOrAdminAccess} / {@link buildOwnerOrAdminShapePredicate} so both surfaces read one claim.
67
68
  */
68
69
  adminRolesClaimPath?: readonly string[];
69
70
  };
@@ -120,8 +121,9 @@ function buildOwnerOrAdminPolicyName(tableName: string, command: SupabaseOwnerOr
120
121
 
121
122
  // ---------------------------------------------------------------------------
122
123
  // Shared predicate leaves (used by both policy families). RLS is the *write* path
123
- // (Postgres), so columns may serialize qualified — unlike the Electric read `where`,
124
- // which needs bare columns. The only bits that stay raw `sql` are genuinely-Postgres
124
+ // (Postgres), so these render to SQL text with columns qualified — unlike the read-path
125
+ // mirrors, which carry the column objects themselves in a predicate AST and render no SQL
126
+ // at all. The only bits that stay raw `sql` are genuinely-Postgres
125
127
  // expressions with no Drizzle operator: the JWT-subject `(select current_setting(...)::type)`
126
128
  // and the admin-roles `EXISTS`. Literal values use `eq(col, value).inlineParams()` so the
127
129
  // value is inlined into the DDL — a bare `$n` is something `CREATE POLICY` cannot carry.
@@ -274,13 +276,13 @@ export const supabaseOwnerOrAdminDefaults = {
274
276
  } as const;
275
277
 
276
278
  // ---------------------------------------------------------------------------
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
279
+ // Read-path mirror of the owner-or-admin policies. The read path never runs RLS, so the control plane
280
+ // has to reach the same verdict in JS, from the same claims: the policy's `OR` admin branch becomes "no
281
+ // filter at all" (every row streams), and its owner branch becomes the ownership shape predicate. One
280
282
  // declaration — the owner column plus the admin role name — two enforcement surfaces, so a row can
281
283
  // never be writable-but-unreadable (or the reverse).
282
284
  //
283
- // SELECT only, by construction: a shape `where` filters a read stream, so it mirrors the `select`
285
+ // SELECT only, by construction: a shape predicate filters a read stream, so it mirrors the `select`
284
286
  // policy. INSERT/UPDATE/DELETE remain the policies' business.
285
287
  // ---------------------------------------------------------------------------
286
288
 
@@ -326,20 +328,17 @@ export function resolveOwnerOrAdminAccess(
326
328
  }
327
329
 
328
330
  /**
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`).
331
+ * The owner-or-admin **predicate** — the native-path counterpart to
332
+ * the owner-or-admin `select` policy, from the same declaration. An admin gets `null` (no filter,
333
+ * every row — the policy's bypass branch); anyone else gets {@link buildOwnershipShapePredicate}.
335
334
  */
336
- export function buildOwnerOrAdminShapeWhere(
335
+ export function buildOwnerOrAdminShapePredicate(
337
336
  ownerColumn: AnyColumn,
338
337
  claims: JwtClaims | null,
339
338
  options: OwnerOrAdminAccessOptions = {},
340
- ): SQL | null {
339
+ ): Predicate | null {
341
340
  const access = resolveOwnerOrAdminAccess(claims, options);
342
- return access.admin ? null : buildOwnershipShapeWhere(ownerColumn, access.subject);
341
+ return access.admin ? null : buildOwnershipShapePredicate(ownerColumn, access.subject);
343
342
  }
344
343
 
345
344
  // ---------------------------------------------------------------------------
@@ -360,11 +359,12 @@ export function buildOwnerOrAdminShapeWhere(
360
359
  // leaves stay `sql`: the `IN (subquery)` containment (Drizzle's `inArray` cannot wrap a raw subquery)
361
360
  // and the `(select current_setting(...)::type)` JWT-subject expression (wrapped in a scalar subquery —
362
361
  // the Supabase per-statement-eval RLS perf idiom). Columns serialize qualified
363
- // (`"work_items"."workspace_id"`) — fine for Postgres RLS (the write path, unlike Electric's bare rule).
362
+ // (`"work_items"."workspace_id"`) — fine for Postgres RLS, which is the write path; the read mirror
363
+ // builds a predicate AST from the same column objects and serializes no SQL at all.
364
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.
365
+ // The `select` half of this family is mirrored on the read path by
366
+ // {@link buildMembershipShapePredicate}, built from the same column declarations — the sync engine cannot
367
+ // read RLS, so the two surfaces are generated from one declaration and must agree.
368
368
  // ---------------------------------------------------------------------------
369
369
 
370
370
  type MembershipPolicyKind = "select" | "insert" | "update" | "delete";
@@ -519,26 +519,26 @@ export function buildSupabaseMembershipNativePolicies(options: SupabaseMembershi
519
519
  }
520
520
 
521
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
522
+ // Read-path mirror of the membership policies. The read path never runs RLS, so the control plane must
523
+ // re-derive the same visible set in the shape predicate, from the SAME Drizzle columns the policies were
524
524
  // built from — one declaration, two enforcement surfaces, so a row can never be readable-but-unwritable
525
525
  // (or the reverse) through a rename or a typo.
526
526
  //
527
527
  // SELECT only, by construction: the mirror reproduces the family's `select` predicate — plain
528
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
529
+ // concerns (INSERT/UPDATE/DELETE) and are deliberately absent here; a shape predicate filters a read
530
530
  // stream and has nothing to gate.
531
531
  //
532
- // The two surfaces render the SAME containment differently, on purpose:
532
+ // The two surfaces express the SAME containment differently, on purpose:
533
533
  // - RLS (`membershipMatch`) renders `= ANY(ARRAY(select …))` — the InitPlan/bitmap-index-scan
534
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.
535
+ // - The mirror emits `p.in(col, p.subquery(…))` — an AST node the engine plans itself. There is no
536
+ // Postgres planner on this side to appease, and no SQL text for anything to lex.
537
+ // Same columns, two forms — that is exactly what the mirror is for.
538
538
  // ---------------------------------------------------------------------------
539
539
 
540
540
  /**
541
- * The columns {@link buildMembershipShapeWhere} needs: the SELECT-relevant subset of
541
+ * The columns {@link buildMembershipShapePredicate} needs: the SELECT-relevant subset of
542
542
  * {@link SupabaseMembershipPredicateColumns}. The write-only fields (owner, manager role, subject cast,
543
543
  * write gate, policy role) are accepted but ignored, so the **same declaration object** you hand to
544
544
  * {@link buildSupabaseMembershipNativePolicies} can be handed to the read mirror verbatim.
@@ -550,24 +550,28 @@ export type SupabaseMembershipShapeColumns = Pick<
550
550
  Partial<SupabaseMembershipNativePoliciesOptions>;
551
551
 
552
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.
553
+ * The membership **predicate** — the read-path mirror of the membership `select` policy, from the
554
+ * same column declarations.
560
555
  *
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.
556
+ * The containment becomes a first-class {@link InSubqueryPredicate} rather than SQL text, which buys
557
+ * something the text form could not: the engine maintains the inner set incrementally and **shares it
558
+ * across every shape referencing the same subquery**, so an entitlement-shaped membership costs one
559
+ * index rather than one per shape. The subquery is uncorrelated, as the engine requires — the inner
560
+ * `where` reads the membership table's own columns only.
563
561
  */
564
- export function buildMembershipShapeWhere(columns: SupabaseMembershipShapeColumns, claims: JwtClaims | null): SQL {
562
+ export function buildMembershipShapePredicate(
563
+ columns: SupabaseMembershipShapeColumns,
564
+ claims: JwtClaims | null,
565
+ ): Predicate {
565
566
  const subject = readSubjectClaim(claims);
566
567
  if (subject === null) {
567
- return DENY_ALL;
568
+ return DENY_ALL_PREDICATE;
568
569
  }
569
570
 
570
- return sql`${c(columns.containerColumn)} in (select ${c(columns.membershipContainerColumn)} from ${columns.membershipTable} where ${c(columns.membershipSubjectColumn)} = ${subject})`;
571
+ return p.in(
572
+ columns.containerColumn,
573
+ p.subquery(columns.membershipContainerColumn, p.eq(columns.membershipSubjectColumn, subject)),
574
+ );
571
575
  }
572
576
 
573
577
  // ---------------------------------------------------------------------------
@@ -589,10 +593,10 @@ export function buildMembershipShapeWhere(columns: SupabaseMembershipShapeColumn
589
593
  // regression-guard the InitPlan discipline (see the `rls-read-load` perf track);
590
594
  // never ship it.
591
595
  //
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.
596
+ // The same grant set is mirrored on the read path by {@link resolveGrantScopeAccess} (or
597
+ // {@link resolveGrantScopeIds} for the id set alone) + {@link buildGrantScopeShapePredicate}: the control
598
+ // plane resolves the ids from the claims in JS and compiles them into the shape's predicate — the sync
599
+ // engine cannot read RLS, so the two surfaces are generated from one declaration and must agree.
596
600
  // ---------------------------------------------------------------------------
597
601
 
598
602
  type GrantScopePolicyKind = "select" | "insert" | "update" | "delete";
@@ -607,7 +611,7 @@ const defaultBypassScopeKind = "platform";
607
611
  * An unconditional bypass declaration: any grant whose `role` ∈ `roleValues` and whose `scope.kind` =
608
612
  * `scopeKind` (default `"platform"`) confers access to every row — e.g. a platform-scoped
609
613
  * `platform_admin`. Hand the SAME object to the policy builder and to
610
- * {@link resolveGrantScopeAccess} / {@link buildGrantScopeAccessShapeWhere}.
614
+ * {@link resolveGrantScopeAccess} / {@link buildGrantScopeAccessShapePredicate}.
611
615
  */
612
616
  export type GrantScopeBypassOptions = {
613
617
  roleValues: string[];
@@ -635,7 +639,7 @@ export type SupabaseGrantScopePredicateColumns = GrantScopeClaimOptions & {
635
639
  * `bypass.roleValues` and whose `scope.kind` = `bypass.scopeKind` (default "platform") grants all
636
640
  * rows — e.g. a platform-scoped `platform_admin`. The bypass is an **uncorrelated** EXISTS, so it
637
641
  * 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).
642
+ * {@link buildGrantScopeAccessShapePredicate} (bypass → `null`, i.e. no shape filter at all).
639
643
  */
640
644
  bypass?: GrantScopeBypassOptions;
641
645
  };
@@ -753,13 +757,13 @@ export function buildSupabaseGrantScopeNativePolicies(options: SupabaseGrantScop
753
757
  }
754
758
 
755
759
  // ---------------------------------------------------------------------------
756
- // Electric read-path mirror of the grant-scope policy. Electric cannot read RLS, so the proxy must
757
- // resolve the same visible scope-id set from the claims in JS and inject a literal `IN (…)` shape
758
- // `where`. These helpers are the read-path counterpart to the policy above — one declaration,
760
+ // Read-path mirror of the grant-scope policy. The read path never runs RLS, so the control plane must
761
+ // resolve the same visible scope-id set from the claims in JS and emit it as a literal `in` predicate.
762
+ // These helpers are the read-path counterpart to the policy above — one declaration,
759
763
  // two enforcement surfaces, derived from the same grant data so they cannot drift.
760
764
  //
761
765
  // 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
766
+ // {@link buildGrantScopeAccessShapePredicate} turns it into `null` — no shape filter at all, every row
763
767
  // streams — exactly as the `exists (…)` OR-branch makes the scope test irrelevant on the write side.
764
768
  // Without it a bypass grant would be enforced on writes yet invisible on reads.
765
769
  // ---------------------------------------------------------------------------
@@ -804,20 +808,20 @@ export function resolveGrantScopeIds(claims: JwtClaims | null, options: GrantSco
804
808
  }
805
809
 
806
810
  /**
807
- * The Electric shape `where` for a grant-scope table: an `IN (…)` over the resolved ids (what the
808
- * proxy injects). Takes the real Drizzle scope column — referenced bare via `c()` (Electric's grammar
809
- * requires bare columns), so the reference is rename-safe — and returns a typed fragment whose ids
810
- * are **bound params** once `buildRowFilterShape` serializes it (never hand-escaped literals). An
811
- * empty id set denies all rows ({@link DENY_ALL}), mirroring the policy returning no rows.
811
+ * The grant-scope **predicate** — the read-path mirror of the grant-scope `select` policy.
812
+ * An empty id set denies all rows ({@link DENY_ALL_PREDICATE}), mirroring the policy returning no rows.
813
+ *
814
+ * An `OR` of equalities, not an `IN`: the engine's `In` leaf takes a *subquery*, and a grant set lives
815
+ * in the JWT rather than in a table, so there is nothing to select from. This is not a workaround —
816
+ * `OR(=v…)` is exactly what the engine's own SQL parser desugars `IN (list)` to, so the two forms
817
+ * compile to the same nodes.
812
818
  */
813
- export function buildGrantScopeShapeWhere(scopeColumn: AnyColumn, ids: string[]): SQL {
819
+ export function buildGrantScopeShapePredicate(scopeColumn: AnyColumn, ids: string[]): Predicate {
814
820
  if (ids.length === 0) {
815
- return DENY_ALL;
821
+ return DENY_ALL_PREDICATE;
816
822
  }
817
- return sql`${c(scopeColumn)} in (${sql.join(
818
- ids.map((id) => sql`${id}`),
819
- sql`, `,
820
- )})`;
823
+ const equalities = ids.map((id) => p.eq(scopeColumn, id));
824
+ return equalities.length === 1 ? equalities[0]! : p.or(...equalities);
821
825
  }
822
826
 
823
827
  /** The full grant-scope declaration the read mirror needs: the claim options plus the optional bypass. */
@@ -879,7 +883,7 @@ function hasGrantScopeBypass(claims: JwtClaims | null, options: GrantScopeAccess
879
883
  * options object you gave {@link buildSupabaseGrantScopeNativePolicies} and a bypass grant cannot be
880
884
  * enforced on writes yet invisible on reads.
881
885
  *
882
- * Never throws on malformed claims (they reach a `customWhere` unverified in shape) — a wrong shape
886
+ * Never throws on malformed claims (they reach a `customPredicate` unverified in shape) — a wrong shape
883
887
  * simply confers nothing. A malformed `grantsClaimPath`/`scopeIdField` **option** is still a loud error.
884
888
  */
885
889
  export function resolveGrantScopeAccess(claims: JwtClaims | null, options: GrantScopeAccessOptions): GrantScopeAccess {
@@ -890,18 +894,16 @@ export function resolveGrantScopeAccess(claims: JwtClaims | null, options: Grant
890
894
  }
891
895
 
892
896
  /**
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.
897
+ * The grant-scope **predicate**, bypass included — the native-path counterpart to
898
+ * the grant-scope `select` policy, from the same declaration. A caller holding a bypass grant
899
+ * gets `null` (no filter, every row); anyone else gets {@link buildGrantScopeShapePredicate} over
900
+ * their resolved ids.
899
901
  */
900
- export function buildGrantScopeAccessShapeWhere(
902
+ export function buildGrantScopeAccessShapePredicate(
901
903
  scopeColumn: AnyColumn,
902
904
  claims: JwtClaims | null,
903
905
  options: GrantScopeAccessOptions,
904
- ): SQL | null {
906
+ ): Predicate | null {
905
907
  const access = resolveGrantScopeAccess(claims, options);
906
- return access.bypass ? null : buildGrantScopeShapeWhere(scopeColumn, access.ids);
908
+ return access.bypass ? null : buildGrantScopeShapePredicate(scopeColumn, access.ids);
907
909
  }