@rebasepro/server-postgres 0.9.1-canary.fd3754b → 0.9.1-canary.ff338b5

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 (54) hide show
  1. package/dist/PostgresBackendDriver.d.ts +25 -2
  2. package/dist/PostgresBootstrapper.d.ts +10 -0
  3. package/dist/auth/services.d.ts +16 -0
  4. package/dist/collections/buildRegistry.d.ts +27 -0
  5. package/dist/connection.d.ts +21 -0
  6. package/dist/data-transformer.d.ts +9 -2
  7. package/dist/index.es.js +2005 -2583
  8. package/dist/index.es.js.map +1 -1
  9. package/dist/schema/doctor.d.ts +1 -1
  10. package/dist/security/policy-drift.d.ts +46 -5
  11. package/dist/security/rls-enforcement.d.ts +27 -2
  12. package/dist/services/FetchService.d.ts +4 -24
  13. package/dist/services/PersistService.d.ts +27 -1
  14. package/dist/services/RelationService.d.ts +34 -1
  15. package/dist/services/collection-helpers.d.ts +79 -14
  16. package/dist/services/dataService.d.ts +3 -1
  17. package/dist/services/index.d.ts +1 -1
  18. package/dist/services/realtimeService.d.ts +7 -0
  19. package/dist/services/row-pipeline.d.ts +63 -0
  20. package/package.json +16 -17
  21. package/src/PostgresBackendDriver.ts +127 -13
  22. package/src/PostgresBootstrapper.ts +68 -26
  23. package/src/auth/ensure-tables.ts +73 -11
  24. package/src/auth/services.ts +49 -19
  25. package/src/cli-helpers.ts +2 -20
  26. package/src/cli.ts +60 -0
  27. package/src/collections/buildRegistry.ts +59 -0
  28. package/src/connection.ts +61 -1
  29. package/src/data-transformer.ts +11 -9
  30. package/src/databasePoolManager.ts +2 -0
  31. package/src/schema/doctor-cli.ts +5 -1
  32. package/src/schema/doctor.ts +45 -20
  33. package/src/schema/generate-drizzle-schema-logic.ts +24 -29
  34. package/src/schema/generate-postgres-ddl-logic.ts +76 -28
  35. package/src/schema/introspect-db.ts +19 -2
  36. package/src/security/policy-drift.test.ts +153 -14
  37. package/src/security/policy-drift.ts +128 -10
  38. package/src/security/rls-enforcement.ts +64 -3
  39. package/src/services/BranchService.ts +42 -10
  40. package/src/services/FetchService.ts +65 -270
  41. package/src/services/PersistService.ts +130 -14
  42. package/src/services/RelationService.ts +153 -94
  43. package/src/services/collection-helpers.ts +164 -47
  44. package/src/services/dataService.ts +3 -2
  45. package/src/services/index.ts +1 -0
  46. package/src/services/realtimeService.ts +40 -19
  47. package/src/services/row-pipeline.ts +239 -0
  48. package/src/utils/drizzle-conditions.ts +13 -0
  49. package/src/websocket.ts +4 -1
  50. package/dist/chunk-DSJWtz9O.js +0 -40
  51. package/dist/schema/auth-default-policies.d.ts +0 -10
  52. package/dist/src-Eh-CZosp.js +0 -595
  53. package/dist/src-Eh-CZosp.js.map +0 -1
  54. package/src/schema/auth-default-policies.ts +0 -125
