@rebasepro/server-postgres 0.0.1-canary.fc811d7 → 0.9.1-canary.0de22e0
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/README.md +21 -0
- package/dist/PostgresBackendDriver.d.ts +43 -2
- package/dist/PostgresBootstrapper.d.ts +17 -1
- package/dist/auth/services.d.ts +16 -0
- package/dist/collections/buildRegistry.d.ts +27 -0
- package/dist/connection.d.ts +21 -0
- package/dist/data-transformer.d.ts +9 -2
- package/dist/index.es.js +2502 -2624
- package/dist/index.es.js.map +1 -1
- package/dist/module-dir.d.ts +1 -0
- package/dist/schema/doctor.d.ts +1 -1
- package/dist/schema/introspect-db-logic.d.ts +0 -5
- package/dist/schema/introspect-db-naming.d.ts +10 -0
- package/dist/security/policy-drift.d.ts +46 -5
- package/dist/security/rls-enforcement.d.ts +28 -3
- package/dist/services/FetchService.d.ts +4 -24
- package/dist/services/PersistService.d.ts +27 -1
- package/dist/services/RelationService.d.ts +34 -1
- package/dist/services/channel-history.d.ts +118 -0
- package/dist/services/collection-helpers.d.ts +79 -14
- package/dist/services/dataService.d.ts +3 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +76 -2
- package/dist/services/row-pipeline.d.ts +63 -0
- package/package.json +15 -40
- package/src/PostgresBackendDriver.ts +183 -18
- package/src/PostgresBootstrapper.ts +86 -27
- package/src/auth/ensure-tables.ts +73 -11
- package/src/auth/services.ts +49 -19
- package/src/cli-helpers.ts +2 -20
- package/src/cli.ts +60 -0
- package/src/collections/buildRegistry.ts +59 -0
- package/src/connection.ts +61 -1
- package/src/data-transformer.ts +11 -9
- package/src/databasePoolManager.ts +2 -0
- package/src/module-dir.ts +7 -0
- package/src/schema/doctor-cli.ts +5 -1
- package/src/schema/doctor.ts +45 -20
- package/src/schema/generate-drizzle-schema-logic.ts +24 -29
- package/src/schema/generate-postgres-ddl-logic.ts +76 -28
- package/src/schema/introspect-db-inference.ts +1 -1
- package/src/schema/introspect-db-logic.ts +1 -10
- package/src/schema/introspect-db-naming.ts +15 -0
- package/src/schema/introspect-db.ts +19 -2
- package/src/schema/introspect-runtime.ts +1 -1
- package/src/security/anonymous-grants.test.ts +71 -0
- package/src/security/policy-drift.test.ts +153 -14
- package/src/security/policy-drift.ts +128 -10
- package/src/security/rls-enforcement.ts +67 -6
- package/src/services/BranchService.ts +42 -10
- package/src/services/FetchService.ts +65 -270
- package/src/services/PersistService.ts +130 -14
- package/src/services/RelationService.ts +153 -94
- package/src/services/channel-history.ts +343 -0
- package/src/services/collection-helpers.ts +164 -47
- package/src/services/dataService.ts +3 -2
- package/src/services/index.ts +1 -0
- package/src/services/realtimeService.ts +237 -28
- package/src/services/row-pipeline.ts +239 -0
- package/src/utils/drizzle-conditions.ts +13 -0
- package/src/websocket.ts +34 -12
- package/dist/chunk-DSJWtz9O.js +0 -40
- package/dist/schema/auth-default-policies.d.ts +0 -10
- package/dist/src-Eh-CZosp.js +0 -595
- package/dist/src-Eh-CZosp.js.map +0 -1
- package/src/schema/auth-default-policies.ts +0 -125
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Implements the `BackendBootstrapper` interface for PostgreSQL.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import {
|
|
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";
|
|
@@ -17,10 +17,12 @@ import {
|
|
|
17
17
|
CollectionConfig,
|
|
18
18
|
type HistoryConfig,
|
|
19
19
|
InitializedDriver,
|
|
20
|
-
RealtimeProvider
|
|
20
|
+
RealtimeProvider,
|
|
21
|
+
type RealtimeChannelsConfig
|
|
21
22
|
} from "@rebasepro/types";
|
|
22
23
|
import { PostgresBackendDriver } from "./PostgresBackendDriver";
|
|
23
24
|
import { RealtimeService } from "./services/realtimeService";
|
|
25
|
+
import { buildCollectionRegistry } from "./collections/buildRegistry";
|
|
24
26
|
import { DatabasePoolManager } from "./databasePoolManager";
|
|
25
27
|
import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry";
|
|
26
28
|
import { createEmailService, type EmailConfig, type EmailService, logger } from "@rebasepro/server";
|
|
@@ -33,7 +35,7 @@ import { ensureHistoryTableExists } from "./history/ensure-history-table";
|
|
|
33
35
|
import { patchPgArrayNullSafety } from "./utils/pg-array-null-patch";
|
|
34
36
|
import { buildCollectionsFromSchema, introspectSchema, readRlsStatus } from "./schema/introspect-runtime";
|
|
35
37
|
import { buildDrizzleTablesFromSchema, buildDrizzleRelationsFromSchema } from "./schema/dynamic-tables";
|
|
36
|
-
import { detectConnectionPosture, ensureAppRole, validatePolicyPgRoles, REBASE_USER_ROLE, type RawSqlRunner } from "./security/rls-enforcement";
|
|
38
|
+
import { detectConnectionPosture, ensureAppRole, validatePolicyPgRoles, warnOnAnonymousGrants, REBASE_USER_ROLE, type RawSqlRunner } from "./security/rls-enforcement";
|
|
37
39
|
import { provisionTriggerCdc, type CdcTableRef } from "./services/cdc/trigger-cdc";
|
|
38
40
|
|
|
39
41
|
export interface PostgresDriverConfig {
|
|
@@ -51,6 +53,12 @@ export interface PostgresDriverConfig {
|
|
|
51
53
|
* (BaaS mode). Defaults to `public`.
|
|
52
54
|
*/
|
|
53
55
|
introspectionSchema?: string;
|
|
56
|
+
/**
|
|
57
|
+
* Realtime options. Currently only channel retention, which is opt-in:
|
|
58
|
+
* without rules here no channel keeps any history and broadcast stays
|
|
59
|
+
* fire-and-forget. See {@link ChannelRetentionRule}.
|
|
60
|
+
*/
|
|
61
|
+
realtime?: RealtimeChannelsConfig;
|
|
54
62
|
}
|
|
55
63
|
|
|
56
64
|
/**
|
|
@@ -64,6 +72,15 @@ export interface PostgresDriverInternals {
|
|
|
64
72
|
realtimeService: RealtimeService;
|
|
65
73
|
driver: PostgresBackendDriver;
|
|
66
74
|
poolManager?: DatabasePoolManager;
|
|
75
|
+
/**
|
|
76
|
+
* Attach CDC triggers to tables that did not exist when the driver
|
|
77
|
+
* bootstrapped. Only set when database-level capture is actually active.
|
|
78
|
+
*
|
|
79
|
+
* Auth owns its own tables and creates them later in boot, so at driver
|
|
80
|
+
* bootstrap they are legitimately missing and get skipped; without this
|
|
81
|
+
* they would stay uninstrumented until the next restart.
|
|
82
|
+
*/
|
|
83
|
+
provisionCdcForTables?: (tables: CdcTableRef[]) => Promise<void>;
|
|
67
84
|
}
|
|
68
85
|
|
|
69
86
|
// Re-export from shared CLI error utilities
|
|
@@ -161,30 +178,17 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
161
178
|
}
|
|
162
179
|
|
|
163
180
|
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
181
|
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
182
|
const schemaRelations = introspectedRelations ?? (pgConfig.schema?.relations as Record<string, Relations> | undefined);
|
|
187
|
-
|
|
183
|
+
|
|
184
|
+
// Create a fresh registry for this driver. Registration order is
|
|
185
|
+
// load-bearing, so it lives in one place — see `buildCollectionRegistry`.
|
|
186
|
+
const registry = buildCollectionRegistry({
|
|
187
|
+
collections: activeCollections,
|
|
188
|
+
tables: schemaTables,
|
|
189
|
+
enums: pgConfig.schema?.enums as Record<string, PgEnum<[string, ...string[]]>> | undefined,
|
|
190
|
+
relations: schemaRelations
|
|
191
|
+
});
|
|
188
192
|
|
|
189
193
|
// Patch Drizzle's PgArray columns to handle NULL values safely.
|
|
190
194
|
// Drizzle's mapFromDriverValue crashes with "value.map is not a function"
|
|
@@ -303,6 +307,11 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
303
307
|
registry.getCollections() as never,
|
|
304
308
|
driver.rlsUserRole ?? posture.role
|
|
305
309
|
);
|
|
310
|
+
|
|
311
|
+
// The same habit one surface over, and the dangerous direction:
|
|
312
|
+
// a rule that reads as "signed in only" but is true for every
|
|
313
|
+
// caller grants the data away rather than hiding it.
|
|
314
|
+
warnOnAnonymousGrants(registry.getCollections() as never);
|
|
306
315
|
}
|
|
307
316
|
|
|
308
317
|
// Ensure branch metadata table exists when branching is available
|
|
@@ -314,6 +323,16 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
314
323
|
}
|
|
315
324
|
}
|
|
316
325
|
|
|
326
|
+
// ── Channel history ──────────────────────────────────────────────
|
|
327
|
+
// Opt-in per channel pattern. With no rules this creates no tables
|
|
328
|
+
// and leaves broadcast on its original fire-and-forget path, so
|
|
329
|
+
// presence-only apps pay nothing for it.
|
|
330
|
+
try {
|
|
331
|
+
await realtimeService.configureChannelHistory(pgConfig.realtime?.channels);
|
|
332
|
+
} catch (err) {
|
|
333
|
+
logger.warn("⚠️ Could not initialize channel history tables — retained channels will not replay", { error: err });
|
|
334
|
+
}
|
|
335
|
+
|
|
317
336
|
// ── Realtime change source ───────────────────────────────────────
|
|
318
337
|
// Prefer DATABASE_DIRECT_URL to bypass PgBouncer for LISTEN/NOTIFY.
|
|
319
338
|
const directUrl = process.env.DATABASE_DIRECT_URL || pgConfig.connectionString;
|
|
@@ -341,6 +360,7 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
341
360
|
const wantsCdc = cdcMode !== "off";
|
|
342
361
|
const explicitCdc = cdcMode === "trigger" || cdcMode === "wal";
|
|
343
362
|
let cdcEnabled = false;
|
|
363
|
+
let provisionCdcForTables: PostgresDriverInternals["provisionCdcForTables"];
|
|
344
364
|
|
|
345
365
|
if (wantsCdc && !directUrl) {
|
|
346
366
|
const reason = "no direct database connection is available for the realtime LISTEN client (set DATABASE_DIRECT_URL)";
|
|
@@ -374,6 +394,11 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
374
394
|
await provisionTriggerCdc(cdcRunSql, cdcTables);
|
|
375
395
|
await realtimeService.enableCdc(directUrl);
|
|
376
396
|
cdcEnabled = true;
|
|
397
|
+
// Boot steps that create their own tables (auth) run after
|
|
398
|
+
// this one and use it to instrument what they just created.
|
|
399
|
+
provisionCdcForTables = async (tables) => {
|
|
400
|
+
await provisionTriggerCdc(cdcRunSql, tables);
|
|
401
|
+
};
|
|
377
402
|
logger.info(
|
|
378
403
|
`📡 [CDC] Realtime source = database-level change capture (mode: ${cdcMode === "wal" ? "wal→trigger" : "trigger"}). ` +
|
|
379
404
|
`All writes now emit realtime events regardless of origin.`
|
|
@@ -424,6 +449,14 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
424
449
|
);
|
|
425
450
|
const missing: Array<{ slug: string; table: string }> = [];
|
|
426
451
|
for (const col of registeredCollections) {
|
|
452
|
+
// Auth owns its table and creates it later in this same
|
|
453
|
+
// boot (initializeAuth → ensureAuthTablesExist), so it is
|
|
454
|
+
// legitimately absent right now. Reporting it as drift
|
|
455
|
+
// tells the user to `db:push` a table that is about to
|
|
456
|
+
// exist — and on an introspected database, one that the
|
|
457
|
+
// database was never supposed to hold.
|
|
458
|
+
if ((col as { auth?: { enabled?: boolean } }).auth?.enabled) continue;
|
|
459
|
+
|
|
427
460
|
const schemaName = "schema" in col && col.schema ? col.schema : "public";
|
|
428
461
|
const tableName = registry.hasTableForCollection(
|
|
429
462
|
col.table ?? col.slug
|
|
@@ -438,8 +471,10 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
438
471
|
const checkName = resolvedTable ?? tableName;
|
|
439
472
|
const fullCheckName = schemaName === "public" ? checkName : `${schemaName}.${checkName}`;
|
|
440
473
|
if (!dbTables.has(fullCheckName)) {
|
|
474
|
+
// Report what was actually looked up: an unqualified
|
|
475
|
+
// "users" sends people hunting for public.users.
|
|
441
476
|
missing.push({ slug: col.slug,
|
|
442
|
-
table:
|
|
477
|
+
table: fullCheckName });
|
|
443
478
|
}
|
|
444
479
|
}
|
|
445
480
|
if (missing.length > 0) {
|
|
@@ -473,7 +508,8 @@ table: checkName });
|
|
|
473
508
|
registry,
|
|
474
509
|
realtimeService,
|
|
475
510
|
driver,
|
|
476
|
-
poolManager
|
|
511
|
+
poolManager,
|
|
512
|
+
provisionCdcForTables
|
|
477
513
|
};
|
|
478
514
|
|
|
479
515
|
return {
|
|
@@ -502,6 +538,29 @@ table: checkName });
|
|
|
502
538
|
// ensureAuthTablesExist works with the collection abstraction — no Drizzle leakage.
|
|
503
539
|
await ensureAuthTablesExist(db, authCollection);
|
|
504
540
|
|
|
541
|
+
// The driver bootstrapped before these tables existed, so CDC skipped
|
|
542
|
+
// them. Instrument them now, or writes to the user table emit no
|
|
543
|
+
// realtime events until the next restart.
|
|
544
|
+
if (authCollection && internals.provisionCdcForTables) {
|
|
545
|
+
const authSchema = "schema" in authCollection && typeof authCollection.schema === "string"
|
|
546
|
+
? authCollection.schema
|
|
547
|
+
: "rebase";
|
|
548
|
+
const authTable = "table" in authCollection && typeof authCollection.table === "string"
|
|
549
|
+
? authCollection.table
|
|
550
|
+
: authCollection.slug;
|
|
551
|
+
if (authTable) {
|
|
552
|
+
try {
|
|
553
|
+
await internals.provisionCdcForTables([{ schema: authSchema, table: authTable }]);
|
|
554
|
+
} catch (err) {
|
|
555
|
+
logger.warn(
|
|
556
|
+
`⚠️ [CDC] Could not attach change-capture to the auth table "${authSchema}.${authTable}" — ` +
|
|
557
|
+
"writes to it won't emit database-level events.",
|
|
558
|
+
{ detail: err instanceof Error ? err.message : String(err) }
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
505
564
|
let emailService: EmailService | undefined;
|
|
506
565
|
if (authConfig.email) {
|
|
507
566
|
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:
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
//
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
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 });
|
package/src/auth/services.ts
CHANGED
|
@@ -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] =
|
|
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] =
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
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
|
/**
|
package/src/cli-helpers.ts
CHANGED
|
@@ -1,29 +1,11 @@
|
|
|
1
1
|
import path from "path";
|
|
2
2
|
import fs from "fs";
|
|
3
3
|
import { execSync } from "child_process";
|
|
4
|
-
import {
|
|
4
|
+
import { pathToFileURL } from "url";
|
|
5
5
|
import chalk from "chalk";
|
|
6
6
|
import { logger } from "@rebasepro/server";
|
|
7
7
|
import type { CollectionConfig, Relation } from "@rebasepro/types";
|
|
8
|
-
|
|
9
|
-
const getHelpersDirname = () => {
|
|
10
|
-
try {
|
|
11
|
-
return eval("__dirname");
|
|
12
|
-
} catch {
|
|
13
|
-
const err = new Error();
|
|
14
|
-
const stackLine = err.stack?.split("\n")[1] || "";
|
|
15
|
-
const match = stackLine.match(/\((.*?):\d+:\d+\)/) || stackLine.match(/at (.*?):\d+:\d+/);
|
|
16
|
-
if (match && match[1]) {
|
|
17
|
-
let cleanPath = match[1];
|
|
18
|
-
if (cleanPath.startsWith("file://")) {
|
|
19
|
-
cleanPath = fileURLToPath(cleanPath);
|
|
20
|
-
}
|
|
21
|
-
return path.dirname(cleanPath);
|
|
22
|
-
}
|
|
23
|
-
return process.cwd();
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
const __helpersDirname = getHelpersDirname();
|
|
8
|
+
import { moduleDir as __helpersDirname } from "./module-dir";
|
|
27
9
|
|
|
28
10
|
|
|
29
11
|
|
package/src/cli.ts
CHANGED
|
@@ -176,6 +176,7 @@ async function dbCommand(subcommand: string, rawArgs: string[]): Promise<void> {
|
|
|
176
176
|
|
|
177
177
|
if (databaseUrl) {
|
|
178
178
|
await applyPolicies(databaseUrl);
|
|
179
|
+
await reconcilePolicies(databaseUrl, collectionsPath);
|
|
179
180
|
await ensureRlsUserRole(databaseUrl);
|
|
180
181
|
} else {
|
|
181
182
|
logger.warn(chalk.yellow(" ⚠️ DATABASE_URL not found in environment, skipping RLS policies application."));
|
|
@@ -269,6 +270,65 @@ async function applyPolicies(databaseUrl: string): Promise<void> {
|
|
|
269
270
|
}
|
|
270
271
|
}
|
|
271
272
|
|
|
273
|
+
/**
|
|
274
|
+
* Remove the policies an earlier push superseded but never dropped.
|
|
275
|
+
*
|
|
276
|
+
* `policies.sql` only DROPs the names it is about to CREATE, and a rule's
|
|
277
|
+
* generated name contains a hash of its own semantics — so editing a rule
|
|
278
|
+
* writes a *new* policy and abandons the old one. Postgres ORs PERMISSIVE
|
|
279
|
+
* policies together, which makes an abandoned grant outrank every tightening
|
|
280
|
+
* that replaced it, and push reported success the whole time.
|
|
281
|
+
*
|
|
282
|
+
* Runs after `applyPolicies` so the current policies are already in place: the
|
|
283
|
+
* drift check then sees exactly the set that should survive, and anything else
|
|
284
|
+
* on a managed table is by definition left over.
|
|
285
|
+
*/
|
|
286
|
+
async function reconcilePolicies(databaseUrl: string, collectionsPath: string): Promise<void> {
|
|
287
|
+
try {
|
|
288
|
+
const { checkPolicyDrift, dropOrphanedPolicies, formatPolicyDrift, hasDrift } =
|
|
289
|
+
await import("./security/policy-drift");
|
|
290
|
+
const { loadCollections } = await import("./schema/doctor");
|
|
291
|
+
|
|
292
|
+
const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
|
|
293
|
+
const { Client } = await import("pg");
|
|
294
|
+
const client = new Client({ connectionString: databaseUrl });
|
|
295
|
+
await client.connect();
|
|
296
|
+
try {
|
|
297
|
+
const drift = await checkPolicyDrift(client as never, collections);
|
|
298
|
+
const { dropped, kept } = await dropOrphanedPolicies(client as never, drift, collections);
|
|
299
|
+
|
|
300
|
+
for (const p of dropped) {
|
|
301
|
+
logger.info(chalk.gray(` ✓ Dropped superseded policy "${p.name}" on ${p.schema}.${p.table}`));
|
|
302
|
+
}
|
|
303
|
+
if (dropped.length > 0) {
|
|
304
|
+
logger.info(chalk.green(` ✓ Removed ${dropped.length} superseded RLS ${dropped.length === 1 ? "policy" : "policies"}.`));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Custom-named orphans are indistinguishable from policies someone
|
|
308
|
+
// wrote in SQL deliberately, so they are reported, never dropped.
|
|
309
|
+
if (kept.length > 0) {
|
|
310
|
+
logger.warn(chalk.yellow(" ⚠️ Policies in the database that no collection describes:"));
|
|
311
|
+
for (const p of kept) {
|
|
312
|
+
logger.warn(chalk.yellow(` • ${p.schema}.${p.table} → "${p.name}" (${p.command} TO ${p.roles.join(", ")})`));
|
|
313
|
+
}
|
|
314
|
+
logger.warn(chalk.yellow(" These still grant access. Drop them by hand if they are stale."));
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Missing/diverged are not push's to fix, but staying silent about
|
|
318
|
+
// them is how a database ends up not matching its config.
|
|
319
|
+
const remaining = { ...drift, orphaned: kept };
|
|
320
|
+
if (hasDrift(remaining) && (remaining.missing.length > 0 || remaining.diverged.length > 0)) {
|
|
321
|
+
logger.warn(chalk.yellow(" ⚠️ RLS policies do not match your collections:"));
|
|
322
|
+
logger.warn(formatPolicyDrift({ ...remaining, orphaned: [] }));
|
|
323
|
+
}
|
|
324
|
+
} finally {
|
|
325
|
+
await client.end();
|
|
326
|
+
}
|
|
327
|
+
} catch (err) {
|
|
328
|
+
logger.warn(chalk.yellow(` ⚠️ Could not reconcile RLS policies: ${err instanceof Error ? err.message : String(err)}`));
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
272
332
|
async function branchCommand(rawArgs: string[]): Promise<void> {
|
|
273
333
|
const branchAction = rawArgs[2]; // create, list, delete, info
|
|
274
334
|
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { isTable, getTableName, Relations } from "drizzle-orm";
|
|
2
|
+
import { PgEnum, PgTable } from "drizzle-orm/pg-core";
|
|
3
|
+
import { CollectionConfig } from "@rebasepro/types";
|
|
4
|
+
import { logger } from "@rebasepro/server";
|
|
5
|
+
import { PostgresCollectionRegistry } from "./PostgresCollectionRegistry";
|
|
6
|
+
import { warnOnKeysTheAdminCannotResolve } from "../services/collection-helpers";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Everything a registry is built from: the collections, and the drizzle schema
|
|
10
|
+
* they are backed by. In BaaS mode all of it is introspected from the live
|
|
11
|
+
* database; in CMS mode it comes from the config and the generated schema.
|
|
12
|
+
*/
|
|
13
|
+
export interface RegistrySchema {
|
|
14
|
+
collections?: CollectionConfig[];
|
|
15
|
+
tables?: Record<string, unknown>;
|
|
16
|
+
enums?: Record<string, PgEnum<[string, ...string[]]>>;
|
|
17
|
+
relations?: Record<string, Relations>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Build the collection registry for a driver.
|
|
22
|
+
*
|
|
23
|
+
* The order matters and is the reason this is one function rather than a run of
|
|
24
|
+
* statements in the bootstrapper. Keys are resolved from the drizzle schema, so
|
|
25
|
+
* anything that inspects them has to run *after* the tables are registered —
|
|
26
|
+
* and `warnOnKeysTheAdminCannotResolve` fails open if it does not, because a
|
|
27
|
+
* collection whose table it cannot look up is one it has nothing to say about.
|
|
28
|
+
* Warned too early, it would skip every collection and report nothing, which
|
|
29
|
+
* reads exactly like having nothing to report.
|
|
30
|
+
*/
|
|
31
|
+
export function buildCollectionRegistry(schema: RegistrySchema): PostgresCollectionRegistry {
|
|
32
|
+
const registry = new PostgresCollectionRegistry();
|
|
33
|
+
|
|
34
|
+
if (schema.collections) {
|
|
35
|
+
registry.registerMultiple(schema.collections);
|
|
36
|
+
logger.info(
|
|
37
|
+
`📋 [PostgresRegistry] Registered ${registry.getCollections().length} collections: ` +
|
|
38
|
+
`[${registry.getCollections().map(c => c.slug).join(", ")}]`
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (schema.tables) {
|
|
43
|
+
Object.values(schema.tables).forEach((table) => {
|
|
44
|
+
if (isTable(table)) {
|
|
45
|
+
registry.registerTable(table as PgTable, getTableName(table));
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (schema.enums) registry.registerEnums(schema.enums);
|
|
51
|
+
if (schema.relations) registry.registerRelations(schema.relations);
|
|
52
|
+
|
|
53
|
+
// Now that the keys resolve: say which of them the admin cannot see. It
|
|
54
|
+
// compiles the same collection files into its bundle but never the drizzle
|
|
55
|
+
// schema, and nothing serves it one, so only an edit to the config fixes it.
|
|
56
|
+
warnOnKeysTheAdminCannotResolve(registry.getCollections(), registry);
|
|
57
|
+
|
|
58
|
+
return registry;
|
|
59
|
+
}
|