@rebasepro/server-postgres 0.9.1-canary.ff338b5 → 0.10.1-canary.a54c057

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/index.es.js CHANGED
@@ -353,7 +353,7 @@ function getDeclaredSubcollections(collection) {
353
353
  /**
354
354
  * The id a request without a logged-in user reports as `auth.uid()`.
355
355
  *
356
- * A user-context request always sets `app.user_id`: blank would read back as
356
+ * A user-context request always sets `app.uid`: blank would read back as
357
357
  * `NULL`, and `NULL` is how the trusted server context is recognised, so an
358
358
  * anonymous visitor would be promoted to server privileges. The driver
359
359
  * therefore substitutes this sentinel at the single chokepoint where the GUC
@@ -2134,7 +2134,7 @@ function getSubcollections(collection) {
2134
2134
  * It handles:
2135
2135
  * - `field = 'literal'`
2136
2136
  * - `field != 'literal'`
2137
- * - `field = current_setting('app.user_id')`
2137
+ * - `field = current_setting('app.uid')` (or the legacy `app.user_id`)
2138
2138
  * - `A AND B`, `A OR B` — only where the keyword is at the top level
2139
2139
  * - `true`
2140
2140
  * - `IN (...)` (as optimistic true)
@@ -2335,7 +2335,7 @@ function findAnonymousGrants(expr) {
2335
2335
  return found;
2336
2336
  }
2337
2337
  function parseOperand(str) {
2338
- if (/current_setting\s*\(\s*'app\.user_id'\s*\)/i.test(str) || /auth\.uid\(\)/i.test(str)) return policy.authUid();
2338
+ if (/current_setting\s*\(\s*'app\.(uid|user_id)'\s*\)/i.test(str) || /auth\.uid\(\)/i.test(str)) return policy.authUid();
2339
2339
  const stringMatch = str.match(/^'(.+)'$/);
2340
2340
  if (stringMatch) return policy.literal(stringMatch[1]);
2341
2341
  if (/^\w+$/.test(str)) return policy.field(str);
@@ -8182,7 +8182,7 @@ async function ensureAppRole(run, schemas) {
8182
8182
  * SECURITY: this function is only ever called on the **user** path (the server
8183
8183
  * context uses the base/owner driver and never calls it). The default policies
8184
8184
  * treat `auth.uid() IS NULL` as the trusted server context, and `auth.uid()`
8185
- * is `NULLIF(current_setting('app.user_id'), '')` — so an EMPTY user id would
8185
+ * is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would
8186
8186
  * be read as NULL and silently escalate a user request to server privileges.
8187
8187
  * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
8188
8188
  * rather than trusting every caller (e.g. realtime subscription auth) to do it.
@@ -8190,14 +8190,15 @@ async function ensureAppRole(run, schemas) {
8190
8190
  * semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
8191
8191
  */
8192
8192
  async function applyAuthContext(tx, auth, userRole) {
8193
- const userId = typeof auth.userId === "string" && auth.userId.trim() !== "" ? auth.userId : ANONYMOUS_USER_ID;
8193
+ const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
8194
8194
  const normalizedRoles = auth.roles.map((r) => typeof r === "string" ? r : r?.id ?? String(r));
8195
8195
  await tx.execute(sql`
8196
8196
  SELECT
8197
- set_config('app.user_id', ${userId}, true),
8197
+ set_config('app.uid', ${uid}, true),
8198
+ set_config('app.user_id', ${uid}, true),
8198
8199
  set_config('app.user_roles', ${normalizedRoles.join(",")}, true),
8199
8200
  set_config('app.jwt', ${JSON.stringify({
8200
- sub: userId,
8201
+ sub: uid,
8201
8202
  roles: auth.roles
8202
8203
  })}, true)
8203
8204
  `);
@@ -8343,6 +8344,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
8343
8344
  executeSql: (...args) => this.executeSql(...args),
8344
8345
  fetchAvailableDatabases: () => this.fetchAvailableDatabases(),
8345
8346
  fetchAvailableRoles: () => this.fetchAvailableRoles(),
8347
+ fetchApplicationRoles: () => this.fetchApplicationRoles(),
8346
8348
  fetchCurrentDatabase: () => this.fetchCurrentDatabase(),
8347
8349
  fetchUnmappedTables: (...args) => this.fetchUnmappedTables(...args),
8348
8350
  fetchTableMetadata: (...args) => this.fetchTableMetadata(...args),
@@ -8996,6 +8998,45 @@ var PostgresBackendDriver = class PostgresBackendDriver {
8996
8998
  async fetchAvailableRoles() {
8997
8999
  return (await this.executeSql("SELECT rolname FROM pg_roles WHERE pg_has_role(current_user, rolname, 'member') ORDER BY rolname;")).map((r) => r.rolname);
8998
9000
  }
9001
+ /**
9002
+ * Application-level roles actually in use in this project.
9003
+ *
9004
+ * Distinct from {@link fetchAvailableRoles}, which returns native
9005
+ * PostgreSQL roles from `pg_roles` (`postgres`, `rebase_user`, …). Those
9006
+ * are the roles the SQL editor can `SET ROLE` to. *These* are the strings
9007
+ * held in the users table's `roles` column, injected per-transaction as
9008
+ * `auth.roles()` and matched by `SecurityRule.roles`. Feeding the pg roles
9009
+ * into a `SecurityRule.roles` field produces a condition no user can ever
9010
+ * satisfy, so the two must not be conflated.
9011
+ *
9012
+ * Roles have no registry table — they were migrated out of
9013
+ * `rebase.user_roles` onto an inline `roles TEXT[]` column — so the live
9014
+ * set is derived from what is assigned. A role that is declared in a policy
9015
+ * but held by nobody yet cannot be discovered here; callers that need it
9016
+ * should union in the roles they already know about.
9017
+ */
9018
+ async fetchApplicationRoles() {
9019
+ const located = await this.executeSql(`
9020
+ SELECT table_schema, table_name
9021
+ FROM information_schema.columns
9022
+ WHERE column_name = 'roles'
9023
+ AND data_type = 'ARRAY'
9024
+ AND table_name = 'users'
9025
+ AND table_schema NOT IN ('information_schema', 'pg_catalog')
9026
+ ORDER BY (table_schema = 'rebase') DESC, table_schema
9027
+ LIMIT 1;
9028
+ `);
9029
+ if (located.length === 0) return [];
9030
+ const schema = located[0].table_schema;
9031
+ const table = located[0].table_name;
9032
+ const qualified = `"${schema.replace(/"/g, "\"\"")}"."${table.replace(/"/g, "\"\"")}"`;
9033
+ return (await this.executeSql(`
9034
+ SELECT DISTINCT unnest(roles) AS role
9035
+ FROM ${qualified}
9036
+ WHERE roles IS NOT NULL
9037
+ ORDER BY role;
9038
+ `)).map((r) => r.role).filter((r) => typeof r === "string" && r.length > 0);
9039
+ }
8999
9040
  async fetchCurrentDatabase() {
9000
9041
  return this.poolManager?.defaultDatabaseName;
9001
9042
  }
@@ -9137,15 +9178,15 @@ var AuthenticatedPostgresBackendDriver = class {
9137
9178
  async withTransaction(operation, options) {
9138
9179
  const pendingNotifications = [];
9139
9180
  const result = await this.delegate.db.transaction(async (tx) => {
9140
- let userId = this.user?.uid;
9141
- if (!userId) {
9181
+ let uid = this.user?.uid;
9182
+ if (!uid) {
9142
9183
  logger.warn("[DataDriver] User ID (uid) is missing for authenticated delegate. Using 'anonymous'. User object", { detail: this.user });
9143
- userId = "anonymous";
9184
+ uid = "anonymous";
9144
9185
  }
9145
9186
  const userRoles = this.user?.roles ?? [];
9146
9187
  if (!this.user?.roles) logger.warn("[DataDriver] User roles are missing for authenticated delegate. Using empty array. User object", { detail: this.user });
9147
9188
  await applyAuthContext(tx, {
9148
- userId,
9189
+ uid,
9149
9190
  roles: userRoles
9150
9191
  }, this.delegate.rlsUserRole);
9151
9192
  const txEntityService = new DataService(tx, this.delegate.registry);
@@ -9172,7 +9213,7 @@ var AuthenticatedPostgresBackendDriver = class {
9172
9213
  */
9173
9214
  injectAuthContext(unsubscribe) {
9174
9215
  const authContext = {
9175
- userId: this.user?.uid || "anonymous",
9216
+ uid: this.user?.uid || "anonymous",
9176
9217
  roles: this.user?.roles ?? []
9177
9218
  };
9178
9219
  const entries = Array.from(this.delegate.realtimeService.subscriptions.entries());
@@ -9316,19 +9357,19 @@ function createAuthSchema(usersSchemaName = "rebase") {
9316
9357
  */
9317
9358
  const refreshTokens = tableCreator("refresh_tokens", {
9318
9359
  id: uuid("id").defaultRandom().primaryKey(),
9319
- userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
9360
+ uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
9320
9361
  tokenHash: varchar("token_hash", { length: 255 }).notNull().unique(),
9321
9362
  expiresAt: timestamp("expires_at").notNull(),
9322
9363
  userAgent: varchar("user_agent", { length: 500 }),
9323
9364
  ipAddress: varchar("ip_address", { length: 45 }),
9324
9365
  createdAt: timestamp("created_at").defaultNow().notNull()
9325
- }, (table) => ({ uniqueDeviceSession: unique("unique_device_session").on(table.userId, table.userAgent, table.ipAddress) }));
9366
+ }, (table) => ({ uniqueDeviceSession: unique("unique_device_session").on(table.uid, table.userAgent, table.ipAddress) }));
9326
9367
  /**
9327
9368
  * Password reset tokens for forgot password flow
9328
9369
  */
9329
9370
  const passwordResetTokens = tableCreator("password_reset_tokens", {
9330
9371
  id: uuid("id").defaultRandom().primaryKey(),
9331
- userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
9372
+ uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
9332
9373
  tokenHash: varchar("token_hash", { length: 255 }).notNull().unique(),
9333
9374
  expiresAt: timestamp("expires_at").notNull(),
9334
9375
  usedAt: timestamp("used_at"),
@@ -9347,7 +9388,7 @@ function createAuthSchema(usersSchemaName = "rebase") {
9347
9388
  */
9348
9389
  const userIdentities = tableCreator("user_identities", {
9349
9390
  id: uuid("id").defaultRandom().primaryKey(),
9350
- userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
9391
+ uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
9351
9392
  provider: varchar("provider", { length: 50 }).notNull(),
9352
9393
  providerId: varchar("provider_id", { length: 255 }).notNull(),
9353
9394
  profileData: jsonb("profile_data"),
@@ -9359,7 +9400,7 @@ function createAuthSchema(usersSchemaName = "rebase") {
9359
9400
  */
9360
9401
  const mfaFactors = tableCreator("mfa_factors", {
9361
9402
  id: uuid("id").defaultRandom().primaryKey(),
9362
- userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
9403
+ uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
9363
9404
  factorType: varchar("factor_type", { length: 20 }).notNull(),
9364
9405
  secretEncrypted: varchar("secret_encrypted", { length: 500 }).notNull(),
9365
9406
  friendlyName: varchar("friendly_name", { length: 255 }),
@@ -9385,14 +9426,14 @@ function createAuthSchema(usersSchemaName = "rebase") {
9385
9426
  }),
9386
9427
  recoveryCodes: tableCreator("recovery_codes", {
9387
9428
  id: uuid("id").defaultRandom().primaryKey(),
9388
- userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
9429
+ uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
9389
9430
  codeHash: varchar("code_hash", { length: 255 }).notNull(),
9390
9431
  usedAt: timestamp("used_at"),
9391
9432
  createdAt: timestamp("created_at").defaultNow().notNull()
9392
9433
  }),
9393
9434
  magicLinkTokens: tableCreator("magic_link_tokens", {
9394
9435
  id: uuid("id").defaultRandom().primaryKey(),
9395
- userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
9436
+ uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
9396
9437
  tokenHash: varchar("token_hash", { length: 255 }).notNull().unique(),
9397
9438
  expiresAt: timestamp("expires_at").notNull(),
9398
9439
  usedAt: timestamp("used_at"),
@@ -9420,20 +9461,20 @@ var usersRelations = relations(users, ({ many }) => ({
9420
9461
  magicLinkTokens: many(magicLinkTokens)
9421
9462
  }));
9422
9463
  var refreshTokensRelations = relations(refreshTokens, ({ one }) => ({ user: one(users, {
9423
- fields: [refreshTokens.userId],
9464
+ fields: [refreshTokens.uid],
9424
9465
  references: [users.id]
9425
9466
  }) }));
9426
9467
  var passwordResetTokensRelations = relations(passwordResetTokens, ({ one }) => ({ user: one(users, {
9427
- fields: [passwordResetTokens.userId],
9468
+ fields: [passwordResetTokens.uid],
9428
9469
  references: [users.id]
9429
9470
  }) }));
9430
9471
  var userIdentitiesRelations = relations(userIdentities, ({ one }) => ({ user: one(users, {
9431
- fields: [userIdentities.userId],
9472
+ fields: [userIdentities.uid],
9432
9473
  references: [users.id]
9433
9474
  }) }));
9434
9475
  var mfaFactorsRelations = relations(mfaFactors, ({ one, many }) => ({
9435
9476
  user: one(users, {
9436
- fields: [mfaFactors.userId],
9477
+ fields: [mfaFactors.uid],
9437
9478
  references: [users.id]
9438
9479
  }),
9439
9480
  challenges: many(mfaChallenges)
@@ -9443,11 +9484,11 @@ var mfaChallengesRelations = relations(mfaChallenges, ({ one }) => ({ factor: on
9443
9484
  references: [mfaFactors.id]
9444
9485
  }) }));
9445
9486
  var recoveryCodesRelations = relations(recoveryCodes, ({ one }) => ({ user: one(users, {
9446
- fields: [recoveryCodes.userId],
9487
+ fields: [recoveryCodes.uid],
9447
9488
  references: [users.id]
9448
9489
  }) }));
9449
9490
  var magicLinkTokensRelations = relations(magicLinkTokens, ({ one }) => ({ user: one(users, {
9450
- fields: [magicLinkTokens.userId],
9491
+ fields: [magicLinkTokens.uid],
9451
9492
  references: [users.id]
9452
9493
  }) }));
9453
9494
  //#endregion
@@ -10280,6 +10321,267 @@ var CdcListener = class CdcListener {
10280
10321
  }
10281
10322
  };
10282
10323
  //#endregion
10324
+ //#region src/services/channel-history.ts
10325
+ /**
10326
+ * Ordered, replayable per-channel message history.
10327
+ *
10328
+ * Broadcast on its own is fire-and-forget to whoever is connected at the
10329
+ * instant it is sent: fine for presence and for "someone saved" notifications,
10330
+ * not enough for op-based collaborative editing, where a client that blinks
10331
+ * out for two seconds has to resync a whole document rather than catch up on
10332
+ * the four operations it missed. This adds the missing half — every retained
10333
+ * broadcast gets a per-channel sequence number, and a client can ask for
10334
+ * everything after the last one it saw.
10335
+ *
10336
+ * Three decisions worth stating, because each rules out a simpler-looking one:
10337
+ *
10338
+ * - **Retention is server-side and opt-in.** A channel is created by whoever
10339
+ * names it, so a client-supplied history depth would let any visitor commit
10340
+ * the backend to unbounded storage. And presence channels — the common case
10341
+ * — must not pay for this: with no rules configured nothing is written, no
10342
+ * table is created, and `broadcast` runs exactly the code it ran before.
10343
+ *
10344
+ * - **Sequence numbers come from the database, not from a counter in this
10345
+ * process.** They have to survive a restart and be shared across instances;
10346
+ * an in-memory counter would restart at 1 after a deploy and hand a
10347
+ * reconnecting client a replay from the wrong era, silently.
10348
+ *
10349
+ * - **The cursor row outlives the messages it numbered.** Pruning is what
10350
+ * makes retention affordable, but pruning the cursor along with the messages
10351
+ * would restart the sequence and make `sinceSeq` mean something different
10352
+ * before and after — the worst kind of bug, because replay would still
10353
+ * return rows and they would look plausible. Cursors are tiny and are kept
10354
+ * forever; see {@link prune}, which touches only `channel_messages`.
10355
+ */
10356
+ /** How many messages a replay returns when the caller does not say. */
10357
+ var DEFAULT_REPLAY_LIMIT = 200;
10358
+ /**
10359
+ * Hard ceiling on one replay, whatever the caller asks for.
10360
+ *
10361
+ * A reconnecting client names its own `limit`, so this is the only thing
10362
+ * standing between a stale `sinceSeq` and a single frame carrying a channel's
10363
+ * entire retained history. A client that is further behind than this is told so
10364
+ * via `latestSeq` and can decide to resync wholesale instead of paging.
10365
+ */
10366
+ var MAX_REPLAY_LIMIT = 1e3;
10367
+ /** Minimum gap between two prunes of the same channel. */
10368
+ var PRUNE_THROTTLE_MS = 3e4;
10369
+ /**
10370
+ * Parse a retention TTL into milliseconds.
10371
+ *
10372
+ * Accepts a raw millisecond count or a short duration string (`"30s"`, `"15m"`,
10373
+ * `"24h"`, `"7d"`). Returns undefined for anything unparseable, which the
10374
+ * caller treats as "no TTL" — a misspelt duration must not silently become an
10375
+ * aggressive one.
10376
+ */
10377
+ function parseTtlMs(ttl) {
10378
+ if (ttl === void 0 || ttl === null) return void 0;
10379
+ if (typeof ttl === "number") return Number.isFinite(ttl) && ttl > 0 ? ttl : void 0;
10380
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.exec(ttl);
10381
+ if (!match) {
10382
+ logger.warn(`⚠️ [ChannelHistory] Ignoring unparseable retention ttl "${ttl}" — expected e.g. "30s", "15m", "24h", "7d".`);
10383
+ return;
10384
+ }
10385
+ const value = parseFloat(match[1]);
10386
+ const unit = match[2].toLowerCase();
10387
+ const ms = value * (unit === "ms" ? 1 : unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5);
10388
+ return ms > 0 ? ms : void 0;
10389
+ }
10390
+ /**
10391
+ * Whether `channel` is covered by `rule`.
10392
+ *
10393
+ * Exact match, or a trailing `*` acting as a prefix. Not a general glob: this
10394
+ * decides what reaches disk, and a pattern language whose reach is not obvious
10395
+ * at a glance is the wrong tool for that job.
10396
+ */
10397
+ function channelMatchesRule(channel, rule) {
10398
+ const pattern = rule.match;
10399
+ if (pattern === "*") return true;
10400
+ if (pattern.endsWith("*")) return channel.startsWith(pattern.slice(0, -1));
10401
+ return channel === pattern;
10402
+ }
10403
+ /**
10404
+ * Persistence and replay for retained channels.
10405
+ *
10406
+ * Inert unless constructed with at least one rule: {@link enabled} is false,
10407
+ * {@link ensureTables} does nothing, and {@link retentionFor} answers undefined
10408
+ * for every channel, so the realtime service never reaches the SQL below.
10409
+ */
10410
+ var ChannelHistoryStore = class {
10411
+ db;
10412
+ rules;
10413
+ /** Resolved rule per channel name, so the match runs once per channel. */
10414
+ resolved = /* @__PURE__ */ new Map();
10415
+ /** Channel → timestamp of its last prune, for {@link PRUNE_THROTTLE_MS}. */
10416
+ lastPruned = /* @__PURE__ */ new Map();
10417
+ tablesReady = false;
10418
+ constructor(db, rules = []) {
10419
+ this.db = db;
10420
+ this.rules = rules.filter((rule) => {
10421
+ if (!rule?.match) {
10422
+ logger.warn("⚠️ [ChannelHistory] Ignoring a retention rule with no `match`.");
10423
+ return false;
10424
+ }
10425
+ if (!(rule.limit !== void 0 || rule.ttl !== void 0)) {
10426
+ logger.warn(`⚠️ [ChannelHistory] Retention rule "${rule.match}" sets neither \`limit\` nor \`ttl\` — ignoring it, as it would retain forever.`);
10427
+ return false;
10428
+ }
10429
+ return true;
10430
+ });
10431
+ }
10432
+ /** Whether any channel retains anything at all. */
10433
+ get enabled() {
10434
+ return this.rules.length > 0;
10435
+ }
10436
+ /**
10437
+ * The retention that applies to `channel`, or undefined when none does.
10438
+ *
10439
+ * First matching rule wins, so callers order them most-specific first.
10440
+ */
10441
+ retentionFor(channel) {
10442
+ if (!this.enabled || !channel) return void 0;
10443
+ const cached = this.resolved.get(channel);
10444
+ if (cached !== void 0) return cached ?? void 0;
10445
+ const rule = this.rules.find((r) => channelMatchesRule(channel, r));
10446
+ const resolved = rule ? {
10447
+ limit: rule.limit,
10448
+ ttlMs: parseTtlMs(rule.ttl)
10449
+ } : null;
10450
+ this.resolved.set(channel, resolved);
10451
+ return resolved ?? void 0;
10452
+ }
10453
+ /**
10454
+ * Create the history tables. Idempotent, and a no-op when no rule is set —
10455
+ * a deployment that never retains anything gets no schema for it.
10456
+ */
10457
+ async ensureTables() {
10458
+ if (!this.enabled || this.tablesReady) return;
10459
+ await this.db.execute(sql`CREATE SCHEMA IF NOT EXISTS rebase`);
10460
+ await this.db.execute(sql`
10461
+ CREATE TABLE IF NOT EXISTS rebase.channel_messages (
10462
+ channel TEXT NOT NULL,
10463
+ seq BIGINT NOT NULL,
10464
+ event TEXT NOT NULL,
10465
+ payload JSONB,
10466
+ sender_id TEXT,
10467
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
10468
+ PRIMARY KEY (channel, seq)
10469
+ )
10470
+ `);
10471
+ await this.db.execute(sql`
10472
+ CREATE INDEX IF NOT EXISTS idx_channel_messages_created
10473
+ ON rebase.channel_messages (created_at)
10474
+ `);
10475
+ await this.db.execute(sql`
10476
+ CREATE TABLE IF NOT EXISTS rebase.channel_cursors (
10477
+ channel TEXT PRIMARY KEY,
10478
+ last_seq BIGINT NOT NULL
10479
+ )
10480
+ `);
10481
+ this.tablesReady = true;
10482
+ logger.info(`✅ [ChannelHistory] Retained channels ready (${this.rules.length} rule(s)).`);
10483
+ }
10484
+ /**
10485
+ * Append a broadcast and return the sequence number it was given.
10486
+ *
10487
+ * The sequence is allocated by the same statement that stores the message,
10488
+ * so a crash between the two is not a possibility. `ON CONFLICT DO UPDATE`
10489
+ * takes a row lock on the channel's cursor, which is what makes concurrent
10490
+ * broadcasts to one channel line up in a single order — and what keeps
10491
+ * different channels from contending with each other at all.
10492
+ */
10493
+ async append(channel, event, payload, senderId) {
10494
+ const row = (await this.db.execute(sql`
10495
+ WITH next AS (
10496
+ INSERT INTO rebase.channel_cursors (channel, last_seq)
10497
+ VALUES (${channel}, 1)
10498
+ ON CONFLICT (channel)
10499
+ DO UPDATE SET last_seq = rebase.channel_cursors.last_seq + 1
10500
+ RETURNING last_seq
10501
+ )
10502
+ INSERT INTO rebase.channel_messages (channel, seq, event, payload, sender_id)
10503
+ SELECT ${channel}, next.last_seq, ${event}, ${JSON.stringify(payload ?? null)}::jsonb, ${senderId ?? null}
10504
+ FROM next
10505
+ RETURNING seq, created_at
10506
+ `)).rows[0];
10507
+ if (!row) throw new Error(`Failed to append to channel history for "${channel}"`);
10508
+ return {
10509
+ seq: Number(row.seq),
10510
+ at: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at)
10511
+ };
10512
+ }
10513
+ /**
10514
+ * Everything retained for `channel` after `sinceSeq`, oldest first.
10515
+ *
10516
+ * `latestSeq` is reported whether or not the messages were capped, so a
10517
+ * client that is further behind than one page can tell.
10518
+ */
10519
+ async replay(channel, sinceSeq = 0, limit = DEFAULT_REPLAY_LIMIT) {
10520
+ const capped = Math.max(1, Math.min(Math.floor(limit) || DEFAULT_REPLAY_LIMIT, MAX_REPLAY_LIMIT));
10521
+ const after = Number.isFinite(sinceSeq) && sinceSeq > 0 ? Math.floor(sinceSeq) : 0;
10522
+ const messages = (await this.db.execute(sql`
10523
+ SELECT seq, event, payload, sender_id, created_at
10524
+ FROM rebase.channel_messages
10525
+ WHERE channel = ${channel} AND seq > ${after}
10526
+ ORDER BY seq ASC
10527
+ LIMIT ${capped}
10528
+ `)).rows.map((row) => ({
10529
+ seq: Number(row.seq),
10530
+ event: row.event,
10531
+ payload: row.payload,
10532
+ senderId: row.sender_id ?? void 0,
10533
+ at: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at)
10534
+ }));
10535
+ const cursorRow = (await this.db.execute(sql`
10536
+ SELECT last_seq FROM rebase.channel_cursors WHERE channel = ${channel}
10537
+ `)).rows[0];
10538
+ return {
10539
+ messages,
10540
+ latestSeq: cursorRow ? Number(cursorRow.last_seq) : 0
10541
+ };
10542
+ }
10543
+ /**
10544
+ * Enforce a channel's retention bounds.
10545
+ *
10546
+ * Throttled per channel, so a burst of operations prunes once rather than
10547
+ * once per message — the cost then tracks elapsed time instead of write
10548
+ * volume, which is what makes retention affordable on a hot channel.
10549
+ */
10550
+ async prune(channel, retention) {
10551
+ const now = Date.now();
10552
+ if (now - (this.lastPruned.get(channel) ?? 0) < PRUNE_THROTTLE_MS) return 0;
10553
+ this.lastPruned.set(channel, now);
10554
+ let deleted = 0;
10555
+ if (retention.ttlMs !== void 0) {
10556
+ const result = await this.db.execute(sql`
10557
+ DELETE FROM rebase.channel_messages
10558
+ WHERE channel = ${channel}
10559
+ AND created_at < NOW() - MAKE_INTERVAL(secs => ${retention.ttlMs / 1e3})
10560
+ `);
10561
+ deleted += result.rowCount ?? 0;
10562
+ }
10563
+ if (retention.limit !== void 0 && retention.limit > 0) {
10564
+ const result = await this.db.execute(sql`
10565
+ DELETE FROM rebase.channel_messages
10566
+ WHERE channel = ${channel}
10567
+ AND seq <= (
10568
+ SELECT seq FROM rebase.channel_messages
10569
+ WHERE channel = ${channel}
10570
+ ORDER BY seq DESC
10571
+ OFFSET ${Math.floor(retention.limit)} LIMIT 1
10572
+ )
10573
+ `);
10574
+ deleted += result.rowCount ?? 0;
10575
+ }
10576
+ return deleted;
10577
+ }
10578
+ /** Forget throttle and match caches. Called on shutdown. */
10579
+ clear() {
10580
+ this.resolved.clear();
10581
+ this.lastPruned.clear();
10582
+ }
10583
+ };
10584
+ //#endregion
10283
10585
  //#region src/services/realtimeService.ts
10284
10586
  /** Channel name used for Postgres LISTEN/NOTIFY cross-instance realtime. */
10285
10587
  var PG_NOTIFY_CHANNEL = "rebase_entity_changes";
@@ -10295,6 +10597,26 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10295
10597
  clients = /* @__PURE__ */ new Map();
10296
10598
  channels = /* @__PURE__ */ new Map();
10297
10599
  presence = /* @__PURE__ */ new Map();
10600
+ /**
10601
+ * Ordered, replayable history for channels that opt into it.
10602
+ *
10603
+ * Undefined until {@link configureChannelHistory} is called, and inert even
10604
+ * then unless retention rules were supplied — so presence and ephemeral
10605
+ * notification channels never touch it. See `channel-history.ts`.
10606
+ */
10607
+ channelHistory;
10608
+ /**
10609
+ * One promise chain per retained channel, so that assigning a sequence
10610
+ * number and fanning the message out happen in the same order for every
10611
+ * message on that channel.
10612
+ *
10613
+ * Without it, two concurrent broadcasts can be numbered 4 and 5 by the
10614
+ * database and still reach subscribers as 5 then 4 — live order and replay
10615
+ * order would disagree, which is exactly the divergence sequence numbers
10616
+ * are supposed to rule out. Keyed by channel, so unrelated channels never
10617
+ * wait on each other.
10618
+ */
10619
+ channelSendQueues = /* @__PURE__ */ new Map();
10298
10620
  presenceInterval;
10299
10621
  static PRESENCE_TIMEOUT_MS = 3e4;
10300
10622
  dataService;
@@ -10471,6 +10793,9 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10471
10793
  case "broadcast":
10472
10794
  this.broadcastToChannel(clientId, payload?.channel, payload?.event, payload?.payload);
10473
10795
  break;
10796
+ case "channel_history":
10797
+ await this.handleChannelHistoryRequest(clientId, payload?.channel, payload?.sinceSeq, payload?.limit);
10798
+ break;
10474
10799
  case "presence_track":
10475
10800
  this.joinChannel(clientId, payload?.channel);
10476
10801
  this.trackPresence(clientId, payload?.channel, payload?.state ?? {});
@@ -10681,12 +11006,12 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10681
11006
  if (this.driver) {
10682
11007
  const collection = this.registry.getCollectionByPath(notifyPath);
10683
11008
  const activeAuth = authContext || {
10684
- userId: "anon",
11009
+ uid: "anon",
10685
11010
  roles: ["anon"]
10686
11011
  };
10687
11012
  return await this.db.transaction(async (tx) => {
10688
11013
  await applyAuthContext(tx, {
10689
- userId: activeAuth.userId,
11014
+ uid: activeAuth.uid,
10690
11015
  roles: activeAuth.roles
10691
11016
  }, this.rlsUserRole);
10692
11017
  const txEntityService = new DataService(tx, this.registry);
@@ -10718,7 +11043,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10718
11043
  if (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead) {
10719
11044
  const contextForCallback = {
10720
11045
  user: {
10721
- uid: activeAuth.userId,
11046
+ uid: activeAuth.uid,
10722
11047
  roles: activeAuth.roles
10723
11048
  },
10724
11049
  driver: this.driver,
@@ -10810,12 +11135,12 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10810
11135
  if (this.driver) {
10811
11136
  const collection = this.registry.getCollectionByPath(notifyPath);
10812
11137
  const activeAuth = authContext || {
10813
- userId: "anon",
11138
+ uid: "anon",
10814
11139
  roles: ["anon"]
10815
11140
  };
10816
11141
  return await this.db.transaction(async (tx) => {
10817
11142
  await applyAuthContext(tx, {
10818
- userId: activeAuth.userId,
11143
+ uid: activeAuth.uid,
10819
11144
  roles: activeAuth.roles
10820
11145
  }, this.rlsUserRole);
10821
11146
  let processedEntity = await new DataService(tx, this.registry).fetchOne(notifyPath, id, collection?.databaseId);
@@ -10831,7 +11156,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10831
11156
  if (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead) {
10832
11157
  const contextForCallback = {
10833
11158
  user: {
10834
- uid: activeAuth.userId,
11159
+ uid: activeAuth.uid,
10835
11160
  roles: activeAuth.roles
10836
11161
  },
10837
11162
  driver: this.driver,
@@ -10957,15 +11282,67 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10957
11282
  }
10958
11283
  this.removePresence(clientId, channel);
10959
11284
  }
10960
- /** Broadcast a message to all clients in a channel except sender */
11285
+ /**
11286
+ * Broadcast a message to all clients in a channel except the sender.
11287
+ *
11288
+ * On a channel with no retention rule this is what it always was: a
11289
+ * synchronous fan-out to whoever is connected, with no sequence number, no
11290
+ * SQL and no await — the body below runs to completion before returning.
11291
+ *
11292
+ * On a retained channel the message is durably numbered first and only then
11293
+ * delivered, through a per-channel queue so that delivery order matches
11294
+ * sequence order. That ordering is the whole point: a client that catches up
11295
+ * with `sinceSeq` has to arrive at the same state as one that never
11296
+ * disconnected.
11297
+ */
10961
11298
  broadcastToChannel(clientId, channel, event, payload) {
11299
+ const retention = this.channelHistory?.retentionFor(channel);
11300
+ if (!retention) {
11301
+ this.fanOutBroadcast(clientId, channel, event, payload);
11302
+ return;
11303
+ }
11304
+ const next = (this.channelSendQueues.get(channel) ?? Promise.resolve()).catch(() => {}).then(() => this.persistAndFanOut(clientId, channel, event, payload, retention));
11305
+ this.channelSendQueues.set(channel, next);
11306
+ next.finally(() => {
11307
+ if (this.channelSendQueues.get(channel) === next) this.channelSendQueues.delete(channel);
11308
+ });
11309
+ }
11310
+ /**
11311
+ * Number a broadcast, store it, then deliver it.
11312
+ *
11313
+ * A message that cannot be stored is **not** delivered. Delivering it would
11314
+ * put it in front of live subscribers while leaving it absent from every
11315
+ * future replay — the two views of the channel would disagree permanently,
11316
+ * and no later message could repair the gap. Failing loudly to the sender
11317
+ * instead lets it retry, which for an operation stream is the only outcome
11318
+ * that keeps clients convergent.
11319
+ */
11320
+ async persistAndFanOut(clientId, channel, event, payload, retention) {
11321
+ let seq;
11322
+ try {
11323
+ ({seq} = await this.channelHistory.append(channel, event, payload, clientId));
11324
+ } catch (error) {
11325
+ logger.error(`❌ [ChannelHistory] Could not persist broadcast on "${channel}" — message dropped`, { error });
11326
+ this.sendError(clientId, `Could not persist broadcast on retained channel "${channel}"`, void 0, "CHANNEL_HISTORY_WRITE_FAILED");
11327
+ return;
11328
+ }
11329
+ this.fanOutBroadcast(clientId, channel, event, payload, seq);
11330
+ try {
11331
+ await this.channelHistory.prune(channel, retention);
11332
+ } catch (error) {
11333
+ logger.warn(`⚠️ [ChannelHistory] Prune failed for "${channel}"`, { error });
11334
+ }
11335
+ }
11336
+ /** Deliver a broadcast frame to every member of a channel but the sender. */
11337
+ fanOutBroadcast(clientId, channel, event, payload, seq) {
10962
11338
  const members = this.channels.get(channel);
10963
11339
  if (!members) return;
10964
11340
  const message = JSON.stringify({
10965
11341
  type: "broadcast",
10966
11342
  channel,
10967
11343
  event,
10968
- payload
11344
+ payload,
11345
+ ...seq !== void 0 ? { seq } : {}
10969
11346
  });
10970
11347
  for (const memberId of members) {
10971
11348
  if (memberId === clientId) continue;
@@ -10973,6 +11350,55 @@ var RealtimeService = class RealtimeService extends EventEmitter {
10973
11350
  if (ws && ws.readyState === WebSocket.OPEN) ws.send(message);
10974
11351
  }
10975
11352
  }
11353
+ /**
11354
+ * Install retention rules and create the tables they need.
11355
+ *
11356
+ * Safe to call with no rules (and safe not to call at all): the store stays
11357
+ * inert, no schema is created, and broadcast keeps its original
11358
+ * fire-and-forget path.
11359
+ */
11360
+ async configureChannelHistory(rules) {
11361
+ this.channelHistory = new ChannelHistoryStore(this.db, rules ?? []);
11362
+ if (!this.channelHistory.enabled) return;
11363
+ await this.channelHistory.ensureTables();
11364
+ }
11365
+ /** Whether any channel is configured to retain messages. */
11366
+ isChannelHistoryEnabled() {
11367
+ return this.channelHistory?.enabled ?? false;
11368
+ }
11369
+ /**
11370
+ * Answer a client's catch-up request.
11371
+ *
11372
+ * A channel with no retention rule is answered with `retained: false`
11373
+ * rather than an empty list, so the client can tell "you missed nothing"
11374
+ * apart from "this channel never keeps anything" — the second means its
11375
+ * reconnect strategy has to be a full resync, and silence would leave it
11376
+ * guessing.
11377
+ */
11378
+ async handleChannelHistoryRequest(clientId, channel, sinceSeq, limit) {
11379
+ if (!channel) return;
11380
+ if (!this.channelHistory?.retentionFor(channel)) {
11381
+ this.sendChannelHistory(clientId, channel, [], false);
11382
+ return;
11383
+ }
11384
+ try {
11385
+ const { messages, latestSeq } = await this.channelHistory.replay(channel, sinceSeq, limit);
11386
+ this.sendChannelHistory(clientId, channel, messages, true, latestSeq);
11387
+ } catch (error) {
11388
+ logger.error(`❌ [ChannelHistory] Replay failed for "${channel}"`, { error });
11389
+ this.sendError(clientId, `Could not replay history for channel "${channel}"`, void 0, "CHANNEL_HISTORY_READ_FAILED");
11390
+ }
11391
+ }
11392
+ sendChannelHistory(clientId, channel, messages, retained, latestSeq) {
11393
+ const ws = this.clients.get(clientId);
11394
+ if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({
11395
+ type: "channel_history",
11396
+ channel,
11397
+ messages,
11398
+ retained,
11399
+ ...latestSeq !== void 0 ? { latestSeq } : {}
11400
+ }));
11401
+ }
10976
11402
  /** Track presence in a channel */
10977
11403
  trackPresence(clientId, channel, state) {
10978
11404
  if (!this.presence.has(channel)) this.presence.set(channel, /* @__PURE__ */ new Map());
@@ -11053,6 +11479,9 @@ var RealtimeService = class RealtimeService extends EventEmitter {
11053
11479
  this.subscriptionCallbacks.clear();
11054
11480
  this.channels.clear();
11055
11481
  this.presence.clear();
11482
+ await Promise.allSettled([...this.channelSendQueues.values()]);
11483
+ this.channelSendQueues.clear();
11484
+ this.channelHistory?.clear();
11056
11485
  if (this.presenceInterval) {
11057
11486
  clearInterval(this.presenceInterval);
11058
11487
  this.presenceInterval = void 0;
@@ -11394,20 +11823,20 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11394
11823
  if (authAdapter) try {
11395
11824
  const adapterUser = authAdapter.verifyToken ? await authAdapter.verifyToken(token) : await authAdapter.verifyRequest(new Request("http://localhost/_ws_auth", { headers: { Authorization: `Bearer ${token}` } }));
11396
11825
  if (adapterUser) verifiedUser = {
11397
- userId: adapterUser.uid,
11826
+ uid: adapterUser.uid,
11398
11827
  roles: adapterUser.roles,
11399
11828
  isAdmin: adapterUser.isAdmin
11400
11829
  };
11401
11830
  } catch {}
11402
11831
  else if (authConfig?.serviceKey && safeCompare(token, authConfig.serviceKey)) verifiedUser = {
11403
- userId: "service",
11832
+ uid: "service",
11404
11833
  roles: ["admin"],
11405
11834
  isAdmin: true
11406
11835
  };
11407
11836
  else {
11408
11837
  const jwtPayload = extractUserFromToken(token);
11409
11838
  if (jwtPayload) verifiedUser = {
11410
- userId: jwtPayload.userId,
11839
+ uid: jwtPayload.uid,
11411
11840
  roles: jwtPayload.roles ?? [],
11412
11841
  isAdmin: (jwtPayload.roles ?? []).some((r) => r === "admin")
11413
11842
  };
@@ -11423,11 +11852,11 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11423
11852
  type: "AUTH_SUCCESS",
11424
11853
  requestId,
11425
11854
  payload: {
11426
- userId: verifiedUser.userId,
11855
+ uid: verifiedUser.uid,
11427
11856
  roles: verifiedUser.roles
11428
11857
  }
11429
11858
  }));
11430
- wsDebug(`🔐 [WebSocket Server] Client ${clientId} authenticated as ${verifiedUser.userId}`);
11859
+ wsDebug(`🔐 [WebSocket Server] Client ${clientId} authenticated as ${verifiedUser.uid}`);
11431
11860
  } else {
11432
11861
  wsDebug(`[WS] replying AUTH_ERROR for requestId ${requestId} (invalid token)`);
11433
11862
  sendError("AUTH_ERROR", "INVALID_TOKEN", "Invalid or expired token");
@@ -11465,7 +11894,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11465
11894
  const session = clientSessions.get(clientId);
11466
11895
  if (typeof driver.withAuth === "function") try {
11467
11896
  const userForAuth = session?.user ? {
11468
- uid: session.user.userId,
11897
+ uid: session.user.uid,
11469
11898
  displayName: null,
11470
11899
  email: null,
11471
11900
  photoURL: null,
@@ -11599,7 +12028,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11599
12028
  sql: typeof sql === "string" ? sql.substring(0, 500) : sql,
11600
12029
  options,
11601
12030
  resultRows: Array.isArray(result) ? result.length : "unknown",
11602
- userId: auditSession?.user?.userId ?? "unknown",
12031
+ uid: auditSession?.user?.uid ?? "unknown",
11603
12032
  roles: auditSession?.user?.roles ?? [],
11604
12033
  isAdmin: auditSession?.user?.isAdmin ?? false
11605
12034
  }));
@@ -11644,6 +12073,21 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11644
12073
  ws.send(JSON.stringify(response));
11645
12074
  }
11646
12075
  break;
12076
+ case "FETCH_APPLICATION_ROLES":
12077
+ {
12078
+ wsDebug("👤 [WebSocket Server] Processing FETCH_APPLICATION_ROLES request");
12079
+ const admin = (await getScopedDelegate()).admin;
12080
+ let roles = [];
12081
+ if (isSQLAdmin(admin) && admin.fetchApplicationRoles) roles = await admin.fetchApplicationRoles();
12082
+ wsDebug(`👤 [WebSocket Server] Fetched ${roles.length} application roles.`);
12083
+ const response = {
12084
+ type: "FETCH_APPLICATION_ROLES_SUCCESS",
12085
+ payload: { roles },
12086
+ requestId
12087
+ };
12088
+ ws.send(JSON.stringify(response));
12089
+ }
12090
+ break;
11647
12091
  case "FETCH_CURRENT_DATABASE":
11648
12092
  {
11649
12093
  wsDebug("📚 [WebSocket Server] Processing FETCH_CURRENT_DATABASE request");
@@ -11750,14 +12194,15 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
11750
12194
  case "broadcast":
11751
12195
  case "presence_track":
11752
12196
  case "presence_untrack":
11753
- case "presence_state": {
12197
+ case "presence_state":
12198
+ case "channel_history": {
11754
12199
  wsDebug("🔄 [WebSocket Server] Routing realtime message to RealtimeService:", type);
11755
12200
  const session = clientSessions.get(clientId);
11756
12201
  const authContext = session?.user ? {
11757
- userId: session.user.userId,
12202
+ uid: session.user.uid,
11758
12203
  roles: session.user.roles ?? []
11759
12204
  } : {
11760
- userId: "anon",
12205
+ uid: "anon",
11761
12206
  roles: ["anon"]
11762
12207
  };
11763
12208
  await realtimeService.handleClientMessage(clientId, {
@@ -20713,9 +21158,65 @@ async function ensureAuthTablesExist(db, collection) {
20713
21158
  )
20714
21159
  `);
20715
21160
  await db.execute(sql`
21161
+ CREATE OR REPLACE FUNCTION ${sql.raw(`"${authSchema}"`)}.sync_uid_user_id() RETURNS trigger AS $$
21162
+ BEGIN
21163
+ IF NEW.uid IS NULL AND NEW.user_id IS NOT NULL THEN
21164
+ NEW.uid := NEW.user_id;
21165
+ ELSIF NEW.user_id IS NULL AND NEW.uid IS NOT NULL THEN
21166
+ NEW.user_id := NEW.uid;
21167
+ END IF;
21168
+ RETURN NEW;
21169
+ END $$ LANGUAGE plpgsql
21170
+ `);
21171
+ for (const authTable of [
21172
+ "user_identities",
21173
+ "refresh_tokens",
21174
+ "password_reset_tokens",
21175
+ "magic_link_tokens",
21176
+ "mfa_factors",
21177
+ "recovery_codes"
21178
+ ]) {
21179
+ const qualified = `"${authSchema}"."${authTable}"`;
21180
+ await db.execute(sql`
21181
+ DO $$
21182
+ DECLARE
21183
+ has_legacy boolean;
21184
+ has_uid boolean;
21185
+ BEGIN
21186
+ SELECT
21187
+ bool_or(column_name = 'user_id'),
21188
+ bool_or(column_name = 'uid')
21189
+ INTO has_legacy, has_uid
21190
+ FROM information_schema.columns
21191
+ WHERE table_schema = ${sql.raw(`'${authSchema}'`)}
21192
+ AND table_name = ${sql.raw(`'${authTable}'`)};
21193
+
21194
+ -- Table absent, or already uid-only (a fresh install, or
21195
+ -- phase 2 already run): nothing to do.
21196
+ IF has_legacy IS NOT TRUE THEN
21197
+ RETURN;
21198
+ END IF;
21199
+
21200
+ IF has_uid IS NOT TRUE THEN
21201
+ EXECUTE ${sql.raw(`'ALTER TABLE ${qualified} ADD COLUMN uid ${userIdType} REFERENCES ${usersTableName}(id) ON DELETE CASCADE'`)};
21202
+ EXECUTE ${sql.raw(`'UPDATE ${qualified} SET uid = user_id WHERE uid IS NULL'`)};
21203
+ EXECUTE ${sql.raw(`'CREATE INDEX IF NOT EXISTS idx_${authTable}_uid ON ${qualified}(uid)'`)};
21204
+ END IF;
21205
+
21206
+ -- New code inserts uid and never user_id, so the legacy
21207
+ -- column can no longer be NOT NULL. The trigger below
21208
+ -- backfills it, but the constraint is checked first.
21209
+ EXECUTE ${sql.raw(`'ALTER TABLE ${qualified} ALTER COLUMN user_id DROP NOT NULL'`)};
21210
+
21211
+ EXECUTE ${sql.raw(`'DROP TRIGGER IF EXISTS sync_uid_user_id ON ${qualified}'`)};
21212
+ EXECUTE ${sql.raw(`'CREATE TRIGGER sync_uid_user_id BEFORE INSERT OR UPDATE ON ${qualified} FOR EACH ROW EXECUTE FUNCTION "${authSchema}".sync_uid_user_id()'`)};
21213
+ END $$
21214
+ `);
21215
+ }
21216
+ await db.execute(sql`
20716
21217
  CREATE TABLE IF NOT EXISTS ${sql.raw(userIdentitiesTable)} (
20717
21218
  id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
20718
- user_id ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
21219
+ uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
20719
21220
  provider TEXT NOT NULL,
20720
21221
  provider_id TEXT NOT NULL,
20721
21222
  profile_data JSONB,
@@ -20726,18 +21227,18 @@ async function ensureAuthTablesExist(db, collection) {
20726
21227
  `);
20727
21228
  await db.execute(sql`
20728
21229
  CREATE INDEX IF NOT EXISTS idx_user_identities_user
20729
- ON ${sql.raw(userIdentitiesTable)}(user_id)
21230
+ ON ${sql.raw(userIdentitiesTable)}(uid)
20730
21231
  `);
20731
21232
  await db.execute(sql`
20732
21233
  CREATE TABLE IF NOT EXISTS ${sql.raw(refreshTokensTableName)} (
20733
21234
  id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
20734
- user_id ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
21235
+ uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
20735
21236
  token_hash TEXT NOT NULL UNIQUE,
20736
21237
  expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
20737
21238
  user_agent TEXT,
20738
21239
  ip_address TEXT,
20739
21240
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
20740
- CONSTRAINT unique_device_session UNIQUE (user_id, user_agent, ip_address)
21241
+ CONSTRAINT unique_device_session UNIQUE (uid, user_agent, ip_address)
20741
21242
  )
20742
21243
  `);
20743
21244
  await db.execute(sql`
@@ -20746,12 +21247,12 @@ async function ensureAuthTablesExist(db, collection) {
20746
21247
  `);
20747
21248
  await db.execute(sql`
20748
21249
  CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user
20749
- ON ${sql.raw(refreshTokensTableName)}(user_id)
21250
+ ON ${sql.raw(refreshTokensTableName)}(uid)
20750
21251
  `);
20751
21252
  await db.execute(sql`
20752
21253
  CREATE TABLE IF NOT EXISTS ${sql.raw(passwordResetTokensTableName)} (
20753
21254
  id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
20754
- user_id ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
21255
+ uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
20755
21256
  token_hash TEXT NOT NULL UNIQUE,
20756
21257
  expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
20757
21258
  used_at TIMESTAMP WITH TIME ZONE,
@@ -20764,13 +21265,13 @@ async function ensureAuthTablesExist(db, collection) {
20764
21265
  `);
20765
21266
  await db.execute(sql`
20766
21267
  CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_user
20767
- ON ${sql.raw(passwordResetTokensTableName)}(user_id)
21268
+ ON ${sql.raw(passwordResetTokensTableName)}(uid)
20768
21269
  `);
20769
21270
  const magicLinkTokensTableName = `"${authSchema}"."magic_link_tokens"`;
20770
21271
  await db.execute(sql`
20771
21272
  CREATE TABLE IF NOT EXISTS ${sql.raw(magicLinkTokensTableName)} (
20772
21273
  id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
20773
- user_id ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
21274
+ uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
20774
21275
  token_hash TEXT NOT NULL UNIQUE,
20775
21276
  expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
20776
21277
  used_at TIMESTAMP WITH TIME ZONE,
@@ -20783,7 +21284,7 @@ async function ensureAuthTablesExist(db, collection) {
20783
21284
  `);
20784
21285
  await db.execute(sql`
20785
21286
  CREATE INDEX IF NOT EXISTS idx_magic_link_tokens_user
20786
- ON ${sql.raw(magicLinkTokensTableName)}(user_id)
21287
+ ON ${sql.raw(magicLinkTokensTableName)}(uid)
20787
21288
  `);
20788
21289
  await db.execute(sql`
20789
21290
  CREATE TABLE IF NOT EXISTS ${sql.raw(appConfigTableName)} (
@@ -20797,7 +21298,10 @@ async function ensureAuthTablesExist(db, collection) {
20797
21298
  await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext('rebase_auth_functions_init'))`);
20798
21299
  await tx.execute(sql`
20799
21300
  CREATE OR REPLACE FUNCTION auth.uid() RETURNS text AS $$
20800
- SELECT NULLIF(current_setting('app.user_id', true), '');
21301
+ SELECT COALESCE(
21302
+ NULLIF(current_setting('app.uid', true), ''),
21303
+ NULLIF(current_setting('app.user_id', true), '')
21304
+ );
20801
21305
  $$ LANGUAGE sql STABLE
20802
21306
  `);
20803
21307
  await tx.execute(sql`
@@ -20830,6 +21334,53 @@ async function ensureAuthTablesExist(db, collection) {
20830
21334
  ALTER TABLE ${sql.raw(usersTableName)}
20831
21335
  ADD COLUMN IF NOT EXISTS ${sql.raw(columnDef)}
20832
21336
  `);
21337
+ try {
21338
+ const found = (await db.execute(sql`
21339
+ SELECT table_schema, table_name
21340
+ FROM information_schema.tables
21341
+ WHERE table_name = 'refresh_tokens'
21342
+ `)).rows;
21343
+ logger.info(`🔍 refresh_tokens reconcile: found ${found.length} table(s): ${found.map((r) => `"${r.table_schema}"."${r.table_name}"`).join(", ") || "(none)"}`);
21344
+ for (const { table_schema } of found) {
21345
+ const qualified = `"${table_schema}"."refresh_tokens"`;
21346
+ try {
21347
+ await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS user_agent TEXT`);
21348
+ await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS ip_address TEXT`);
21349
+ await db.execute(sql`UPDATE ${sql.raw(qualified)} SET user_agent = '' WHERE user_agent IS NULL`);
21350
+ await db.execute(sql`UPDATE ${sql.raw(qualified)} SET ip_address = '' WHERE ip_address IS NULL`);
21351
+ await db.execute(sql`
21352
+ DELETE FROM ${sql.raw(qualified)} a
21353
+ USING ${sql.raw(qualified)} b
21354
+ WHERE a.ctid < b.ctid
21355
+ AND a.uid = b.uid
21356
+ AND a.user_agent = b.user_agent
21357
+ AND a.ip_address = b.ip_address
21358
+ `);
21359
+ const uniques = await db.execute(sql`
21360
+ SELECT conname, pg_get_constraintdef(oid) AS def
21361
+ FROM pg_constraint
21362
+ WHERE conrelid = ${sql.raw(`'${qualified}'`)}::regclass AND contype = 'u'
21363
+ `);
21364
+ for (const u of uniques.rows) logger.info(` ${qualified} unique: ${u.conname} → ${u.def}`);
21365
+ if (uniques.rows.some((u) => {
21366
+ const cols = (u.def.match(/\(([^)]*)\)/)?.[1] || "").split(",").map((c) => c.trim().replace(/"/g, ""));
21367
+ return cols.length === 3 && cols.includes("uid") && cols.includes("user_agent") && cols.includes("ip_address");
21368
+ })) logger.info(`✓ correct device-session unique already present on ${qualified}`);
21369
+ else {
21370
+ await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} DROP CONSTRAINT IF EXISTS unique_device_session`);
21371
+ await db.execute(sql`
21372
+ ALTER TABLE ${sql.raw(qualified)}
21373
+ ADD CONSTRAINT unique_device_session UNIQUE (uid, user_agent, ip_address)
21374
+ `);
21375
+ logger.info(`✅ Added correct unique_device_session constraint to ${qualified}`);
21376
+ }
21377
+ } catch (perTableError) {
21378
+ logger.warn(`⚠️ refresh_tokens reconcile failed for ${qualified}: ${perTableError instanceof Error ? perTableError.message : String(perTableError)}`);
21379
+ }
21380
+ }
21381
+ } catch (migrationError) {
21382
+ logger.warn(`⚠️ refresh_tokens device-session migration skipped: ${migrationError instanceof Error ? migrationError.message : String(migrationError)}`);
21383
+ }
20833
21384
  try {
20834
21385
  if ((await db.execute(sql`
20835
21386
  SELECT EXISTS (
@@ -20860,7 +21411,7 @@ async function ensureAuthTablesExist(db, collection) {
20860
21411
  await db.execute(sql`
20861
21412
  CREATE TABLE IF NOT EXISTS ${sql.raw(mfaFactorsTableName)} (
20862
21413
  id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
20863
- user_id ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
21414
+ uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
20864
21415
  factor_type TEXT NOT NULL DEFAULT 'totp',
20865
21416
  secret_encrypted TEXT NOT NULL,
20866
21417
  friendly_name TEXT,
@@ -20871,7 +21422,7 @@ async function ensureAuthTablesExist(db, collection) {
20871
21422
  `);
20872
21423
  await db.execute(sql`
20873
21424
  CREATE INDEX IF NOT EXISTS idx_mfa_factors_user
20874
- ON ${sql.raw(mfaFactorsTableName)}(user_id)
21425
+ ON ${sql.raw(mfaFactorsTableName)}(uid)
20875
21426
  `);
20876
21427
  await db.execute(sql`
20877
21428
  CREATE TABLE IF NOT EXISTS ${sql.raw(mfaChallengesTableName)} (
@@ -20890,7 +21441,7 @@ async function ensureAuthTablesExist(db, collection) {
20890
21441
  await db.execute(sql`
20891
21442
  CREATE TABLE IF NOT EXISTS ${sql.raw(recoveryCodesTableName)} (
20892
21443
  id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
20893
- user_id ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
21444
+ uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
20894
21445
  code_hash TEXT NOT NULL,
20895
21446
  used_at TIMESTAMP WITH TIME ZONE,
20896
21447
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
@@ -20898,7 +21449,7 @@ async function ensureAuthTablesExist(db, collection) {
20898
21449
  `);
20899
21450
  await db.execute(sql`
20900
21451
  CREATE INDEX IF NOT EXISTS idx_recovery_codes_user
20901
- ON ${sql.raw(recoveryCodesTableName)}(user_id)
21452
+ ON ${sql.raw(recoveryCodesTableName)}(uid)
20902
21453
  `);
20903
21454
  try {
20904
21455
  const authTablePairs = [
@@ -20979,7 +21530,7 @@ var UserService = class {
20979
21530
  * Run a privileged auth write with an explicitly cleared RLS context.
20980
21531
  *
20981
21532
  * The auth services run on the base/owner connection, which by design
20982
- * carries a NULL `app.user_id` so the `auth.uid() IS NULL` server-escape
21533
+ * carries a NULL `app.uid` so the `auth.uid() IS NULL` server-escape
20983
21534
  * in the default policies applies. That NULL is normally guaranteed by
20984
21535
  * `set_config(..., is_local = true)` resetting at transaction end — but a
20985
21536
  * GUC that survives on a pooled connection (or a connection role that
@@ -20993,7 +21544,8 @@ var UserService = class {
20993
21544
  async withServerContext(fn) {
20994
21545
  return await this.db.transaction(async (tx) => {
20995
21546
  await tx.execute(sql`
20996
- SELECT set_config('app.user_id', '', true),
21547
+ SELECT set_config('app.uid', '', true),
21548
+ set_config('app.user_id', '', true),
20997
21549
  set_config('app.user_roles', '', true),
20998
21550
  set_config('app.jwt', '', true)
20999
21551
  `);
@@ -21115,19 +21667,19 @@ var UserService = class {
21115
21667
  async getUserByIdentity(provider, providerId) {
21116
21668
  const userIdCol = getColumn(this.usersTable, "id");
21117
21669
  if (!userIdCol) return null;
21118
- const result = await this.db.select({ user: this.usersTable }).from(this.usersTable).innerJoin(this.userIdentitiesTable, eq(userIdCol, this.userIdentitiesTable.userId)).where(sql`${this.userIdentitiesTable.provider} = ${provider} AND ${this.userIdentitiesTable.providerId} = ${providerId}`).limit(1);
21670
+ const result = await this.db.select({ user: this.usersTable }).from(this.usersTable).innerJoin(this.userIdentitiesTable, eq(userIdCol, this.userIdentitiesTable.uid)).where(sql`${this.userIdentitiesTable.provider} = ${provider} AND ${this.userIdentitiesTable.providerId} = ${providerId}`).limit(1);
21119
21671
  if (result.length === 0) return null;
21120
21672
  return this.mapRowToUser(result[0].user);
21121
21673
  }
21122
- async getUserIdentities(userId) {
21674
+ async getUserIdentities(uid) {
21123
21675
  const schema = getTableConfig(this.userIdentitiesTable).schema || "public";
21124
21676
  return (await this.db.execute(sql`
21125
- SELECT id, user_id, provider, provider_id, profile_data, created_at, updated_at
21677
+ SELECT id, uid, provider, provider_id, profile_data, created_at, updated_at
21126
21678
  FROM ${sql.raw(`"${schema}"."user_identities"`)}
21127
- WHERE user_id = ${userId}
21679
+ WHERE uid = ${uid}
21128
21680
  `)).rows.map((row) => ({
21129
21681
  id: row.id,
21130
- userId: row.user_id,
21682
+ uid: row.uid,
21131
21683
  provider: row.provider,
21132
21684
  providerId: row.provider_id,
21133
21685
  profileData: row.profile_data ?? null,
@@ -21135,9 +21687,9 @@ var UserService = class {
21135
21687
  updatedAt: row.updated_at
21136
21688
  }));
21137
21689
  }
21138
- async linkUserIdentity(userId, provider, providerId, profileData) {
21690
+ async linkUserIdentity(uid, provider, providerId, profileData) {
21139
21691
  await this.withServerContext(async (db) => db.insert(this.userIdentitiesTable).values({
21140
- userId,
21692
+ uid,
21141
21693
  provider,
21142
21694
  providerId,
21143
21695
  profileData: profileData || null
@@ -21256,10 +21808,10 @@ var UserService = class {
21256
21808
  /**
21257
21809
  * Get roles for a user from database (inline TEXT[] column)
21258
21810
  */
21259
- async getUserRoles(userId) {
21811
+ async getUserRoles(uid) {
21260
21812
  const usersTableName = this.getQualifiedUsersTableName();
21261
21813
  const result = await this.db.execute(sql`
21262
- SELECT roles FROM ${sql.raw(usersTableName)} WHERE id = ${userId}
21814
+ SELECT roles FROM ${sql.raw(usersTableName)} WHERE id = ${uid}
21263
21815
  `);
21264
21816
  if (result.rows.length === 0) return [];
21265
21817
  return (result.rows[0].roles ?? []).map((id) => ({
@@ -21273,10 +21825,10 @@ var UserService = class {
21273
21825
  /**
21274
21826
  * Get role IDs for a user
21275
21827
  */
21276
- async getUserRoleIds(userId) {
21828
+ async getUserRoleIds(uid) {
21277
21829
  const usersTableName = this.getQualifiedUsersTableName();
21278
21830
  const result = await this.db.execute(sql`
21279
- SELECT roles FROM ${sql.raw(usersTableName)} WHERE id = ${userId}
21831
+ SELECT roles FROM ${sql.raw(usersTableName)} WHERE id = ${uid}
21280
21832
  `);
21281
21833
  if (result.rows.length === 0) return [];
21282
21834
  return result.rows[0].roles ?? [];
@@ -21284,35 +21836,35 @@ var UserService = class {
21284
21836
  /**
21285
21837
  * Set roles for a user (replaces existing roles)
21286
21838
  */
21287
- async setUserRoles(userId, roleIds) {
21839
+ async setUserRoles(uid, roleIds) {
21288
21840
  const usersTableName = this.getQualifiedUsersTableName();
21289
21841
  const rolesArray = `{${roleIds.join(",")}}`;
21290
21842
  await this.withServerContext(async (db) => db.execute(sql`
21291
21843
  UPDATE ${sql.raw(usersTableName)}
21292
21844
  SET roles = ${rolesArray}::text[], updated_at = NOW()
21293
- WHERE id = ${userId}
21845
+ WHERE id = ${uid}
21294
21846
  `));
21295
21847
  }
21296
21848
  /**
21297
21849
  * Assign a specific role to new user (appends if not present)
21298
21850
  */
21299
- async assignDefaultRole(userId, roleId) {
21851
+ async assignDefaultRole(uid, roleId) {
21300
21852
  const usersTableName = this.getQualifiedUsersTableName();
21301
21853
  await this.withServerContext(async (db) => db.execute(sql`
21302
21854
  UPDATE ${sql.raw(usersTableName)}
21303
21855
  SET roles = array_append(roles, ${roleId}), updated_at = NOW()
21304
- WHERE id = ${userId} AND NOT (${roleId} = ANY(roles))
21856
+ WHERE id = ${uid} AND NOT (${roleId} = ANY(roles))
21305
21857
  `));
21306
21858
  }
21307
21859
  /**
21308
21860
  * Get user with their roles
21309
21861
  */
21310
- async getUserWithRoles(userId) {
21311
- const user = await this.getUserById(userId);
21862
+ async getUserWithRoles(uid) {
21863
+ const user = await this.getUserById(uid);
21312
21864
  if (!user) return null;
21313
21865
  return {
21314
21866
  user,
21315
- roles: await this.getUserRoles(userId)
21867
+ roles: await this.getUserRoles(uid)
21316
21868
  };
21317
21869
  }
21318
21870
  };
@@ -21324,18 +21876,18 @@ var RefreshTokenService = class {
21324
21876
  if (tableOrTables && (tableOrTables.refreshTokens || tableOrTables.users)) this.refreshTokensTable = tableOrTables.refreshTokens || refreshTokens;
21325
21877
  else this.refreshTokensTable = tableOrTables || refreshTokens;
21326
21878
  }
21327
- async createToken(userId, tokenHash, expiresAt, userAgent, ipAddress) {
21879
+ async createToken(uid, tokenHash, expiresAt, userAgent, ipAddress) {
21328
21880
  const safeUserAgent = userAgent || "";
21329
21881
  const safeIpAddress = ipAddress || "";
21330
21882
  await this.db.insert(this.refreshTokensTable).values({
21331
- userId,
21883
+ uid,
21332
21884
  tokenHash,
21333
21885
  expiresAt,
21334
21886
  userAgent: safeUserAgent,
21335
21887
  ipAddress: safeIpAddress
21336
21888
  }).onConflictDoUpdate({
21337
21889
  target: [
21338
- this.refreshTokensTable.userId,
21890
+ this.refreshTokensTable.uid,
21339
21891
  this.refreshTokensTable.userAgent,
21340
21892
  this.refreshTokensTable.ipAddress
21341
21893
  ],
@@ -21348,7 +21900,7 @@ var RefreshTokenService = class {
21348
21900
  async findByHash(tokenHash) {
21349
21901
  const [token] = await this.db.select({
21350
21902
  id: this.refreshTokensTable.id,
21351
- userId: this.refreshTokensTable.userId,
21903
+ uid: this.refreshTokensTable.uid,
21352
21904
  tokenHash: this.refreshTokensTable.tokenHash,
21353
21905
  expiresAt: this.refreshTokensTable.expiresAt,
21354
21906
  createdAt: this.refreshTokensTable.createdAt,
@@ -21360,22 +21912,22 @@ var RefreshTokenService = class {
21360
21912
  async deleteByHash(tokenHash) {
21361
21913
  await this.db.delete(this.refreshTokensTable).where(eq(this.refreshTokensTable.tokenHash, tokenHash));
21362
21914
  }
21363
- async deleteAllForUser(userId) {
21364
- await this.db.delete(this.refreshTokensTable).where(eq(this.refreshTokensTable.userId, userId));
21915
+ async deleteAllForUser(uid) {
21916
+ await this.db.delete(this.refreshTokensTable).where(eq(this.refreshTokensTable.uid, uid));
21365
21917
  }
21366
- async listForUser(userId) {
21918
+ async listForUser(uid) {
21367
21919
  return await this.db.select({
21368
21920
  id: this.refreshTokensTable.id,
21369
- userId: this.refreshTokensTable.userId,
21921
+ uid: this.refreshTokensTable.uid,
21370
21922
  tokenHash: this.refreshTokensTable.tokenHash,
21371
21923
  expiresAt: this.refreshTokensTable.expiresAt,
21372
21924
  createdAt: this.refreshTokensTable.createdAt,
21373
21925
  userAgent: this.refreshTokensTable.userAgent,
21374
21926
  ipAddress: this.refreshTokensTable.ipAddress
21375
- }).from(this.refreshTokensTable).where(eq(this.refreshTokensTable.userId, userId)).orderBy(this.refreshTokensTable.createdAt);
21927
+ }).from(this.refreshTokensTable).where(eq(this.refreshTokensTable.uid, uid)).orderBy(this.refreshTokensTable.createdAt);
21376
21928
  }
21377
- async deleteById(id, userId) {
21378
- await this.db.delete(this.refreshTokensTable).where(sql`${this.refreshTokensTable.id} = ${id} AND ${this.refreshTokensTable.userId} = ${userId}`);
21929
+ async deleteById(id, uid) {
21930
+ await this.db.delete(this.refreshTokensTable).where(sql`${this.refreshTokensTable.id} = ${id} AND ${this.refreshTokensTable.uid} = ${uid}`);
21379
21931
  }
21380
21932
  };
21381
21933
  /**
@@ -21396,14 +21948,14 @@ var PasswordResetTokenService = class {
21396
21948
  /**
21397
21949
  * Create a password reset token
21398
21950
  */
21399
- async createToken(userId, tokenHash, expiresAt) {
21951
+ async createToken(uid, tokenHash, expiresAt) {
21400
21952
  const tableName = this.getQualifiedPasswordResetTokensTableName();
21401
21953
  await this.db.execute(sql`
21402
21954
  DELETE FROM ${sql.raw(tableName)}
21403
- WHERE user_id = ${userId} AND used_at IS NULL
21955
+ WHERE uid = ${uid} AND used_at IS NULL
21404
21956
  `);
21405
21957
  await this.db.insert(this.passwordResetTokensTable).values({
21406
- userId,
21958
+ uid,
21407
21959
  tokenHash,
21408
21960
  expiresAt
21409
21961
  });
@@ -21413,13 +21965,13 @@ var PasswordResetTokenService = class {
21413
21965
  */
21414
21966
  async findValidByHash(tokenHash) {
21415
21967
  const [token] = await this.db.select({
21416
- userId: this.passwordResetTokensTable.userId,
21968
+ uid: this.passwordResetTokensTable.uid,
21417
21969
  expiresAt: this.passwordResetTokensTable.expiresAt
21418
21970
  }).from(this.passwordResetTokensTable).where(eq(this.passwordResetTokensTable.tokenHash, tokenHash));
21419
21971
  if (!token) return null;
21420
21972
  const tableName = this.getQualifiedPasswordResetTokensTableName();
21421
21973
  const result = await this.db.execute(sql`
21422
- SELECT user_id, expires_at
21974
+ SELECT uid, expires_at
21423
21975
  FROM ${sql.raw(tableName)}
21424
21976
  WHERE token_hash = ${tokenHash}
21425
21977
  AND used_at IS NULL
@@ -21428,7 +21980,7 @@ var PasswordResetTokenService = class {
21428
21980
  if (result.rows.length === 0) return null;
21429
21981
  const row = result.rows[0];
21430
21982
  return {
21431
- userId: row.user_id,
21983
+ uid: row.uid,
21432
21984
  expiresAt: new Date(row.expires_at)
21433
21985
  };
21434
21986
  }
@@ -21441,8 +21993,8 @@ var PasswordResetTokenService = class {
21441
21993
  /**
21442
21994
  * Delete all tokens for a user
21443
21995
  */
21444
- async deleteAllForUser(userId) {
21445
- await this.db.delete(this.passwordResetTokensTable).where(eq(this.passwordResetTokensTable.userId, userId));
21996
+ async deleteAllForUser(uid) {
21997
+ await this.db.delete(this.passwordResetTokensTable).where(eq(this.passwordResetTokensTable.uid, uid));
21446
21998
  }
21447
21999
  /**
21448
22000
  * Clean up expired tokens
@@ -21470,14 +22022,14 @@ var MagicLinkTokenService = class {
21470
22022
  const name = getTableName(this.magicLinkTokensTable);
21471
22023
  return `"${getTableConfig(this.magicLinkTokensTable).schema || "public"}"."${name}"`;
21472
22024
  }
21473
- async createToken(userId, tokenHash, expiresAt) {
22025
+ async createToken(uid, tokenHash, expiresAt) {
21474
22026
  const tableName = this.getQualifiedTableName();
21475
22027
  await this.db.execute(sql`
21476
22028
  DELETE FROM ${sql.raw(tableName)}
21477
- WHERE user_id = ${userId} AND used_at IS NULL
22029
+ WHERE uid = ${uid} AND used_at IS NULL
21478
22030
  `);
21479
22031
  await this.db.insert(this.magicLinkTokensTable).values({
21480
- userId,
22032
+ uid,
21481
22033
  tokenHash,
21482
22034
  expiresAt
21483
22035
  });
@@ -21485,7 +22037,7 @@ var MagicLinkTokenService = class {
21485
22037
  async findValidByHash(tokenHash) {
21486
22038
  const tableName = this.getQualifiedTableName();
21487
22039
  const result = await this.db.execute(sql`
21488
- SELECT user_id, expires_at
22040
+ SELECT uid, expires_at
21489
22041
  FROM ${sql.raw(tableName)}
21490
22042
  WHERE token_hash = ${tokenHash}
21491
22043
  AND used_at IS NULL
@@ -21494,7 +22046,7 @@ var MagicLinkTokenService = class {
21494
22046
  if (result.rows.length === 0) return null;
21495
22047
  const row = result.rows[0];
21496
22048
  return {
21497
- userId: row.user_id,
22049
+ uid: row.uid,
21498
22050
  expiresAt: new Date(row.expires_at)
21499
22051
  };
21500
22052
  }
@@ -21517,8 +22069,8 @@ var PostgresTokenRepository = class {
21517
22069
  this.passwordResetTokenService = new PasswordResetTokenService(db, tableOrTables);
21518
22070
  this.magicLinkTokenService = new MagicLinkTokenService(db, tableOrTables);
21519
22071
  }
21520
- async createRefreshToken(userId, tokenHash, expiresAt, userAgent, ipAddress) {
21521
- await this.refreshTokenService.createToken(userId, tokenHash, expiresAt, userAgent, ipAddress);
22072
+ async createRefreshToken(uid, tokenHash, expiresAt, userAgent, ipAddress) {
22073
+ await this.refreshTokenService.createToken(uid, tokenHash, expiresAt, userAgent, ipAddress);
21522
22074
  }
21523
22075
  async findRefreshTokenByHash(tokenHash) {
21524
22076
  return this.refreshTokenService.findByHash(tokenHash);
@@ -21526,17 +22078,17 @@ var PostgresTokenRepository = class {
21526
22078
  async deleteRefreshToken(tokenHash) {
21527
22079
  await this.refreshTokenService.deleteByHash(tokenHash);
21528
22080
  }
21529
- async deleteAllRefreshTokensForUser(userId) {
21530
- await this.refreshTokenService.deleteAllForUser(userId);
22081
+ async deleteAllRefreshTokensForUser(uid) {
22082
+ await this.refreshTokenService.deleteAllForUser(uid);
21531
22083
  }
21532
- async listRefreshTokensForUser(userId) {
21533
- return this.refreshTokenService.listForUser(userId);
22084
+ async listRefreshTokensForUser(uid) {
22085
+ return this.refreshTokenService.listForUser(uid);
21534
22086
  }
21535
- async deleteRefreshTokenById(id, userId) {
21536
- await this.refreshTokenService.deleteById(id, userId);
22087
+ async deleteRefreshTokenById(id, uid) {
22088
+ await this.refreshTokenService.deleteById(id, uid);
21537
22089
  }
21538
- async createPasswordResetToken(userId, tokenHash, expiresAt) {
21539
- await this.passwordResetTokenService.createToken(userId, tokenHash, expiresAt);
22090
+ async createPasswordResetToken(uid, tokenHash, expiresAt) {
22091
+ await this.passwordResetTokenService.createToken(uid, tokenHash, expiresAt);
21540
22092
  }
21541
22093
  async findValidPasswordResetToken(tokenHash) {
21542
22094
  return this.passwordResetTokenService.findValidByHash(tokenHash);
@@ -21544,14 +22096,14 @@ var PostgresTokenRepository = class {
21544
22096
  async markPasswordResetTokenUsed(tokenHash) {
21545
22097
  await this.passwordResetTokenService.markAsUsed(tokenHash);
21546
22098
  }
21547
- async deleteAllPasswordResetTokensForUser(userId) {
21548
- await this.passwordResetTokenService.deleteAllForUser(userId);
22099
+ async deleteAllPasswordResetTokensForUser(uid) {
22100
+ await this.passwordResetTokenService.deleteAllForUser(uid);
21549
22101
  }
21550
22102
  async deleteExpiredTokens() {
21551
22103
  await this.passwordResetTokenService.deleteExpired();
21552
22104
  }
21553
- async createMagicLinkToken(userId, tokenHash, expiresAt) {
21554
- await this.magicLinkTokenService.createToken(userId, tokenHash, expiresAt);
22105
+ async createMagicLinkToken(uid, tokenHash, expiresAt) {
22106
+ await this.magicLinkTokenService.createToken(uid, tokenHash, expiresAt);
21555
22107
  }
21556
22108
  async findValidMagicLinkToken(tokenHash) {
21557
22109
  return this.magicLinkTokenService.findValidByHash(tokenHash);
@@ -21586,11 +22138,11 @@ var PostgresAuthRepository = class {
21586
22138
  async getUserByIdentity(provider, providerId) {
21587
22139
  return this.userService.getUserByIdentity(provider, providerId);
21588
22140
  }
21589
- async getUserIdentities(userId) {
21590
- return this.userService.getUserIdentities(userId);
22141
+ async getUserIdentities(uid) {
22142
+ return this.userService.getUserIdentities(uid);
21591
22143
  }
21592
- async linkUserIdentity(userId, provider, providerId, profileData) {
21593
- return this.userService.linkUserIdentity(userId, provider, providerId, profileData);
22144
+ async linkUserIdentity(uid, provider, providerId, profileData) {
22145
+ return this.userService.linkUserIdentity(uid, provider, providerId, profileData);
21594
22146
  }
21595
22147
  async updateUser(id, data) {
21596
22148
  return this.userService.updateUser(id, data);
@@ -21616,20 +22168,20 @@ var PostgresAuthRepository = class {
21616
22168
  async getUserByVerificationToken(token) {
21617
22169
  return this.userService.getUserByVerificationToken(token);
21618
22170
  }
21619
- async getUserRoles(userId) {
21620
- return this.userService.getUserRoles(userId);
22171
+ async getUserRoles(uid) {
22172
+ return this.userService.getUserRoles(uid);
21621
22173
  }
21622
- async getUserRoleIds(userId) {
21623
- return this.userService.getUserRoleIds(userId);
22174
+ async getUserRoleIds(uid) {
22175
+ return this.userService.getUserRoleIds(uid);
21624
22176
  }
21625
- async setUserRoles(userId, roleIds) {
21626
- await this.userService.setUserRoles(userId, roleIds);
22177
+ async setUserRoles(uid, roleIds) {
22178
+ await this.userService.setUserRoles(uid, roleIds);
21627
22179
  }
21628
- async assignDefaultRole(userId, roleId) {
21629
- await this.userService.assignDefaultRole(userId, roleId);
22180
+ async assignDefaultRole(uid, roleId) {
22181
+ await this.userService.assignDefaultRole(uid, roleId);
21630
22182
  }
21631
- async getUserWithRoles(userId) {
21632
- return this.userService.getUserWithRoles(userId);
22183
+ async getUserWithRoles(uid) {
22184
+ return this.userService.getUserWithRoles(uid);
21633
22185
  }
21634
22186
  async getRoleById(id) {
21635
22187
  return {
@@ -21684,8 +22236,8 @@ var PostgresAuthRepository = class {
21684
22236
  };
21685
22237
  }
21686
22238
  async deleteRole(_id) {}
21687
- async createRefreshToken(userId, tokenHash, expiresAt, userAgent, ipAddress) {
21688
- await this.tokenRepository.createRefreshToken(userId, tokenHash, expiresAt, userAgent, ipAddress);
22239
+ async createRefreshToken(uid, tokenHash, expiresAt, userAgent, ipAddress) {
22240
+ await this.tokenRepository.createRefreshToken(uid, tokenHash, expiresAt, userAgent, ipAddress);
21689
22241
  }
21690
22242
  async findRefreshTokenByHash(tokenHash) {
21691
22243
  return this.tokenRepository.findRefreshTokenByHash(tokenHash);
@@ -21693,17 +22245,17 @@ var PostgresAuthRepository = class {
21693
22245
  async deleteRefreshToken(tokenHash) {
21694
22246
  await this.tokenRepository.deleteRefreshToken(tokenHash);
21695
22247
  }
21696
- async deleteAllRefreshTokensForUser(userId) {
21697
- await this.tokenRepository.deleteAllRefreshTokensForUser(userId);
22248
+ async deleteAllRefreshTokensForUser(uid) {
22249
+ await this.tokenRepository.deleteAllRefreshTokensForUser(uid);
21698
22250
  }
21699
- async listRefreshTokensForUser(userId) {
21700
- return this.tokenRepository.listRefreshTokensForUser(userId);
22251
+ async listRefreshTokensForUser(uid) {
22252
+ return this.tokenRepository.listRefreshTokensForUser(uid);
21701
22253
  }
21702
- async deleteRefreshTokenById(id, userId) {
21703
- await this.tokenRepository.deleteRefreshTokenById(id, userId);
22254
+ async deleteRefreshTokenById(id, uid) {
22255
+ await this.tokenRepository.deleteRefreshTokenById(id, uid);
21704
22256
  }
21705
- async createPasswordResetToken(userId, tokenHash, expiresAt) {
21706
- await this.tokenRepository.createPasswordResetToken(userId, tokenHash, expiresAt);
22257
+ async createPasswordResetToken(uid, tokenHash, expiresAt) {
22258
+ await this.tokenRepository.createPasswordResetToken(uid, tokenHash, expiresAt);
21707
22259
  }
21708
22260
  async findValidPasswordResetToken(tokenHash) {
21709
22261
  return this.tokenRepository.findValidPasswordResetToken(tokenHash);
@@ -21711,14 +22263,14 @@ var PostgresAuthRepository = class {
21711
22263
  async markPasswordResetTokenUsed(tokenHash) {
21712
22264
  await this.tokenRepository.markPasswordResetTokenUsed(tokenHash);
21713
22265
  }
21714
- async deleteAllPasswordResetTokensForUser(userId) {
21715
- await this.tokenRepository.deleteAllPasswordResetTokensForUser(userId);
22266
+ async deleteAllPasswordResetTokensForUser(uid) {
22267
+ await this.tokenRepository.deleteAllPasswordResetTokensForUser(uid);
21716
22268
  }
21717
22269
  async deleteExpiredTokens() {
21718
22270
  await this.tokenRepository.deleteExpiredTokens();
21719
22271
  }
21720
- async createMagicLinkToken(userId, tokenHash, expiresAt) {
21721
- await this.tokenRepository.createMagicLinkToken(userId, tokenHash, expiresAt);
22272
+ async createMagicLinkToken(uid, tokenHash, expiresAt) {
22273
+ await this.tokenRepository.createMagicLinkToken(uid, tokenHash, expiresAt);
21722
22274
  }
21723
22275
  async findValidMagicLinkToken(tokenHash) {
21724
22276
  return this.tokenRepository.findValidMagicLinkToken(tokenHash);
@@ -21731,11 +22283,11 @@ var PostgresAuthRepository = class {
21731
22283
  if (!this._mfaService) this._mfaService = new MfaService(this.db);
21732
22284
  return this._mfaService;
21733
22285
  }
21734
- async createMfaFactor(userId, factorType, secretEncrypted, friendlyName) {
21735
- return this.getMfaService().createMfaFactor(userId, factorType, secretEncrypted, friendlyName);
22286
+ async createMfaFactor(uid, factorType, secretEncrypted, friendlyName) {
22287
+ return this.getMfaService().createMfaFactor(uid, factorType, secretEncrypted, friendlyName);
21736
22288
  }
21737
- async getMfaFactors(userId) {
21738
- return this.getMfaService().getMfaFactors(userId);
22289
+ async getMfaFactors(uid) {
22290
+ return this.getMfaService().getMfaFactors(uid);
21739
22291
  }
21740
22292
  async getMfaFactorById(factorId) {
21741
22293
  return this.getMfaService().getMfaFactorById(factorId);
@@ -21743,8 +22295,8 @@ var PostgresAuthRepository = class {
21743
22295
  async verifyMfaFactor(factorId) {
21744
22296
  return this.getMfaService().verifyMfaFactor(factorId);
21745
22297
  }
21746
- async deleteMfaFactor(factorId, userId) {
21747
- return this.getMfaService().deleteMfaFactor(factorId, userId);
22298
+ async deleteMfaFactor(factorId, uid) {
22299
+ return this.getMfaService().deleteMfaFactor(factorId, uid);
21748
22300
  }
21749
22301
  async createMfaChallenge(factorId, ipAddress) {
21750
22302
  return this.getMfaService().createMfaChallenge(factorId, ipAddress);
@@ -21755,20 +22307,20 @@ var PostgresAuthRepository = class {
21755
22307
  async verifyMfaChallenge(challengeId) {
21756
22308
  return this.getMfaService().verifyMfaChallenge(challengeId);
21757
22309
  }
21758
- async createRecoveryCodes(userId, codeHashes) {
21759
- return this.getMfaService().createRecoveryCodes(userId, codeHashes);
22310
+ async createRecoveryCodes(uid, codeHashes) {
22311
+ return this.getMfaService().createRecoveryCodes(uid, codeHashes);
21760
22312
  }
21761
- async useRecoveryCode(userId, codeHash) {
21762
- return this.getMfaService().useRecoveryCode(userId, codeHash);
22313
+ async useRecoveryCode(uid, codeHash) {
22314
+ return this.getMfaService().useRecoveryCode(uid, codeHash);
21763
22315
  }
21764
- async getUnusedRecoveryCodeCount(userId) {
21765
- return this.getMfaService().getUnusedRecoveryCodeCount(userId);
22316
+ async getUnusedRecoveryCodeCount(uid) {
22317
+ return this.getMfaService().getUnusedRecoveryCodeCount(uid);
21766
22318
  }
21767
- async deleteAllRecoveryCodes(userId) {
21768
- return this.getMfaService().deleteAllRecoveryCodes(userId);
22319
+ async deleteAllRecoveryCodes(uid) {
22320
+ return this.getMfaService().deleteAllRecoveryCodes(uid);
21769
22321
  }
21770
- async hasVerifiedMfaFactors(userId) {
21771
- return this.getMfaService().hasVerifiedMfaFactors(userId);
22322
+ async hasVerifiedMfaFactors(uid) {
22323
+ return this.getMfaService().hasVerifiedMfaFactors(uid);
21772
22324
  }
21773
22325
  };
21774
22326
  /**
@@ -21785,16 +22337,16 @@ var MfaService = class {
21785
22337
  qualify(tableName) {
21786
22338
  return `"${this.schemaName}"."${tableName}"`;
21787
22339
  }
21788
- async createMfaFactor(userId, factorType, secretEncrypted, friendlyName) {
22340
+ async createMfaFactor(uid, factorType, secretEncrypted, friendlyName) {
21789
22341
  const tableName = this.qualify("mfa_factors");
21790
22342
  const row = (await this.db.execute(sql`
21791
- INSERT INTO ${sql.raw(tableName)} (user_id, factor_type, secret_encrypted, friendly_name)
21792
- VALUES (${userId}, ${factorType}, ${secretEncrypted}, ${friendlyName ?? null})
21793
- RETURNING id, user_id, factor_type, friendly_name, verified, created_at, updated_at
22343
+ INSERT INTO ${sql.raw(tableName)} (uid, factor_type, secret_encrypted, friendly_name)
22344
+ VALUES (${uid}, ${factorType}, ${secretEncrypted}, ${friendlyName ?? null})
22345
+ RETURNING id, uid, factor_type, friendly_name, verified, created_at, updated_at
21794
22346
  `)).rows[0];
21795
22347
  return {
21796
22348
  id: row.id,
21797
- userId: row.user_id,
22349
+ uid: row.uid,
21798
22350
  factorType: row.factor_type,
21799
22351
  friendlyName: row.friendly_name ?? void 0,
21800
22352
  verified: row.verified,
@@ -21802,16 +22354,16 @@ var MfaService = class {
21802
22354
  updatedAt: new Date(row.updated_at)
21803
22355
  };
21804
22356
  }
21805
- async getMfaFactors(userId) {
22357
+ async getMfaFactors(uid) {
21806
22358
  const tableName = this.qualify("mfa_factors");
21807
22359
  return (await this.db.execute(sql`
21808
- SELECT id, user_id, factor_type, friendly_name, verified, created_at, updated_at
22360
+ SELECT id, uid, factor_type, friendly_name, verified, created_at, updated_at
21809
22361
  FROM ${sql.raw(tableName)}
21810
- WHERE user_id = ${userId}
22362
+ WHERE uid = ${uid}
21811
22363
  ORDER BY created_at
21812
22364
  `)).rows.map((row) => ({
21813
22365
  id: row.id,
21814
- userId: row.user_id,
22366
+ uid: row.uid,
21815
22367
  factorType: row.factor_type,
21816
22368
  friendlyName: row.friendly_name ?? void 0,
21817
22369
  verified: row.verified,
@@ -21822,7 +22374,7 @@ var MfaService = class {
21822
22374
  async getMfaFactorById(factorId) {
21823
22375
  const tableName = this.qualify("mfa_factors");
21824
22376
  const result = await this.db.execute(sql`
21825
- SELECT id, user_id, factor_type, secret_encrypted, friendly_name, verified, created_at, updated_at
22377
+ SELECT id, uid, factor_type, secret_encrypted, friendly_name, verified, created_at, updated_at
21826
22378
  FROM ${sql.raw(tableName)}
21827
22379
  WHERE id = ${factorId}
21828
22380
  `);
@@ -21830,7 +22382,7 @@ var MfaService = class {
21830
22382
  const row = result.rows[0];
21831
22383
  return {
21832
22384
  id: row.id,
21833
- userId: row.user_id,
22385
+ uid: row.uid,
21834
22386
  factorType: row.factor_type,
21835
22387
  secretEncrypted: row.secret_encrypted,
21836
22388
  friendlyName: row.friendly_name ?? void 0,
@@ -21847,11 +22399,11 @@ var MfaService = class {
21847
22399
  WHERE id = ${factorId}
21848
22400
  `);
21849
22401
  }
21850
- async deleteMfaFactor(factorId, userId) {
22402
+ async deleteMfaFactor(factorId, uid) {
21851
22403
  const tableName = this.qualify("mfa_factors");
21852
22404
  await this.db.execute(sql`
21853
22405
  DELETE FROM ${sql.raw(tableName)}
21854
- WHERE id = ${factorId} AND user_id = ${userId}
22406
+ WHERE id = ${factorId} AND uid = ${uid}
21855
22407
  `);
21856
22408
  }
21857
22409
  async createMfaChallenge(factorId, ipAddress) {
@@ -21895,43 +22447,43 @@ var MfaService = class {
21895
22447
  WHERE id = ${challengeId}
21896
22448
  `);
21897
22449
  }
21898
- async createRecoveryCodes(userId, codeHashes) {
22450
+ async createRecoveryCodes(uid, codeHashes) {
21899
22451
  const tableName = this.qualify("recovery_codes");
21900
22452
  await this.db.execute(sql`
21901
- DELETE FROM ${sql.raw(tableName)} WHERE user_id = ${userId}
22453
+ DELETE FROM ${sql.raw(tableName)} WHERE uid = ${uid}
21902
22454
  `);
21903
22455
  for (const hash of codeHashes) await this.db.execute(sql`
21904
- INSERT INTO ${sql.raw(tableName)} (user_id, code_hash)
21905
- VALUES (${userId}, ${hash})
22456
+ INSERT INTO ${sql.raw(tableName)} (uid, code_hash)
22457
+ VALUES (${uid}, ${hash})
21906
22458
  `);
21907
22459
  }
21908
- async useRecoveryCode(userId, codeHash) {
22460
+ async useRecoveryCode(uid, codeHash) {
21909
22461
  const tableName = this.qualify("recovery_codes");
21910
22462
  return (await this.db.execute(sql`
21911
22463
  UPDATE ${sql.raw(tableName)}
21912
22464
  SET used_at = NOW()
21913
- WHERE user_id = ${userId} AND code_hash = ${codeHash} AND used_at IS NULL
22465
+ WHERE uid = ${uid} AND code_hash = ${codeHash} AND used_at IS NULL
21914
22466
  RETURNING id
21915
22467
  `)).rows.length > 0;
21916
22468
  }
21917
- async getUnusedRecoveryCodeCount(userId) {
22469
+ async getUnusedRecoveryCodeCount(uid) {
21918
22470
  const tableName = this.qualify("recovery_codes");
21919
22471
  return (await this.db.execute(sql`
21920
22472
  SELECT COUNT(*)::int as count FROM ${sql.raw(tableName)}
21921
- WHERE user_id = ${userId} AND used_at IS NULL
22473
+ WHERE uid = ${uid} AND used_at IS NULL
21922
22474
  `)).rows[0].count;
21923
22475
  }
21924
- async deleteAllRecoveryCodes(userId) {
22476
+ async deleteAllRecoveryCodes(uid) {
21925
22477
  const tableName = this.qualify("recovery_codes");
21926
22478
  await this.db.execute(sql`
21927
- DELETE FROM ${sql.raw(tableName)} WHERE user_id = ${userId}
22479
+ DELETE FROM ${sql.raw(tableName)} WHERE uid = ${uid}
21928
22480
  `);
21929
22481
  }
21930
- async hasVerifiedMfaFactors(userId) {
22482
+ async hasVerifiedMfaFactors(uid) {
21931
22483
  const tableName = this.qualify("mfa_factors");
21932
22484
  return (await this.db.execute(sql`
21933
22485
  SELECT COUNT(*)::int as count FROM ${sql.raw(tableName)}
21934
- WHERE user_id = ${userId} AND verified = TRUE
22486
+ WHERE uid = ${uid} AND verified = TRUE
21935
22487
  `)).rows[0].count > 0;
21936
22488
  }
21937
22489
  };
@@ -22171,6 +22723,20 @@ function patchPgArrayNullSafety(tables) {
22171
22723
  if (patchedCount > 0) logger.debug(`[PgArray] Patched ${patchedCount} array column(s) for null-safety`);
22172
22724
  }
22173
22725
  //#endregion
22726
+ //#region src/schema/introspect-db-naming.ts
22727
+ /**
22728
+ * Naming helpers shared by the introspection modules. These live apart from
22729
+ * `introspect-db-logic.ts` because the inference pass needs them too, and
22730
+ * importing them from there would close a cycle back through this module.
22731
+ */
22732
+ /**
22733
+ * Convert a snake_case name to a human-readable Title Case label.
22734
+ * e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
22735
+ */
22736
+ function humanize(snakeName) {
22737
+ return snakeName.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
22738
+ }
22739
+ //#endregion
22174
22740
  //#region src/schema/introspect-db-logic.ts
22175
22741
  var IRREGULAR_SINGULARS = {
22176
22742
  people: "person",
@@ -22230,13 +22796,6 @@ function singularize(word) {
22230
22796
  if (lower.endsWith("s") && !lower.endsWith("ss") && !lower.endsWith("us") && !lower.endsWith("is")) return word.slice(0, -1);
22231
22797
  return word;
22232
22798
  }
22233
- /**
22234
- * Convert a snake_case name to a human-readable Title Case label.
22235
- * e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
22236
- */
22237
- function humanize(snakeName) {
22238
- return snakeName.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
22239
- }
22240
22799
  function getIconForTable(tableName) {
22241
22800
  const table = tableName.toLowerCase();
22242
22801
  if (table.includes("user") || table.includes("account") || table.includes("member") || table.includes("customer") || table.includes("client") || table.includes("patient")) return "Users";
@@ -22757,6 +23316,11 @@ function createPostgresBootstrapper(pgConfig) {
22757
23316
  } catch (err) {
22758
23317
  logger.warn("⚠️ Could not initialize branch metadata table", { error: err });
22759
23318
  }
23319
+ try {
23320
+ await realtimeService.configureChannelHistory(pgConfig.realtime?.channels);
23321
+ } catch (err) {
23322
+ logger.warn("⚠️ Could not initialize channel history tables — retained channels will not replay", { error: err });
23323
+ }
22760
23324
  const directUrl = process.env.DATABASE_DIRECT_URL || pgConfig.connectionString;
22761
23325
  const validModes = new Set([
22762
23326
  "auto",