@rebasepro/server-postgres 0.9.1-canary.f0ac103 → 0.9.1-canary.fd3754b
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.
- package/dist/PostgresBackendDriver.d.ts +2 -25
- package/dist/PostgresBootstrapper.d.ts +0 -10
- package/dist/auth/services.d.ts +0 -16
- package/dist/chunk-DSJWtz9O.js +40 -0
- package/dist/connection.d.ts +0 -21
- package/dist/data-transformer.d.ts +2 -9
- package/dist/index.es.js +2604 -2007
- package/dist/index.es.js.map +1 -1
- package/dist/schema/auth-default-policies.d.ts +10 -0
- package/dist/security/policy-drift.d.ts +5 -16
- package/dist/security/rls-enforcement.d.ts +2 -27
- package/dist/services/FetchService.d.ts +24 -4
- package/dist/services/PersistService.d.ts +1 -27
- package/dist/services/RelationService.d.ts +1 -34
- package/dist/services/collection-helpers.d.ts +14 -79
- package/dist/services/dataService.d.ts +1 -3
- package/dist/services/index.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +0 -7
- package/dist/src-Eh-CZosp.js +595 -0
- package/dist/src-Eh-CZosp.js.map +1 -0
- package/package.json +17 -15
- package/src/PostgresBackendDriver.ts +13 -127
- package/src/PostgresBootstrapper.ts +26 -68
- package/src/auth/ensure-tables.ts +11 -73
- package/src/auth/services.ts +19 -49
- package/src/cli-helpers.ts +20 -2
- package/src/connection.ts +1 -61
- package/src/data-transformer.ts +9 -11
- package/src/databasePoolManager.ts +0 -2
- package/src/schema/auth-default-policies.ts +125 -0
- package/src/schema/doctor-cli.ts +1 -5
- package/src/schema/generate-drizzle-schema-logic.ts +29 -24
- package/src/schema/generate-postgres-ddl-logic.ts +28 -76
- package/src/schema/introspect-db.ts +2 -19
- package/src/security/policy-drift.test.ts +14 -48
- package/src/security/policy-drift.ts +10 -72
- package/src/security/rls-enforcement.ts +3 -64
- package/src/services/BranchService.ts +10 -42
- package/src/services/FetchService.ts +270 -65
- package/src/services/PersistService.ts +14 -130
- package/src/services/RelationService.ts +94 -153
- package/src/services/collection-helpers.ts +47 -164
- package/src/services/dataService.ts +2 -3
- package/src/services/index.ts +0 -1
- package/src/services/realtimeService.ts +19 -40
- package/src/utils/drizzle-conditions.ts +0 -13
- package/src/websocket.ts +1 -4
- package/dist/collections/buildRegistry.d.ts +0 -27
- package/dist/services/row-pipeline.d.ts +0 -63
- package/src/collections/buildRegistry.ts +0 -59
- package/src/services/row-pipeline.ts +0 -215
|
@@ -17,7 +17,6 @@ import {
|
|
|
17
17
|
RebaseData,
|
|
18
18
|
RebaseSdkData,
|
|
19
19
|
RestFetchService,
|
|
20
|
-
SaveManyProps,
|
|
21
20
|
SaveProps,
|
|
22
21
|
TableColumnInfo,
|
|
23
22
|
TableForeignKeyInfo,
|
|
@@ -29,7 +28,6 @@ import {
|
|
|
29
28
|
import { sql as drizzleSql } from "drizzle-orm";
|
|
30
29
|
import { buildPropertyCallbacks, buildSdkData, resolveCollectionRelations, updateDateAutoValues } from "@rebasepro/common";
|
|
31
30
|
import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry";
|
|
32
|
-
import { deriveRowAddress } from "./services/collection-helpers";
|
|
33
31
|
import { HistoryService } from "./history/HistoryService";
|
|
34
32
|
import { mergeDeep } from "@rebasepro/utils";
|
|
35
33
|
import { logger } from "@rebasepro/server";
|
|
@@ -534,8 +532,7 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
534
532
|
id,
|
|
535
533
|
values,
|
|
536
534
|
collection,
|
|
537
|
-
status
|
|
538
|
-
upsert
|
|
535
|
+
status
|
|
539
536
|
}: SaveProps<M>): Promise<Record<string, unknown>> {
|
|
540
537
|
|
|
541
538
|
const {
|
|
@@ -548,26 +545,13 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
548
545
|
let updatedValues = values;
|
|
549
546
|
const contextForCallback = this.buildCallContext();
|
|
550
547
|
|
|
551
|
-
// Fetch previous values for callbacks AND history recording
|
|
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.
|
|
548
|
+
// Fetch previous values for callbacks AND history recording
|
|
556
549
|
let previousValuesForHistory: Partial<M> | undefined;
|
|
557
550
|
if (status === "existing" && id) {
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
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) });
|
|
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>;
|
|
571
555
|
}
|
|
572
556
|
}
|
|
573
557
|
|
|
@@ -632,8 +616,7 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
632
616
|
path,
|
|
633
617
|
updatedValues,
|
|
634
618
|
id,
|
|
635
|
-
resolvedCollection?.databaseId
|
|
636
|
-
{ upsert }
|
|
619
|
+
resolvedCollection?.databaseId
|
|
637
620
|
);
|
|
638
621
|
|
|
639
622
|
if (savedRow && (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead)) {
|
|
@@ -666,19 +649,8 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
666
649
|
}
|
|
667
650
|
}
|
|
668
651
|
|
|
669
|
-
|
|
670
|
-
|
|
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;
|
|
652
|
+
const savedId = savedRow.id as string | number;
|
|
653
|
+
const { id: _savedId, ...savedValues } = savedRow;
|
|
682
654
|
|
|
683
655
|
if (globalCallbacks?.afterSave || callbacks?.afterSave || propertyCallbacks?.afterSave) {
|
|
684
656
|
// 1. Global callbacks first
|
|
@@ -723,7 +695,7 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
723
695
|
if (this.historyService && resolvedCollection?.history) {
|
|
724
696
|
this.historyService.recordHistory({
|
|
725
697
|
tableName: path,
|
|
726
|
-
id: savedId,
|
|
698
|
+
id: savedId.toString(),
|
|
727
699
|
action: status === "new" ? "create" : "update",
|
|
728
700
|
values: savedValues as Record<string, unknown>,
|
|
729
701
|
previousValues: previousValuesForHistory as Record<string, unknown> | undefined,
|
|
@@ -735,14 +707,14 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
735
707
|
if (this._deferNotifications) {
|
|
736
708
|
this._pendingNotifications.push({
|
|
737
709
|
path,
|
|
738
|
-
id: savedId,
|
|
710
|
+
id: savedId.toString(),
|
|
739
711
|
row: savedRow,
|
|
740
712
|
databaseId: resolvedCollection?.databaseId
|
|
741
713
|
});
|
|
742
714
|
} else {
|
|
743
715
|
await this.realtimeService.notifyUpdate(
|
|
744
716
|
path,
|
|
745
|
-
savedId,
|
|
717
|
+
savedId.toString(),
|
|
746
718
|
savedRow,
|
|
747
719
|
resolvedCollection?.databaseId
|
|
748
720
|
);
|
|
@@ -792,86 +764,13 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
792
764
|
}
|
|
793
765
|
}
|
|
794
766
|
|
|
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
|
-
|
|
865
767
|
async delete<M extends Record<string, unknown>>({
|
|
866
768
|
row,
|
|
867
769
|
collection
|
|
868
770
|
}: DeleteProps<M>): Promise<void> {
|
|
869
771
|
|
|
870
772
|
const targetPath = row.path;
|
|
871
|
-
|
|
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 ?? {}) };
|
|
773
|
+
const targetRow: Record<string, unknown> = { id: row.id, ...(row.values ?? {}) };
|
|
875
774
|
|
|
876
775
|
// Resolve from backend registry to restore callbacks lost during WebSocket serialization
|
|
877
776
|
const {
|
|
@@ -1463,19 +1362,6 @@ export class AuthenticatedPostgresBackendDriver implements DataDriver {
|
|
|
1463
1362
|
return this.withTransaction((delegate) => delegate.save(props));
|
|
1464
1363
|
}
|
|
1465
1364
|
|
|
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
|
-
|
|
1479
1365
|
async delete<M extends Record<string, unknown>>(props: DeleteProps<M>): Promise<void> {
|
|
1480
1366
|
return this.withTransaction((delegate) => delegate.delete(props));
|
|
1481
1367
|
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Implements the `BackendBootstrapper` interface for PostgreSQL.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import { Relations, sql } from "drizzle-orm";
|
|
7
|
+
import { getTableName, isTable, 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,7 +21,6 @@ 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";
|
|
25
24
|
import { DatabasePoolManager } from "./databasePoolManager";
|
|
26
25
|
import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry";
|
|
27
26
|
import { createEmailService, type EmailConfig, type EmailService, logger } from "@rebasepro/server";
|
|
@@ -34,7 +33,7 @@ import { ensureHistoryTableExists } from "./history/ensure-history-table";
|
|
|
34
33
|
import { patchPgArrayNullSafety } from "./utils/pg-array-null-patch";
|
|
35
34
|
import { buildCollectionsFromSchema, introspectSchema, readRlsStatus } from "./schema/introspect-runtime";
|
|
36
35
|
import { buildDrizzleTablesFromSchema, buildDrizzleRelationsFromSchema } from "./schema/dynamic-tables";
|
|
37
|
-
import { detectConnectionPosture, ensureAppRole, validatePolicyPgRoles,
|
|
36
|
+
import { detectConnectionPosture, ensureAppRole, validatePolicyPgRoles, REBASE_USER_ROLE, type RawSqlRunner } from "./security/rls-enforcement";
|
|
38
37
|
import { provisionTriggerCdc, type CdcTableRef } from "./services/cdc/trigger-cdc";
|
|
39
38
|
|
|
40
39
|
export interface PostgresDriverConfig {
|
|
@@ -65,15 +64,6 @@ export interface PostgresDriverInternals {
|
|
|
65
64
|
realtimeService: RealtimeService;
|
|
66
65
|
driver: PostgresBackendDriver;
|
|
67
66
|
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>;
|
|
77
67
|
}
|
|
78
68
|
|
|
79
69
|
// Re-export from shared CLI error utilities
|
|
@@ -171,17 +161,30 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
171
161
|
}
|
|
172
162
|
|
|
173
163
|
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
|
+
|
|
174
172
|
const schemaTables = introspectedTables ?? pgConfig.schema?.tables;
|
|
175
|
-
const schemaRelations = introspectedRelations ?? (pgConfig.schema?.relations as Record<string, Relations> | undefined);
|
|
176
173
|
|
|
177
|
-
//
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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
|
+
const schemaRelations = introspectedRelations ?? (pgConfig.schema?.relations as Record<string, Relations> | undefined);
|
|
187
|
+
if (schemaRelations) registry.registerRelations(schemaRelations);
|
|
185
188
|
|
|
186
189
|
// Patch Drizzle's PgArray columns to handle NULL values safely.
|
|
187
190
|
// Drizzle's mapFromDriverValue crashes with "value.map is not a function"
|
|
@@ -300,11 +303,6 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
300
303
|
registry.getCollections() as never,
|
|
301
304
|
driver.rlsUserRole ?? posture.role
|
|
302
305
|
);
|
|
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);
|
|
308
306
|
}
|
|
309
307
|
|
|
310
308
|
// Ensure branch metadata table exists when branching is available
|
|
@@ -343,7 +341,6 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
343
341
|
const wantsCdc = cdcMode !== "off";
|
|
344
342
|
const explicitCdc = cdcMode === "trigger" || cdcMode === "wal";
|
|
345
343
|
let cdcEnabled = false;
|
|
346
|
-
let provisionCdcForTables: PostgresDriverInternals["provisionCdcForTables"];
|
|
347
344
|
|
|
348
345
|
if (wantsCdc && !directUrl) {
|
|
349
346
|
const reason = "no direct database connection is available for the realtime LISTEN client (set DATABASE_DIRECT_URL)";
|
|
@@ -377,11 +374,6 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
377
374
|
await provisionTriggerCdc(cdcRunSql, cdcTables);
|
|
378
375
|
await realtimeService.enableCdc(directUrl);
|
|
379
376
|
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
|
-
};
|
|
385
377
|
logger.info(
|
|
386
378
|
`📡 [CDC] Realtime source = database-level change capture (mode: ${cdcMode === "wal" ? "wal→trigger" : "trigger"}). ` +
|
|
387
379
|
`All writes now emit realtime events regardless of origin.`
|
|
@@ -432,14 +424,6 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
432
424
|
);
|
|
433
425
|
const missing: Array<{ slug: string; table: string }> = [];
|
|
434
426
|
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
|
-
|
|
443
427
|
const schemaName = "schema" in col && col.schema ? col.schema : "public";
|
|
444
428
|
const tableName = registry.hasTableForCollection(
|
|
445
429
|
col.table ?? col.slug
|
|
@@ -454,10 +438,8 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
454
438
|
const checkName = resolvedTable ?? tableName;
|
|
455
439
|
const fullCheckName = schemaName === "public" ? checkName : `${schemaName}.${checkName}`;
|
|
456
440
|
if (!dbTables.has(fullCheckName)) {
|
|
457
|
-
// Report what was actually looked up: an unqualified
|
|
458
|
-
// "users" sends people hunting for public.users.
|
|
459
441
|
missing.push({ slug: col.slug,
|
|
460
|
-
table:
|
|
442
|
+
table: checkName });
|
|
461
443
|
}
|
|
462
444
|
}
|
|
463
445
|
if (missing.length > 0) {
|
|
@@ -491,8 +473,7 @@ table: fullCheckName });
|
|
|
491
473
|
registry,
|
|
492
474
|
realtimeService,
|
|
493
475
|
driver,
|
|
494
|
-
poolManager
|
|
495
|
-
provisionCdcForTables
|
|
476
|
+
poolManager
|
|
496
477
|
};
|
|
497
478
|
|
|
498
479
|
return {
|
|
@@ -521,29 +502,6 @@ table: fullCheckName });
|
|
|
521
502
|
// ensureAuthTablesExist works with the collection abstraction — no Drizzle leakage.
|
|
522
503
|
await ensureAuthTablesExist(db, authCollection);
|
|
523
504
|
|
|
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
|
-
|
|
547
505
|
let emailService: EmailService | undefined;
|
|
548
506
|
if (authConfig.email) {
|
|
549
507
|
emailService = createEmailService(authConfig.email as EmailConfig);
|
|
@@ -251,32 +251,17 @@ 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:
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
//
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
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
|
-
}
|
|
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
|
+
`);
|
|
280
265
|
|
|
281
266
|
// ── Migration: Copy roles from legacy junction table to inline column ──
|
|
282
267
|
// If the old rebase.user_roles and rebase.roles tables exist, migrate
|
|
@@ -373,53 +358,6 @@ export async function ensureAuthTablesExist(db: NodePgDatabase, collection?: Col
|
|
|
373
358
|
ON ${sql.raw(recoveryCodesTableName)}(user_id)
|
|
374
359
|
`);
|
|
375
360
|
|
|
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
|
-
|
|
423
361
|
logger.info("✅ Auth tables ready");
|
|
424
362
|
} catch (error) {
|
|
425
363
|
logger.error("❌ Failed to create auth tables", { error });
|
package/src/auth/services.ts
CHANGED
|
@@ -82,32 +82,6 @@ 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
|
-
|
|
111
85
|
private mapRowToUser(row: Record<string, unknown>): UserData {
|
|
112
86
|
if (!row) return row as UserData;
|
|
113
87
|
|
|
@@ -226,9 +200,7 @@ export class UserService implements UserRepository {
|
|
|
226
200
|
|
|
227
201
|
async createUser(data: CreateUserData): Promise<UserData> {
|
|
228
202
|
const payload = this.mapPayload(data);
|
|
229
|
-
const [row] = await this.
|
|
230
|
-
(await db.insert(this.usersTable).values(payload).returning()) as Record<string, unknown>[]
|
|
231
|
-
);
|
|
203
|
+
const [row] = (await this.db.insert(this.usersTable).values(payload).returning()) as Record<string, unknown>[];
|
|
232
204
|
return this.mapRowToUser(row);
|
|
233
205
|
}
|
|
234
206
|
|
|
@@ -283,12 +255,12 @@ export class UserService implements UserRepository {
|
|
|
283
255
|
}
|
|
284
256
|
|
|
285
257
|
async linkUserIdentity(userId: string, provider: string, providerId: string, profileData?: Record<string, unknown>): Promise<void> {
|
|
286
|
-
await this.
|
|
258
|
+
await this.db.insert(this.userIdentitiesTable).values({
|
|
287
259
|
userId,
|
|
288
260
|
provider,
|
|
289
261
|
providerId,
|
|
290
262
|
profileData: profileData || null
|
|
291
|
-
}).onConflictDoNothing({ target: [this.userIdentitiesTable.provider, this.userIdentitiesTable.providerId] })
|
|
263
|
+
}).onConflictDoNothing({ target: [this.userIdentitiesTable.provider, this.userIdentitiesTable.providerId] });
|
|
292
264
|
}
|
|
293
265
|
|
|
294
266
|
async updateUser(id: string, data: Partial<Omit<CreateUserData, "id">>): Promise<UserData | null> {
|
|
@@ -298,20 +270,18 @@ export class UserService implements UserRepository {
|
|
|
298
270
|
const updatedAtKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
|
|
299
271
|
payload[updatedAtKey] = new Date();
|
|
300
272
|
|
|
301
|
-
const [row] = await this.
|
|
302
|
-
(
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
.returning()) as Record<string, unknown>[]
|
|
307
|
-
);
|
|
273
|
+
const [row] = (await this.db
|
|
274
|
+
.update(this.usersTable)
|
|
275
|
+
.set(payload)
|
|
276
|
+
.where(eq(idCol, id))
|
|
277
|
+
.returning()) as Record<string, unknown>[];
|
|
308
278
|
return row ? this.mapRowToUser(row) : null;
|
|
309
279
|
}
|
|
310
280
|
|
|
311
281
|
async deleteUser(id: string): Promise<void> {
|
|
312
282
|
const idCol = getColumn(this.usersTable, "id");
|
|
313
283
|
if (!idCol) return;
|
|
314
|
-
await this.
|
|
284
|
+
await this.db.delete(this.usersTable).where(eq(idCol, id));
|
|
315
285
|
}
|
|
316
286
|
|
|
317
287
|
async listUsers(): Promise<UserData[]> {
|
|
@@ -387,13 +357,13 @@ export class UserService implements UserRepository {
|
|
|
387
357
|
const passwordHashColKey = getColumnKey(this.usersTable, "passwordHash", "password_hash") || "passwordHash";
|
|
388
358
|
const updatedAtColKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
|
|
389
359
|
|
|
390
|
-
await this.
|
|
360
|
+
await this.db
|
|
391
361
|
.update(this.usersTable)
|
|
392
362
|
.set({
|
|
393
363
|
[passwordHashColKey]: passwordHash,
|
|
394
364
|
[updatedAtColKey]: new Date()
|
|
395
365
|
})
|
|
396
|
-
.where(eq(idCol, id))
|
|
366
|
+
.where(eq(idCol, id));
|
|
397
367
|
}
|
|
398
368
|
|
|
399
369
|
/**
|
|
@@ -406,14 +376,14 @@ export class UserService implements UserRepository {
|
|
|
406
376
|
const emailVerificationTokenColKey = getColumnKey(this.usersTable, "emailVerificationToken", "email_verification_token") || "emailVerificationToken";
|
|
407
377
|
const updatedAtColKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
|
|
408
378
|
|
|
409
|
-
await this.
|
|
379
|
+
await this.db
|
|
410
380
|
.update(this.usersTable)
|
|
411
381
|
.set({
|
|
412
382
|
[emailVerifiedColKey]: verified,
|
|
413
383
|
[emailVerificationTokenColKey]: null,
|
|
414
384
|
[updatedAtColKey]: new Date()
|
|
415
385
|
})
|
|
416
|
-
.where(eq(idCol, id))
|
|
386
|
+
.where(eq(idCol, id));
|
|
417
387
|
}
|
|
418
388
|
|
|
419
389
|
/**
|
|
@@ -426,14 +396,14 @@ export class UserService implements UserRepository {
|
|
|
426
396
|
const emailVerificationSentAtColKey = getColumnKey(this.usersTable, "emailVerificationSentAt", "email_verification_sent_at") || "emailVerificationSentAt";
|
|
427
397
|
const updatedAtColKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
|
|
428
398
|
|
|
429
|
-
await this.
|
|
399
|
+
await this.db
|
|
430
400
|
.update(this.usersTable)
|
|
431
401
|
.set({
|
|
432
402
|
[emailVerificationTokenColKey]: token,
|
|
433
403
|
[emailVerificationSentAtColKey]: token ? new Date() : null,
|
|
434
404
|
[updatedAtColKey]: new Date()
|
|
435
405
|
})
|
|
436
|
-
.where(eq(idCol, id))
|
|
406
|
+
.where(eq(idCol, id));
|
|
437
407
|
}
|
|
438
408
|
|
|
439
409
|
/**
|
|
@@ -493,11 +463,11 @@ export class UserService implements UserRepository {
|
|
|
493
463
|
async setUserRoles(userId: string, roleIds: string[]): Promise<void> {
|
|
494
464
|
const usersTableName = this.getQualifiedUsersTableName();
|
|
495
465
|
const rolesArray = `{${roleIds.join(",")}}`;
|
|
496
|
-
await this.
|
|
466
|
+
await this.db.execute(sql`
|
|
497
467
|
UPDATE ${sql.raw(usersTableName)}
|
|
498
468
|
SET roles = ${rolesArray}::text[], updated_at = NOW()
|
|
499
469
|
WHERE id = ${userId}
|
|
500
|
-
`)
|
|
470
|
+
`);
|
|
501
471
|
}
|
|
502
472
|
|
|
503
473
|
/**
|
|
@@ -505,11 +475,11 @@ export class UserService implements UserRepository {
|
|
|
505
475
|
*/
|
|
506
476
|
async assignDefaultRole(userId: string, roleId: string): Promise<void> {
|
|
507
477
|
const usersTableName = this.getQualifiedUsersTableName();
|
|
508
|
-
await this.
|
|
478
|
+
await this.db.execute(sql`
|
|
509
479
|
UPDATE ${sql.raw(usersTableName)}
|
|
510
480
|
SET roles = array_append(roles, ${roleId}), updated_at = NOW()
|
|
511
481
|
WHERE id = ${userId} AND NOT (${roleId} = ANY(roles))
|
|
512
|
-
`)
|
|
482
|
+
`);
|
|
513
483
|
}
|
|
514
484
|
|
|
515
485
|
/**
|