@@ -17,6 +17,7 @@ import {
17
17
  RebaseData,
18
18
  RebaseSdkData,
19
19
  RestFetchService,
20
+ SaveManyProps,
20
21
  SaveProps,
21
22
  TableColumnInfo,
22
23
  TableForeignKeyInfo,
@@ -28,6 +29,7 @@ import {
28
29
  import { sql as drizzleSql } from "drizzle-orm";
29
30
  import { buildPropertyCallbacks, buildSdkData, resolveCollectionRelations, updateDateAutoValues } from "@rebasepro/common";
30
31
  import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry";
32
+ import { deriveRowAddress } from "./services/collection-helpers";
31
33
  import { HistoryService } from "./history/HistoryService";
32
34
  import { mergeDeep } from "@rebasepro/utils";
33
35
  import { logger } from "@rebasepro/server";
@@ -532,7 +534,8 @@ export class PostgresBackendDriver implements DataDriver {
532
534
  id,
533
535
  values,
534
536
  collection,
535
- status
537
+ status,
538
+ upsert
536
539
  }: SaveProps<M>): Promise<Record<string, unknown>> {
537
540
 
538
541
  const {
@@ -545,13 +548,26 @@ export class PostgresBackendDriver implements DataDriver {
545
548
  let updatedValues = values;
546
549
  const contextForCallback = this.buildCallContext();
547
550
 
548
- // Fetch previous values for callbacks AND history recording
551
+ // Fetch previous values for callbacks AND history recording. Same walk
552
+ // as the saved row the callbacks receive (`fetchOneForRest`), so
553
+ // `values` and `previousValues` compare like with like — a Date on one
554
+ // side and its ISO string on the other reads as a change that never
555
+ // happened.
549
556
  let previousValuesForHistory: Partial<M> | undefined;
550
557
  if (status === "existing" && id) {
551
- const existing = await this.dataService.fetchOne<M>(path, id, resolvedCollection?.databaseId);
552
- if (existing) {
553
- const { id: _existingId, ...existingValues } = existing;
554
- previousValuesForHistory = existingValues as Partial<M>;
558
+ try {
559
+ const existing = await this.dataService.getFetchService()
560
+ .fetchOneForRest(path, id, undefined, resolvedCollection?.databaseId);
561
+ if (existing) {
562
+ const { id: _existingId, ...existingValues } = existing;
563
+ previousValuesForHistory = existingValues as Partial<M>;
564
+ }
565
+ } catch (err) {
566
+ // Best-effort enrichment: callbacks and history run without
567
+ // previous values rather than the save failing on a read the
568
+ // write itself does not need (e.g. a collection whose key the
569
+ // registry cannot resolve).
570
+ logger.debug(`[save] Could not fetch previous values for "${path}"`, { detail: err instanceof Error ? err.message : String(err) });
555
571
  }
556
572
  }
557
573
 
@@ -616,7 +632,8 @@ export class PostgresBackendDriver implements DataDriver {
616
632
  path,
617
633
  updatedValues,
618
634
  id,
619
- resolvedCollection?.databaseId
635
+ resolvedCollection?.databaseId,
636
+ { upsert }
620
637
  );
621
638
 
622
639
  if (savedRow && (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead)) {
@@ -649,8 +666,19 @@ export class PostgresBackendDriver implements DataDriver {
649
666
  }
650
667
  }
651
668
 
652
- const savedId = savedRow.id as string | number;
653
- const { id: _savedId, ...savedValues } = savedRow;
669
+ // The row is exactly its columns, so its address is derived, not read
670
+ // off it: `savedRow.id` is undefined for every table whose key is not
671
+ // literally named `id`, and is ordinary data for a table that has such
672
+ // a column without it being the key.
673
+ const savedId = deriveRowAddress(
674
+ savedRow,
675
+ (resolvedCollection ?? collection) as CollectionConfig,
676
+ this.registry
677
+ );
678
+ // `values` are the row's columns — all of them. For an `id`-keyed table
679
+ // that includes `id`, which used to be stripped here because it was the
680
+ // synthesized address rather than the column it now is.
681
+ const savedValues = savedRow;
654
682
 
655
683
  if (globalCallbacks?.afterSave || callbacks?.afterSave || propertyCallbacks?.afterSave) {
656
684
  // 1. Global callbacks first
@@ -695,7 +723,7 @@ export class PostgresBackendDriver implements DataDriver {
695
723
  if (this.historyService && resolvedCollection?.history) {
696
724
  this.historyService.recordHistory({
697
725
  tableName: path,
698
- id: savedId.toString(),
726
+ id: savedId,
699
727
  action: status === "new" ? "create" : "update",
700
728
  values: savedValues as Record<string, unknown>,
701
729
  previousValues: previousValuesForHistory as Record<string, unknown> | undefined,
@@ -707,14 +735,14 @@ export class PostgresBackendDriver implements DataDriver {
707
735
  if (this._deferNotifications) {
708
736
  this._pendingNotifications.push({
709
737
  path,
710
- id: savedId.toString(),
738
+ id: savedId,
711
739
  row: savedRow,
712
740
  databaseId: resolvedCollection?.databaseId
713
741
  });
714
742
  } else {
715
743
  await this.realtimeService.notifyUpdate(
716
744
  path,
717
- savedId.toString(),
745
+ savedId,
718
746
  savedRow,
719
747
  resolvedCollection?.databaseId
720
748
  );
@@ -764,13 +792,86 @@ export class PostgresBackendDriver implements DataDriver {
764
792
  }
765
793
  }
766
794
 
795
+ /**
796
+ * Write many rows through the same pipeline as {@link save}.
797
+ *
798
+ * The batch runs in one transaction of its own, so a failure part-way leaves
799
+ * nothing behind — the point of a batch is that a re-run starts from a known
800
+ * state. When this driver is already inside a transaction (the authenticated
801
+ * path, via `withTransaction`) the nested call becomes a savepoint, which is
802
+ * still atomic and still commits once.
803
+ *
804
+ * Rows are applied in order, so a batch that touches the same key twice ends
805
+ * with the last write winning, exactly as separate calls would.
806
+ */
807
+ async saveMany<M extends Record<string, unknown>>({
808
+ path,
809
+ rows,
810
+ collection,
811
+ upsert
812
+ }: SaveManyProps<M>): Promise<Record<string, unknown>[]> {
813
+ return this.db.transaction(async (tx) => {
814
+ // Bind the whole batch to the transaction handle. Without this the
815
+ // rows would be written through `this.db` and survive a rollback.
816
+ const txDriver = new PostgresBackendDriver(
817
+ tx, this.realtimeService, this.registry, this.user, this.poolManager, this.historyService
818
+ );
819
+ txDriver.dataService = new DataService(tx, this.registry);
820
+ txDriver.client = this.client;
821
+ // Carry the caller's notification batching through, so a bulk write
822
+ // nested in an outer transaction still holds its events until commit.
823
+ txDriver._deferNotifications = this._deferNotifications;
824
+ txDriver._pendingNotifications = this._pendingNotifications;
825
+
826
+ const saved: Record<string, unknown>[] = [];
827
+
828
+ for (let i = 0; i < rows.length; i++) {
829
+ const values = rows[i];
830
+ const id = (values as Record<string, unknown>)?.id as string | number | undefined;
831
+ try {
832
+ saved.push(await txDriver.save<M>({
833
+ path,
834
+ values,
835
+ // No `id` argument, deliberately: passing one selects the
836
+ // UPDATE path, and an import's rows usually carry a natural
837
+ // key for a row that does not exist yet — which would 404 on
838
+ // every one. Leaving the key inside `values` is what
839
+ // single-row `create(data, id)` does, and it inserts.
840
+ // Callers who want existing rows overwritten pass `upsert`.
841
+ collection,
842
+ status: "new",
843
+ upsert
844
+ }));
845
+ } catch (error) {
846
+ // One bad row in ten thousand is impossible to find from a
847
+ // message that only says the batch failed. Say which row, and
848
+ // keep the original error as the cause so its status survives.
849
+ const label = id !== undefined ? `id ${JSON.stringify(id)}` : "no id";
850
+ throw Object.assign(
851
+ new Error(`Row ${i} of ${rows.length} (${label}) failed: ${(error as Error)?.message ?? error}`, { cause: error }),
852
+ {
853
+ statusCode: (error as { statusCode?: number })?.statusCode,
854
+ code: (error as { code?: string })?.code,
855
+ name: (error as Error)?.name
856
+ }
857
+ );
858
+ }
859
+ }
860
+
861
+ return saved;
862
+ });
863
+ }
864
+
767
865
  async delete<M extends Record<string, unknown>>({
768
866
  row,
769
867
  collection
770
868
  }: DeleteProps<M>): Promise<void> {
771
869
 
772
870
  const targetPath = row.path;
773
- const targetRow: Record<string, unknown> = { id: row.id, ...(row.values ?? {}) };
871
+ // The callbacks' `row` is the row: its columns, nothing else. The address
872
+ // travels beside it as `id`, so merging it in here only ever invented an
873
+ // `id` field for tables that have no such column.
874
+ const targetRow: Record<string, unknown> = { ...(row.values ?? {}) };
774
875
 
775
876
  // Resolve from backend registry to restore callbacks lost during WebSocket serialization
776
877
  const {
@@ -1362,6 +1463,19 @@ export class AuthenticatedPostgresBackendDriver implements DataDriver {
1362
1463
  return this.withTransaction((delegate) => delegate.save(props));
1363
1464
  }
1364
1465
 
1466
+ /**
1467
+ * One transaction for the whole batch, rather than one per row.
1468
+ *
1469
+ * This is the point of the method: `save` opens a transaction per call, so
1470
+ * importing 10k rows through it means 10k transactions (and, over HTTP, 10k
1471
+ * round trips). Here the RLS context is established once and every row lands
1472
+ * or none does. Realtime notifications are already deferred to commit by
1473
+ * `withTransaction`, so a batch does not flood subscribers mid-flight.
1474
+ */
1475
+ async saveMany<M extends Record<string, unknown>>(props: SaveManyProps<M>): Promise<Record<string, unknown>[]> {
1476
+ return this.withTransaction((delegate) => delegate.saveMany(props));
1477
+ }
1478
+
1365
1479
  async delete<M extends Record<string, unknown>>(props: DeleteProps<M>): Promise<void> {
1366
1480
  return this.withTransaction((delegate) => delegate.delete(props));
1367
1481
  }
@@ -4,7 +4,7 @@
4
4
  * Implements the `BackendBootstrapper` interface for PostgreSQL.
5
5
  */
6
6
 
7
- import { getTableName, isTable, Relations, sql } from "drizzle-orm";
7
+ import { Relations, sql } from "drizzle-orm";
8
8
  import { NodePgDatabase } from "drizzle-orm/node-postgres";
9
9
  import { PgEnum, PgTable } from "drizzle-orm/pg-core";
10
10
  import type { RebasePgTable } from "./types";
@@ -21,6 +21,7 @@ import {
21
21
  } from "@rebasepro/types";
22
22
  import { PostgresBackendDriver } from "./PostgresBackendDriver";
23
23
  import { RealtimeService } from "./services/realtimeService";
24
+ import { buildCollectionRegistry } from "./collections/buildRegistry";
24
25
  import { DatabasePoolManager } from "./databasePoolManager";
25
26
  import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry";
26
27
  import { createEmailService, type EmailConfig, type EmailService, logger } from "@rebasepro/server";
@@ -33,7 +34,7 @@ import { ensureHistoryTableExists } from "./history/ensure-history-table";
33
34
  import { patchPgArrayNullSafety } from "./utils/pg-array-null-patch";
34
35
  import { buildCollectionsFromSchema, introspectSchema, readRlsStatus } from "./schema/introspect-runtime";
35
36
  import { buildDrizzleTablesFromSchema, buildDrizzleRelationsFromSchema } from "./schema/dynamic-tables";
36
- import { detectConnectionPosture, ensureAppRole, validatePolicyPgRoles, REBASE_USER_ROLE, type RawSqlRunner } from "./security/rls-enforcement";
37
+ import { detectConnectionPosture, ensureAppRole, validatePolicyPgRoles, warnOnAnonymousGrants, REBASE_USER_ROLE, type RawSqlRunner } from "./security/rls-enforcement";
37
38
  import { provisionTriggerCdc, type CdcTableRef } from "./services/cdc/trigger-cdc";
38
39
 
39
40
  export interface PostgresDriverConfig {
@@ -64,6 +65,15 @@ export interface PostgresDriverInternals {
64
65
  realtimeService: RealtimeService;
65
66
  driver: PostgresBackendDriver;
66
67
  poolManager?: DatabasePoolManager;
68
+ /**
69
+ * Attach CDC triggers to tables that did not exist when the driver
70
+ * bootstrapped. Only set when database-level capture is actually active.
71
+ *
72
+ * Auth owns its own tables and creates them later in boot, so at driver
73
+ * bootstrap they are legitimately missing and get skipped; without this
74
+ * they would stay uninstrumented until the next restart.
75
+ */
76
+ provisionCdcForTables?: (tables: CdcTableRef[]) => Promise<void>;
67
77
  }
68
78
 
69
79
  // Re-export from shared CLI error utilities
@@ -161,30 +171,17 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
161
171
  }
162
172
 
163
173
  const activeCollections = introspectedCollections ?? collections;
164
-
165
- // Create a fresh registry for this driver
166
- const registry = new PostgresCollectionRegistry();
167
- if (activeCollections) {
168
- registry.registerMultiple(activeCollections);
169
- logger.info(`📋 [PostgresRegistry] Registered ${registry.getCollections().length} collections: [${registry.getCollections().map(c => c.slug).join(", ")}]`);
170
- }
171
-
172
174
  const schemaTables = introspectedTables ?? pgConfig.schema?.tables;
173
-
174
- // Register tables
175
- if (schemaTables) {
176
- Object.values(schemaTables).forEach((table) => {
177
- if (isTable(table)) {
178
- const tableName = getTableName(table);
179
- registry.registerTable(table as PgTable, tableName);
180
- }
181
- });
182
- }
183
-
184
- if (pgConfig.schema?.enums) registry.registerEnums(pgConfig.schema.enums as Record<string, PgEnum<[string, ...string[]]>>);
185
-
186
175
  const schemaRelations = introspectedRelations ?? (pgConfig.schema?.relations as Record<string, Relations> | undefined);
187
- if (schemaRelations) registry.registerRelations(schemaRelations);
176
+
177
+ // Create a fresh registry for this driver. Registration order is
178
+ // load-bearing, so it lives in one place — see `buildCollectionRegistry`.
179
+ const registry = buildCollectionRegistry({
180
+ collections: activeCollections,
181
+ tables: schemaTables,
182
+ enums: pgConfig.schema?.enums as Record<string, PgEnum<[string, ...string[]]>> | undefined,
183
+ relations: schemaRelations
184
+ });
188
185
 
189
186
  // Patch Drizzle's PgArray columns to handle NULL values safely.
190
187
  // Drizzle's mapFromDriverValue crashes with "value.map is not a function"
@@ -303,6 +300,11 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
303
300
  registry.getCollections() as never,
304
301
  driver.rlsUserRole ?? posture.role
305
302
  );
303
+
304
+ // The same habit one surface over, and the dangerous direction:
305
+ // a rule that reads as "signed in only" but is true for every
306
+ // caller grants the data away rather than hiding it.
307
+ warnOnAnonymousGrants(registry.getCollections() as never);
306
308
  }
307
309
 
308
310
  // Ensure branch metadata table exists when branching is available
@@ -341,6 +343,7 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
341
343
  const wantsCdc = cdcMode !== "off";
342
344
  const explicitCdc = cdcMode === "trigger" || cdcMode === "wal";
343
345
  let cdcEnabled = false;
346
+ let provisionCdcForTables: PostgresDriverInternals["provisionCdcForTables"];
344
347
 
345
348
  if (wantsCdc && !directUrl) {
346
349
  const reason = "no direct database connection is available for the realtime LISTEN client (set DATABASE_DIRECT_URL)";
@@ -374,6 +377,11 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
374
377
  await provisionTriggerCdc(cdcRunSql, cdcTables);
375
378
  await realtimeService.enableCdc(directUrl);
376
379
  cdcEnabled = true;
380
+ // Boot steps that create their own tables (auth) run after
381
+ // this one and use it to instrument what they just created.
382
+ provisionCdcForTables = async (tables) => {
383
+ await provisionTriggerCdc(cdcRunSql, tables);
384
+ };
377
385
  logger.info(
378
386
  `📡 [CDC] Realtime source = database-level change capture (mode: ${cdcMode === "wal" ? "wal→trigger" : "trigger"}). ` +
379
387
  `All writes now emit realtime events regardless of origin.`
@@ -424,6 +432,14 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
424
432
  );
425
433
  const missing: Array<{ slug: string; table: string }> = [];
426
434
  for (const col of registeredCollections) {
435
+ // Auth owns its table and creates it later in this same
436
+ // boot (initializeAuth → ensureAuthTablesExist), so it is
437
+ // legitimately absent right now. Reporting it as drift
438
+ // tells the user to `db:push` a table that is about to
439
+ // exist — and on an introspected database, one that the
440
+ // database was never supposed to hold.
441
+ if ((col as { auth?: { enabled?: boolean } }).auth?.enabled) continue;
442
+
427
443
  const schemaName = "schema" in col && col.schema ? col.schema : "public";
428
444
  const tableName = registry.hasTableForCollection(
429
445
  col.table ?? col.slug
@@ -438,8 +454,10 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
438
454
  const checkName = resolvedTable ?? tableName;
439
455
  const fullCheckName = schemaName === "public" ? checkName : `${schemaName}.${checkName}`;
440
456
  if (!dbTables.has(fullCheckName)) {
457
+ // Report what was actually looked up: an unqualified
458
+ // "users" sends people hunting for public.users.
441
459
  missing.push({ slug: col.slug,
442
- table: checkName });
460
+ table: fullCheckName });
443
461
  }
444
462
  }
445
463
  if (missing.length > 0) {
@@ -473,7 +491,8 @@ table: checkName });
473
491
  registry,
474
492
  realtimeService,
475
493
  driver,
476
- poolManager
494
+ poolManager,
495
+ provisionCdcForTables
477
496
  };
478
497
 
479
498
  return {
@@ -502,6 +521,29 @@ table: checkName });
502
521
  // ensureAuthTablesExist works with the collection abstraction — no Drizzle leakage.
503
522
  await ensureAuthTablesExist(db, authCollection);
504
523
 
524
+ // The driver bootstrapped before these tables existed, so CDC skipped
525
+ // them. Instrument them now, or writes to the user table emit no
526
+ // realtime events until the next restart.
527
+ if (authCollection && internals.provisionCdcForTables) {
528
+ const authSchema = "schema" in authCollection && typeof authCollection.schema === "string"
529
+ ? authCollection.schema
530
+ : "rebase";
531
+ const authTable = "table" in authCollection && typeof authCollection.table === "string"
532
+ ? authCollection.table
533
+ : authCollection.slug;
534
+ if (authTable) {
535
+ try {
536
+ await internals.provisionCdcForTables([{ schema: authSchema, table: authTable }]);
537
+ } catch (err) {
538
+ logger.warn(
539
+ `⚠️ [CDC] Could not attach change-capture to the auth table "${authSchema}.${authTable}" — ` +
540
+ "writes to it won't emit database-level events.",
541
+ { detail: err instanceof Error ? err.message : String(err) }
542
+ );
543
+ }
544
+ }
545
+ }
546
+
505
547
  let emailService: EmailService | undefined;
506
548
  if (authConfig.email) {
507
549
  emailService = createEmailService(authConfig.email as EmailConfig);
@@ -251,17 +251,32 @@ export async function ensureAuthTablesExist(db: NodePgDatabase, collection?: Col
251
251
  // Seed default roles if none exist
252
252
  // (no-op: roles are now stored inline on the users table)
253
253
 
254
- // ── Migration: Add is_anonymous column (safe for existing tables) ────
255
- await db.execute(sql`
256
- ALTER TABLE ${sql.raw(usersTableName)}
257
- ADD COLUMN IF NOT EXISTS is_anonymous BOOLEAN DEFAULT FALSE
258
- `);
259
-
260
- // ── Migration: Add inline roles column (safe for existing tables) ────
261
- await db.execute(sql`
262
- ALTER TABLE ${sql.raw(usersTableName)}
263
- ADD COLUMN IF NOT EXISTS roles TEXT[] DEFAULT '{}' NOT NULL
264
- `);
254
+ // ── Migration: reconcile the full users column set (safe for existing tables) ──
255
+ // CREATE TABLE IF NOT EXISTS never revisits an existing table, so a
256
+ // database provisioned by an older framework era is missing every
257
+ // column added since. Each column the auth services read or write must
258
+ // be back-filled here, or upgraded deployments break on the first
259
+ // statement that references it. `email` is deliberately absent: it has
260
+ // existed since the first era and cannot be added NOT NULL safely.
261
+ const userColumnBackfills = [
262
+ "display_name VARCHAR(255)",
263
+ "photo_url VARCHAR(500)",
264
+ "roles TEXT[] DEFAULT '{}' NOT NULL",
265
+ "password_hash VARCHAR(255)",
266
+ "email_verified BOOLEAN DEFAULT FALSE NOT NULL",
267
+ "email_verification_token VARCHAR(255)",
268
+ "email_verification_sent_at TIMESTAMP WITH TIME ZONE",
269
+ "is_anonymous BOOLEAN DEFAULT FALSE NOT NULL",
270
+ "metadata JSONB DEFAULT '{}' NOT NULL",
271
+ "created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL",
272
+ "updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL"
273
+ ];
274
+ for (const columnDef of userColumnBackfills) {
275
+ await db.execute(sql`
276
+ ALTER TABLE ${sql.raw(usersTableName)}
277
+ ADD COLUMN IF NOT EXISTS ${sql.raw(columnDef)}
278
+ `);
279
+ }
265
280
 
266
281
  // ── Migration: Copy roles from legacy junction table to inline column ──
267
282
  // If the old rebase.user_roles and rebase.roles tables exist, migrate
@@ -358,6 +373,53 @@ export async function ensureAuthTablesExist(db: NodePgDatabase, collection?: Col
358
373
  ON ${sql.raw(recoveryCodesTableName)}(user_id)
359
374
  `);
360
375
 
376
+ // ── Migration: clear stale FORCE ROW LEVEL SECURITY (older RLS model) ──
377
+ // The current model never emits FORCE: privileged auth writes run as
378
+ // the table owner and rely on the owner bypassing plain ENABLE RLS
379
+ // (see generate-postgres-ddl-logic). A table still carrying FORCE from
380
+ // an older framework era binds the owner too, so the first user
381
+ // registration after an upgrade fails with SQLSTATE 42501. Reconcile
382
+ // on boot; only tables actually flagged get the ALTER (and its lock).
383
+ try {
384
+ const authTablePairs: [string, string][] = [
385
+ [usersSchema, resolvedTable],
386
+ [authSchema, "user_identities"],
387
+ [authSchema, "refresh_tokens"],
388
+ [authSchema, "password_reset_tokens"],
389
+ [authSchema, "app_config"],
390
+ [authSchema, "mfa_factors"],
391
+ [authSchema, "mfa_challenges"],
392
+ [authSchema, "recovery_codes"]
393
+ ];
394
+ for (const [schemaName, tableName] of authTablePairs) {
395
+ const forced = await db.execute(sql`
396
+ SELECT 1
397
+ FROM pg_class c
398
+ JOIN pg_namespace n ON n.oid = c.relnamespace
399
+ WHERE n.nspname = ${schemaName}
400
+ AND c.relname = ${tableName}
401
+ AND c.relforcerowsecurity
402
+ `);
403
+ if (forced.rows.length > 0) {
404
+ await db.execute(sql`
405
+ ALTER TABLE ${sql.raw(`"${schemaName}"."${tableName}"`)}
406
+ NO FORCE ROW LEVEL SECURITY
407
+ `);
408
+ logger.warn(
409
+ `🔧 Cleared stale FORCE ROW LEVEL SECURITY on "${schemaName}"."${tableName}" ` +
410
+ "(legacy RLS model — it binds the owner connection and breaks privileged auth writes)"
411
+ );
412
+ }
413
+ }
414
+ } catch (rlsReconcileError: unknown) {
415
+ // Non-fatal: the connection may lack ownership on a pre-provisioned
416
+ // table; registration will still fail loudly (42501) if FORCE remains.
417
+ logger.warn(
418
+ `⚠️ Could not reconcile FORCE ROW LEVEL SECURITY on auth tables: ` +
419
+ `${rlsReconcileError instanceof Error ? rlsReconcileError.message : String(rlsReconcileError)}`
420
+ );
421
+ }
422
+
361
423
  logger.info("✅ Auth tables ready");
362
424
  } catch (error) {
363
425
  logger.error("❌ Failed to create auth tables", { error });
@@ -82,6 +82,32 @@ export class UserService implements UserRepository {
82
82
  return `"${schema}"."${name}"`;
83
83
  }
84
84
 
85
+ /**
86
+ * Run a privileged auth write with an explicitly cleared RLS context.
87
+ *
88
+ * The auth services run on the base/owner connection, which by design
89
+ * carries a NULL `app.user_id` so the `auth.uid() IS NULL` server-escape
90
+ * in the default policies applies. That NULL is normally guaranteed by
91
+ * `set_config(..., is_local = true)` resetting at transaction end — but a
92
+ * GUC that survives on a pooled connection (or a connection role that
93
+ * doesn't bypass RLS: FORCE ROW LEVEL SECURITY, or a non-owner role)
94
+ * turns the trusted write into an RLS-scoped one and denies it with
95
+ * SQLSTATE 42501. Clearing the GUCs here, transaction-locally at the
96
+ * single chokepoint, makes the server context deterministic instead of
97
+ * trusting whatever state the pool hands us. `auth.uid()` reads '' as
98
+ * NULL via NULLIF, so '' is the server context.
99
+ */
100
+ private async withServerContext<T>(fn: (db: NodePgDatabase) => Promise<T>): Promise<T> {
101
+ return await this.db.transaction(async (tx) => {
102
+ await tx.execute(sql`
103
+ SELECT set_config('app.user_id', '', true),
104
+ set_config('app.user_roles', '', true),
105
+ set_config('app.jwt', '', true)
106
+ `);
107
+ return await fn(tx as unknown as NodePgDatabase);
108
+ });
109
+ }
110
+
85
111
  private mapRowToUser(row: Record<string, unknown>): UserData {
86
112
  if (!row) return row as UserData;
87
113
 
@@ -200,7 +226,9 @@ export class UserService implements UserRepository {
200
226
 
201
227
  async createUser(data: CreateUserData): Promise<UserData> {
202
228
  const payload = this.mapPayload(data);
203
- const [row] = (await this.db.insert(this.usersTable).values(payload).returning()) as Record<string, unknown>[];
229
+ const [row] = await this.withServerContext(async (db) =>
230
+ (await db.insert(this.usersTable).values(payload).returning()) as Record<string, unknown>[]
231
+ );
204
232
  return this.mapRowToUser(row);
205
233
  }
206
234
 
@@ -255,12 +283,12 @@ export class UserService implements UserRepository {
255
283
  }
256
284
 
257
285
  async linkUserIdentity(userId: string, provider: string, providerId: string, profileData?: Record<string, unknown>): Promise<void> {
258
- await this.db.insert(this.userIdentitiesTable).values({
286
+ await this.withServerContext(async (db) => db.insert(this.userIdentitiesTable).values({
259
287
  userId,
260
288
  provider,
261
289
  providerId,
262
290
  profileData: profileData || null
263
- }).onConflictDoNothing({ target: [this.userIdentitiesTable.provider, this.userIdentitiesTable.providerId] });
291
+ }).onConflictDoNothing({ target: [this.userIdentitiesTable.provider, this.userIdentitiesTable.providerId] }));
264
292
  }
265
293
 
266
294
  async updateUser(id: string, data: Partial<Omit<CreateUserData, "id">>): Promise<UserData | null> {
@@ -270,18 +298,20 @@ export class UserService implements UserRepository {
270
298
  const updatedAtKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
271
299
  payload[updatedAtKey] = new Date();
272
300
 
273
- const [row] = (await this.db
274
- .update(this.usersTable)
275
- .set(payload)
276
- .where(eq(idCol, id))
277
- .returning()) as Record<string, unknown>[];
301
+ const [row] = await this.withServerContext(async (db) =>
302
+ (await db
303
+ .update(this.usersTable)
304
+ .set(payload)
305
+ .where(eq(idCol, id))
306
+ .returning()) as Record<string, unknown>[]
307
+ );
278
308
  return row ? this.mapRowToUser(row) : null;
279
309
  }
280
310
 
281
311
  async deleteUser(id: string): Promise<void> {
282
312
  const idCol = getColumn(this.usersTable, "id");
283
313
  if (!idCol) return;
284
- await this.db.delete(this.usersTable).where(eq(idCol, id));
314
+ await this.withServerContext(async (db) => db.delete(this.usersTable).where(eq(idCol, id)));
285
315
  }
286
316
 
287
317
  async listUsers(): Promise<UserData[]> {
@@ -357,13 +387,13 @@ export class UserService implements UserRepository {
357
387
  const passwordHashColKey = getColumnKey(this.usersTable, "passwordHash", "password_hash") || "passwordHash";
358
388
  const updatedAtColKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
359
389
 
360
- await this.db
390
+ await this.withServerContext(async (db) => db
361
391
  .update(this.usersTable)
362
392
  .set({
363
393
  [passwordHashColKey]: passwordHash,
364
394
  [updatedAtColKey]: new Date()
365
395
  })
366
- .where(eq(idCol, id));
396
+ .where(eq(idCol, id)));
367
397
  }
368
398
 
369
399
  /**
@@ -376,14 +406,14 @@ export class UserService implements UserRepository {
376
406
  const emailVerificationTokenColKey = getColumnKey(this.usersTable, "emailVerificationToken", "email_verification_token") || "emailVerificationToken";
377
407
  const updatedAtColKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
378
408
 
379
- await this.db
409
+ await this.withServerContext(async (db) => db
380
410
  .update(this.usersTable)
381
411
  .set({
382
412
  [emailVerifiedColKey]: verified,
383
413
  [emailVerificationTokenColKey]: null,
384
414
  [updatedAtColKey]: new Date()
385
415
  })
386
- .where(eq(idCol, id));
416
+ .where(eq(idCol, id)));
387
417
  }
388
418
 
389
419
  /**
@@ -396,14 +426,14 @@ export class UserService implements UserRepository {
396
426
  const emailVerificationSentAtColKey = getColumnKey(this.usersTable, "emailVerificationSentAt", "email_verification_sent_at") || "emailVerificationSentAt";
397
427
  const updatedAtColKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
398
428
 
399
- await this.db
429
+ await this.withServerContext(async (db) => db
400
430
  .update(this.usersTable)
401
431
  .set({
402
432
  [emailVerificationTokenColKey]: token,
403
433
  [emailVerificationSentAtColKey]: token ? new Date() : null,
404
434
  [updatedAtColKey]: new Date()
405
435
  })
406
- .where(eq(idCol, id));
436
+ .where(eq(idCol, id)));
407
437
  }
408
438
 
409
439
  /**
@@ -463,11 +493,11 @@ export class UserService implements UserRepository {
463
493
  async setUserRoles(userId: string, roleIds: string[]): Promise<void> {
464
494
  const usersTableName = this.getQualifiedUsersTableName();
465
495
  const rolesArray = `{${roleIds.join(",")}}`;
466
- await this.db.execute(sql`
496
+ await this.withServerContext(async (db) => db.execute(sql`
467
497
  UPDATE ${sql.raw(usersTableName)}
468
498
  SET roles = ${rolesArray}::text[], updated_at = NOW()
469
499
  WHERE id = ${userId}
470
- `);
500
+ `));
471
501
  }
472
502
 
473
503
  /**
@@ -475,11 +505,11 @@ export class UserService implements UserRepository {
475
505
  */
476
506
  async assignDefaultRole(userId: string, roleId: string): Promise<void> {
477
507
  const usersTableName = this.getQualifiedUsersTableName();
478
- await this.db.execute(sql`
508
+ await this.withServerContext(async (db) => db.execute(sql`
479
509
  UPDATE ${sql.raw(usersTableName)}
480
510
  SET roles = array_append(roles, ${roleId}), updated_at = NOW()
481
511
  WHERE id = ${userId} AND NOT (${roleId} = ANY(roles))
482
- `);
512
+ `));
483
513
  }
484
514
 
485
515
  /**