@rebasepro/server-postgres 0.9.1-canary.7ba0e49 → 0.9.1-canary.7dddf96
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/PostgresBootstrapper.d.ts +0 -10
- package/dist/auth/services.d.ts +0 -16
- package/dist/connection.d.ts +0 -21
- package/dist/index.es.js +243 -436
- package/dist/index.es.js.map +1 -1
- package/dist/schema/doctor.d.ts +1 -1
- package/dist/services/FetchService.d.ts +38 -4
- package/dist/services/RelationService.d.ts +0 -34
- package/dist/services/collection-helpers.d.ts +7 -34
- package/package.json +7 -10
- package/src/PostgresBackendDriver.ts +5 -18
- package/src/PostgresBootstrapper.ts +2 -51
- package/src/auth/ensure-tables.ts +11 -73
- package/src/auth/services.ts +19 -49
- package/src/connection.ts +1 -61
- package/src/databasePoolManager.ts +0 -2
- package/src/schema/doctor.ts +20 -45
- package/src/schema/introspect-db.ts +2 -19
- package/src/services/FetchService.ts +163 -29
- package/src/services/PersistService.ts +2 -9
- package/src/services/RelationService.ts +93 -153
- package/src/services/collection-helpers.ts +27 -59
- package/src/services/realtimeService.ts +2 -4
- package/src/utils/drizzle-conditions.ts +0 -13
- package/dist/services/row-pipeline.d.ts +0 -63
- package/src/services/row-pipeline.ts +0 -215
package/dist/schema/doctor.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { CollectionConfig, Property } from "@rebasepro/types";
|
|
|
2
2
|
export type IssueSeverity = "error" | "warning" | "info";
|
|
3
3
|
export interface DoctorIssue {
|
|
4
4
|
severity: IssueSeverity;
|
|
5
|
-
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale"
|
|
5
|
+
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale";
|
|
6
6
|
table?: string;
|
|
7
7
|
column?: string;
|
|
8
8
|
expected?: string;
|
|
@@ -40,11 +40,37 @@ export declare class FetchService {
|
|
|
40
40
|
* the target relation so actual row data is returned.
|
|
41
41
|
*/
|
|
42
42
|
private buildWithConfig;
|
|
43
|
+
/**
|
|
44
|
+
* Detect if a many-to-many relation uses a junction table in the Drizzle schema.
|
|
45
|
+
*/
|
|
46
|
+
private isJunctionRelation;
|
|
43
47
|
/**
|
|
44
48
|
* Get the Drizzle relation name on the junction table that points to the actual target row.
|
|
45
49
|
* For example, for posts_tags junction, this returns "tag_id" (the relation pointing to tags).
|
|
46
50
|
*/
|
|
47
51
|
private getJunctionTargetRelationName;
|
|
52
|
+
/**
|
|
53
|
+
* The address a relation ref points at.
|
|
54
|
+
*
|
|
55
|
+
* The whole key, not its first column: a composite-keyed target addressed
|
|
56
|
+
* by `tenant_id` alone points at every row that shares it. And a target
|
|
57
|
+
* whose key cannot be resolved at all used to throw here — reading
|
|
58
|
+
* `targetPks[0]` of an empty array — taking down the parent's fetch over a
|
|
59
|
+
* relation it may not even have asked for; the first column is a guess, but
|
|
60
|
+
* a ref that resolves to nothing beats no rows at all.
|
|
61
|
+
*/
|
|
62
|
+
private relationTargetAddress;
|
|
63
|
+
/**
|
|
64
|
+
* Convert a db.query result row (with nested relation objects) to a flat row.
|
|
65
|
+
* Handles:
|
|
66
|
+
* - Type normalization (dates, numbers, NaN) via normalizeDbValues
|
|
67
|
+
* - Converting nested relation objects to { id, path, __type: "relation" } for CMS
|
|
68
|
+
* - Flattening junction-table many-to-many results
|
|
69
|
+
*
|
|
70
|
+
* The row's own address is not among them: it is derived by the consumer
|
|
71
|
+
* from the collection's primary keys.
|
|
72
|
+
*/
|
|
73
|
+
private drizzleResultToRow;
|
|
48
74
|
/**
|
|
49
75
|
* Post-fetch joinPath relations for a single flat row.
|
|
50
76
|
* joinPath relations cannot be expressed via Drizzle's `with` config,
|
|
@@ -56,6 +82,16 @@ export declare class FetchService {
|
|
|
56
82
|
* Uses RelationService to query the database and maps results back to the flattened objects.
|
|
57
83
|
*/
|
|
58
84
|
private resolveJoinPathRelationsBatchRest;
|
|
85
|
+
/**
|
|
86
|
+
* Convert a db.query result row to a flat REST-style row with populated relations.
|
|
87
|
+
*
|
|
88
|
+
* Every column is copied through under its own name, with the value Postgres
|
|
89
|
+
* returned. This used to open with a synthesized `id` and then skip the key
|
|
90
|
+
* column, which renamed it (a `sku` primary key was served as `id`, and `sku`
|
|
91
|
+
* did not appear at all) and restringified it (`42` → `"42"`). Consumers that
|
|
92
|
+
* need an address derive it from the collection's primary keys.
|
|
93
|
+
*/
|
|
94
|
+
private drizzleResultToRestRow;
|
|
59
95
|
/**
|
|
60
96
|
* Build db.query-compatible options from standard fetch options.
|
|
61
97
|
* Handles filter, search, orderBy, limit, and cursor-based pagination.
|
|
@@ -86,10 +122,8 @@ export declare class FetchService {
|
|
|
86
122
|
}): Promise<Record<string, unknown>[]>;
|
|
87
123
|
/**
|
|
88
124
|
* Fallback path used when db.query is unavailable.
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
* relations from what drizzle already nested — no query per row. This one
|
|
92
|
-
* has no nesting to read, so it resolves relations itself, in batches.
|
|
125
|
+
* The primary path uses drizzleResultToRow which handles relation
|
|
126
|
+
* mapping without N+1 queries.
|
|
93
127
|
*
|
|
94
128
|
* Process raw database results into flat rows with relations.
|
|
95
129
|
*/
|
|
@@ -20,40 +20,6 @@ export declare class RelationService {
|
|
|
20
20
|
private db;
|
|
21
21
|
private registry;
|
|
22
22
|
constructor(db: DrizzleClient, registry: PostgresCollectionRegistry);
|
|
23
|
-
/**
|
|
24
|
-
* One target row, as the {@link RelatedRow} everything here returns.
|
|
25
|
-
*
|
|
26
|
-
* Eight sites built this by hand, which is how the address came to be the
|
|
27
|
-
* target's first key column in all eight — one edit, eight places to miss.
|
|
28
|
-
*
|
|
29
|
-
* `resolveNested` is the one thing they did not agree on, and the
|
|
30
|
-
* disagreement was invisible: the single-parent fetches pass `db` and
|
|
31
|
-
* `registry` to `parseDataFromServer`, so the target's *own* relations get
|
|
32
|
-
* resolved too, while the batch paths deliberately do not — a query per
|
|
33
|
-
* target row is the N+1 the batching exists to avoid. Naming the parameter
|
|
34
|
-
* makes that a decision rather than a difference between two call sites
|
|
35
|
-
* nobody was comparing.
|
|
36
|
-
*/
|
|
37
|
-
private toRelatedRow;
|
|
38
|
-
/**
|
|
39
|
-
* A WHERE matching any of `parentIds`, by the whole key.
|
|
40
|
-
*
|
|
41
|
-
* A single key is an `IN (…)`. A composite one cannot be: matching
|
|
42
|
-
* `tenant_id IN (1, 1)` collects every row of tenant 1, so two parents that
|
|
43
|
-
* share their first column each receive the other's relations. It becomes
|
|
44
|
-
* an OR of ANDs — one exact address per parent — which Postgres indexes the
|
|
45
|
-
* same way it would a multi-column key lookup.
|
|
46
|
-
*/
|
|
47
|
-
private parentKeyCondition;
|
|
48
|
-
/**
|
|
49
|
-
* Reject a relation that cannot express a composite-keyed parent.
|
|
50
|
-
*
|
|
51
|
-
* `localKey` and `foreignKeyOnTarget` are single column names: one column
|
|
52
|
-
* cannot reference a two-column key, so such a relation has no correct
|
|
53
|
-
* reading. Left alone it would silently match on the first key column and
|
|
54
|
-
* hand a tenant's rows to its neighbour — say so instead.
|
|
55
|
-
*/
|
|
56
|
-
private assertSingleKeyAddressable;
|
|
57
23
|
/**
|
|
58
24
|
* Fetch rows related to a parent row through a specific relation
|
|
59
25
|
*/
|
|
@@ -24,37 +24,7 @@ export interface DrizzleColumnMeta {
|
|
|
24
24
|
export declare function getColumnMeta(col: AnyPgColumn): DrizzleColumnMeta;
|
|
25
25
|
export declare function getCollectionByPath(collectionPath: string, registry: PostgresCollectionRegistry): CollectionConfig;
|
|
26
26
|
export declare function getTableForCollection(collection: CollectionConfig, registry: PostgresCollectionRegistry): PgTable<any>;
|
|
27
|
-
/**
|
|
28
|
-
* The key columns a collection's rows are addressed by.
|
|
29
|
-
*
|
|
30
|
-
* Three tiers, in order: properties marked `isId`, the primary keys of the
|
|
31
|
-
* drizzle schema, and finally a column literally named `id`. Only the first is
|
|
32
|
-
* visible to the browser, which is why a key known only to drizzle is reported
|
|
33
|
-
* at boot — see {@link warnOnKeysTheAdminCannotResolve}.
|
|
34
|
-
*
|
|
35
|
-
* Returns `[]` when nothing resolves, rather than throwing. It used to open by
|
|
36
|
-
* resolving the table, which throws when there is none — so the `isId` tier,
|
|
37
|
-
* which needs no table at all, was unreachable for exactly the collections
|
|
38
|
-
* most likely to have no table registered. Every caller that wanted "no keys"
|
|
39
|
-
* to mean "no keys" had to spell that out in a try/catch.
|
|
40
|
-
*
|
|
41
|
-
* Callers that cannot proceed without a key must say so themselves, naming the
|
|
42
|
-
* collection: an empty array here means "this collection has no address", which
|
|
43
|
-
* is a different answer in a notification (broadcast a wildcard) than in a save
|
|
44
|
-
* (fail).
|
|
45
|
-
*/
|
|
46
27
|
export declare function getPrimaryKeys(collection: CollectionConfig, registry: PostgresCollectionRegistry): PrimaryKeyInfo[];
|
|
47
|
-
/**
|
|
48
|
-
* The key columns, for callers that cannot do their job without one.
|
|
49
|
-
*
|
|
50
|
-
* {@link getPrimaryKeys} answers "what keys, if any" and returns `[]` for a
|
|
51
|
-
* collection with no address. Most of this driver, though, is building a WHERE
|
|
52
|
-
* clause and has no meaning without a key — for those, an empty array is not an
|
|
53
|
-
* answer, and indexing `[0]` into it produces `Cannot read properties of
|
|
54
|
-
* undefined` three frames from where the real problem is. This says what is
|
|
55
|
-
* wrong and which collection it is wrong about.
|
|
56
|
-
*/
|
|
57
|
-
export declare function requirePrimaryKeys(collection: CollectionConfig, registry: PostgresCollectionRegistry): PrimaryKeyInfo[];
|
|
58
28
|
/**
|
|
59
29
|
* Collections whose key the *browser* cannot resolve, and what it will do
|
|
60
30
|
* instead.
|
|
@@ -95,9 +65,12 @@ export declare function warnOnKeysTheAdminCannotResolve(collections: CollectionC
|
|
|
95
65
|
* The address of a row: derived from the collection's primary keys, because a
|
|
96
66
|
* row does not carry one — it is exactly its columns.
|
|
97
67
|
*
|
|
98
|
-
* Falls back to a literal `id` column,
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
68
|
+
* Falls back to a literal `id` column, which covers the two cases where the
|
|
69
|
+
* keys cannot be resolved: a row that reached us from somewhere other than the
|
|
70
|
+
* postgres driver, and a collection whose table the registry cannot look up
|
|
71
|
+
* (`getPrimaryKeys` throws for an unregistered table rather than returning
|
|
72
|
+
* nothing). Returns `""` when there is no key and no `id` — callers decide what
|
|
73
|
+
* that means, since "unaddressable" is a different answer in a notification
|
|
74
|
+
* (broadcast a wildcard) than in a save (fail).
|
|
102
75
|
*/
|
|
103
76
|
export declare function deriveRowAddress(row: Record<string, unknown>, collection: CollectionConfig, registry: PostgresCollectionRegistry): string;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/server-postgres",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.9.1-canary.
|
|
4
|
+
"version": "0.9.1-canary.7dddf96",
|
|
5
5
|
"description": "PostgreSQL data source backend implementation for Rebase with Drizzle ORM",
|
|
6
6
|
"funding": {
|
|
7
7
|
"url": "https://github.com/sponsors/rebaseco"
|
|
@@ -71,20 +71,18 @@
|
|
|
71
71
|
"execa": "^9.6.1",
|
|
72
72
|
"pg": "^8.21.0",
|
|
73
73
|
"ws": "^8.21.0",
|
|
74
|
-
"@rebasepro/
|
|
75
|
-
"@rebasepro/
|
|
76
|
-
"@rebasepro/server": "0.9.1-canary.
|
|
77
|
-
"@rebasepro/types": "0.9.1-canary.
|
|
78
|
-
"@rebasepro/utils": "0.9.1-canary.
|
|
74
|
+
"@rebasepro/common": "0.9.1-canary.7dddf96",
|
|
75
|
+
"@rebasepro/codegen": "0.9.1-canary.7dddf96",
|
|
76
|
+
"@rebasepro/server": "0.9.1-canary.7dddf96",
|
|
77
|
+
"@rebasepro/types": "0.9.1-canary.7dddf96",
|
|
78
|
+
"@rebasepro/utils": "0.9.1-canary.7dddf96"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
|
-
"@hono/node-server": "^2.0.9",
|
|
82
81
|
"@types/jest": "^30.0.0",
|
|
83
82
|
"@types/node": "^25.9.3",
|
|
84
83
|
"@types/pg": "^8.20.0",
|
|
85
84
|
"@types/ws": "^8.18.1",
|
|
86
85
|
"@vitejs/plugin-react": "^6.0.2",
|
|
87
|
-
"hono": "^4.12.25",
|
|
88
86
|
"jest": "^30.4.2",
|
|
89
87
|
"ts-jest": "^29.4.11",
|
|
90
88
|
"typescript": "^6.0.3",
|
|
@@ -105,7 +103,6 @@
|
|
|
105
103
|
"test:lint": "eslint \"src/**\" --quiet",
|
|
106
104
|
"test": "jest --passWithNoTests",
|
|
107
105
|
"test:e2e": "vitest run --config vitest.e2e.config.ts",
|
|
108
|
-
"clean": "rm -rf dist && find ./src -name '*.js' -type f | xargs rm -f"
|
|
109
|
-
"smoke:baas": "tsx scripts/smoke-baas.ts"
|
|
106
|
+
"clean": "rm -rf dist && find ./src -name '*.js' -type f | xargs rm -f"
|
|
110
107
|
}
|
|
111
108
|
}
|
|
@@ -548,26 +548,13 @@ export class PostgresBackendDriver implements DataDriver {
|
|
|
548
548
|
let updatedValues = values;
|
|
549
549
|
const contextForCallback = this.buildCallContext();
|
|
550
550
|
|
|
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.
|
|
551
|
+
// Fetch previous values for callbacks AND history recording
|
|
556
552
|
let previousValuesForHistory: Partial<M> | undefined;
|
|
557
553
|
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) });
|
|
554
|
+
const existing = await this.dataService.fetchOne<M>(path, id, resolvedCollection?.databaseId);
|
|
555
|
+
if (existing) {
|
|
556
|
+
const { id: _existingId, ...existingValues } = existing;
|
|
557
|
+
previousValuesForHistory = existingValues as Partial<M>;
|
|
571
558
|
}
|
|
572
559
|
}
|
|
573
560
|
|
|
@@ -65,15 +65,6 @@ export interface PostgresDriverInternals {
|
|
|
65
65
|
realtimeService: RealtimeService;
|
|
66
66
|
driver: PostgresBackendDriver;
|
|
67
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>;
|
|
77
68
|
}
|
|
78
69
|
|
|
79
70
|
// Re-export from shared CLI error utilities
|
|
@@ -343,7 +334,6 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
343
334
|
const wantsCdc = cdcMode !== "off";
|
|
344
335
|
const explicitCdc = cdcMode === "trigger" || cdcMode === "wal";
|
|
345
336
|
let cdcEnabled = false;
|
|
346
|
-
let provisionCdcForTables: PostgresDriverInternals["provisionCdcForTables"];
|
|
347
337
|
|
|
348
338
|
if (wantsCdc && !directUrl) {
|
|
349
339
|
const reason = "no direct database connection is available for the realtime LISTEN client (set DATABASE_DIRECT_URL)";
|
|
@@ -377,11 +367,6 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
377
367
|
await provisionTriggerCdc(cdcRunSql, cdcTables);
|
|
378
368
|
await realtimeService.enableCdc(directUrl);
|
|
379
369
|
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
370
|
logger.info(
|
|
386
371
|
`📡 [CDC] Realtime source = database-level change capture (mode: ${cdcMode === "wal" ? "wal→trigger" : "trigger"}). ` +
|
|
387
372
|
`All writes now emit realtime events regardless of origin.`
|
|
@@ -432,14 +417,6 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
432
417
|
);
|
|
433
418
|
const missing: Array<{ slug: string; table: string }> = [];
|
|
434
419
|
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
420
|
const schemaName = "schema" in col && col.schema ? col.schema : "public";
|
|
444
421
|
const tableName = registry.hasTableForCollection(
|
|
445
422
|
col.table ?? col.slug
|
|
@@ -454,10 +431,8 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
454
431
|
const checkName = resolvedTable ?? tableName;
|
|
455
432
|
const fullCheckName = schemaName === "public" ? checkName : `${schemaName}.${checkName}`;
|
|
456
433
|
if (!dbTables.has(fullCheckName)) {
|
|
457
|
-
// Report what was actually looked up: an unqualified
|
|
458
|
-
// "users" sends people hunting for public.users.
|
|
459
434
|
missing.push({ slug: col.slug,
|
|
460
|
-
table:
|
|
435
|
+
table: checkName });
|
|
461
436
|
}
|
|
462
437
|
}
|
|
463
438
|
if (missing.length > 0) {
|
|
@@ -491,8 +466,7 @@ table: fullCheckName });
|
|
|
491
466
|
registry,
|
|
492
467
|
realtimeService,
|
|
493
468
|
driver,
|
|
494
|
-
poolManager
|
|
495
|
-
provisionCdcForTables
|
|
469
|
+
poolManager
|
|
496
470
|
};
|
|
497
471
|
|
|
498
472
|
return {
|
|
@@ -521,29 +495,6 @@ table: fullCheckName });
|
|
|
521
495
|
// ensureAuthTablesExist works with the collection abstraction — no Drizzle leakage.
|
|
522
496
|
await ensureAuthTablesExist(db, authCollection);
|
|
523
497
|
|
|
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
498
|
let emailService: EmailService | undefined;
|
|
548
499
|
if (authConfig.email) {
|
|
549
500
|
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
|
/**
|