@rebasepro/server-postgres 0.9.1-canary.742f831 → 0.9.1-canary.78ab3dc

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`
@@ -20860,7 +21364,7 @@ async function ensureAuthTablesExist(db, collection) {
20860
21364
  await db.execute(sql`
20861
21365
  CREATE TABLE IF NOT EXISTS ${sql.raw(mfaFactorsTableName)} (
20862
21366
  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,
21367
+ uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
20864
21368
  factor_type TEXT NOT NULL DEFAULT 'totp',
20865
21369
  secret_encrypted TEXT NOT NULL,
20866
21370
  friendly_name TEXT,
@@ -20871,7 +21375,7 @@ async function ensureAuthTablesExist(db, collection) {
20871
21375
  `);
20872
21376
  await db.execute(sql`
20873
21377
  CREATE INDEX IF NOT EXISTS idx_mfa_factors_user
20874
- ON ${sql.raw(mfaFactorsTableName)}(user_id)
21378
+ ON ${sql.raw(mfaFactorsTableName)}(uid)
20875
21379
  `);
20876
21380
  await db.execute(sql`
20877
21381
  CREATE TABLE IF NOT EXISTS ${sql.raw(mfaChallengesTableName)} (
@@ -20890,7 +21394,7 @@ async function ensureAuthTablesExist(db, collection) {
20890
21394
  await db.execute(sql`
20891
21395
  CREATE TABLE IF NOT EXISTS ${sql.raw(recoveryCodesTableName)} (
20892
21396
  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,
21397
+ uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,
20894
21398
  code_hash TEXT NOT NULL,
20895
21399
  used_at TIMESTAMP WITH TIME ZONE,
20896
21400
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
@@ -20898,7 +21402,7 @@ async function ensureAuthTablesExist(db, collection) {
20898
21402
  `);
20899
21403
  await db.execute(sql`
20900
21404
  CREATE INDEX IF NOT EXISTS idx_recovery_codes_user
20901
- ON ${sql.raw(recoveryCodesTableName)}(user_id)
21405
+ ON ${sql.raw(recoveryCodesTableName)}(uid)
20902
21406
  `);
20903
21407
  try {
20904
21408
  const authTablePairs = [
@@ -20979,7 +21483,7 @@ var UserService = class {
20979
21483
  * Run a privileged auth write with an explicitly cleared RLS context.
20980
21484
  *
20981
21485
  * 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
21486
+ * carries a NULL `app.uid` so the `auth.uid() IS NULL` server-escape
20983
21487
  * in the default policies applies. That NULL is normally guaranteed by
20984
21488
  * `set_config(..., is_local = true)` resetting at transaction end — but a
20985
21489
  * GUC that survives on a pooled connection (or a connection role that
@@ -20993,7 +21497,8 @@ var UserService = class {
20993
21497
  async withServerContext(fn) {
20994
21498
  return await this.db.transaction(async (tx) => {
20995
21499
  await tx.execute(sql`
20996
- SELECT set_config('app.user_id', '', true),
21500
+ SELECT set_config('app.uid', '', true),
21501
+ set_config('app.user_id', '', true),
20997
21502
  set_config('app.user_roles', '', true),
20998
21503
  set_config('app.jwt', '', true)
20999
21504
  `);
@@ -21115,19 +21620,19 @@ var UserService = class {
21115
21620
  async getUserByIdentity(provider, providerId) {
21116
21621
  const userIdCol = getColumn(this.usersTable, "id");
21117
21622
  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);
21623
+ 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
21624
  if (result.length === 0) return null;
21120
21625
  return this.mapRowToUser(result[0].user);
21121
21626
  }
21122
- async getUserIdentities(userId) {
21627
+ async getUserIdentities(uid) {
21123
21628
  const schema = getTableConfig(this.userIdentitiesTable).schema || "public";
21124
21629
  return (await this.db.execute(sql`
21125
- SELECT id, user_id, provider, provider_id, profile_data, created_at, updated_at
21630
+ SELECT id, uid, provider, provider_id, profile_data, created_at, updated_at
21126
21631
  FROM ${sql.raw(`"${schema}"."user_identities"`)}
21127
- WHERE user_id = ${userId}
21632
+ WHERE uid = ${uid}
21128
21633
  `)).rows.map((row) => ({
21129
21634
  id: row.id,
21130
- userId: row.user_id,
21635
+ uid: row.uid,
21131
21636
  provider: row.provider,
21132
21637
  providerId: row.provider_id,
21133
21638
  profileData: row.profile_data ?? null,
@@ -21135,9 +21640,9 @@ var UserService = class {
21135
21640
  updatedAt: row.updated_at
21136
21641
  }));
21137
21642
  }
21138
- async linkUserIdentity(userId, provider, providerId, profileData) {
21643
+ async linkUserIdentity(uid, provider, providerId, profileData) {
21139
21644
  await this.withServerContext(async (db) => db.insert(this.userIdentitiesTable).values({
21140
- userId,
21645
+ uid,
21141
21646
  provider,
21142
21647
  providerId,
21143
21648
  profileData: profileData || null
@@ -21256,10 +21761,10 @@ var UserService = class {
21256
21761
  /**
21257
21762
  * Get roles for a user from database (inline TEXT[] column)
21258
21763
  */
21259
- async getUserRoles(userId) {
21764
+ async getUserRoles(uid) {
21260
21765
  const usersTableName = this.getQualifiedUsersTableName();
21261
21766
  const result = await this.db.execute(sql`
21262
- SELECT roles FROM ${sql.raw(usersTableName)} WHERE id = ${userId}
21767
+ SELECT roles FROM ${sql.raw(usersTableName)} WHERE id = ${uid}
21263
21768
  `);
21264
21769
  if (result.rows.length === 0) return [];
21265
21770
  return (result.rows[0].roles ?? []).map((id) => ({
@@ -21273,10 +21778,10 @@ var UserService = class {
21273
21778
  /**
21274
21779
  * Get role IDs for a user
21275
21780
  */
21276
- async getUserRoleIds(userId) {
21781
+ async getUserRoleIds(uid) {
21277
21782
  const usersTableName = this.getQualifiedUsersTableName();
21278
21783
  const result = await this.db.execute(sql`
21279
- SELECT roles FROM ${sql.raw(usersTableName)} WHERE id = ${userId}
21784
+ SELECT roles FROM ${sql.raw(usersTableName)} WHERE id = ${uid}
21280
21785
  `);
21281
21786
  if (result.rows.length === 0) return [];
21282
21787
  return result.rows[0].roles ?? [];
@@ -21284,35 +21789,35 @@ var UserService = class {
21284
21789
  /**
21285
21790
  * Set roles for a user (replaces existing roles)
21286
21791
  */
21287
- async setUserRoles(userId, roleIds) {
21792
+ async setUserRoles(uid, roleIds) {
21288
21793
  const usersTableName = this.getQualifiedUsersTableName();
21289
21794
  const rolesArray = `{${roleIds.join(",")}}`;
21290
21795
  await this.withServerContext(async (db) => db.execute(sql`
21291
21796
  UPDATE ${sql.raw(usersTableName)}
21292
21797
  SET roles = ${rolesArray}::text[], updated_at = NOW()
21293
- WHERE id = ${userId}
21798
+ WHERE id = ${uid}
21294
21799
  `));
21295
21800
  }
21296
21801
  /**
21297
21802
  * Assign a specific role to new user (appends if not present)
21298
21803
  */
21299
- async assignDefaultRole(userId, roleId) {
21804
+ async assignDefaultRole(uid, roleId) {
21300
21805
  const usersTableName = this.getQualifiedUsersTableName();
21301
21806
  await this.withServerContext(async (db) => db.execute(sql`
21302
21807
  UPDATE ${sql.raw(usersTableName)}
21303
21808
  SET roles = array_append(roles, ${roleId}), updated_at = NOW()
21304
- WHERE id = ${userId} AND NOT (${roleId} = ANY(roles))
21809
+ WHERE id = ${uid} AND NOT (${roleId} = ANY(roles))
21305
21810
  `));
21306
21811
  }
21307
21812
  /**
21308
21813
  * Get user with their roles
21309
21814
  */
21310
- async getUserWithRoles(userId) {
21311
- const user = await this.getUserById(userId);
21815
+ async getUserWithRoles(uid) {
21816
+ const user = await this.getUserById(uid);
21312
21817
  if (!user) return null;
21313
21818
  return {
21314
21819
  user,
21315
- roles: await this.getUserRoles(userId)
21820
+ roles: await this.getUserRoles(uid)
21316
21821
  };
21317
21822
  }
21318
21823
  };
@@ -21324,18 +21829,18 @@ var RefreshTokenService = class {
21324
21829
  if (tableOrTables && (tableOrTables.refreshTokens || tableOrTables.users)) this.refreshTokensTable = tableOrTables.refreshTokens || refreshTokens;
21325
21830
  else this.refreshTokensTable = tableOrTables || refreshTokens;
21326
21831
  }
21327
- async createToken(userId, tokenHash, expiresAt, userAgent, ipAddress) {
21832
+ async createToken(uid, tokenHash, expiresAt, userAgent, ipAddress) {
21328
21833
  const safeUserAgent = userAgent || "";
21329
21834
  const safeIpAddress = ipAddress || "";
21330
21835
  await this.db.insert(this.refreshTokensTable).values({
21331
- userId,
21836
+ uid,
21332
21837
  tokenHash,
21333
21838
  expiresAt,
21334
21839
  userAgent: safeUserAgent,
21335
21840
  ipAddress: safeIpAddress
21336
21841
  }).onConflictDoUpdate({
21337
21842
  target: [
21338
- this.refreshTokensTable.userId,
21843
+ this.refreshTokensTable.uid,
21339
21844
  this.refreshTokensTable.userAgent,
21340
21845
  this.refreshTokensTable.ipAddress
21341
21846
  ],
@@ -21348,7 +21853,7 @@ var RefreshTokenService = class {
21348
21853
  async findByHash(tokenHash) {
21349
21854
  const [token] = await this.db.select({
21350
21855
  id: this.refreshTokensTable.id,
21351
- userId: this.refreshTokensTable.userId,
21856
+ uid: this.refreshTokensTable.uid,
21352
21857
  tokenHash: this.refreshTokensTable.tokenHash,
21353
21858
  expiresAt: this.refreshTokensTable.expiresAt,
21354
21859
  createdAt: this.refreshTokensTable.createdAt,
@@ -21360,22 +21865,22 @@ var RefreshTokenService = class {
21360
21865
  async deleteByHash(tokenHash) {
21361
21866
  await this.db.delete(this.refreshTokensTable).where(eq(this.refreshTokensTable.tokenHash, tokenHash));
21362
21867
  }
21363
- async deleteAllForUser(userId) {
21364
- await this.db.delete(this.refreshTokensTable).where(eq(this.refreshTokensTable.userId, userId));
21868
+ async deleteAllForUser(uid) {
21869
+ await this.db.delete(this.refreshTokensTable).where(eq(this.refreshTokensTable.uid, uid));
21365
21870
  }
21366
- async listForUser(userId) {
21871
+ async listForUser(uid) {
21367
21872
  return await this.db.select({
21368
21873
  id: this.refreshTokensTable.id,
21369
- userId: this.refreshTokensTable.userId,
21874
+ uid: this.refreshTokensTable.uid,
21370
21875
  tokenHash: this.refreshTokensTable.tokenHash,
21371
21876
  expiresAt: this.refreshTokensTable.expiresAt,
21372
21877
  createdAt: this.refreshTokensTable.createdAt,
21373
21878
  userAgent: this.refreshTokensTable.userAgent,
21374
21879
  ipAddress: this.refreshTokensTable.ipAddress
21375
- }).from(this.refreshTokensTable).where(eq(this.refreshTokensTable.userId, userId)).orderBy(this.refreshTokensTable.createdAt);
21880
+ }).from(this.refreshTokensTable).where(eq(this.refreshTokensTable.uid, uid)).orderBy(this.refreshTokensTable.createdAt);
21376
21881
  }
21377
- async deleteById(id, userId) {
21378
- await this.db.delete(this.refreshTokensTable).where(sql`${this.refreshTokensTable.id} = ${id} AND ${this.refreshTokensTable.userId} = ${userId}`);
21882
+ async deleteById(id, uid) {
21883
+ await this.db.delete(this.refreshTokensTable).where(sql`${this.refreshTokensTable.id} = ${id} AND ${this.refreshTokensTable.uid} = ${uid}`);
21379
21884
  }
21380
21885
  };
21381
21886
  /**
@@ -21396,14 +21901,14 @@ var PasswordResetTokenService = class {
21396
21901
  /**
21397
21902
  * Create a password reset token
21398
21903
  */
21399
- async createToken(userId, tokenHash, expiresAt) {
21904
+ async createToken(uid, tokenHash, expiresAt) {
21400
21905
  const tableName = this.getQualifiedPasswordResetTokensTableName();
21401
21906
  await this.db.execute(sql`
21402
21907
  DELETE FROM ${sql.raw(tableName)}
21403
- WHERE user_id = ${userId} AND used_at IS NULL
21908
+ WHERE uid = ${uid} AND used_at IS NULL
21404
21909
  `);
21405
21910
  await this.db.insert(this.passwordResetTokensTable).values({
21406
- userId,
21911
+ uid,
21407
21912
  tokenHash,
21408
21913
  expiresAt
21409
21914
  });
@@ -21413,13 +21918,13 @@ var PasswordResetTokenService = class {
21413
21918
  */
21414
21919
  async findValidByHash(tokenHash) {
21415
21920
  const [token] = await this.db.select({
21416
- userId: this.passwordResetTokensTable.userId,
21921
+ uid: this.passwordResetTokensTable.uid,
21417
21922
  expiresAt: this.passwordResetTokensTable.expiresAt
21418
21923
  }).from(this.passwordResetTokensTable).where(eq(this.passwordResetTokensTable.tokenHash, tokenHash));
21419
21924
  if (!token) return null;
21420
21925
  const tableName = this.getQualifiedPasswordResetTokensTableName();
21421
21926
  const result = await this.db.execute(sql`
21422
- SELECT user_id, expires_at
21927
+ SELECT uid, expires_at
21423
21928
  FROM ${sql.raw(tableName)}
21424
21929
  WHERE token_hash = ${tokenHash}
21425
21930
  AND used_at IS NULL
@@ -21428,7 +21933,7 @@ var PasswordResetTokenService = class {
21428
21933
  if (result.rows.length === 0) return null;
21429
21934
  const row = result.rows[0];
21430
21935
  return {
21431
- userId: row.user_id,
21936
+ uid: row.uid,
21432
21937
  expiresAt: new Date(row.expires_at)
21433
21938
  };
21434
21939
  }
@@ -21441,8 +21946,8 @@ var PasswordResetTokenService = class {
21441
21946
  /**
21442
21947
  * Delete all tokens for a user
21443
21948
  */
21444
- async deleteAllForUser(userId) {
21445
- await this.db.delete(this.passwordResetTokensTable).where(eq(this.passwordResetTokensTable.userId, userId));
21949
+ async deleteAllForUser(uid) {
21950
+ await this.db.delete(this.passwordResetTokensTable).where(eq(this.passwordResetTokensTable.uid, uid));
21446
21951
  }
21447
21952
  /**
21448
21953
  * Clean up expired tokens
@@ -21470,14 +21975,14 @@ var MagicLinkTokenService = class {
21470
21975
  const name = getTableName(this.magicLinkTokensTable);
21471
21976
  return `"${getTableConfig(this.magicLinkTokensTable).schema || "public"}"."${name}"`;
21472
21977
  }
21473
- async createToken(userId, tokenHash, expiresAt) {
21978
+ async createToken(uid, tokenHash, expiresAt) {
21474
21979
  const tableName = this.getQualifiedTableName();
21475
21980
  await this.db.execute(sql`
21476
21981
  DELETE FROM ${sql.raw(tableName)}
21477
- WHERE user_id = ${userId} AND used_at IS NULL
21982
+ WHERE uid = ${uid} AND used_at IS NULL
21478
21983
  `);
21479
21984
  await this.db.insert(this.magicLinkTokensTable).values({
21480
- userId,
21985
+ uid,
21481
21986
  tokenHash,
21482
21987
  expiresAt
21483
21988
  });
@@ -21485,7 +21990,7 @@ var MagicLinkTokenService = class {
21485
21990
  async findValidByHash(tokenHash) {
21486
21991
  const tableName = this.getQualifiedTableName();
21487
21992
  const result = await this.db.execute(sql`
21488
- SELECT user_id, expires_at
21993
+ SELECT uid, expires_at
21489
21994
  FROM ${sql.raw(tableName)}
21490
21995
  WHERE token_hash = ${tokenHash}
21491
21996
  AND used_at IS NULL
@@ -21494,7 +21999,7 @@ var MagicLinkTokenService = class {
21494
21999
  if (result.rows.length === 0) return null;
21495
22000
  const row = result.rows[0];
21496
22001
  return {
21497
- userId: row.user_id,
22002
+ uid: row.uid,
21498
22003
  expiresAt: new Date(row.expires_at)
21499
22004
  };
21500
22005
  }
@@ -21517,8 +22022,8 @@ var PostgresTokenRepository = class {
21517
22022
  this.passwordResetTokenService = new PasswordResetTokenService(db, tableOrTables);
21518
22023
  this.magicLinkTokenService = new MagicLinkTokenService(db, tableOrTables);
21519
22024
  }
21520
- async createRefreshToken(userId, tokenHash, expiresAt, userAgent, ipAddress) {
21521
- await this.refreshTokenService.createToken(userId, tokenHash, expiresAt, userAgent, ipAddress);
22025
+ async createRefreshToken(uid, tokenHash, expiresAt, userAgent, ipAddress) {
22026
+ await this.refreshTokenService.createToken(uid, tokenHash, expiresAt, userAgent, ipAddress);
21522
22027
  }
21523
22028
  async findRefreshTokenByHash(tokenHash) {
21524
22029
  return this.refreshTokenService.findByHash(tokenHash);
@@ -21526,17 +22031,17 @@ var PostgresTokenRepository = class {
21526
22031
  async deleteRefreshToken(tokenHash) {
21527
22032
  await this.refreshTokenService.deleteByHash(tokenHash);
21528
22033
  }
21529
- async deleteAllRefreshTokensForUser(userId) {
21530
- await this.refreshTokenService.deleteAllForUser(userId);
22034
+ async deleteAllRefreshTokensForUser(uid) {
22035
+ await this.refreshTokenService.deleteAllForUser(uid);
21531
22036
  }
21532
- async listRefreshTokensForUser(userId) {
21533
- return this.refreshTokenService.listForUser(userId);
22037
+ async listRefreshTokensForUser(uid) {
22038
+ return this.refreshTokenService.listForUser(uid);
21534
22039
  }
21535
- async deleteRefreshTokenById(id, userId) {
21536
- await this.refreshTokenService.deleteById(id, userId);
22040
+ async deleteRefreshTokenById(id, uid) {
22041
+ await this.refreshTokenService.deleteById(id, uid);
21537
22042
  }
21538
- async createPasswordResetToken(userId, tokenHash, expiresAt) {
21539
- await this.passwordResetTokenService.createToken(userId, tokenHash, expiresAt);
22043
+ async createPasswordResetToken(uid, tokenHash, expiresAt) {
22044
+ await this.passwordResetTokenService.createToken(uid, tokenHash, expiresAt);
21540
22045
  }
21541
22046
  async findValidPasswordResetToken(tokenHash) {
21542
22047
  return this.passwordResetTokenService.findValidByHash(tokenHash);
@@ -21544,14 +22049,14 @@ var PostgresTokenRepository = class {
21544
22049
  async markPasswordResetTokenUsed(tokenHash) {
21545
22050
  await this.passwordResetTokenService.markAsUsed(tokenHash);
21546
22051
  }
21547
- async deleteAllPasswordResetTokensForUser(userId) {
21548
- await this.passwordResetTokenService.deleteAllForUser(userId);
22052
+ async deleteAllPasswordResetTokensForUser(uid) {
22053
+ await this.passwordResetTokenService.deleteAllForUser(uid);
21549
22054
  }
21550
22055
  async deleteExpiredTokens() {
21551
22056
  await this.passwordResetTokenService.deleteExpired();
21552
22057
  }
21553
- async createMagicLinkToken(userId, tokenHash, expiresAt) {
21554
- await this.magicLinkTokenService.createToken(userId, tokenHash, expiresAt);
22058
+ async createMagicLinkToken(uid, tokenHash, expiresAt) {
22059
+ await this.magicLinkTokenService.createToken(uid, tokenHash, expiresAt);
21555
22060
  }
21556
22061
  async findValidMagicLinkToken(tokenHash) {
21557
22062
  return this.magicLinkTokenService.findValidByHash(tokenHash);
@@ -21586,11 +22091,11 @@ var PostgresAuthRepository = class {
21586
22091
  async getUserByIdentity(provider, providerId) {
21587
22092
  return this.userService.getUserByIdentity(provider, providerId);
21588
22093
  }
21589
- async getUserIdentities(userId) {
21590
- return this.userService.getUserIdentities(userId);
22094
+ async getUserIdentities(uid) {
22095
+ return this.userService.getUserIdentities(uid);
21591
22096
  }
21592
- async linkUserIdentity(userId, provider, providerId, profileData) {
21593
- return this.userService.linkUserIdentity(userId, provider, providerId, profileData);
22097
+ async linkUserIdentity(uid, provider, providerId, profileData) {
22098
+ return this.userService.linkUserIdentity(uid, provider, providerId, profileData);
21594
22099
  }
21595
22100
  async updateUser(id, data) {
21596
22101
  return this.userService.updateUser(id, data);
@@ -21616,20 +22121,20 @@ var PostgresAuthRepository = class {
21616
22121
  async getUserByVerificationToken(token) {
21617
22122
  return this.userService.getUserByVerificationToken(token);
21618
22123
  }
21619
- async getUserRoles(userId) {
21620
- return this.userService.getUserRoles(userId);
22124
+ async getUserRoles(uid) {
22125
+ return this.userService.getUserRoles(uid);
21621
22126
  }
21622
- async getUserRoleIds(userId) {
21623
- return this.userService.getUserRoleIds(userId);
22127
+ async getUserRoleIds(uid) {
22128
+ return this.userService.getUserRoleIds(uid);
21624
22129
  }
21625
- async setUserRoles(userId, roleIds) {
21626
- await this.userService.setUserRoles(userId, roleIds);
22130
+ async setUserRoles(uid, roleIds) {
22131
+ await this.userService.setUserRoles(uid, roleIds);
21627
22132
  }
21628
- async assignDefaultRole(userId, roleId) {
21629
- await this.userService.assignDefaultRole(userId, roleId);
22133
+ async assignDefaultRole(uid, roleId) {
22134
+ await this.userService.assignDefaultRole(uid, roleId);
21630
22135
  }
21631
- async getUserWithRoles(userId) {
21632
- return this.userService.getUserWithRoles(userId);
22136
+ async getUserWithRoles(uid) {
22137
+ return this.userService.getUserWithRoles(uid);
21633
22138
  }
21634
22139
  async getRoleById(id) {
21635
22140
  return {
@@ -21684,8 +22189,8 @@ var PostgresAuthRepository = class {
21684
22189
  };
21685
22190
  }
21686
22191
  async deleteRole(_id) {}
21687
- async createRefreshToken(userId, tokenHash, expiresAt, userAgent, ipAddress) {
21688
- await this.tokenRepository.createRefreshToken(userId, tokenHash, expiresAt, userAgent, ipAddress);
22192
+ async createRefreshToken(uid, tokenHash, expiresAt, userAgent, ipAddress) {
22193
+ await this.tokenRepository.createRefreshToken(uid, tokenHash, expiresAt, userAgent, ipAddress);
21689
22194
  }
21690
22195
  async findRefreshTokenByHash(tokenHash) {
21691
22196
  return this.tokenRepository.findRefreshTokenByHash(tokenHash);
@@ -21693,17 +22198,17 @@ var PostgresAuthRepository = class {
21693
22198
  async deleteRefreshToken(tokenHash) {
21694
22199
  await this.tokenRepository.deleteRefreshToken(tokenHash);
21695
22200
  }
21696
- async deleteAllRefreshTokensForUser(userId) {
21697
- await this.tokenRepository.deleteAllRefreshTokensForUser(userId);
22201
+ async deleteAllRefreshTokensForUser(uid) {
22202
+ await this.tokenRepository.deleteAllRefreshTokensForUser(uid);
21698
22203
  }
21699
- async listRefreshTokensForUser(userId) {
21700
- return this.tokenRepository.listRefreshTokensForUser(userId);
22204
+ async listRefreshTokensForUser(uid) {
22205
+ return this.tokenRepository.listRefreshTokensForUser(uid);
21701
22206
  }
21702
- async deleteRefreshTokenById(id, userId) {
21703
- await this.tokenRepository.deleteRefreshTokenById(id, userId);
22207
+ async deleteRefreshTokenById(id, uid) {
22208
+ await this.tokenRepository.deleteRefreshTokenById(id, uid);
21704
22209
  }
21705
- async createPasswordResetToken(userId, tokenHash, expiresAt) {
21706
- await this.tokenRepository.createPasswordResetToken(userId, tokenHash, expiresAt);
22210
+ async createPasswordResetToken(uid, tokenHash, expiresAt) {
22211
+ await this.tokenRepository.createPasswordResetToken(uid, tokenHash, expiresAt);
21707
22212
  }
21708
22213
  async findValidPasswordResetToken(tokenHash) {
21709
22214
  return this.tokenRepository.findValidPasswordResetToken(tokenHash);
@@ -21711,14 +22216,14 @@ var PostgresAuthRepository = class {
21711
22216
  async markPasswordResetTokenUsed(tokenHash) {
21712
22217
  await this.tokenRepository.markPasswordResetTokenUsed(tokenHash);
21713
22218
  }
21714
- async deleteAllPasswordResetTokensForUser(userId) {
21715
- await this.tokenRepository.deleteAllPasswordResetTokensForUser(userId);
22219
+ async deleteAllPasswordResetTokensForUser(uid) {
22220
+ await this.tokenRepository.deleteAllPasswordResetTokensForUser(uid);
21716
22221
  }
21717
22222
  async deleteExpiredTokens() {
21718
22223
  await this.tokenRepository.deleteExpiredTokens();
21719
22224
  }
21720
- async createMagicLinkToken(userId, tokenHash, expiresAt) {
21721
- await this.tokenRepository.createMagicLinkToken(userId, tokenHash, expiresAt);
22225
+ async createMagicLinkToken(uid, tokenHash, expiresAt) {
22226
+ await this.tokenRepository.createMagicLinkToken(uid, tokenHash, expiresAt);
21722
22227
  }
21723
22228
  async findValidMagicLinkToken(tokenHash) {
21724
22229
  return this.tokenRepository.findValidMagicLinkToken(tokenHash);
@@ -21731,11 +22236,11 @@ var PostgresAuthRepository = class {
21731
22236
  if (!this._mfaService) this._mfaService = new MfaService(this.db);
21732
22237
  return this._mfaService;
21733
22238
  }
21734
- async createMfaFactor(userId, factorType, secretEncrypted, friendlyName) {
21735
- return this.getMfaService().createMfaFactor(userId, factorType, secretEncrypted, friendlyName);
22239
+ async createMfaFactor(uid, factorType, secretEncrypted, friendlyName) {
22240
+ return this.getMfaService().createMfaFactor(uid, factorType, secretEncrypted, friendlyName);
21736
22241
  }
21737
- async getMfaFactors(userId) {
21738
- return this.getMfaService().getMfaFactors(userId);
22242
+ async getMfaFactors(uid) {
22243
+ return this.getMfaService().getMfaFactors(uid);
21739
22244
  }
21740
22245
  async getMfaFactorById(factorId) {
21741
22246
  return this.getMfaService().getMfaFactorById(factorId);
@@ -21743,8 +22248,8 @@ var PostgresAuthRepository = class {
21743
22248
  async verifyMfaFactor(factorId) {
21744
22249
  return this.getMfaService().verifyMfaFactor(factorId);
21745
22250
  }
21746
- async deleteMfaFactor(factorId, userId) {
21747
- return this.getMfaService().deleteMfaFactor(factorId, userId);
22251
+ async deleteMfaFactor(factorId, uid) {
22252
+ return this.getMfaService().deleteMfaFactor(factorId, uid);
21748
22253
  }
21749
22254
  async createMfaChallenge(factorId, ipAddress) {
21750
22255
  return this.getMfaService().createMfaChallenge(factorId, ipAddress);
@@ -21755,20 +22260,20 @@ var PostgresAuthRepository = class {
21755
22260
  async verifyMfaChallenge(challengeId) {
21756
22261
  return this.getMfaService().verifyMfaChallenge(challengeId);
21757
22262
  }
21758
- async createRecoveryCodes(userId, codeHashes) {
21759
- return this.getMfaService().createRecoveryCodes(userId, codeHashes);
22263
+ async createRecoveryCodes(uid, codeHashes) {
22264
+ return this.getMfaService().createRecoveryCodes(uid, codeHashes);
21760
22265
  }
21761
- async useRecoveryCode(userId, codeHash) {
21762
- return this.getMfaService().useRecoveryCode(userId, codeHash);
22266
+ async useRecoveryCode(uid, codeHash) {
22267
+ return this.getMfaService().useRecoveryCode(uid, codeHash);
21763
22268
  }
21764
- async getUnusedRecoveryCodeCount(userId) {
21765
- return this.getMfaService().getUnusedRecoveryCodeCount(userId);
22269
+ async getUnusedRecoveryCodeCount(uid) {
22270
+ return this.getMfaService().getUnusedRecoveryCodeCount(uid);
21766
22271
  }
21767
- async deleteAllRecoveryCodes(userId) {
21768
- return this.getMfaService().deleteAllRecoveryCodes(userId);
22272
+ async deleteAllRecoveryCodes(uid) {
22273
+ return this.getMfaService().deleteAllRecoveryCodes(uid);
21769
22274
  }
21770
- async hasVerifiedMfaFactors(userId) {
21771
- return this.getMfaService().hasVerifiedMfaFactors(userId);
22275
+ async hasVerifiedMfaFactors(uid) {
22276
+ return this.getMfaService().hasVerifiedMfaFactors(uid);
21772
22277
  }
21773
22278
  };
21774
22279
  /**
@@ -21785,16 +22290,16 @@ var MfaService = class {
21785
22290
  qualify(tableName) {
21786
22291
  return `"${this.schemaName}"."${tableName}"`;
21787
22292
  }
21788
- async createMfaFactor(userId, factorType, secretEncrypted, friendlyName) {
22293
+ async createMfaFactor(uid, factorType, secretEncrypted, friendlyName) {
21789
22294
  const tableName = this.qualify("mfa_factors");
21790
22295
  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
22296
+ INSERT INTO ${sql.raw(tableName)} (uid, factor_type, secret_encrypted, friendly_name)
22297
+ VALUES (${uid}, ${factorType}, ${secretEncrypted}, ${friendlyName ?? null})
22298
+ RETURNING id, uid, factor_type, friendly_name, verified, created_at, updated_at
21794
22299
  `)).rows[0];
21795
22300
  return {
21796
22301
  id: row.id,
21797
- userId: row.user_id,
22302
+ uid: row.uid,
21798
22303
  factorType: row.factor_type,
21799
22304
  friendlyName: row.friendly_name ?? void 0,
21800
22305
  verified: row.verified,
@@ -21802,16 +22307,16 @@ var MfaService = class {
21802
22307
  updatedAt: new Date(row.updated_at)
21803
22308
  };
21804
22309
  }
21805
- async getMfaFactors(userId) {
22310
+ async getMfaFactors(uid) {
21806
22311
  const tableName = this.qualify("mfa_factors");
21807
22312
  return (await this.db.execute(sql`
21808
- SELECT id, user_id, factor_type, friendly_name, verified, created_at, updated_at
22313
+ SELECT id, uid, factor_type, friendly_name, verified, created_at, updated_at
21809
22314
  FROM ${sql.raw(tableName)}
21810
- WHERE user_id = ${userId}
22315
+ WHERE uid = ${uid}
21811
22316
  ORDER BY created_at
21812
22317
  `)).rows.map((row) => ({
21813
22318
  id: row.id,
21814
- userId: row.user_id,
22319
+ uid: row.uid,
21815
22320
  factorType: row.factor_type,
21816
22321
  friendlyName: row.friendly_name ?? void 0,
21817
22322
  verified: row.verified,
@@ -21822,7 +22327,7 @@ var MfaService = class {
21822
22327
  async getMfaFactorById(factorId) {
21823
22328
  const tableName = this.qualify("mfa_factors");
21824
22329
  const result = await this.db.execute(sql`
21825
- SELECT id, user_id, factor_type, secret_encrypted, friendly_name, verified, created_at, updated_at
22330
+ SELECT id, uid, factor_type, secret_encrypted, friendly_name, verified, created_at, updated_at
21826
22331
  FROM ${sql.raw(tableName)}
21827
22332
  WHERE id = ${factorId}
21828
22333
  `);
@@ -21830,7 +22335,7 @@ var MfaService = class {
21830
22335
  const row = result.rows[0];
21831
22336
  return {
21832
22337
  id: row.id,
21833
- userId: row.user_id,
22338
+ uid: row.uid,
21834
22339
  factorType: row.factor_type,
21835
22340
  secretEncrypted: row.secret_encrypted,
21836
22341
  friendlyName: row.friendly_name ?? void 0,
@@ -21847,11 +22352,11 @@ var MfaService = class {
21847
22352
  WHERE id = ${factorId}
21848
22353
  `);
21849
22354
  }
21850
- async deleteMfaFactor(factorId, userId) {
22355
+ async deleteMfaFactor(factorId, uid) {
21851
22356
  const tableName = this.qualify("mfa_factors");
21852
22357
  await this.db.execute(sql`
21853
22358
  DELETE FROM ${sql.raw(tableName)}
21854
- WHERE id = ${factorId} AND user_id = ${userId}
22359
+ WHERE id = ${factorId} AND uid = ${uid}
21855
22360
  `);
21856
22361
  }
21857
22362
  async createMfaChallenge(factorId, ipAddress) {
@@ -21895,43 +22400,43 @@ var MfaService = class {
21895
22400
  WHERE id = ${challengeId}
21896
22401
  `);
21897
22402
  }
21898
- async createRecoveryCodes(userId, codeHashes) {
22403
+ async createRecoveryCodes(uid, codeHashes) {
21899
22404
  const tableName = this.qualify("recovery_codes");
21900
22405
  await this.db.execute(sql`
21901
- DELETE FROM ${sql.raw(tableName)} WHERE user_id = ${userId}
22406
+ DELETE FROM ${sql.raw(tableName)} WHERE uid = ${uid}
21902
22407
  `);
21903
22408
  for (const hash of codeHashes) await this.db.execute(sql`
21904
- INSERT INTO ${sql.raw(tableName)} (user_id, code_hash)
21905
- VALUES (${userId}, ${hash})
22409
+ INSERT INTO ${sql.raw(tableName)} (uid, code_hash)
22410
+ VALUES (${uid}, ${hash})
21906
22411
  `);
21907
22412
  }
21908
- async useRecoveryCode(userId, codeHash) {
22413
+ async useRecoveryCode(uid, codeHash) {
21909
22414
  const tableName = this.qualify("recovery_codes");
21910
22415
  return (await this.db.execute(sql`
21911
22416
  UPDATE ${sql.raw(tableName)}
21912
22417
  SET used_at = NOW()
21913
- WHERE user_id = ${userId} AND code_hash = ${codeHash} AND used_at IS NULL
22418
+ WHERE uid = ${uid} AND code_hash = ${codeHash} AND used_at IS NULL
21914
22419
  RETURNING id
21915
22420
  `)).rows.length > 0;
21916
22421
  }
21917
- async getUnusedRecoveryCodeCount(userId) {
22422
+ async getUnusedRecoveryCodeCount(uid) {
21918
22423
  const tableName = this.qualify("recovery_codes");
21919
22424
  return (await this.db.execute(sql`
21920
22425
  SELECT COUNT(*)::int as count FROM ${sql.raw(tableName)}
21921
- WHERE user_id = ${userId} AND used_at IS NULL
22426
+ WHERE uid = ${uid} AND used_at IS NULL
21922
22427
  `)).rows[0].count;
21923
22428
  }
21924
- async deleteAllRecoveryCodes(userId) {
22429
+ async deleteAllRecoveryCodes(uid) {
21925
22430
  const tableName = this.qualify("recovery_codes");
21926
22431
  await this.db.execute(sql`
21927
- DELETE FROM ${sql.raw(tableName)} WHERE user_id = ${userId}
22432
+ DELETE FROM ${sql.raw(tableName)} WHERE uid = ${uid}
21928
22433
  `);
21929
22434
  }
21930
- async hasVerifiedMfaFactors(userId) {
22435
+ async hasVerifiedMfaFactors(uid) {
21931
22436
  const tableName = this.qualify("mfa_factors");
21932
22437
  return (await this.db.execute(sql`
21933
22438
  SELECT COUNT(*)::int as count FROM ${sql.raw(tableName)}
21934
- WHERE user_id = ${userId} AND verified = TRUE
22439
+ WHERE uid = ${uid} AND verified = TRUE
21935
22440
  `)).rows[0].count > 0;
21936
22441
  }
21937
22442
  };
@@ -22171,6 +22676,20 @@ function patchPgArrayNullSafety(tables) {
22171
22676
  if (patchedCount > 0) logger.debug(`[PgArray] Patched ${patchedCount} array column(s) for null-safety`);
22172
22677
  }
22173
22678
  //#endregion
22679
+ //#region src/schema/introspect-db-naming.ts
22680
+ /**
22681
+ * Naming helpers shared by the introspection modules. These live apart from
22682
+ * `introspect-db-logic.ts` because the inference pass needs them too, and
22683
+ * importing them from there would close a cycle back through this module.
22684
+ */
22685
+ /**
22686
+ * Convert a snake_case name to a human-readable Title Case label.
22687
+ * e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
22688
+ */
22689
+ function humanize(snakeName) {
22690
+ return snakeName.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
22691
+ }
22692
+ //#endregion
22174
22693
  //#region src/schema/introspect-db-logic.ts
22175
22694
  var IRREGULAR_SINGULARS = {
22176
22695
  people: "person",
@@ -22230,13 +22749,6 @@ function singularize(word) {
22230
22749
  if (lower.endsWith("s") && !lower.endsWith("ss") && !lower.endsWith("us") && !lower.endsWith("is")) return word.slice(0, -1);
22231
22750
  return word;
22232
22751
  }
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
22752
  function getIconForTable(tableName) {
22241
22753
  const table = tableName.toLowerCase();
22242
22754
  if (table.includes("user") || table.includes("account") || table.includes("member") || table.includes("customer") || table.includes("client") || table.includes("patient")) return "Users";
@@ -22757,6 +23269,11 @@ function createPostgresBootstrapper(pgConfig) {
22757
23269
  } catch (err) {
22758
23270
  logger.warn("⚠️ Could not initialize branch metadata table", { error: err });
22759
23271
  }
23272
+ try {
23273
+ await realtimeService.configureChannelHistory(pgConfig.realtime?.channels);
23274
+ } catch (err) {
23275
+ logger.warn("⚠️ Could not initialize channel history tables — retained channels will not replay", { error: err });
23276
+ }
22760
23277
  const directUrl = process.env.DATABASE_DIRECT_URL || pgConfig.connectionString;
22761
23278
  const validModes = new Set([
22762
23279
  "auto",