@rebasepro/server-postgres 0.9.1-canary.d906fb7 → 0.9.1-canary.e3f810f
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/auth/services.d.ts +16 -0
- package/dist/connection.d.ts +21 -0
- package/dist/index.es.js +148 -29
- package/dist/index.es.js.map +1 -1
- package/dist/schema/doctor.d.ts +1 -1
- package/package.json +6 -6
- package/src/auth/ensure-tables.ts +73 -11
- package/src/auth/services.ts +49 -19
- package/src/connection.ts +61 -1
- package/src/databasePoolManager.ts +2 -0
- package/src/schema/doctor.ts +45 -20
- package/src/services/row-pipeline.ts +27 -3
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" | "sdk_not_generated";
|
|
6
6
|
table?: string;
|
|
7
7
|
column?: string;
|
|
8
8
|
expected?: 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.e3f810f",
|
|
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,11 +71,11 @@
|
|
|
71
71
|
"execa": "^9.6.1",
|
|
72
72
|
"pg": "^8.21.0",
|
|
73
73
|
"ws": "^8.21.0",
|
|
74
|
-
"@rebasepro/codegen": "0.9.1-canary.
|
|
75
|
-
"@rebasepro/
|
|
76
|
-
"@rebasepro/
|
|
77
|
-
"@rebasepro/
|
|
78
|
-
"@rebasepro/
|
|
74
|
+
"@rebasepro/codegen": "0.9.1-canary.e3f810f",
|
|
75
|
+
"@rebasepro/common": "0.9.1-canary.e3f810f",
|
|
76
|
+
"@rebasepro/server": "0.9.1-canary.e3f810f",
|
|
77
|
+
"@rebasepro/types": "0.9.1-canary.e3f810f",
|
|
78
|
+
"@rebasepro/utils": "0.9.1-canary.e3f810f"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
81
|
"@hono/node-server": "^2.0.9",
|
|
@@ -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/connection.ts
CHANGED
|
@@ -27,11 +27,68 @@ const DEFAULT_POOL: Required<PostgresPoolConfig> = {
|
|
|
27
27
|
max: 20,
|
|
28
28
|
idleTimeoutMillis: 30_000,
|
|
29
29
|
connectionTimeoutMillis: 10_000,
|
|
30
|
-
|
|
30
|
+
// The client-side read timeout MUST be comfortably above the server-side
|
|
31
|
+
// statement_timeout. When the client timer fires first, node-postgres
|
|
32
|
+
// abandons the in-flight statement but keeps the connection — inside a
|
|
33
|
+
// transaction that leaves the tx open (and any pending ROLLBACK is
|
|
34
|
+
// spliced out of the client queue before it ever reaches the wire), so
|
|
35
|
+
// the pooled connection is returned still in-transaction with its RLS
|
|
36
|
+
// GUCs set. The server abort (SQLSTATE 57014) is the clean path; the
|
|
37
|
+
// client timeout is only a backstop for a dead network.
|
|
38
|
+
queryTimeout: 60_000,
|
|
31
39
|
statementTimeout: 30_000,
|
|
32
40
|
keepAlive: true
|
|
33
41
|
};
|
|
34
42
|
|
|
43
|
+
/** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */
|
|
44
|
+
const TX_IDLE = "I";
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Destroy pool clients that are released while still inside a transaction.
|
|
48
|
+
*
|
|
49
|
+
* pg-pool returns a client to the idle list whenever `release()` is called
|
|
50
|
+
* without an error — even if the connection is still mid-transaction (status
|
|
51
|
+
* `T`/`E`). That happens in practice: drizzle's pool transaction releases in
|
|
52
|
+
* a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails
|
|
53
|
+
* (e.g. it was queued behind a statement that hit the client-side
|
|
54
|
+
* query_timeout), the client goes back dirty. The next checkout then runs
|
|
55
|
+
* its statements inside the zombie transaction — with the previous request's
|
|
56
|
+
* `app.*` RLS GUCs still applied, which turns unrelated queries into
|
|
57
|
+
* RLS-scoped ones (observed in production as registration failing with
|
|
58
|
+
* SQLSTATE 42501 under a leaked anonymous context).
|
|
59
|
+
*
|
|
60
|
+
* pg-pool emits `release` before it consults its private `_expired` set, so
|
|
61
|
+
* marking the client expired here makes `_release()` destroy it instead of
|
|
62
|
+
* pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are
|
|
63
|
+
* private APIs — feature-detect and fall back to loud logging so an upstream
|
|
64
|
+
* change degrades to observability, never to silent corruption.
|
|
65
|
+
*/
|
|
66
|
+
export function guardPoolAgainstDirtyRelease(pool: Pool, label: string): void {
|
|
67
|
+
pool.on("release", (err: Error | undefined, client: unknown) => {
|
|
68
|
+
if (err) return; // errored clients are already destroyed by pg-pool
|
|
69
|
+
const txStatus = (client as { _txStatus?: string | null })?._txStatus;
|
|
70
|
+
if (typeof txStatus !== "string" || txStatus === TX_IDLE) return;
|
|
71
|
+
|
|
72
|
+
// pg-pool keeps expired clients in a WeakSet (a plain object works too
|
|
73
|
+
// if upstream ever changes it — duck-type on add/has).
|
|
74
|
+
const expired = (pool as unknown as { _expired?: { add(c: object): unknown; has(c: object): boolean } })._expired;
|
|
75
|
+
if (expired && typeof expired.add === "function" && typeof expired.has === "function" && client && typeof client === "object") {
|
|
76
|
+
expired.add(client);
|
|
77
|
+
logger.error(
|
|
78
|
+
`[${label}] Client released back to the pool while still in a transaction ` +
|
|
79
|
+
`(status '${txStatus}') — destroying it so the open transaction and its ` +
|
|
80
|
+
`session state (RLS GUCs) cannot leak into the next request.`
|
|
81
|
+
);
|
|
82
|
+
} else {
|
|
83
|
+
logger.error(
|
|
84
|
+
`[${label}] Client released mid-transaction (status '${txStatus}') but the ` +
|
|
85
|
+
`pool's internal expiry set is unavailable (pg-pool internals changed?). ` +
|
|
86
|
+
`The connection may leak its open transaction into subsequent requests.`
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
35
92
|
/**
|
|
36
93
|
* Create a Drizzle-backed Postgres connection with a production-grade
|
|
37
94
|
* connection pool.
|
|
@@ -75,6 +132,7 @@ export function createPostgresDatabaseConnection(
|
|
|
75
132
|
logger.warn("[pg-pool] Connection timeout detected — pool will auto-retry");
|
|
76
133
|
}
|
|
77
134
|
});
|
|
135
|
+
guardPoolAgainstDirtyRelease(pool, "pg-pool");
|
|
78
136
|
|
|
79
137
|
// Create drizzle instance — pass schema when available to enable db.query relational API
|
|
80
138
|
const db = schema ? drizzle(pool, { schema }) : drizzle(pool);
|
|
@@ -118,6 +176,7 @@ export function createDirectDatabaseConnection(
|
|
|
118
176
|
pool.on("error", (err) => {
|
|
119
177
|
logger.error("[pg-direct-pool] Unexpected pool error", { detail: err.message });
|
|
120
178
|
});
|
|
179
|
+
guardPoolAgainstDirtyRelease(pool, "pg-direct-pool");
|
|
121
180
|
|
|
122
181
|
const db = schema ? drizzle(pool, { schema }) : drizzle(pool);
|
|
123
182
|
|
|
@@ -157,6 +216,7 @@ export function createReadReplicaConnection(
|
|
|
157
216
|
pool.on("error", (err) => {
|
|
158
217
|
logger.error("[pg-replica-pool] Unexpected pool error", { detail: err.message });
|
|
159
218
|
});
|
|
219
|
+
guardPoolAgainstDirtyRelease(pool, "pg-replica-pool");
|
|
160
220
|
|
|
161
221
|
const db = schema ? drizzle(pool, { schema }) : drizzle(pool);
|
|
162
222
|
|
|
@@ -2,6 +2,7 @@ import { Pool } from "pg";
|
|
|
2
2
|
import { drizzle } from "drizzle-orm/node-postgres";
|
|
3
3
|
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
4
4
|
import { logger } from "@rebasepro/server";
|
|
5
|
+
import { guardPoolAgainstDirtyRelease } from "./connection";
|
|
5
6
|
|
|
6
7
|
export class DatabasePoolManager {
|
|
7
8
|
private pools: Map<string, Pool> = new Map();
|
|
@@ -50,6 +51,7 @@ export class DatabasePoolManager {
|
|
|
50
51
|
pool.on("error", (err) => {
|
|
51
52
|
logger.error(`[DatabasePoolManager] Unexpected error on idle client for db ${databaseName}`, { error: err });
|
|
52
53
|
});
|
|
54
|
+
guardPoolAgainstDirtyRelease(pool, `pg-pool:${databaseName}`);
|
|
53
55
|
|
|
54
56
|
this.pools.set(databaseName, pool);
|
|
55
57
|
return pool;
|
package/src/schema/doctor.ts
CHANGED
|
@@ -37,7 +37,7 @@ export type IssueSeverity = "error" | "warning" | "info";
|
|
|
37
37
|
|
|
38
38
|
export interface DoctorIssue {
|
|
39
39
|
severity: IssueSeverity;
|
|
40
|
-
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale";
|
|
40
|
+
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale" | "sdk_not_generated";
|
|
41
41
|
table?: string;
|
|
42
42
|
column?: string;
|
|
43
43
|
expected?: string;
|
|
@@ -61,19 +61,29 @@ export function getExpectedColumnType(prop: Property): string | null {
|
|
|
61
61
|
const sp = prop as StringProperty;
|
|
62
62
|
if (sp.enum) return "USER-DEFINED"; // pgEnum → USER-DEFINED in information_schema
|
|
63
63
|
if ("isId" in sp && sp.isId === "uuid") return "uuid";
|
|
64
|
-
if (sp.columnType === "
|
|
64
|
+
if (sp.columnType === "uuid") return "uuid";
|
|
65
|
+
// A markdown/multiline string compiles to `text`, not varchar — the
|
|
66
|
+
// generator treats those UI hints as column-type signals, so the
|
|
67
|
+
// expectation here must too or every such column reads as drift.
|
|
68
|
+
if (sp.columnType === "text" || sp.ui?.markdown || sp.ui?.multiline) return "text";
|
|
65
69
|
if (sp.columnType === "char") return "character";
|
|
66
70
|
return "character varying";
|
|
67
71
|
}
|
|
68
72
|
case "number": {
|
|
69
73
|
const np = prop as NumberProperty;
|
|
70
|
-
if (np.columnType
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
74
|
+
if (np.columnType) {
|
|
75
|
+
// The generator passes any columnType straight through to drizzle,
|
|
76
|
+
// so mirror that rather than enumerating a subset (which reported
|
|
77
|
+
// drift for anything unlisted, e.g. smallint). Serial types are
|
|
78
|
+
// integers with a sequence default; information_schema reports the
|
|
79
|
+
// underlying width.
|
|
80
|
+
const serialWidths: Record<string, string> = {
|
|
81
|
+
serial: "integer",
|
|
82
|
+
bigserial: "bigint",
|
|
83
|
+
smallserial: "smallint"
|
|
84
|
+
};
|
|
85
|
+
return serialWidths[np.columnType] ?? np.columnType;
|
|
86
|
+
}
|
|
77
87
|
if (np.validation?.integer || ("isId" in np && np.isId)) return "integer";
|
|
78
88
|
return "numeric";
|
|
79
89
|
}
|
|
@@ -201,15 +211,18 @@ export async function checkCollectionsVsSdk(
|
|
|
201
211
|
): Promise<{ passed: boolean; issues: DoctorIssue[] }> {
|
|
202
212
|
const issues: DoctorIssue[] = [];
|
|
203
213
|
|
|
204
|
-
//
|
|
214
|
+
// The typed SDK is opt-in — nothing in a scaffolded project imports it until
|
|
215
|
+
// you choose to. A project that never generated one isn't drifting, so report
|
|
216
|
+
// it as information rather than a warning; otherwise `doctor` can never come
|
|
217
|
+
// back clean on a fresh project and users learn to ignore its output.
|
|
205
218
|
if (!fs.existsSync(sdkFilePath)) {
|
|
206
219
|
issues.push({
|
|
207
|
-
severity: "
|
|
208
|
-
category: "
|
|
209
|
-
message:
|
|
210
|
-
fix: "Run `rebase generate-sdk`"
|
|
220
|
+
severity: "info",
|
|
221
|
+
category: "sdk_not_generated",
|
|
222
|
+
message: "Typed SDK not generated (optional).",
|
|
223
|
+
fix: "Run `rebase generate-sdk` if you want typed collection access"
|
|
211
224
|
});
|
|
212
|
-
return { passed:
|
|
225
|
+
return { passed: true,
|
|
213
226
|
issues };
|
|
214
227
|
}
|
|
215
228
|
|
|
@@ -631,11 +644,15 @@ export function renderReport(report: DoctorReport): void {
|
|
|
631
644
|
}
|
|
632
645
|
|
|
633
646
|
function renderPhase(label: string, passed: boolean, issues: DoctorIssue[]): void {
|
|
634
|
-
|
|
647
|
+
const errorCount = issues.filter((i) => i.severity === "error").length;
|
|
648
|
+
const warnCount = issues.filter((i) => i.severity === "warning").length;
|
|
649
|
+
const infoIssues = issues.filter((i) => i.severity === "info");
|
|
650
|
+
|
|
651
|
+
// Informational notes don't make a phase unhealthy, so key the header off
|
|
652
|
+
// real problems rather than `passed` alone.
|
|
653
|
+
if (errorCount === 0 && warnCount === 0) {
|
|
635
654
|
logger.info(` ${chalk.green("✅")} ${label}: ${chalk.green("In sync")}`);
|
|
636
655
|
} else {
|
|
637
|
-
const errorCount = issues.filter((i) => i.severity === "error").length;
|
|
638
|
-
const warnCount = issues.filter((i) => i.severity === "warning").length;
|
|
639
656
|
const parts: string[] = [];
|
|
640
657
|
if (errorCount > 0) parts.push(`${errorCount} error${errorCount > 1 ? "s" : ""}`);
|
|
641
658
|
if (warnCount > 0) parts.push(`${warnCount} warning${warnCount > 1 ? "s" : ""}`);
|
|
@@ -643,7 +660,14 @@ function renderPhase(label: string, passed: boolean, issues: DoctorIssue[]): voi
|
|
|
643
660
|
}
|
|
644
661
|
logger.info("");
|
|
645
662
|
|
|
646
|
-
|
|
663
|
+
// Notes render as a quiet one-liner, not a full drift box.
|
|
664
|
+
for (const issue of infoIssues) {
|
|
665
|
+
const fixPart = issue.fix ? chalk.gray(` — ${issue.fix}`) : "";
|
|
666
|
+
logger.info(` ${chalk.gray("ℹ")} ${chalk.gray(issue.message)}${fixPart}`);
|
|
667
|
+
logger.info("");
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
for (const issue of issues.filter((i) => i.severity !== "info")) {
|
|
647
671
|
const severityIcon = issue.severity === "error" ? chalk.red("✗") : chalk.yellow("⚠");
|
|
648
672
|
const categoryLabel = formatCategory(issue.category);
|
|
649
673
|
logger.info(` ${chalk.gray("┌─")} ${severityIcon} ${chalk.bold(categoryLabel)} ${chalk.gray("─".repeat(Math.max(0, 42 - categoryLabel.length)))}`);
|
|
@@ -674,7 +698,8 @@ function formatCategory(cat: DoctorIssue["category"]): string {
|
|
|
674
698
|
missing_enum: "Missing Enum",
|
|
675
699
|
enum_value_mismatch: "Enum Value Mismatch",
|
|
676
700
|
missing_foreign_key: "Missing Foreign Key",
|
|
677
|
-
sdk_stale: "Stale SDK Types"
|
|
701
|
+
sdk_stale: "Stale SDK Types",
|
|
702
|
+
sdk_not_generated: "SDK Types Not Generated"
|
|
678
703
|
};
|
|
679
704
|
return labels[cat];
|
|
680
705
|
}
|
|
@@ -91,6 +91,30 @@ function coerceDeclaredNumbers(
|
|
|
91
91
|
}
|
|
92
92
|
|
|
93
93
|
/** Render one target row in the requested style. */
|
|
94
|
+
/**
|
|
95
|
+
* Drop every column the collection marked `excludeFromApi`.
|
|
96
|
+
*
|
|
97
|
+
* Password hashes and verification tokens have to be readable server-side but
|
|
98
|
+
* must never reach a client — and "never" has to mean every exit from this
|
|
99
|
+
* pipeline, including relation targets, or a secret leaks through whichever
|
|
100
|
+
* path was overlooked. Keyed by both the property name and its column name,
|
|
101
|
+
* since a row can arrive keyed either way depending on the caller.
|
|
102
|
+
*/
|
|
103
|
+
function stripExcluded(
|
|
104
|
+
row: Record<string, unknown>,
|
|
105
|
+
collection: CollectionConfig
|
|
106
|
+
): Record<string, unknown> {
|
|
107
|
+
const properties = collection.properties as Record<string, Property> | undefined;
|
|
108
|
+
if (!properties) return row;
|
|
109
|
+
|
|
110
|
+
for (const [key, property] of Object.entries(properties)) {
|
|
111
|
+
if (!property?.excludeFromApi) continue;
|
|
112
|
+
delete row[key];
|
|
113
|
+
if (property.columnName) delete row[property.columnName];
|
|
114
|
+
}
|
|
115
|
+
return row;
|
|
116
|
+
}
|
|
117
|
+
|
|
94
118
|
function renderTarget(
|
|
95
119
|
targetRow: Record<string, unknown>,
|
|
96
120
|
targetCollection: CollectionConfig,
|
|
@@ -100,7 +124,7 @@ function renderTarget(
|
|
|
100
124
|
if (style === "inline") {
|
|
101
125
|
// The target's columns, and only those: its address is the consumer's
|
|
102
126
|
// to derive, and merging one in overwrites a real `id` column.
|
|
103
|
-
return coerceDeclaredNumbers({ ...targetRow }, targetCollection);
|
|
127
|
+
return stripExcluded(coerceDeclaredNumbers({ ...targetRow }, targetCollection), targetCollection);
|
|
104
128
|
}
|
|
105
129
|
|
|
106
130
|
const address = relationTargetAddress(targetRow, targetCollection, registry);
|
|
@@ -168,7 +192,7 @@ export function toCmsRow(
|
|
|
168
192
|
}
|
|
169
193
|
}
|
|
170
194
|
|
|
171
|
-
return normalized;
|
|
195
|
+
return stripExcluded(normalized, collection);
|
|
172
196
|
}
|
|
173
197
|
|
|
174
198
|
/**
|
|
@@ -211,5 +235,5 @@ export function toRestRow(
|
|
|
211
235
|
}
|
|
212
236
|
}
|
|
213
237
|
|
|
214
|
-
return flat;
|
|
238
|
+
return stripExcluded(flat, collection);
|
|
215
239
|
}
|