@rebasepro/server-postgres 0.13.1-canary.g18cfeb7 → 0.13.1-canary.g1bf9303

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.
Files changed (88) hide show
  1. package/dist/PostgresBootstrapper.d.ts +26 -0
  2. package/dist/auth/services.d.ts +21 -0
  3. package/dist/{auth-users-columns-Do9mw5Y5.js → auth-users-columns-BxT6FRyu.js} +819 -68
  4. package/dist/auth-users-columns-BxT6FRyu.js.map +1 -0
  5. package/dist/{backup-service-Bww-Lg0s.js → backup-service-BH0Dzo_h.js} +2 -3
  6. package/dist/{backup-service-Bww-Lg0s.js.map → backup-service-BH0Dzo_h.js.map} +1 -1
  7. package/dist/cli-helpers.d.ts +56 -0
  8. package/dist/cli-output.d.ts +34 -0
  9. package/dist/data-transformer.d.ts +7 -2
  10. package/dist/data_driver-ULAyJEi9.js +193 -0
  11. package/dist/data_driver-ULAyJEi9.js.map +1 -0
  12. package/dist/ensure-collection-policies-CP5_YttS.js +124 -0
  13. package/dist/ensure-collection-policies-CP5_YttS.js.map +1 -0
  14. package/dist/{ensure-collection-tables-DSIxvLLD.js → ensure-collection-tables-DWVISfcC.js} +119 -13
  15. package/dist/ensure-collection-tables-DWVISfcC.js.map +1 -0
  16. package/dist/index.es.js +998 -600
  17. package/dist/index.es.js.map +1 -1
  18. package/dist/{rls-bootstrap-sql-Bpv3nUZo.js → rls-bootstrap-sql-69hYT8nr.js} +2 -2
  19. package/dist/{rls-bootstrap-sql-Bpv3nUZo.js.map → rls-bootstrap-sql-69hYT8nr.js.map} +1 -1
  20. package/dist/rls-enforcement-Ct9ab42o.js +425 -0
  21. package/dist/rls-enforcement-Ct9ab42o.js.map +1 -0
  22. package/dist/schema/auth-schema.d.ts +102 -0
  23. package/dist/schema/doctor-policy-checks.d.ts +28 -0
  24. package/dist/schema/doctor.d.ts +41 -25
  25. package/dist/schema/ensure-collection-policies.d.ts +33 -9
  26. package/dist/schema/ensure-collection-tables.d.ts +60 -6
  27. package/dist/schema/generate-drizzle-schema-logic.d.ts +9 -1
  28. package/dist/schema/generate-postgres-ddl-logic.d.ts +48 -0
  29. package/dist/schema/search-column.d.ts +248 -0
  30. package/dist/security/rls-enforcement.d.ts +8 -3
  31. package/dist/services/FetchService.d.ts +24 -0
  32. package/dist/services/RelationService.d.ts +30 -0
  33. package/dist/services/collection-helpers.d.ts +26 -0
  34. package/dist/services/dataService.d.ts +3 -0
  35. package/dist/services/realtimeService.d.ts +139 -2
  36. package/dist/{src-C_wvdMnl.js → src-DCdn3Val.js} +35 -3
  37. package/dist/src-DCdn3Val.js.map +1 -0
  38. package/dist/utils/drizzle-conditions.d.ts +124 -2
  39. package/dist/{websocket-D0TBU3ia.js → websocket-C8ZqVBiV.js} +75 -18
  40. package/dist/websocket-C8ZqVBiV.js.map +1 -0
  41. package/package.json +6 -6
  42. package/src/PostgresBackendDriver.ts +7 -3
  43. package/src/PostgresBootstrapper.ts +95 -9
  44. package/src/auth/ensure-tables.ts +27 -5
  45. package/src/auth/services.ts +82 -5
  46. package/src/backup/backup-cli.ts +59 -57
  47. package/src/cli-errors.ts +6 -6
  48. package/src/cli-helpers.ts +110 -4
  49. package/src/cli-output.ts +43 -0
  50. package/src/cli.ts +210 -145
  51. package/src/collections/buildRegistry.ts +3 -1
  52. package/src/data-transformer.ts +107 -14
  53. package/src/history/ensure-history-table.ts +2 -2
  54. package/src/schema/auth-schema.ts +17 -1
  55. package/src/schema/doctor-cli.ts +14 -65
  56. package/src/schema/doctor-policy-checks.ts +105 -0
  57. package/src/schema/doctor.ts +149 -72
  58. package/src/schema/ensure-collection-policies.ts +99 -6
  59. package/src/schema/ensure-collection-tables.ts +286 -13
  60. package/src/schema/generate-drizzle-schema-logic.ts +126 -42
  61. package/src/schema/generate-drizzle-schema.ts +11 -10
  62. package/src/schema/generate-postgres-ddl-logic.ts +204 -10
  63. package/src/schema/generate-postgres-ddl.ts +38 -14
  64. package/src/schema/introspect-db-logic.ts +65 -33
  65. package/src/schema/introspect-db.ts +24 -24
  66. package/src/schema/search-column.ts +643 -0
  67. package/src/security/rls-enforcement.ts +9 -4
  68. package/src/services/FetchService.ts +229 -15
  69. package/src/services/PersistService.ts +24 -1
  70. package/src/services/RelationService.ts +119 -69
  71. package/src/services/cdc/trigger-cdc.ts +5 -1
  72. package/src/services/channel-history.ts +9 -3
  73. package/src/services/channel-presence.ts +10 -3
  74. package/src/services/collection-helpers.ts +54 -1
  75. package/src/services/dataService.ts +3 -0
  76. package/src/services/pg-notify-listener.ts +1 -1
  77. package/src/services/realtimeService.ts +347 -86
  78. package/src/utils/drizzle-conditions.ts +365 -23
  79. package/src/utils/pg-error-utils.ts +8 -3
  80. package/src/websocket.ts +113 -16
  81. package/dist/auth-users-columns-Do9mw5Y5.js.map +0 -1
  82. package/dist/ensure-collection-policies-DMUdRQdM.js +0 -57
  83. package/dist/ensure-collection-policies-DMUdRQdM.js.map +0 -1
  84. package/dist/ensure-collection-tables-DSIxvLLD.js.map +0 -1
  85. package/dist/policy-CPkCqVTz.js +0 -105
  86. package/dist/policy-CPkCqVTz.js.map +0 -1
  87. package/dist/src-C_wvdMnl.js.map +0 -1
  88. package/dist/websocket-D0TBU3ia.js.map +0 -1
package/dist/index.es.js CHANGED
@@ -2,17 +2,18 @@ import { createRequire as __createRequire } from "module";
2
2
  import process from "process";
3
3
  __createRequire(import.meta.url);
4
4
  import { a as guardPoolAgainstDirtyRelease, i as createReadReplicaConnection, n as createDirectDatabaseConnection, o as pinSearchPath, r as createPostgresDatabaseConnection } from "./connection-BuZ97wsr.js";
5
- import { A as generateForeignKeyName, B as hasForeignKeyOnTarget, C as getDeclaredPrimaryKeys, D as createRelationRefWithData, E as createRelationRef, F as camelCase, H as Vector, I as toSnakeCase, M as getPolicyNamesForRule, N as isPrototypePollutingKey, O as normalizeToEntityRelation, P as mergeDeep, S as buildCompositeId, T as parseIdValues, V as isManyToMany, _ as getColumnName, a as buildSdkData, b as getTableVarName, c as resolveStringColumnLength, d as resolveJunctionSpecs, f as getEffectiveSecurityRules, g as findRelation, h as findAnonymousGrants, j as legacyForeignKeyName, k as updateDateAutoValues, l as getJunctionCollectionConfig, m as securityRuleToConditions, o as CollectionRegistry, p as policyToPostgres, r as authUsersColumnSql, s as relationalCollections, t as AUTH_USERS_COLUMNS, u as getJunctionSecurityRules, v as getEnumVarName, w as isAddressableId, x as resolveCollectionRelations, y as getTableName$1, z as resolveClientListLimit } from "./auth-users-columns-Do9mw5Y5.js";
6
- import { c as isPostgresCollectionConfig, l as isRelationalCollectionConfig, n as REBASE_SCHEMA, o as usesLegacyRlsFunctions } from "./src-C_wvdMnl.js";
7
- import { t as ANONYMOUS_USER_ID } from "./policy-CPkCqVTz.js";
8
- import { t as createPostgresWebSocket } from "./websocket-D0TBU3ia.js";
9
- import { A as parsePgToolMajor, C as checkToolServerCompatibility, D as parseBackupDestination, E as joinStorageKey, M as serverVersionNumToMajor, N as splitGlobalsStatements, O as parseBackupTimestamp, P as withDatabaseName, S as buildRowSecurityPgOptions, T as globalsFileForDump, _ as buildBackupFilename, a as detectToolMajor, b as buildPgRestoreArgs, c as listBackups, d as resolvePgBinary, f as restoreDump, g as selectBackupsToPrune, h as require_source, i as createDump, j as resolveConnectionString, k as parseDbNameFromUrl, l as preflight, m as validateDump, n as applyGlobals, o as ensureDatabaseExists, p as uploadBackup, s as getServerVersionMajor, t as BackupToolError, u as pruneBackups, v as buildPgDumpArgs, w as diagnoseRowSecurityDumpFailure, x as buildPgRestoreListArgs, y as buildPgDumpallGlobalsArgs } from "./backup-service-Bww-Lg0s.js";
10
- import { t as RLS_BOOTSTRAP_STATEMENTS } from "./rls-bootstrap-sql-Bpv3nUZo.js";
5
+ import { n as resolveClientListLimit, t as ListLimitError } from "./data_driver-ULAyJEi9.js";
6
+ import { $ as isManyToMany, A as getTableName$1, B as normalizeToEntityRelation, C as getEffectiveSecurityRules, D as findRelation, F as isAddressableId, G as getPolicyNamesForRule, H as generateForeignKeyName, I as parseIdValues, J as camelCase, K as isPrototypePollutingKey, L as sortCollectionsBySlug, M as resolveCollectionRelations, N as buildCompositeId, O as getColumnName, P as getDeclaredPrimaryKeys, Q as hasForeignKeyOnTarget, R as createRelationRef, S as resolveJunctionSpecs, T as securityRuleToConditions, U as legacyForeignKeyName, V as updateDateAutoValues, Y as toSnakeCase, _ as CollectionRegistry, b as getJunctionCollectionConfig, et as Vector, g as buildSdkData, h as visibleColumnProjection, j as getTableVarName, k as getEnumVarName, l as buildSearchColumnSpec, q as mergeDeep, r as authUsersColumnSql, s as SEARCH_UNACCENT_FN, t as AUTH_USERS_COLUMNS, u as hiddenColumnsOption, v as relationalCollections, w as policyToPostgres, x as getJunctionSecurityRules, y as resolveStringColumnLength, z as createRelationRefWithData } from "./auth-users-columns-BxT6FRyu.js";
7
+ import { c as isPostgresCollectionConfig, l as isRelationalCollectionConfig } from "./src-DCdn3Val.js";
8
+ import { t as createPostgresWebSocket } from "./websocket-C8ZqVBiV.js";
9
+ import { a as warnOnAnonymousGrants, c as REBASE_USER_ROLE, i as validatePolicyPgRoles, l as revokeInternalTableAccess, n as detectConnectionPosture, o as warnOnLegacyRlsFunctions, r as ensureAppRole, s as warnOnRoleSchemaCollision, t as applyAuthContext, u as revokeInternalTableSql } from "./rls-enforcement-Ct9ab42o.js";
10
+ import { A as parsePgToolMajor, C as checkToolServerCompatibility, D as parseBackupDestination, E as joinStorageKey, M as serverVersionNumToMajor, N as splitGlobalsStatements, O as parseBackupTimestamp, P as withDatabaseName, S as buildRowSecurityPgOptions, T as globalsFileForDump, _ as buildBackupFilename, a as detectToolMajor, b as buildPgRestoreArgs, c as listBackups, d as resolvePgBinary, f as restoreDump, g as selectBackupsToPrune, h as require_source, i as createDump, j as resolveConnectionString, k as parseDbNameFromUrl, l as preflight, m as validateDump, n as applyGlobals, o as ensureDatabaseExists, p as uploadBackup, s as getServerVersionMajor, t as BackupToolError, u as pruneBackups, v as buildPgDumpArgs, w as diagnoseRowSecurityDumpFailure, x as buildPgRestoreListArgs, y as buildPgDumpallGlobalsArgs } from "./backup-service-BH0Dzo_h.js";
11
+ import { t as RLS_BOOTSTRAP_STATEMENTS } from "./rls-bootstrap-sql-69hYT8nr.js";
11
12
  import { Client, Pool } from "pg";
12
13
  import { drizzle } from "drizzle-orm/node-postgres";
13
14
  import { ApiError, createEmailService, loadCollectionsFromDirectory, logger } from "@rebasepro/server";
14
- import { and, asc, count, desc, eq, getTableColumns, getTableName, gt, ilike, inArray, isTable, lt, or, relations, sql } from "drizzle-orm";
15
- import { PgArray, PgChar, PgTable, PgText, PgVarchar, bigint, boolean, char, cidr, customType, date, doublePrecision, geometry, getTableConfig, index, inet, integer, interval, json, jsonb, line, macaddr, macaddr8, numeric, pgSchema, pgTable, point, primaryKey, real, smallint, text, time, timestamp, unique, uuid, varchar, vector } from "drizzle-orm/pg-core";
15
+ import { and, asc, count, desc, eq, getTableColumns, getTableName, gt, ilike, inArray, isTable, lt, notInArray, or, relations, sql } from "drizzle-orm";
16
+ import { PgArray, PgTable, bigint, boolean, char, cidr, customType, date, doublePrecision, geometry, getTableConfig, index, inet, integer, interval, json, jsonb, line, macaddr, macaddr8, numeric, pgSchema, pgTable, point, primaryKey, real, smallint, text, time, timestamp, unique, uuid, varchar, vector } from "drizzle-orm/pg-core";
16
17
  import fs, { promises } from "fs";
17
18
  import path from "path";
18
19
  import chokidar from "chokidar";
@@ -134,140 +135,25 @@ var buildPropertyCallbacks = (properties) => {
134
135
  return Object.keys(propertyCallbacks).length > 0 ? propertyCallbacks : void 0;
135
136
  };
136
137
  //#endregion
137
- //#region ../common/src/util/internal-tables.ts
138
- /**
139
- * The tables Rebase creates for its own bookkeeping, and the SQL that keeps the
140
- * end-user role away from them.
141
- *
142
- * ## Why this exists
143
- *
144
- * Authenticated requests run as {@link REBASE_USER_ROLE}, and the boot-time role
145
- * provisioning grants that role `SELECT, INSERT, UPDATE, DELETE` on every table
146
- * in the schemas a project uses — including `rebase`, because a project's own
147
- * collections are allowed to live there (the scaffold puts `users` there). It
148
- * also sets `ALTER DEFAULT PRIVILEGES`, so a table created *later* by the
149
- * migrating role inherits the same grant.
150
- *
151
- * Every framework-internal table is created later: auth's tables come up during
152
- * `initializeAuth`, `api_keys` during route mounting, `cron_logs` when the first
153
- * job registers, `idempotency_keys` on the first request that carries a key. So
154
- * they all inherited full DML for the end-user role — and none of them enables
155
- * row-level security, because none of them is a collection with
156
- * `securityRules`. Measured on a freshly provisioned database, `SET ROLE
157
- * rebase_user` could read `rebase.refresh_tokens` (session token hashes),
158
- * `rebase.mfa_factors` (`secret_encrypted`), `rebase.recovery_codes`, and
159
- * `rebase.api_keys` (including its `admin` flag), and insert into
160
- * `rebase.app_config`.
161
- *
162
- * Nothing routes a user-context query at those tables today, so this was not
163
- * reachable over the API. That is the wrong thing to depend on: the documented
164
- * model is that RLS is the authorization boundary, and these tables sat outside
165
- * it. The boundary is now a privilege boundary instead — the role simply cannot
166
- * address them.
167
- *
168
- * ## Why REVOKE rather than ENABLE ROW LEVEL SECURITY
169
- *
170
- * RLS with no policy denies every row, which is the same outcome, but it is the
171
- * *weaker* statement: it leaves the grant in place, so a later policy — or a
172
- * `FORCE` flag cleared by some future migration — reopens the table. There is no
173
- * row of `refresh_tokens` any end user should ever reach, so the honest encoding
174
- * is "this role has no privilege here at all". It also keeps the owner
175
- * connection (which auth actually runs on) completely unaffected.
176
- *
177
- * ## Keeping it true
178
- *
179
- * `packages/rls-check` scans the `rebase` schema — it used to skip it as a
180
- * "platform" schema — and its `rls-disabled` check fires on exactly the
181
- * condition this module removes: RLS off *and* a DML grant to a reachable role.
182
- * So a table added here without a revoke is caught by `pnpm rls:check`, not by
183
- * someone re-reading this file.
184
- */
185
- /**
186
- * The Postgres role authenticated requests run as.
187
- *
188
- * Defined here rather than in the Postgres driver because both the driver (which
189
- * provisions the role) and this module (which revokes on its behalf) need it,
190
- * and a second spelling of a role name is a silent no-op waiting to happen.
191
- */
192
- var REBASE_USER_ROLE = "rebase_user";
193
- /**
194
- * Framework-internal table names, unqualified.
195
- *
196
- * Deliberately NOT including `users`: the auth user table is also a collection,
197
- * with `securityRules`, RLS enabled and policies applied. Users read their own
198
- * row through it — revoking there would break sign-in.
199
- *
200
- * `atlas_schema_revisions` is Atlas's migration ledger, which lands in `rebase`
201
- * because `db migrate apply` passes `--revisions-schema rebase`.
202
- */
203
- var REBASE_INTERNAL_TABLES = [
204
- "user_identities",
205
- "refresh_tokens",
206
- "password_reset_tokens",
207
- "magic_link_tokens",
208
- "mfa_factors",
209
- "mfa_challenges",
210
- "recovery_codes",
211
- "app_config",
212
- "schema_meta",
213
- "api_keys",
214
- "cron_logs",
215
- "cron_claims",
216
- "idempotency_keys",
217
- "entity_history",
218
- "branches",
219
- "channel_messages",
220
- "channel_cursors",
221
- "channel_presence",
222
- "atlas_schema_revisions"
223
- ];
224
- /** Postgres identifiers this module is willing to interpolate. */
225
- var SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
138
+ //#region ../common/src/data/filter-conditions.ts
226
139
  /**
227
- * A single statement that takes every privilege on `schema.table` away from the
228
- * end-user role.
229
- *
230
- * Wrapped in a `DO` block guarded on `pg_roles` for two reasons, both of which
231
- * happen in practice:
140
+ * Read one field's filter as the list of conditions it stands for.
232
141
  *
233
- * - the role does not exist when the connection is unprivileged (Rebase then
234
- * relies on native RLS rather than a role switch), and a bare `REVOKE` on a
235
- * missing role is an error, not a no-op;
236
- * - the table may not exist yet — `cron_logs` never appears in a project with
237
- * no cron jobs — and `to_regclass` returning NULL has to be tolerated too.
142
+ * Accepts both declared shapes and normalises them to a list:
238
143
  *
239
- * One command, so it is safe on handles that speak the extended query protocol
240
- * and reject multi-statement strings.
241
- */
242
- function revokeInternalTableSql(schema, table) {
243
- if (!SAFE_IDENTIFIER.test(schema)) throw new Error(`Refusing to build SQL with an unsafe schema name: ${JSON.stringify(schema)}`);
244
- if (!SAFE_IDENTIFIER.test(table)) throw new Error(`Refusing to build SQL with an unsafe table name: ${JSON.stringify(table)}`);
245
- const qualified = `"${schema}"."${table}"`;
246
- return `
247
- DO $rebase_revoke$
248
- BEGIN
249
- IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}')
250
- AND to_regclass('${qualified}') IS NOT NULL THEN
251
- EXECUTE 'REVOKE ALL ON ${qualified} FROM ${REBASE_USER_ROLE}';
252
- END IF;
253
- END
254
- $rebase_revoke$;
255
- `.trim();
256
- }
257
- /**
258
- * Revoke on every internal table in `schema`, one statement at a time.
144
+ * ```ts
145
+ * toFilterTuples(["==", "active"]) // [["==", "active"]]
146
+ * toFilterTuples([[">=", 18], ["<", 65]]) // [[">=", 18], ["<", 65]]
147
+ * ```
259
148
  *
260
- * Best-effort per table: a connection that does not own one of them (a
261
- * pre-provisioned database, a platform-managed ledger) cannot revoke on it, and
262
- * that must not take down a boot. The caller decides how loud to be — `onError`
263
- * exists so the driver can warn without this module importing a logger.
149
+ * A falsy, non-array or empty param has no conditions in it — the empty list,
150
+ * so a caller iterating adds nothing rather than compiling a tuple of
151
+ * `undefined`s and logging about an operator nobody sent.
264
152
  */
265
- async function revokeInternalTableAccess(execute, schema, options) {
266
- for (const table of options?.tables ?? REBASE_INTERNAL_TABLES) try {
267
- await execute(revokeInternalTableSql(schema, table));
268
- } catch (error) {
269
- options?.onError?.(table, error);
270
- }
153
+ function toFilterTuples(filterParam) {
154
+ if (!filterParam || !Array.isArray(filterParam) || filterParam.length === 0) return [];
155
+ if (Array.isArray(filterParam[0])) return filterParam;
156
+ return [filterParam];
271
157
  }
272
158
  //#endregion
273
159
  //#region ../common/src/table-classification.ts
@@ -375,6 +261,38 @@ function getCollectionByPath(collectionPath, registry) {
375
261
  }
376
262
  return collection;
377
263
  }
264
+ /**
265
+ * Reject a write naming something that is not a column of the table.
266
+ *
267
+ * Drizzle builds INSERT from `Object.entries(table[Symbol.Columns])` and UPDATE
268
+ * from `Object.keys(tableColumns)`, so a key the table does not carry is not
269
+ * rejected by anything — it is *left out of the statement*. The insert answers
270
+ * 201 having stored nothing under that name; the update, if the key was the
271
+ * only one, builds `update "posts" set where …` and Postgres raises a syntax
272
+ * error (SQLSTATE 42601), which is neither class 22 nor 23 and so surfaces as a
273
+ * 500 for what is a caller's typo.
274
+ *
275
+ * That makes this the last honest place to check, and the only one every write
276
+ * passes through. `assertKnownWriteFields` in the REST layer checks the same
277
+ * thing against the *config* and is skipped on four paths — `strictWrites:
278
+ * false`, a collection declaring no properties, an auth adapter that owns the
279
+ * body's shape, and a nested route whose target cannot be walked — and it never
280
+ * sees an in-process `rebase.data` write at all.
281
+ *
282
+ * It also gives `strictWrites: false` a truthful implementation. The flag is
283
+ * documented for "a column that really does exist which the config never
284
+ * declared", and skipping the config check alone could not deliver that: the
285
+ * value was dropped a layer later regardless. Skipping the config check and
286
+ * keeping this one does exactly what the flag says — the column must exist,
287
+ * the property need not.
288
+ */
289
+ function assertWritableColumns(values, table, collectionPath) {
290
+ const columns = getTableColumns(table);
291
+ if (!columns || Object.keys(columns).length === 0) return;
292
+ const unknown = Object.keys(values).filter((key) => !(key in columns));
293
+ if (unknown.length === 0) return;
294
+ throw ApiError.badRequest(`'${collectionPath}' has no column${unknown.length > 1 ? "s" : ""} ${unknown.map((key) => `'${key}'`).join(", ")}, so the value${unknown.length > 1 ? "s" : ""} would have been dropped before the statement was built.`, "VALIDATION_UNKNOWN_FIELDS");
295
+ }
378
296
  function getTableForCollection(collection, registry) {
379
297
  const tableName = getTableName$1(collection);
380
298
  const table = registry.getTable(tableName);
@@ -554,6 +472,71 @@ function deriveRowAddress(row, collection, registry) {
554
472
  //#endregion
555
473
  //#region src/utils/drizzle-conditions.ts
556
474
  /**
475
+ * Postgres's own default for `pg_trgm.word_similarity_threshold`. Named here
476
+ * because the fuzzy predicate has to know when the index-backed operator agrees
477
+ * with the collection's declared threshold and when it would narrow too far.
478
+ */
479
+ var PG_TRGM_WORD_SIMILARITY_DEFAULT = .6;
480
+ /**
481
+ * A user's search term, made safe to drop inside a `%…%` LIKE pattern.
482
+ *
483
+ * The term is already a bind parameter, so this is not about injection. It is
484
+ * about the two things a LIKE metacharacter does when it arrives from a search
485
+ * box:
486
+ *
487
+ * 1. **It changes the query.** `%` and `_` are wildcards, so searching for
488
+ * `50%` returned every row and `a_c` matched `abc`. Nothing the caller
489
+ * could type would find a literal `%`.
490
+ * 2. **It is a cost the caller chooses.** Postgres matches LIKE by
491
+ * backtracking: each `%` re-tries every remaining offset, so
492
+ * `?searchString=a%a%a%a%a%a%a%b` is polynomial with an attacker-chosen
493
+ * exponent — evaluated per row, OR-ed across every string property of the
494
+ * collection, on a sequential scan (a leading `%` cannot use an index), and
495
+ * the page limit does not bound it because the scan happens first.
496
+ *
497
+ * This is the server-side half of the pattern `like-pattern-redos.test.ts`
498
+ * hardened the offline evaluator against; that test's own note ("the same
499
+ * translation in the Mongo driver hands the expression to the database, where
500
+ * it occupies a server thread instead") describes this call site.
501
+ *
502
+ * Backslash is the default `ESCAPE` character for LIKE, and the pattern is
503
+ * bound rather than interpolated, so a single backslash here reaches the
504
+ * matcher as one. Escaping the escape character first is what keeps a term
505
+ * ending in `\` from swallowing the closing `%`.
506
+ *
507
+ * Note this is a *substring search*, not the `like` filter operator: a caller
508
+ * who wants wildcards has `?title=like.foo%` for that, where the pattern is the
509
+ * documented input.
510
+ */
511
+ var escapeLikePattern = (value) => value.replace(/[\\%_]/g, (ch) => `\\${ch}`);
512
+ /** Column types `ILIKE '%…%'` is defined on. */
513
+ var ILIKE_SQL_TYPES = /^(text|varchar|character varying|char|character|bpchar|citext)\b/;
514
+ /**
515
+ * Can this column be matched with `ILIKE`?
516
+ *
517
+ * Asked of the column's *declared SQL type*, never with `instanceof`. The
518
+ * previous version tested `column instanceof PgVarchar || … PgText || … PgChar`,
519
+ * and `instanceof` compares class identity: it is only true when the column was
520
+ * constructed by the very same copy of `drizzle-orm` that this module imported.
521
+ *
522
+ * An application's generated schema builds its tables with the app's own
523
+ * `drizzle-orm`, and this driver declares its own dependency on one. When the
524
+ * two ranges do not overlap — an app scaffolded against `^0.44` with a driver
525
+ * asking for `^0.45` — a strict installer gives the driver a second copy, every
526
+ * check returns false, no condition is produced, and the caller compiles that
527
+ * into an impossible `WHERE`. The result is a 200 with an empty page for every
528
+ * search on every collection without a `search` block: the failure looks
529
+ * exactly like "nothing matched". Observed in production, not theorised.
530
+ *
531
+ * `getSQLType()` is a value the column reports about itself, so it crosses
532
+ * module instances the way a class identity cannot. It also happens to fix
533
+ * `citext`, which the `instanceof` list never covered.
534
+ */
535
+ var supportsILike = (column) => {
536
+ const sqlType = typeof column?.getSQLType === "function" ? column.getSQLType().toLowerCase() : "";
537
+ return ILIKE_SQL_TYPES.test(sqlType);
538
+ };
539
+ /**
557
540
  * Process-wide default, set once when the driver is constructed.
558
541
  *
559
542
  * The condition builder is a set of *static* methods reached from a dozen
@@ -611,7 +594,7 @@ function toMembershipList(value) {
611
594
  * @example
612
595
  * const builder: ConditionBuilderStatic<SQL> = DrizzleConditionBuilder;
613
596
  */
614
- var DrizzleConditionBuilder = class {
597
+ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
615
598
  /**
616
599
  * Express "reachable from this parent through this relation" as a plain
617
600
  * `WHERE` condition on the target table.
@@ -787,8 +770,7 @@ var DrizzleConditionBuilder = class {
787
770
  if (!filterParam) continue;
788
771
  const target = this.resolveFilterTarget(table, field, collectionPath, mode, options);
789
772
  if (!target) continue;
790
- const paramsList = Array.isArray(filterParam) && filterParam.length > 0 && Array.isArray(filterParam[0]) ? filterParam : [filterParam];
791
- for (const [op, value] of paramsList) {
773
+ for (const [op, value] of toFilterTuples(filterParam)) {
792
774
  const condition = this.compileFilterTarget(target, op, value, field, collectionPath);
793
775
  if (condition) conditions.push(condition);
794
776
  }
@@ -1237,22 +1219,153 @@ var DrizzleConditionBuilder = class {
1237
1219
  return or(...conditions);
1238
1220
  }
1239
1221
  /**
1240
- * Build search conditions for text fields
1222
+ * Build search conditions for text fields.
1223
+ *
1224
+ * Two shapes, chosen by whether the collection declared a `search` block:
1225
+ *
1226
+ * - **Declared** — one `@@ websearch_to_tsquery` against the generated
1227
+ * `tsvector` column. Stems, drops stopwords, AND-es the terms, reaches
1228
+ * inside JSONB and arrays, and uses the GIN index.
1229
+ * - **Not declared** — the original `ILIKE '%term%'` OR-ed across top-level
1230
+ * string properties, with the term escaped (see {@link escapeLikePattern})
1231
+ * so it is matched as the literal text the user typed.
1232
+ *
1233
+ * The second is the default and stays the default. A collection that has
1234
+ * not opted in compiles to exactly the SQL it compiled to before this
1235
+ * branch existed, which is the only reason it is safe to have added it.
1236
+ *
1237
+ * `collection` is optional so that the callers which genuinely have no
1238
+ * collection in hand — nested paths, derived views — keep working; without
1239
+ * one there is no `search` block to read and the ILIKE path is correct.
1241
1240
  */
1242
- static buildSearchConditions(searchString, properties, table) {
1241
+ static buildSearchConditions(searchString, properties, table, collection) {
1243
1242
  const searchConditions = [];
1243
+ const ftsCondition = collection ? DrizzleConditionBuilder.buildFullTextCondition(searchString, table, collection) : void 0;
1244
+ if (ftsCondition) return [ftsCondition];
1245
+ let declaredStringProperties = 0;
1244
1246
  for (const [key, prop] of Object.entries(properties)) {
1245
1247
  const p = prop;
1246
1248
  if (p.type === "string" && !p.enum && p.isId !== "uuid") {
1249
+ declaredStringProperties++;
1247
1250
  const fieldColumn = table[key];
1248
- if (fieldColumn) {
1249
- if (fieldColumn instanceof PgVarchar || fieldColumn instanceof PgText || fieldColumn instanceof PgChar || fieldColumn && typeof fieldColumn === "object" && !("columnType" in fieldColumn)) searchConditions.push(ilike(fieldColumn, `%${searchString}%`));
1250
- }
1251
+ if (fieldColumn && supportsILike(fieldColumn)) searchConditions.push(ilike(fieldColumn, `%${escapeLikePattern(searchString)}%`));
1251
1252
  }
1252
1253
  }
1254
+ if (declaredStringProperties > 0 && searchConditions.length === 0) logger.warn(`[search] "${collection?.slug ?? "collection"}" declares ${declaredStringProperties} string property(ies) but none compiled to a searchable column, so this search can only return nothing. Check that the generated schema's column types are text/varchar/char.`);
1253
1255
  return searchConditions;
1254
1256
  }
1255
1257
  /**
1258
+ * The `@@` predicate for a collection that declared a `search` block, or
1259
+ * undefined for one that did not.
1260
+ *
1261
+ * The query is normalized exactly as the indexed content was — same text
1262
+ * search configuration, same accent folding. Skipping that on the query
1263
+ * side is the subtle way to get a search that matches nothing: the column
1264
+ * would hold `gestion` while the query asked for `gestión`.
1265
+ *
1266
+ * `websearch_to_tsquery` rather than `plainto_tsquery` because it is the
1267
+ * one that behaves the way a search box looks like it should — quoted
1268
+ * phrases, `or`, and a leading `-` to exclude — and because it never throws
1269
+ * on user input, which `to_tsquery` does on so much as a stray parenthesis.
1270
+ */
1271
+ static buildFullTextCondition(searchString, table, collection) {
1272
+ let spec;
1273
+ try {
1274
+ spec = buildSearchColumnSpec(collection);
1275
+ } catch {
1276
+ return;
1277
+ }
1278
+ if (!spec) return void 0;
1279
+ const column = table[spec.column];
1280
+ if (!column) return;
1281
+ const exact = sql`${column} @@ ${DrizzleConditionBuilder.normalizedTsQuery(searchString, spec)}`;
1282
+ if (!spec.fuzzy) return exact;
1283
+ const fuzzyColumn = table[spec.fuzzy.column];
1284
+ if (!fuzzyColumn) return exact;
1285
+ const needle = spec.unaccent ? sql`${sql.raw(SEARCH_UNACCENT_FN)}(${searchString})` : sql`${searchString}`;
1286
+ const similar = sql`public.word_similarity(${needle}, ${fuzzyColumn}) >= ${spec.fuzzy.threshold}`;
1287
+ return sql`(${exact} OR ${spec.fuzzy.threshold > PG_TRGM_WORD_SIMILARITY_DEFAULT ? sql`(${needle} OPERATOR(public.<%) ${fuzzyColumn} AND ${similar})` : similar})`;
1288
+ }
1289
+ /**
1290
+ * `websearch_to_tsquery(<config>, <normalized search string>)`.
1291
+ *
1292
+ * Split out because the ranking expression needs the identical query — a
1293
+ * row ranked against a different tsquery than it was matched against is a
1294
+ * ranking of something else.
1295
+ */
1296
+ static normalizedTsQuery(searchString, spec) {
1297
+ const normalized = spec.unaccent ? sql`${sql.raw(SEARCH_UNACCENT_FN)}(${searchString})` : sql`${searchString}`;
1298
+ return sql`websearch_to_tsquery(${spec.language}, ${normalized})`;
1299
+ }
1300
+ /**
1301
+ * A JSONB array of `{ field, snippet }` naming which declared fields matched
1302
+ * and showing the text around each hit — what backs `_matches`.
1303
+ *
1304
+ * A ranked list answers "which rows", never "why this row". For a talent
1305
+ * pool that difference is the product: a candidate surfacing for
1306
+ * "iso 14001" on a *certification* is a different candidate from one whose
1307
+ * bio happens to mention the standard, and the score cannot tell them apart.
1308
+ *
1309
+ * Built as a correlated subquery over a `VALUES` list of the declared
1310
+ * fields, rather than one `CASE` per field, so the shape does not change
1311
+ * with the number of fields and the empty result is a plain `[]`.
1312
+ *
1313
+ * `ts_headline` runs over the same normalized text that was indexed. Over
1314
+ * the *original* text it would find nothing to mark whenever `unaccent` is
1315
+ * on — the query's lexemes are folded and the document's are not — and
1316
+ * would return the text silently unhighlighted. Folded-but-marked beats
1317
+ * pretty-but-inert.
1318
+ *
1319
+ * Undefined when the collection has not opted in, when the column is not on
1320
+ * the table yet, or when the caller did not ask: this costs a `ts_headline`
1321
+ * per field per row and `ts_headline` re-parses the document.
1322
+ */
1323
+ static buildSearchMatchesExpression(searchString, table, collection) {
1324
+ let spec;
1325
+ try {
1326
+ spec = buildSearchColumnSpec(collection);
1327
+ } catch {
1328
+ return;
1329
+ }
1330
+ if (!spec || spec.fields.length === 0) return void 0;
1331
+ if (!table[spec.column]) return void 0;
1332
+ const query = DrizzleConditionBuilder.normalizedTsQuery(searchString, spec);
1333
+ const config = sql`${spec.language}`;
1334
+ const rows = spec.fields.map((f, i) => sql`(${i}, ${f.path}, ${sql.raw(f.textSql)})`);
1335
+ return sql`(
1336
+ SELECT coalesce(jsonb_agg(s.m ORDER BY f.ord), '[]'::jsonb)
1337
+ FROM (VALUES ${sql.join(rows, sql`, `)}) AS f(ord, path, txt)
1338
+ CROSS JOIN LATERAL (
1339
+ SELECT jsonb_build_object(
1340
+ 'field', f.path,
1341
+ 'snippet', ts_headline(${config}::regconfig, f.txt, ${query},
1342
+ 'StartSel=<mark>,StopSel=</mark>,MaxWords=14,MinWords=1,MaxFragments=1,FragmentDelimiter= … ')
1343
+ ) AS m
1344
+ WHERE to_tsvector(${config}::regconfig, f.txt) @@ ${query}
1345
+ ) s
1346
+ )`;
1347
+ }
1348
+ /**
1349
+ * `ts_rank(<column>, <query>)` for the collection, or undefined when it has
1350
+ * not opted in. This is what backs `orderBy: ["_score", "desc"]`.
1351
+ */
1352
+ static buildSearchRankExpression(searchString, table, collection) {
1353
+ let spec;
1354
+ try {
1355
+ spec = buildSearchColumnSpec(collection);
1356
+ } catch {
1357
+ return;
1358
+ }
1359
+ if (!spec) return void 0;
1360
+ const column = table[spec.column];
1361
+ if (!column) return void 0;
1362
+ const rank = sql`ts_rank(${column}, ${DrizzleConditionBuilder.normalizedTsQuery(searchString, spec)})`;
1363
+ if (!spec.fuzzy) return rank;
1364
+ const fuzzyColumn = table[spec.fuzzy.column];
1365
+ if (!fuzzyColumn) return rank;
1366
+ return sql`(${rank} + public.word_similarity(${spec.unaccent ? sql`${sql.raw(SEARCH_UNACCENT_FN)}(${searchString})` : sql`${searchString}`}, ${fuzzyColumn}))`;
1367
+ }
1368
+ /**
1256
1369
  * Build a unique field check condition
1257
1370
  */
1258
1371
  static buildUniqueFieldCondition(fieldColumn, value, idColumn, excludeId) {
@@ -1350,10 +1463,19 @@ var DrizzleConditionBuilder = class {
1350
1463
  * - `orderBy`: SQL expression to ORDER BY distance (ascending = closest first)
1351
1464
  * - `filter`: optional WHERE clause for distance threshold
1352
1465
  * - `distanceSelect`: SQL expression for selecting the distance as `_distance`
1466
+ *
1467
+ * `property` is `?vector_search=` off the querystring, so it is an untrusted
1468
+ * *name*, and it used to be looked up straight in the drizzle table object.
1469
+ * Two ways that went wrong, both answering 500 to a malformed request:
1470
+ * `?vector_search=title` built `"title" <=> '[1,2]'::vector`, which the
1471
+ * database rejects with "operator does not exist"; and a table object also
1472
+ * carries non-column keys (`_`, methods), which passed the `if (!column)`
1473
+ * guard and compiled to nonsense. The name is resolved against the table's
1474
+ * actual columns and required to be a `vector` — anything else is the
1475
+ * caller's mistake and gets a 400 that says so.
1353
1476
  */
1354
1477
  static buildVectorSearchConditions(table, vectorSearch) {
1355
- const column = table[vectorSearch.property];
1356
- if (!column) throw new Error(`Vector column '${vectorSearch.property}' not found in table`);
1478
+ const column = DrizzleConditionBuilder.resolveVectorColumn(table, vectorSearch.property);
1357
1479
  if (!Array.isArray(vectorSearch.vector) || vectorSearch.vector.length === 0 || !vectorSearch.vector.every((n) => typeof n === "number" && Number.isFinite(n))) throw new Error("Vector search requires a non-empty array of finite numbers");
1358
1480
  const vectorLiteral = `'[${vectorSearch.vector.join(",")}]'::vector`;
1359
1481
  const distanceFn = vectorSearch.distance || "cosine";
@@ -1375,7 +1497,33 @@ var DrizzleConditionBuilder = class {
1375
1497
  distanceSelect: sql`(${column} ${sql.raw(operator)} ${sql.raw(vectorLiteral)})`
1376
1498
  };
1377
1499
  }
1500
+ /**
1501
+ * The `vector` column a request named, or a 400 explaining what it named.
1502
+ *
1503
+ * `getTableColumns` rather than a key lookup: it returns only the columns,
1504
+ * so `_`, `getSQL` and every other property of a drizzle table stop looking
1505
+ * like candidates. The type check is on the *physical* column
1506
+ * (`vector(1536)`) rather than on the declared property, so it holds for an
1507
+ * introspected collection too, where the property carries no Rebase type.
1508
+ */
1509
+ static resolveVectorColumn(table, property) {
1510
+ const columns = getTableColumns(table);
1511
+ const column = columns?.[property];
1512
+ if (!column) {
1513
+ const known = Object.entries(columns ?? {}).filter(([, c]) => isVectorColumn(c)).map(([name]) => name);
1514
+ throw ApiError.badRequest(`Unknown vector property "${property}". ` + (known.length > 0 ? `This collection's vector properties are: ${known.join(", ")}.` : "This collection declares no `vector` property to search."), "UNKNOWN_VECTOR_PROPERTY");
1515
+ }
1516
+ if (!isVectorColumn(column)) throw ApiError.badRequest(`Property "${property}" is not a vector column (it is \`${columnSqlType(column) || "unknown"}\`), so it has no distance operator. Name the property declared as \`{ type: "vector" }\`.`, "UNKNOWN_VECTOR_PROPERTY");
1517
+ return column;
1518
+ }
1519
+ };
1520
+ /** The column's SQL type, for a value that may not be a drizzle column at all. */
1521
+ var columnSqlType = (column) => {
1522
+ const getSQLType = column?.getSQLType;
1523
+ return typeof getSQLType === "function" ? getSQLType.call(column).toLowerCase() : "";
1378
1524
  };
1525
+ /** True for `vector(1536)` and its pgvector siblings, whatever the width. */
1526
+ var isVectorColumn = (column) => /^(vector|halfvec|sparsevec)\b/.test(columnSqlType(column));
1379
1527
  /**
1380
1528
  * Alias for DrizzleConditionBuilder for consistent naming with other database implementations.
1381
1529
  * This allows code to use PostgresConditionBuilder alongside future MongoConditionBuilder, etc.
@@ -1428,6 +1576,7 @@ function serializeDataToServer(row, properties, collection, registry) {
1428
1576
  });
1429
1577
  for (const [key, value] of Object.entries(row)) {
1430
1578
  if (isPrototypePollutingKey(key)) continue;
1579
+ if (value === void 0) continue;
1431
1580
  const property = properties[key];
1432
1581
  const effectiveValue = foreignKeys.has(key) && value === "" ? null : value;
1433
1582
  if (!property) {
@@ -1438,11 +1587,11 @@ function serializeDataToServer(row, properties, collection, registry) {
1438
1587
  const relation = findRelation(resolvedRelations, key);
1439
1588
  if (relation) {
1440
1589
  if (relation.kind === "belongsTo") {
1441
- const serializedValue = serializePropertyToServer(effectiveValue, property);
1590
+ const serializedValue = serializePropertyToServer(effectiveValue, property, key);
1442
1591
  if (serializedValue !== void 0) result[relation.localKey] = serializedValue;
1443
1592
  continue;
1444
1593
  } else if (hasForeignKeyOnTarget(relation)) {
1445
- const serializedValue = serializePropertyToServer(effectiveValue, property);
1594
+ const serializedValue = serializePropertyToServer(effectiveValue, property, key);
1446
1595
  inverseRelationUpdates.push({
1447
1596
  relationKey: key,
1448
1597
  relation,
@@ -1450,7 +1599,7 @@ function serializeDataToServer(row, properties, collection, registry) {
1450
1599
  });
1451
1600
  continue;
1452
1601
  } else if (relation.kind === "via") {
1453
- const serializedValue = serializePropertyToServer(effectiveValue, property);
1602
+ const serializedValue = serializePropertyToServer(effectiveValue, property, key);
1454
1603
  if (relation.cardinality === "one") joinPathRelationUpdates.push({
1455
1604
  relationKey: key,
1456
1605
  relation,
@@ -1465,7 +1614,7 @@ function serializeDataToServer(row, properties, collection, registry) {
1465
1614
  }
1466
1615
  }
1467
1616
  }
1468
- result[key] = serializePropertyToServer(effectiveValue, property);
1617
+ result[key] = serializePropertyToServer(effectiveValue, property, key);
1469
1618
  }
1470
1619
  return {
1471
1620
  scalarData: result,
@@ -1474,19 +1623,39 @@ function serializeDataToServer(row, properties, collection, registry) {
1474
1623
  };
1475
1624
  }
1476
1625
  /**
1477
- * Serialize a single property value for database storage
1626
+ * How to name a rejected value in an error, without quoting it back.
1627
+ *
1628
+ * The value may be anything the caller sent, including a secret in the wrong
1629
+ * field, so the message describes its shape rather than echoing it — an echoed
1630
+ * value ends up in logs and in error-reporting services.
1631
+ */
1632
+ function describeValue(value) {
1633
+ if (value === null) return "null";
1634
+ if (Array.isArray(value)) return "an array";
1635
+ if (value instanceof Date) return "a date";
1636
+ const type = typeof value;
1637
+ return type === "object" ? "an object" : `a ${type}`;
1638
+ }
1639
+ /**
1640
+ * Serialize a single property value for database storage.
1641
+ *
1642
+ * `propertyKey` is only ever used to phrase errors and warnings. Without it the
1643
+ * one trace a bad value left was `Expected array value for array property, got
1644
+ * string` — no collection, no property, no value, which in the log of a
1645
+ * thousand-row import names nothing at all.
1478
1646
  */
1479
- function serializePropertyToServer(value, property) {
1647
+ function serializePropertyToServer(value, property, propertyKey) {
1480
1648
  if (value === null || value === void 0) return value;
1649
+ const fieldLabel = propertyKey ? `'${propertyKey}'` : `a '${property.type}' field`;
1481
1650
  switch (property.type) {
1482
1651
  case "relation":
1483
- if (Array.isArray(value)) return value.map((v) => serializePropertyToServer(v, property));
1652
+ if (Array.isArray(value)) return value.map((v) => serializePropertyToServer(v, property, propertyKey));
1484
1653
  else if (typeof value === "object" && value !== null && "id" in value) return value.id;
1485
1654
  if (value === "") return null;
1486
1655
  return value;
1487
1656
  case "array":
1488
1657
  if (Array.isArray(value)) {
1489
- if (property.of) return value.map((item) => serializePropertyToServer(item, property.of));
1658
+ if (property.of) return value.map((item) => serializePropertyToServer(item, property.of, propertyKey));
1490
1659
  else if (property.oneOf) {
1491
1660
  const typeField = property.oneOf.typeField ?? "type";
1492
1661
  const valueField = property.oneOf.valueField ?? "value";
@@ -1499,20 +1668,28 @@ function serializePropertyToServer(value, property) {
1499
1668
  if (!type || !childProperty) return e;
1500
1669
  return {
1501
1670
  [typeField]: type,
1502
- [valueField]: serializePropertyToServer(rec[valueField], childProperty)
1671
+ [valueField]: serializePropertyToServer(rec[valueField], childProperty, propertyKey)
1503
1672
  };
1504
1673
  });
1505
1674
  }
1506
1675
  return value;
1507
1676
  }
1508
- logger.warn(`Expected array value for array property, got ${typeof value}. Coercing to empty array.`);
1509
- return [];
1677
+ throw ApiError.badRequest(`${fieldLabel} expects an array, but received ${describeValue(value)}.`, "VALIDATION_INVALID_VALUE");
1678
+ case "geopoint": {
1679
+ if (typeof value !== "object" || Array.isArray(value)) throw ApiError.badRequest(`${fieldLabel} expects a geopoint object with \`latitude\` and \`longitude\`, but received ${describeValue(value)}.`, "VALIDATION_INVALID_VALUE");
1680
+ const point = value;
1681
+ if (typeof point.latitude !== "number" || typeof point.longitude !== "number") throw ApiError.badRequest(`${fieldLabel} expects a geopoint object with numeric \`latitude\` and \`longitude\`.`, "VALIDATION_INVALID_VALUE");
1682
+ return {
1683
+ latitude: point.latitude,
1684
+ longitude: point.longitude
1685
+ };
1686
+ }
1510
1687
  case "map":
1511
1688
  if (typeof value === "object" && property.properties) {
1512
1689
  const result = {};
1513
1690
  for (const [subKey, subValue] of Object.entries(value)) {
1514
1691
  const subProperty = property.properties[subKey];
1515
- if (subProperty) result[subKey] = serializePropertyToServer(subValue, subProperty);
1692
+ if (subProperty) result[subKey] = serializePropertyToServer(subValue, subProperty, propertyKey ? `${propertyKey}.${subKey}` : subKey);
1516
1693
  else result[subKey] = subValue;
1517
1694
  }
1518
1695
  return result;
@@ -1750,6 +1927,7 @@ function parsePropertyFromServer(value, property, collection, propertyKey) {
1750
1927
  return isNaN(parsed) ? null : parsed;
1751
1928
  }
1752
1929
  return value;
1930
+ case "geopoint": return value;
1753
1931
  case "vector": {
1754
1932
  let nums = [];
1755
1933
  if (typeof value === "string") nums = value.slice(1, -1).split(",").map(Number);
@@ -1793,6 +1971,18 @@ function parsePropertyFromServer(value, property, collection, propertyKey) {
1793
1971
  * from the result (used by `normalizeDbValues` where
1794
1972
  * Drizzle's relational API already hydrates them).
1795
1973
  */
1974
+ /**
1975
+ * Keys a query computes and attaches to a row, rather than reads from a column.
1976
+ *
1977
+ * An explicit set rather than a `_` prefix rule: a user's column may perfectly
1978
+ * well be called `_internal`, and passing it through here would put a value on
1979
+ * the row that no property describes and nothing downstream knows how to type.
1980
+ */
1981
+ var QUERY_METADATA_KEYS = /* @__PURE__ */ new Set([
1982
+ "_score",
1983
+ "_distance",
1984
+ "_matches"
1985
+ ]);
1796
1986
  function normalizeScalarValues(data, properties, collection, resolvedRelations, options) {
1797
1987
  const result = {};
1798
1988
  const internalFKColumns = /* @__PURE__ */ new Set();
@@ -1804,6 +1994,10 @@ function normalizeScalarValues(data, properties, collection, resolvedRelations,
1804
1994
  result[key] = value === null ? null : typeof value === "number" ? value : String(value);
1805
1995
  continue;
1806
1996
  }
1997
+ if (QUERY_METADATA_KEYS.has(key)) {
1998
+ result[key] = value;
1999
+ continue;
2000
+ }
1807
2001
  const property = properties[key];
1808
2002
  if (!property) continue;
1809
2003
  if (options.skipRelations && property.type === "relation") continue;
@@ -2056,7 +2250,7 @@ var RelationService = class {
2056
2250
  let query = this.db.select().from(targetTable).$dynamic();
2057
2251
  const additionalFilters = [];
2058
2252
  if (options.searchString) {
2059
- const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, targetCollection.properties, targetTable);
2253
+ const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, targetCollection.properties, targetTable, targetCollection);
2060
2254
  if (searchConditions.length === 0) return [];
2061
2255
  const searchCombined = DrizzleConditionBuilder.combineConditionsWithOr(searchConditions);
2062
2256
  if (searchCombined) additionalFilters.push(searchCombined);
@@ -2356,6 +2550,55 @@ var RelationService = class {
2356
2550
  return resultMap;
2357
2551
  }
2358
2552
  /**
2553
+ * Bring one row's junction links in line with the ids a save carried,
2554
+ * by diffing against what is stored rather than replacing the lot.
2555
+ *
2556
+ * The old shape was `DELETE every link for this parent` followed by
2557
+ * `INSERT what the client sent`, which makes a save of the parent a full
2558
+ * replacement of the membership set from a list the browser assembled out
2559
+ * of a read it did earlier. Three things follow from that, and the diff
2560
+ * closes all three:
2561
+ *
2562
+ * - **Lost update.** Two editors with post 7 open: A adds tag X and saves;
2563
+ * B saves any field and the whole set is rewritten from B's older list,
2564
+ * dropping X with nothing to show for it. A diff only names the ids that
2565
+ * actually changed, so edits to disjoint tags no longer collide.
2566
+ * - **Partial read, partial delete.** The read that fills the form runs
2567
+ * under RLS, so a user who may edit the parent but cannot *see* some of
2568
+ * the linked rows gets a shorter list — and writing it back deleted the
2569
+ * links they were never shown. The DELETE now names ids instead of
2570
+ * "everything for this parent", and the select that produces them runs
2571
+ * in this same transaction under the same policies, so a link the caller
2572
+ * cannot read is in neither list and survives the save.
2573
+ * - **Junction payload columns.** A junction carrying its own columns
2574
+ * (`position`, `role`, `created_at`) lost them on every save, because
2575
+ * every row was re-inserted with only the two keys. Untouched links are
2576
+ * now left alone.
2577
+ *
2578
+ * The insert is `ON CONFLICT DO NOTHING` so that two sessions adding the
2579
+ * same link concurrently is a no-op rather than a unique violation.
2580
+ */
2581
+ async syncJunctionLinks(tx, junctionTable, sourceJunctionColumn, targetJunctionColumn, parsedParentId, parsedTargetIds) {
2582
+ const existingRows = await tx.select({ targetId: targetJunctionColumn }).from(junctionTable).where(eq(sourceJunctionColumn, parsedParentId));
2583
+ const existingById = /* @__PURE__ */ new Map();
2584
+ for (const row of existingRows) {
2585
+ if (row.targetId === null || row.targetId === void 0) continue;
2586
+ existingById.set(String(row.targetId), row.targetId);
2587
+ }
2588
+ const wantedById = /* @__PURE__ */ new Map();
2589
+ for (const targetId of parsedTargetIds) {
2590
+ if (targetId === null || targetId === void 0) continue;
2591
+ wantedById.set(String(targetId), targetId);
2592
+ }
2593
+ const removed = [...existingById.entries()].filter(([key]) => !wantedById.has(key)).map(([, value]) => value);
2594
+ const added = [...wantedById.entries()].filter(([key]) => !existingById.has(key)).map(([, value]) => value);
2595
+ if (removed.length > 0) await tx.delete(junctionTable).where(and(eq(sourceJunctionColumn, parsedParentId), inArray(targetJunctionColumn, removed)));
2596
+ if (added.length > 0) await tx.insert(junctionTable).values(added.map((targetId) => ({
2597
+ [sourceJunctionColumn.name]: parsedParentId,
2598
+ [targetJunctionColumn.name]: targetId
2599
+ }))).onConflictDoNothing();
2600
+ }
2601
+ /**
2359
2602
  * Update many-to-many and junction relations
2360
2603
  */
2361
2604
  async updateRelationsUsingJoins(tx, collection, id, relationValues) {
@@ -2400,16 +2643,13 @@ var RelationService = class {
2400
2643
  const parentPks = requirePrimaryKeys(collection, this.registry);
2401
2644
  const parentIdInfo = parentPks[0];
2402
2645
  const parsedParentId = parseIdValues(id, parentPks)[parentIdInfo.fieldName];
2403
- await tx.delete(junctionTable).where(eq(sourceJunctionColumn, parsedParentId));
2646
+ let parsedTargetIds = [];
2404
2647
  if (targetEntityIds.length > 0) {
2405
2648
  const targetPks = requirePrimaryKeys(targetCollection, this.registry);
2406
2649
  const targetIdInfo = targetPks[0];
2407
- const newLinks = targetEntityIds.map((id) => parseIdValues(id, targetPks)[targetIdInfo.fieldName]).map((targetId) => ({
2408
- [sourceJunctionColumn.name]: parsedParentId,
2409
- [targetJunctionColumn.name]: targetId
2410
- }));
2411
- if (newLinks.length > 0) await tx.insert(junctionTable).values(newLinks);
2650
+ parsedTargetIds = targetEntityIds.map((id) => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
2412
2651
  }
2652
+ await this.syncJunctionLinks(tx, junctionTable, sourceJunctionColumn, targetJunctionColumn, parsedParentId, parsedTargetIds);
2413
2653
  } else if (relation.kind === "manyToMany") {
2414
2654
  const junctionTable = this.registry.getTable(relation.through.table);
2415
2655
  if (!junctionTable) {
@@ -2425,16 +2665,13 @@ var RelationService = class {
2425
2665
  const parentPks = requirePrimaryKeys(collection, this.registry);
2426
2666
  const parentIdInfo = parentPks[0];
2427
2667
  const parsedParentId = parseIdValues(id, parentPks)[parentIdInfo.fieldName];
2428
- await tx.delete(junctionTable).where(eq(sourceJunctionColumn, parsedParentId));
2668
+ let parsedTargetIds = [];
2429
2669
  if (targetEntityIds.length > 0) {
2430
2670
  const targetPks = requirePrimaryKeys(targetCollection, this.registry);
2431
2671
  const targetIdInfo = targetPks[0];
2432
- const newLinks = targetEntityIds.map((id) => parseIdValues(id, targetPks)[targetIdInfo.fieldName]).map((targetId) => ({
2433
- [sourceJunctionColumn.name]: parsedParentId,
2434
- [targetJunctionColumn.name]: targetId
2435
- }));
2436
- if (newLinks.length > 0) await tx.insert(junctionTable).values(newLinks);
2672
+ parsedTargetIds = targetEntityIds.map((id) => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
2437
2673
  }
2674
+ await this.syncJunctionLinks(tx, junctionTable, sourceJunctionColumn, targetJunctionColumn, parsedParentId, parsedTargetIds);
2438
2675
  } else if (relation.cardinality === "many" && hasForeignKeyOnTarget(relation)) {
2439
2676
  const targetTable = getTableForCollection(targetCollection, this.registry);
2440
2677
  const targetPks = requirePrimaryKeys(targetCollection, this.registry);
@@ -2449,7 +2686,7 @@ var RelationService = class {
2449
2686
  if (parentKeyValue === void 0) throw new Error(`Cannot write relation '${key}' on '${collection.slug}': row '${id}' has no value in \`sourceKey: "${sourceKeyField(relation, collection, this.registry)}"\`, so there is nothing for the related rows to point at.`);
2450
2687
  if (targetEntityIds.length > 0) {
2451
2688
  const parsedTargetIds = targetEntityIds.map((id) => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
2452
- await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(and(eq(fkCol, parentKeyValue), sql`${targetIdCol} NOT IN (${sql.join(parsedTargetIds)})`));
2689
+ await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(and(eq(fkCol, parentKeyValue), notInArray(targetIdCol, parsedTargetIds)));
2453
2690
  await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: parentKeyValue }).where(inArray(targetIdCol, parsedTargetIds));
2454
2691
  } else await tx.update(targetTable).set({ [relation.foreignKeyOnTarget]: null }).where(eq(fkCol, parentKeyValue));
2455
2692
  } else logger.warn(`Many relation '${key}' in collection '${collection.slug}' lacks write configuration and will be skipped during save.`);
@@ -2538,25 +2775,17 @@ var RelationService = class {
2538
2775
  const sourcePks = requirePrimaryKeys(sourceCollection, this.registry);
2539
2776
  const sourceIdInfo = sourcePks[0];
2540
2777
  const parsedSourceId = parseIdValues(sourceEntityId, sourcePks)[sourceIdInfo.fieldName];
2541
- await tx.delete(junctionTable).where(eq(sourceJunctionColumn, parsedSourceId));
2778
+ let parsedTargetIds = [];
2542
2779
  if (newValue && Array.isArray(newValue) && newValue.length > 0) {
2543
2780
  const targetPks = requirePrimaryKeys(targetCollection, this.registry);
2544
2781
  const targetIdInfo = targetPks[0];
2545
- const newLinks = relationTargetIds(newValue, relation.relationName, sourceCollection.slug).map((id) => parseIdValues(id, targetPks)[targetIdInfo.fieldName]).map((targetId) => ({
2546
- [sourceJunctionColumn.name]: parsedSourceId,
2547
- [targetJunctionColumn.name]: targetId
2548
- }));
2549
- if (newLinks.length > 0) await tx.insert(junctionTable).values(newLinks);
2782
+ parsedTargetIds = relationTargetIds(newValue, relation.relationName, sourceCollection.slug).map((id) => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
2550
2783
  } else if (newValue && !Array.isArray(newValue)) {
2551
2784
  const targetPks = requirePrimaryKeys(targetCollection, this.registry);
2552
2785
  const targetIdInfo = targetPks[0];
2553
- const parsedTargetId = parseIdValues(typeof newValue === "object" && newValue !== null ? newValue.id : newValue, targetPks)[targetIdInfo.fieldName];
2554
- const newLink = {
2555
- [sourceJunctionColumn.name]: parsedSourceId,
2556
- [targetJunctionColumn.name]: parsedTargetId
2557
- };
2558
- await tx.insert(junctionTable).values(newLink);
2786
+ parsedTargetIds = [parseIdValues(typeof newValue === "object" && newValue !== null ? newValue.id : newValue, targetPks)[targetIdInfo.fieldName]];
2559
2787
  }
2788
+ await this.syncJunctionLinks(tx, junctionTable, sourceJunctionColumn, targetJunctionColumn, parsedSourceId, parsedTargetIds);
2560
2789
  }
2561
2790
  } catch (error) {
2562
2791
  logger.error(`Failed to update inverse joinPath relation '${relation.relationName}'`, { error });
@@ -2582,16 +2811,14 @@ var RelationService = class {
2582
2811
  const sourcePks = requirePrimaryKeys(sourceCollection, this.registry);
2583
2812
  const sourceIdInfo = sourcePks[0];
2584
2813
  const parsedSourceId = parseIdValues(sourceEntityId, sourcePks)[sourceIdInfo.fieldName];
2585
- await tx.delete(junctionTable).where(eq(sourceJunctionColumn, parsedSourceId));
2586
- if (newValue && Array.isArray(newValue) && newValue.length > 0) {
2814
+ const targetEntityIds = Array.isArray(newValue) ? relationTargetIds(newValue, relation.relationName, sourceCollection.slug) : [];
2815
+ let parsedTargetIds = [];
2816
+ if (targetEntityIds.length > 0) {
2587
2817
  const targetPks = requirePrimaryKeys(targetCollection, this.registry);
2588
2818
  const targetIdInfo = targetPks[0];
2589
- const newLinks = relationTargetIds(newValue, relation.relationName, sourceCollection.slug).map((id) => parseIdValues(id, targetPks)[targetIdInfo.fieldName]).map((targetId) => ({
2590
- [sourceJunctionColumn.name]: parsedSourceId,
2591
- [targetJunctionColumn.name]: targetId
2592
- }));
2593
- if (newLinks.length > 0) await tx.insert(junctionTable).values(newLinks);
2819
+ parsedTargetIds = targetEntityIds.map((id) => parseIdValues(id, targetPks)[targetIdInfo.fieldName]);
2594
2820
  }
2821
+ await this.syncJunctionLinks(tx, junctionTable, sourceJunctionColumn, targetJunctionColumn, parsedSourceId, parsedTargetIds);
2595
2822
  } catch (error) {
2596
2823
  logger.error(`Failed to update many-to-many inverse relation '${relation.relationName}'`, { error });
2597
2824
  throw error;
@@ -3142,8 +3369,7 @@ function sanitizeErrorForClient(error, context) {
3142
3369
  column: pgError.column,
3143
3370
  table: pgError.table,
3144
3371
  constraint: pgError.constraint,
3145
- dataType: pgError.dataType,
3146
- drizzleMessage: error instanceof Error ? error.message : String(error)
3372
+ dataType: pgError.dataType
3147
3373
  });
3148
3374
  return pgErrorToFriendlyMessage(pgError, context);
3149
3375
  }
@@ -3162,7 +3388,7 @@ function sanitizeErrorForClient(error, context) {
3162
3388
  * Service for handling all row read operations.
3163
3389
  * Handles fetching, searching, counting, and filtering rows.
3164
3390
  */
3165
- var FetchService = class {
3391
+ var FetchService = class FetchService {
3166
3392
  db;
3167
3393
  registry;
3168
3394
  relationService;
@@ -3235,6 +3461,24 @@ var FetchService = class {
3235
3461
  * and skips rows rather than erroring. The guesses stay, last, for a
3236
3462
  * caller that hands over no collection to resolve against.
3237
3463
  */
3464
+ /**
3465
+ * The ORDER BY target, which may be relevance rather than a column.
3466
+ *
3467
+ * `_score` is only meaningful for a collection that declared a `search`
3468
+ * block *and* for a request that carried a search string — ranking rows
3469
+ * against no query ranks them all at zero. Outside those two conditions it
3470
+ * is an unknown field and gets the same 400 as any other typo, which is the
3471
+ * behaviour that matters: a sort that is silently dropped returns 200 with
3472
+ * rows in arbitrary order, and paging over that repeats and skips rows.
3473
+ */
3474
+ static SCORE_FIELD = "_score";
3475
+ resolveOrderTarget(table, orderBy, collection, searchString) {
3476
+ if (orderBy === FetchService.SCORE_FIELD && collection && searchString) {
3477
+ const rank = DrizzleConditionBuilder.buildSearchRankExpression(searchString, table, collection);
3478
+ if (rank) return rank;
3479
+ }
3480
+ return this.resolveOrderByField(table, orderBy, collection);
3481
+ }
3238
3482
  resolveOrderByField(table, orderBy, collection) {
3239
3483
  const columnAt = (key) => (key in table ? table[key] : void 0) || void 0;
3240
3484
  const direct = columnAt(orderBy);
@@ -3318,6 +3562,7 @@ var FetchService = class {
3318
3562
  row[key] = createRelationRefWithData(e.id, e.path, e);
3319
3563
  } else if (relation.cardinality === "many") row[key] = relatedRows.map((e) => createRelationRefWithData(e.id, e.path, e));
3320
3564
  } catch (e) {
3565
+ if (reachedDatabase(e)) throw e;
3321
3566
  logger.warn(`Could not resolve joinPath relation '${key}'`, { error: e });
3322
3567
  }
3323
3568
  });
@@ -3353,6 +3598,7 @@ var FetchService = class {
3353
3598
  for (const row of addressable) row[key] = (resultMap.get(String(parentIdOf(row))) || []).map((e) => ({ ...e.values }));
3354
3599
  }
3355
3600
  } catch (e) {
3601
+ if (reachedDatabase(e)) throw e;
3356
3602
  logger.warn(`Could not batch resolve joinPath relation '${key}' for REST`, { error: e });
3357
3603
  }
3358
3604
  }
@@ -3362,12 +3608,14 @@ var FetchService = class {
3362
3608
  */
3363
3609
  buildDrizzleQueryOptions(table, idField, idInfo, options, collectionPath, withConfig, scopeCondition) {
3364
3610
  const queryOpts = {};
3611
+ const hidden = hiddenColumnsOption(getTableColumns(table), this.registry.getCollectionByPath(collectionPath) ?? void 0);
3612
+ if (hidden) queryOpts.columns = hidden;
3365
3613
  if (withConfig) queryOpts.with = withConfig;
3366
3614
  const allConditions = [];
3367
3615
  if (scopeCondition) allConditions.push(scopeCondition);
3368
3616
  if (options.searchString) {
3369
3617
  const collection = getCollectionByPath(collectionPath, this.registry);
3370
- const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table);
3618
+ const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table, collection);
3371
3619
  if (searchConditions.length === 0) {
3372
3620
  queryOpts.where = and(eq(idField, -99999999));
3373
3621
  return queryOpts;
@@ -3390,7 +3638,7 @@ var FetchService = class {
3390
3638
  const orderExpressions = [];
3391
3639
  if (options.orderBy) {
3392
3640
  const collection = getCollectionByPath(collectionPath, this.registry);
3393
- const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
3641
+ const orderByField = this.resolveOrderTarget(table, options.orderBy, collection, options.searchString);
3394
3642
  if (orderByField) orderExpressions.push(options.order === "asc" ? asc(orderByField) : desc(orderByField));
3395
3643
  }
3396
3644
  orderExpressions.push(desc(idField));
@@ -3407,6 +3655,7 @@ var FetchService = class {
3407
3655
  if (!options.startAfter) return [];
3408
3656
  const cursor = options.startAfter;
3409
3657
  if (options.orderBy) {
3658
+ if (options.orderBy === FetchService.SCORE_FIELD) throw ApiError.badRequest("Cursor pagination (`startAfter`) cannot be combined with `orderBy: \"_score\"`. Relevance is computed per query rather than stored, so it cannot key a cursor. Use `limit`/`offset` for relevance-ordered pages, or order by a column.", "SCORE_CURSOR_UNSUPPORTED", { field: FetchService.SCORE_FIELD });
3410
3659
  const collection = collectionPath ? getCollectionByPath(collectionPath, this.registry) : void 0;
3411
3660
  const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
3412
3661
  if (orderByField) {
@@ -3477,9 +3726,11 @@ var FetchService = class {
3477
3726
  const qb = this.getQueryBuilder(tableName);
3478
3727
  if (qb) try {
3479
3728
  const withConfig = this.buildWithConfig(collection);
3729
+ const hidden = hiddenColumnsOption(getTableColumns(table), collection);
3480
3730
  const row = await qb.findFirst({
3481
3731
  where: eq(idField, parsedId),
3482
- with: withConfig
3732
+ with: withConfig,
3733
+ ...hidden ? { columns: hidden } : {}
3483
3734
  });
3484
3735
  if (!row) return void 0;
3485
3736
  const flatRow = toFlatRow(row, collection, this.registry);
@@ -3493,7 +3744,8 @@ var FetchService = class {
3493
3744
  if (reachedDatabase(e)) throw e;
3494
3745
  logger.warn(`[FetchService] db.query.findFirst failed for ${collectionPath}, falling back to db.select`, { error: e });
3495
3746
  }
3496
- const result = await this.db.select().from(table).where(eq(idField, parsedId)).limit(1);
3747
+ const visibleOne = visibleColumnProjection(getTableColumns(table), collection);
3748
+ const result = await this.db.select(visibleOne).from(table).where(eq(idField, parsedId)).limit(1);
3497
3749
  if (result.length === 0) return void 0;
3498
3750
  const raw = result[0];
3499
3751
  const values = await parseDataFromServer(raw, collection, this.db, this.registry);
@@ -3511,6 +3763,7 @@ var FetchService = class {
3511
3763
  values[key] = createRelationRef(e.id, e.path);
3512
3764
  }
3513
3765
  } catch (e) {
3766
+ if (reachedDatabase(e)) throw e;
3514
3767
  logger.warn(`Could not resolve one-to-one relation property: ${key}`, { error: e });
3515
3768
  }
3516
3769
  }
@@ -3549,14 +3802,21 @@ var FetchService = class {
3549
3802
  }
3550
3803
  let vectorMeta;
3551
3804
  if (options.vectorSearch) vectorMeta = DrizzleConditionBuilder.buildVectorSearchConditions(table, options.vectorSearch);
3805
+ const visible = visibleColumnProjection(getTableColumns(table), collection);
3806
+ const rankSelect = options.searchString ? DrizzleConditionBuilder.buildSearchRankExpression(options.searchString, table, collection) : void 0;
3807
+ const matchesSelect = options.searchString && options.searchExplain ? DrizzleConditionBuilder.buildSearchMatchesExpression(options.searchString, table, collection) : void 0;
3552
3808
  let query = vectorMeta ? this.db.select({
3553
- table_row: table,
3809
+ table_row: visible ?? table,
3554
3810
  _distance: vectorMeta.distanceSelect
3555
- }).from(table).$dynamic() : this.db.select().from(table).$dynamic();
3811
+ }).from(table).$dynamic() : rankSelect ? this.db.select({
3812
+ table_row: visible ?? table,
3813
+ _score: rankSelect,
3814
+ ...matchesSelect ? { _matches: matchesSelect } : {}
3815
+ }).from(table).$dynamic() : visible ? this.db.select(visible).from(table).$dynamic() : this.db.select().from(table).$dynamic();
3556
3816
  const allConditions = [];
3557
3817
  if (scopeCondition) allConditions.push(scopeCondition);
3558
3818
  if (options.searchString) {
3559
- const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table);
3819
+ const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table, collection);
3560
3820
  if (searchConditions.length === 0) return [];
3561
3821
  allConditions.push(DrizzleConditionBuilder.combineConditionsWithOr(searchConditions));
3562
3822
  }
@@ -3576,7 +3836,7 @@ var FetchService = class {
3576
3836
  const orderExpressions = [];
3577
3837
  if (vectorMeta) orderExpressions.push(asc(vectorMeta.orderBy));
3578
3838
  else if (options.orderBy) {
3579
- const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
3839
+ const orderByField = this.resolveOrderTarget(table, options.orderBy, collection, options.searchString);
3580
3840
  if (orderByField) orderExpressions.push(options.order === "asc" ? asc(orderByField) : desc(orderByField));
3581
3841
  }
3582
3842
  orderExpressions.push(desc(idField));
@@ -3596,6 +3856,10 @@ var FetchService = class {
3596
3856
  const results = vectorMeta ? rawResults.map((r) => ({
3597
3857
  ...r.table_row,
3598
3858
  _distance: typeof r._distance === "number" ? r._distance : parseFloat(String(r._distance))
3859
+ })) : rankSelect ? rawResults.map((r) => ({
3860
+ ...r.table_row,
3861
+ _score: typeof r._score === "number" ? r._score : parseFloat(String(r._score)),
3862
+ ...matchesSelect ? { _matches: r._matches ?? [] } : {}
3599
3863
  })) : rawResults;
3600
3864
  return this.processRowResults(results, collection, collectionPath, idInfo, options.databaseId, false, idInfoArray);
3601
3865
  }
@@ -3637,6 +3901,7 @@ var FetchService = class {
3637
3901
  if (relatedRow) item.values[key] = createRelationRefWithData(relatedRow.id, relatedRow.path, relatedRow);
3638
3902
  });
3639
3903
  } catch (e) {
3904
+ if (reachedDatabase(e)) throw e;
3640
3905
  logger.warn(`Could not batch load one-to-one relation property: ${key}`, { error: e });
3641
3906
  }
3642
3907
  }
@@ -3650,6 +3915,7 @@ var FetchService = class {
3650
3915
  item.values[key] = relatedRows.map((e) => createRelationRefWithData(e.id, e.path, e));
3651
3916
  });
3652
3917
  } catch (e) {
3918
+ if (reachedDatabase(e)) throw e;
3653
3919
  logger.warn(`Could not batch load many relation property: ${key}`, { error: e });
3654
3920
  }
3655
3921
  }
@@ -3687,7 +3953,7 @@ var FetchService = class {
3687
3953
  const allConditions = [];
3688
3954
  if (hop) allConditions.push(this.buildRelationScope(hop));
3689
3955
  if (options.searchString) {
3690
- const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table);
3956
+ const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table, collection);
3691
3957
  if (searchConditions.length === 0) return 0;
3692
3958
  allConditions.push(DrizzleConditionBuilder.combineConditionsWithOr(searchConditions));
3693
3959
  }
@@ -3783,6 +4049,7 @@ var FetchService = class {
3783
4049
  if (related) row[key] = { ...related.values };
3784
4050
  }
3785
4051
  } catch (e) {
4052
+ if (reachedDatabase(e)) throw e;
3786
4053
  logger.warn(`[include] Failed to batch load one-to-one '${key}'`, { error: e });
3787
4054
  }
3788
4055
  }
@@ -3795,6 +4062,7 @@ var FetchService = class {
3795
4062
  row[key] = batchResults.get(String(eid)) || [];
3796
4063
  }
3797
4064
  } catch (e) {
4065
+ if (reachedDatabase(e)) throw e;
3798
4066
  logger.warn(`[include] Failed to batch load many '${key}'`, { error: e });
3799
4067
  }
3800
4068
  }
@@ -3832,7 +4100,8 @@ var FetchService = class {
3832
4100
  if (reachedDatabase(e)) throw e;
3833
4101
  logger.warn(`[fetchOneForRest] db.query.findFirst failed for ${collectionPath}, falling back`, { error: e });
3834
4102
  }
3835
- const result = await this.db.select().from(table).where(eq(idField, parsedId)).limit(1);
4103
+ const visibleOne = visibleColumnProjection(getTableColumns(table), collection);
4104
+ const result = await this.db.select(visibleOne).from(table).where(eq(idField, parsedId)).limit(1);
3836
4105
  if (result.length === 0) return null;
3837
4106
  const flatEntity = { ...result[0] };
3838
4107
  if (!include || include.length === 0) return flatEntity;
@@ -3856,6 +4125,7 @@ var FetchService = class {
3856
4125
  ...e.values
3857
4126
  }));
3858
4127
  } catch (e) {
4128
+ if (reachedDatabase(e)) throw e;
3859
4129
  logger.warn(`[include] Failed to load relation '${key}'`, { error: e });
3860
4130
  }
3861
4131
  }
@@ -3870,14 +4140,21 @@ var FetchService = class {
3870
4140
  const idField = table[requirePrimaryKeys(collection, this.registry)[0].fieldName];
3871
4141
  let vectorMeta;
3872
4142
  if (options.vectorSearch) vectorMeta = DrizzleConditionBuilder.buildVectorSearchConditions(table, options.vectorSearch);
4143
+ const visible = visibleColumnProjection(getTableColumns(table), collection);
4144
+ const rankSelect = options.searchString ? DrizzleConditionBuilder.buildSearchRankExpression(options.searchString, table, collection) : void 0;
4145
+ const matchesSelect = options.searchString && options.searchExplain ? DrizzleConditionBuilder.buildSearchMatchesExpression(options.searchString, table, collection) : void 0;
3873
4146
  let query = vectorMeta ? this.db.select({
3874
- table_row: table,
4147
+ table_row: visible ?? table,
3875
4148
  _distance: vectorMeta.distanceSelect
3876
- }).from(table).$dynamic() : this.db.select().from(table).$dynamic();
4149
+ }).from(table).$dynamic() : rankSelect ? this.db.select({
4150
+ table_row: visible ?? table,
4151
+ _score: rankSelect,
4152
+ ...matchesSelect ? { _matches: matchesSelect } : {}
4153
+ }).from(table).$dynamic() : visible ? this.db.select(visible).from(table).$dynamic() : this.db.select().from(table).$dynamic();
3877
4154
  const allConditions = [];
3878
4155
  if (options.relatedTo) allConditions.push(this.buildRelationScope(options.relatedTo));
3879
4156
  if (options.searchString) {
3880
- const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table);
4157
+ const searchConditions = DrizzleConditionBuilder.buildSearchConditions(options.searchString, collection.properties, table, collection);
3881
4158
  if (searchConditions.length === 0) return [];
3882
4159
  allConditions.push(DrizzleConditionBuilder.combineConditionsWithOr(searchConditions));
3883
4160
  }
@@ -3885,6 +4162,10 @@ var FetchService = class {
3885
4162
  const filterConditions = this.buildFilterConditions(options.filter, table, collectionPath);
3886
4163
  if (filterConditions.length > 0) allConditions.push(...filterConditions);
3887
4164
  }
4165
+ if (options.logical) {
4166
+ const logicalCondition = DrizzleConditionBuilder.buildLogicalConditions(options.logical, table, collectionPath, this.filterContext(collectionPath, table));
4167
+ if (logicalCondition) allConditions.push(logicalCondition);
4168
+ }
3888
4169
  if (vectorMeta?.filter) allConditions.push(vectorMeta.filter);
3889
4170
  if (allConditions.length > 0) {
3890
4171
  const finalCondition = DrizzleConditionBuilder.combineConditionsWithAnd(allConditions);
@@ -3893,7 +4174,7 @@ var FetchService = class {
3893
4174
  const orderExpressions = [];
3894
4175
  if (vectorMeta) orderExpressions.push(asc(vectorMeta.orderBy));
3895
4176
  else if (options.orderBy) {
3896
- const orderByField = this.resolveOrderByField(table, options.orderBy, collection);
4177
+ const orderByField = this.resolveOrderTarget(table, options.orderBy, collection, options.searchString);
3897
4178
  if (orderByField) orderExpressions.push(options.order === "asc" ? asc(orderByField) : desc(orderByField));
3898
4179
  }
3899
4180
  orderExpressions.push(desc(idField));
@@ -3906,6 +4187,11 @@ var FetchService = class {
3906
4187
  ...r.table_row,
3907
4188
  _distance: typeof r._distance === "number" ? r._distance : parseFloat(String(r._distance))
3908
4189
  }));
4190
+ if (rankSelect) return rawResults.map((r) => ({
4191
+ ...r.table_row,
4192
+ _score: typeof r._score === "number" ? r._score : parseFloat(String(r._score)),
4193
+ ...matchesSelect ? { _matches: r._matches ?? [] } : {}
4194
+ }));
3909
4195
  return rawResults;
3910
4196
  }
3911
4197
  /**
@@ -4101,6 +4387,7 @@ var PersistService = class {
4101
4387
  const inverseRelationUpdates = serializedResult.inverseRelationUpdates;
4102
4388
  const joinPathRelationUpdates = serializedResult.joinPathRelationUpdates;
4103
4389
  const entityData = sanitizeAndConvertDates(serializedResult.scalarData);
4390
+ assertWritableColumns(entityData, table, effectiveCollectionPath);
4104
4391
  savedId = await this.db.transaction(async (tx) => {
4105
4392
  let currentId;
4106
4393
  if (id && !options?.upsert) {
@@ -4127,6 +4414,7 @@ var PersistService = class {
4127
4414
  const target = idInfoArray.map((info) => table[info.fieldName]);
4128
4415
  const set = { ...dataForInsert };
4129
4416
  for (const info of idInfoArray) delete set[info.fieldName];
4417
+ for (const [propName, prop] of Object.entries(collection.properties ?? {})) if (prop.type === "date" && prop.autoValue === "on_create") delete set[propName];
4130
4418
  result = Object.keys(set).length > 0 ? await insertQuery.onConflictDoUpdate({
4131
4419
  target,
4132
4420
  set
@@ -4502,284 +4790,6 @@ var BranchService = class {
4502
4790
  }
4503
4791
  };
4504
4792
  //#endregion
4505
- //#region src/security/rls-enforcement.ts
4506
- var quoteIdent$1 = (name) => `"${name.replace(/"/g, "\"\"")}"`;
4507
- /** DML the user role holds on managed tables (RLS still filters per row). */
4508
- var USER_TABLE_PRIVILEGES = "SELECT, INSERT, UPDATE, DELETE";
4509
- /**
4510
- * Warn when the connection role shares its name with an existing schema.
4511
- *
4512
- * Postgres resolves unqualified names through `search_path`, which defaults to
4513
- * `"$user", public` — and `$user` is the connection ROLE. When a schema of that
4514
- * name exists it sits ahead of `public`, so every unqualified statement
4515
- * silently operates on it instead:
4516
- *
4517
- * CREATE TABLE posts (...); -- you meant public.posts; you got <role>.posts
4518
- *
4519
- * Nothing errors. You get a second table of the same name in the wrong schema,
4520
- * and reads that pin `public` cannot see it — which reads as "missing table" and
4521
- * sends people to re-run a push that creates a *third* copy. The bootstrapper
4522
- * has a whole branch dedicated to recognising the symptom after the fact.
4523
- *
4524
- * Rebase shipped straight into this: it creates a schema named `rebase` while
4525
- * every template named the database role `rebase` too. The scaffold uses
4526
- * `rebase_app` now, and every pool Rebase opens pins `search_path=public`
4527
- * (`pinSearchPath`), which covers the paths the framework controls. This covers
4528
- * the ones it does not — `psql`, `pg_dump`, drizzle-kit, a colleague's script,
4529
- * a hand-written migration — because the hazard is a property of the two NAMES,
4530
- * not of any one connection.
4531
- *
4532
- * A warning rather than a boot failure: the database works, the framework's own
4533
- * traffic is pinned, and refusing to start over a naming choice a user may have
4534
- * inherited would be worse than the risk.
4535
- */
4536
- async function warnOnRoleSchemaCollision(run) {
4537
- try {
4538
- const rows = await run(`
4539
- SELECT current_user AS role,
4540
- EXISTS (
4541
- SELECT 1 FROM pg_namespace n WHERE n.nspname = current_user
4542
- ) AS collides
4543
- `);
4544
- if (rows[0]?.collides !== true) return;
4545
- const role = String(rows[0]?.role ?? "the connection role");
4546
- logger.warn(`⚠️ The database role "${role}" has the same name as a schema. Postgres resolves unqualified names through \`search_path\`, which defaults to \`"$user", public\` — so "${role}" is searched BEFORE public, and any unqualified \`CREATE TABLE\`/\`SELECT\` from a tool that does not pin the path (psql, pg_dump, drizzle-kit, a hand-written migration) silently lands in "${role}" instead. Rebase's own connections pin \`search_path=public\`, so the server is unaffected. To remove the hazard entirely, connect as a role whose name is not also a schema — the scaffold uses "rebase_app".`);
4547
- } catch {}
4548
- }
4549
- async function detectConnectionPosture(run) {
4550
- const row = (await run(`
4551
- SELECT current_user AS role,
4552
- r.rolsuper AS superuser,
4553
- r.rolbypassrls AS bypassrls,
4554
- EXISTS (
4555
- SELECT 1 FROM pg_tables t
4556
- WHERE t.tableowner = current_user
4557
- AND t.schemaname NOT IN ('pg_catalog', 'information_schema')
4558
- ) AS owns_tables
4559
- FROM pg_roles r
4560
- WHERE r.rolname = current_user
4561
- `))[0] ?? {};
4562
- const superuser = row.superuser === true;
4563
- const bypassRLS = row.bypassrls === true;
4564
- const ownsTables = row.owns_tables === true;
4565
- return {
4566
- role: String(row.role ?? "unknown"),
4567
- superuser,
4568
- bypassRLS,
4569
- ownsTables,
4570
- privileged: superuser || bypassRLS || ownsTables
4571
- };
4572
- }
4573
- /**
4574
- * Human-actionable instructions for when the connection cannot provision the
4575
- * user role itself (no CREATEROLE and role not pre-created by the platform).
4576
- */
4577
- function appRoleSetupInstructions(connectionRole, schemas) {
4578
- const grants = schemas.map((s) => `GRANT USAGE ON SCHEMA ${quoteIdent$1(s)} TO ${REBASE_USER_ROLE};\nGRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${quoteIdent$1(s)} TO ${REBASE_USER_ROLE};\nGRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${quoteIdent$1(s)} TO ${REBASE_USER_ROLE};`).join("\n");
4579
- return `Rebase enforces row-level security by running authenticated requests as the restricted role "${REBASE_USER_ROLE}", but the connection role "${connectionRole}" bypasses RLS and cannot create that role itself.\nRun the following as a database administrator, then restart:\n\nCREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\nGRANT ${REBASE_USER_ROLE} TO ${quoteIdent$1(connectionRole)};\n` + grants;
4580
- }
4581
- /**
4582
- * Idempotently provision the `rebase_user` role, membership for the current
4583
- * connection role, and DML grants (+ default privileges for future tables)
4584
- * on every existing schema in `schemas`.
4585
- *
4586
- * Split into privilege tiers so it works both when the connection is a
4587
- * superuser (creates everything) and when the platform pre-created the role
4588
- * and membership (e.g. CNPG `postInitApplicationSQL`) and the connection is
4589
- * merely the table owner — owners can always run the grant tier themselves.
4590
- *
4591
- * RLS still filters every row: these grants only make the tables *reachable*
4592
- * by the role; the policies decide which rows/commands actually pass.
4593
- *
4594
- * Throws with precise setup instructions when the role is missing and the
4595
- * connection cannot create it.
4596
- */
4597
- async function ensureAppRole(run, schemas) {
4598
- const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));
4599
- if ((await run(`SELECT 1 FROM pg_roles WHERE rolname = 'rebase_user'`)).length === 0) try {
4600
- await run(`CREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT`);
4601
- } catch (err) {
4602
- throw new Error(`Failed to create the "${REBASE_USER_ROLE}" role: ${err instanceof Error ? err.message : String(err)}\n\n` + appRoleSetupInstructions("current connection role", uniqueSchemas));
4603
- }
4604
- const memberRows = await run(`
4605
- SELECT (pg_has_role(current_user, '${REBASE_USER_ROLE}', 'MEMBER')
4606
- OR (SELECT rolsuper FROM pg_roles WHERE rolname = current_user)) AS can_set,
4607
- current_user AS role
4608
- `);
4609
- if (memberRows[0]?.can_set !== true) try {
4610
- await run(`GRANT ${REBASE_USER_ROLE} TO CURRENT_USER`);
4611
- } catch (err) {
4612
- throw new Error(`The connection role is not a member of "${REBASE_USER_ROLE}" and cannot grant itself membership: ${err instanceof Error ? err.message : String(err)}\n\n` + appRoleSetupInstructions(String(memberRows[0]?.role ?? "current connection role"), uniqueSchemas));
4613
- }
4614
- const nspRows = await run("SELECT nspname FROM pg_namespace");
4615
- const existing = new Set(nspRows.map((r) => String(r.nspname)));
4616
- for (const schema of uniqueSchemas) {
4617
- if (!existing.has(schema)) continue;
4618
- const s = quoteIdent$1(schema);
4619
- await run(`GRANT USAGE ON SCHEMA ${s} TO ${REBASE_USER_ROLE}`);
4620
- await run(`GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);
4621
- await run(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);
4622
- await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${REBASE_USER_ROLE}`);
4623
- await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${REBASE_USER_ROLE}`);
4624
- await revokeInternalTableAccess(async (text) => {
4625
- await run(text);
4626
- }, schema, { onError: (table, error) => logger.warn(`🔐 [rls] Could not revoke "${REBASE_USER_ROLE}" access to "${schema}"."${table}" — it stays reachable by authenticated requests: ` + (error instanceof Error ? error.message : String(error))) });
4627
- }
4628
- logger.info(`🔐 [rls] User role "${REBASE_USER_ROLE}" provisioned (schemas: ${uniqueSchemas.join(", ")})`);
4629
- }
4630
- /**
4631
- * Apply the authenticated context to a transaction: the `app.*` GUCs that RLS
4632
- * policies read via `auth.uid()` / `auth.roles()` / `auth.jwt()`, and — when
4633
- * `userRole` is set — `SET LOCAL ROLE` so RLS binds every statement in this
4634
- * transaction (reads *and* writes).
4635
- *
4636
- * GUCs are set with `is_local = true` and the role switch is `LOCAL`: both
4637
- * reset at commit/rollback, so pooled connections are never polluted.
4638
- *
4639
- * Fails closed by construction: if the role switch errors, the transaction
4640
- * aborts instead of proceeding privileged.
4641
- *
4642
- * SECURITY: this function is only ever called on the **user** path (the server
4643
- * context uses the base/owner driver and never calls it). The default policies
4644
- * treat `auth.uid() IS NULL` as the trusted server context, and `auth.uid()`
4645
- * is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would
4646
- * be read as NULL and silently escalate a user request to server privileges.
4647
- * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
4648
- * rather than trusting every caller (e.g. realtime subscription auth) to do it.
4649
- * That sentinel is exported from `@rebasepro/types` because it leaks into rule
4650
- * semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
4651
- */
4652
- async function applyAuthContext(tx, auth, userRole) {
4653
- const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
4654
- const normalizedRoles = auth.roles.map((r) => typeof r === "string" ? r : r?.id ?? String(r));
4655
- await tx.execute(sql`
4656
- SELECT
4657
- set_config('app.uid', ${uid}, true),
4658
- set_config('app.user_id', ${uid}, true),
4659
- set_config('app.user_roles', ${normalizedRoles.join(",")}, true),
4660
- set_config('app.jwt', ${JSON.stringify({
4661
- sub: uid,
4662
- roles: auth.roles
4663
- })}, true)
4664
- `);
4665
- if (userRole) await tx.execute(sql.raw(`SET LOCAL ROLE ${quoteIdent$1(userRole)}`));
4666
- }
4667
- /** Role names from other BaaS platforms that people reach for out of habit. */
4668
- var FOREIGN_CONVENTION_ROLES = {
4669
- authenticated: "Supabase",
4670
- anon: "Supabase",
4671
- service_role: "Supabase"
4672
- };
4673
- /**
4674
- * Warn about rules that read as "signed-in users only" but admit anonymous
4675
- * callers — `auth.uid() IS NOT NULL`, or a comparison against another
4676
- * platform's magic user id such as `'anon'`.
4677
- *
4678
- * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling
4679
- * of the same habit. A foreign `pgRoles` value makes a policy unreachable and
4680
- * the table reads empty — loud, and that guard throws. These do the opposite:
4681
- * the rule compiles to a grant, and nothing looks wrong until the data is
4682
- * already public.
4683
- *
4684
- * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are
4685
- * serving traffic today: refusing to boot would take an app offline to report a
4686
- * problem it already has, and on the read path it would take it offline
4687
- * *because* its data was exposed. Rewriting the author's SQL is not an option
4688
- * either — this is the escape hatch whose whole promise is that it means what it
4689
- * says. So: say so, loudly, and leave the rule alone.
4690
- */
4691
- function warnOnAnonymousGrants(collections) {
4692
- const byRisk = /* @__PURE__ */ new Map();
4693
- for (const collection of collections) for (const rule of collection.securityRules ?? []) {
4694
- const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
4695
- const risks = [usingExpr, withCheckExpr].filter((e) => e !== null).flatMap(findAnonymousGrants);
4696
- for (const risk of risks) {
4697
- const key = `${risk.pattern}:${risk.detail}`;
4698
- const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
4699
- const entry = byRisk.get(key) ?? {
4700
- risk,
4701
- sites: []
4702
- };
4703
- if (!entry.sites.includes(site)) entry.sites.push(site);
4704
- byRisk.set(key, entry);
4705
- }
4706
- }
4707
- if (byRisk.size === 0) return;
4708
- const problems = [...byRisk.values()].map(({ risk, sites }) => ` • ${risk.explanation}\n ${sites.length} rule(s): ${sites.join(", ")}`);
4709
- logger.warn(`Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are true for everyone:\n\n` + problems.join("\n\n") + "\n");
4710
- }
4711
- /**
4712
- * Name the collections whose raw policy SQL still calls the pre-1.0 helpers.
4713
- *
4714
- * The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the
4715
- * database, so nothing is broken and no policy is wrong — which is exactly why
4716
- * this has to be said out loud. A silent rewrite that works forever is not a
4717
- * migration, it is a second supported spelling nobody wrote down, and the next
4718
- * person to read those rules will copy the old one.
4719
- *
4720
- * Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,
4721
- * `policy.rolesOverlap(...)`) compile from the model and were never affected.
4722
- */
4723
- function warnOnLegacyRlsFunctions(collections) {
4724
- const sites = [];
4725
- for (const collection of collections) for (const rule of collection.securityRules ?? []) {
4726
- const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
4727
- if (![usingExpr, withCheckExpr].filter((e) => e !== null).some(containsLegacyRlsCall)) continue;
4728
- const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
4729
- if (!sites.includes(site)) sites.push(site);
4730
- }
4731
- if (sites.length === 0) return;
4732
- logger.warn(`These security rules call the pre-1.0 RLS helpers (\`auth.uid()\`, \`auth.roles()\`, \`auth.jwt()\`). They still work — the compiler rewrites them — but the functions now live in the \`rebase\` schema, and the \`auth\` one is Supabase's. Update the raw SQL in these rules to \`${REBASE_SCHEMA}.uid()\` and friends, or switch them to the structured helpers (\`policy.authUid()\`, \`policy.rolesOverlap()\`), which never had to be spelled by hand:\n\n` + sites.map((s) => ` • ${s}`).join("\n") + "\n");
4733
- }
4734
- /** Whether any `raw` expression in the tree calls a pre-1.0 helper. */
4735
- function containsLegacyRlsCall(expr) {
4736
- switch (expr.kind) {
4737
- case "raw": return usesLegacyRlsFunctions(expr.sql);
4738
- case "and":
4739
- case "or": return expr.operands.some(containsLegacyRlsCall);
4740
- case "not": return containsLegacyRlsCall(expr.operand);
4741
- case "existsIn": return containsLegacyRlsCall(expr.where);
4742
- default: return false;
4743
- }
4744
- }
4745
- /**
4746
- * Reject `pgRoles` that this server can never satisfy.
4747
- *
4748
- * `pgRoles` sets the `TO` clause of a generated policy, so a policy naming a
4749
- * role the request never runs as simply never applies — and RLS then filters
4750
- * every row. The table reads as empty, which is indistinguishable from having
4751
- * no data, so the mistake survives review and ships.
4752
- *
4753
- * Requests run as `rebase_user`, so a policy is only reachable if it targets
4754
- * `public` or a role `rebase_user` holds. Anything else is a configuration
4755
- * error worth failing the boot for.
4756
- */
4757
- async function validatePolicyPgRoles(run, collections, requestRole = REBASE_USER_ROLE) {
4758
- const wanted = /* @__PURE__ */ new Map();
4759
- for (const collection of collections) for (const rule of collection.securityRules ?? []) for (const role of rule.pgRoles ?? []) {
4760
- if (role === "public") continue;
4761
- wanted.set(role, [...wanted.get(role) ?? [], collection.slug ?? "(unnamed)"]);
4762
- }
4763
- if (wanted.size === 0) return;
4764
- const names = [...wanted.keys()].map((r) => `'${r.replace(/'/g, "''")}'`).join(",");
4765
- const rows = await run(`
4766
- SELECT r.rolname AS role,
4767
- COALESCE(pg_has_role(to_regrole('${requestRole.replace(/'/g, "''")}'), r.oid, 'MEMBER'), false) AS reachable
4768
- FROM pg_roles r
4769
- WHERE r.rolname IN (${names})
4770
- `);
4771
- const reachable = new Map(rows.map((row) => [String(row.role), row.reachable === true]));
4772
- const problems = [];
4773
- for (const [role, slugs] of wanted) {
4774
- if (reachable.get(role) === true) continue;
4775
- const why = reachable.has(role) ? `"${requestRole}" is not a member of it` : "no such role exists in this database";
4776
- const platform = FOREIGN_CONVENTION_ROLES[role];
4777
- const hint = platform ? `"${role}" is a ${platform} convention, not a PostgreSQL role. Application roles belong in \`roles: ["${role === "service_role" ? "admin" : role}"]\`, which is checked inside the policy via auth.roles().` : `Either grant it (GRANT ${role} TO ${requestRole}) or drop \`pgRoles\` so the policy targets \`public\`.`;
4778
- problems.push(` • pgRoles: ["${role}"] on ${slugs.join(", ")} — ${why}.\n ${hint}`);
4779
- }
4780
- if (problems.length > 0) throw new Error(`Security rules target PostgreSQL roles this server cannot use. Requests run as "${requestRole}", so these policies would never apply and every row would be filtered out — the collections would look empty rather than error.\n\n` + problems.join("\n\n") + "\n");
4781
- }
4782
- //#endregion
4783
4793
  //#region src/PostgresBackendDriver.ts
4784
4794
  var PostgresBackendDriver = class PostgresBackendDriver {
4785
4795
  db;
@@ -6023,6 +6033,13 @@ function createAuthSchema(usersSchemaName = "rebase") {
6023
6033
  * that rotates immediately after it.
6024
6034
  */
6025
6035
  sessionStartedAt: timestamp("session_started_at").defaultNow().notNull(),
6036
+ /**
6037
+ * The assurance level the sign-in was established at — `aal2` only
6038
+ * where a second factor was actually presented. Carried across
6039
+ * rotations, because refresh is not a new authentication and has
6040
+ * nothing else to read the level from.
6041
+ */
6042
+ aal: text("aal"),
6026
6043
  userAgent: text("user_agent"),
6027
6044
  ipAddress: text("ip_address"),
6028
6045
  createdAt: timestamp("created_at").defaultNow().notNull()
@@ -6068,6 +6085,13 @@ function createAuthSchema(usersSchemaName = "rebase") {
6068
6085
  secretEncrypted: text("secret_encrypted").notNull(),
6069
6086
  friendlyName: text("friendly_name"),
6070
6087
  verified: boolean("verified").default(false).notNull(),
6088
+ /**
6089
+ * The highest TOTP time step ever accepted for this factor. RFC 6238
6090
+ * §5.2 forbids accepting an OTP twice, and the ±1 step window that
6091
+ * exists for clock drift is also a 90-second replay window: without
6092
+ * this, one observed code buys a fresh session for a minute and a half.
6093
+ */
6094
+ lastUsedCounter: bigint("last_used_counter", { mode: "number" }),
6071
6095
  createdAt: timestamp("created_at").defaultNow().notNull(),
6072
6096
  updatedAt: timestamp("updated_at").defaultNow().notNull()
6073
6097
  });
@@ -6085,6 +6109,8 @@ function createAuthSchema(usersSchemaName = "rebase") {
6085
6109
  createdAt: timestamp("created_at").defaultNow().notNull(),
6086
6110
  verifiedAt: timestamp("verified_at"),
6087
6111
  ipAddress: text("ip_address"),
6112
+ /** Failed guesses recorded against this challenge; bounded by the route. */
6113
+ attempts: integer("attempts").default(0).notNull(),
6088
6114
  expiresAt: timestamp("expires_at").notNull()
6089
6115
  }),
6090
6116
  recoveryCodes: tableCreator("recovery_codes", {
@@ -6161,6 +6187,26 @@ var magicLinkTokensRelations = relations(magicLinkTokens, ({ one }) => ({ user:
6161
6187
  * Uses the explicit `columnName` when set (e.g. from introspection),
6162
6188
  * falling back to `toSnakeCase(propName)` for manually-authored collections.
6163
6189
  */
6190
+ var JS_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
6191
+ /**
6192
+ * A string literal for the generated schema file.
6193
+ *
6194
+ * Column names, table names and enum values are all written into this file as
6195
+ * literals, and none of them is constrained to be quote-free: a Postgres
6196
+ * identifier only has to be quoted, and `O'Brien` is an ordinary enum value.
6197
+ * Interpolating them raw ended the literal early — for enum values, inside
6198
+ * single quotes, where an apostrophe is not an edge case.
6199
+ */
6200
+ var quote$1 = (value) => JSON.stringify(value);
6201
+ /** An object key: verbatim when it is an identifier, quoted otherwise. */
6202
+ var propKey = (name) => JS_IDENTIFIER.test(name) ? name : quote$1(name);
6203
+ /**
6204
+ * A property access on a generated table variable.
6205
+ *
6206
+ * `users.full name` is not an expression; `users["full name"]` is, and Drizzle
6207
+ * treats the two identically.
6208
+ */
6209
+ var member = (object, key) => JS_IDENTIFIER.test(key) ? `${object}.${key}` : `${object}[${quote$1(key)}]`;
6164
6210
  var resolveColumnName = (propName, prop) => {
6165
6211
  if (prop && "columnName" in prop && typeof prop.columnName === "string") return prop.columnName;
6166
6212
  return toSnakeCase(propName);
@@ -6221,18 +6267,25 @@ var isIdProperty = (propName, prop, collection) => {
6221
6267
  if ("isId" in prop && Boolean(prop.isId)) return true;
6222
6268
  return !Object.values(collection.properties ?? {}).some((p) => "isId" in p && Boolean(p.isId)) && propName === "id";
6223
6269
  };
6270
+ /**
6271
+ * The Drizzle column declaration a property compiles to, or `null` when the
6272
+ * property puts no column on *this* table (an inverse relation, whose column
6273
+ * lives on the target). Exported so it can be checked against its DDL twin
6274
+ * `getSqlColumnType` directly — the two disagreeing is what left `geopoint`
6275
+ * with a database column and no Drizzle key.
6276
+ */
6224
6277
  var getDrizzleColumn = (propName, prop, collection, collections) => {
6225
6278
  const colName = resolveColumnName(propName, prop);
6226
6279
  let columnDefinition;
6227
6280
  switch (prop.type) {
6228
6281
  case "string": {
6229
6282
  const stringProp = prop;
6230
- if (stringProp.enum) columnDefinition = `${getEnumVarName(getTableName$1(collection), propName)}("${colName}")`;
6231
- else if ("isId" in stringProp && stringProp.isId === "uuid") columnDefinition = `uuid("${colName}")`;
6232
- else if (stringProp.columnType === "uuid") columnDefinition = `uuid("${colName}")`;
6233
- else if (stringProp.columnType === "char") columnDefinition = `char("${colName}", { length: ${resolveStringColumnLength(stringProp)} })`;
6234
- else if (stringProp.columnType === "varchar") columnDefinition = `varchar("${colName}", { length: ${resolveStringColumnLength(stringProp)} })`;
6235
- else columnDefinition = `text("${colName}")`;
6283
+ if (stringProp.enum) columnDefinition = `${getEnumVarName(getTableName$1(collection), propName)}(${quote$1(colName)})`;
6284
+ else if ("isId" in stringProp && stringProp.isId === "uuid") columnDefinition = `uuid(${quote$1(colName)})`;
6285
+ else if (stringProp.columnType === "uuid") columnDefinition = `uuid(${quote$1(colName)})`;
6286
+ else if (stringProp.columnType === "char") columnDefinition = `char(${quote$1(colName)}, { length: ${resolveStringColumnLength(stringProp)} })`;
6287
+ else if (stringProp.columnType === "varchar") columnDefinition = `varchar(${quote$1(colName)}, { length: ${resolveStringColumnLength(stringProp)} })`;
6288
+ else columnDefinition = `text(${quote$1(colName)})`;
6236
6289
  if (isIdProperty(propName, prop, collection)) columnDefinition += ".primaryKey()";
6237
6290
  if ("isId" in stringProp && stringProp.isId !== "manual" && stringProp.isId !== true) {
6238
6291
  if (stringProp.isId === "uuid") columnDefinition += ".defaultRandom()";
@@ -6248,10 +6301,10 @@ var getDrizzleColumn = (propName, prop, collection, collections) => {
6248
6301
  case "number": {
6249
6302
  const numProp = prop;
6250
6303
  const isId = isIdProperty(propName, prop, collection);
6251
- let baseType = numProp.validation?.integer || isId ? `integer("${colName}")` : `numeric("${colName}")`;
6252
- if (numProp.columnType) if (numProp.columnType === "double precision") baseType = `doublePrecision("${colName}")`;
6253
- else if (numProp.columnType === "bigint" || numProp.columnType === "bigserial") baseType = `${numProp.columnType}("${colName}", { mode: "number" })`;
6254
- else baseType = `${numProp.columnType}("${colName}")`;
6304
+ let baseType = numProp.validation?.integer || isId ? `integer(${quote$1(colName)})` : `numeric(${quote$1(colName)})`;
6305
+ if (numProp.columnType) if (numProp.columnType === "double precision") baseType = `doublePrecision(${quote$1(colName)})`;
6306
+ else if (numProp.columnType === "bigint" || numProp.columnType === "bigserial") baseType = `${numProp.columnType}(${quote$1(colName)}, { mode: "number" })`;
6307
+ else baseType = `${numProp.columnType}(${quote$1(colName)})`;
6255
6308
  if ("isId" in numProp && numProp.isId === "increment") columnDefinition = `${baseType}.generatedByDefaultAsIdentity()`;
6256
6309
  else if ("isId" in numProp && typeof numProp.isId === "string" && numProp.isId !== "manual") {
6257
6310
  columnDefinition = baseType;
@@ -6263,19 +6316,22 @@ var getDrizzleColumn = (propName, prop, collection, collections) => {
6263
6316
  break;
6264
6317
  }
6265
6318
  case "boolean":
6266
- columnDefinition = `boolean("${colName}")`;
6319
+ columnDefinition = `boolean(${quote$1(colName)})`;
6267
6320
  break;
6268
6321
  case "date": {
6269
6322
  const dateProp = prop;
6270
- if (dateProp.columnType === "date") columnDefinition = `date("${colName}", { mode: 'string' })`;
6271
- else if (dateProp.columnType === "time") columnDefinition = `time("${colName}")`;
6272
- else columnDefinition = `timestamp("${colName}", { withTimezone: true, mode: 'string' })`;
6323
+ if (dateProp.columnType === "date") columnDefinition = `date(${quote$1(colName)}, { mode: 'string' })`;
6324
+ else if (dateProp.columnType === "time") columnDefinition = `time(${quote$1(colName)})`;
6325
+ else columnDefinition = `timestamp(${quote$1(colName)}, { withTimezone: true, mode: 'string' })`;
6273
6326
  if (dateProp.autoValue === "on_create" || dateProp.autoValue === "on_update") columnDefinition += ".default(sql`now()`)";
6274
6327
  break;
6275
6328
  }
6276
6329
  case "map":
6277
- if (prop.columnType === "json") columnDefinition = `json("${colName}")`;
6278
- else columnDefinition = `jsonb("${colName}")`;
6330
+ if (prop.columnType === "json") columnDefinition = `json(${quote$1(colName)})`;
6331
+ else columnDefinition = `jsonb(${quote$1(colName)})`;
6332
+ break;
6333
+ case "geopoint":
6334
+ columnDefinition = `jsonb(${quote$1(colName)})`;
6279
6335
  break;
6280
6336
  case "array": {
6281
6337
  const arrayProp = prop;
@@ -6286,19 +6342,21 @@ var getDrizzleColumn = (propName, prop, collection, collections) => {
6286
6342
  else if (ofProp.type === "number") colType = ofProp.validation?.integer ? "integer[]" : "numeric[]";
6287
6343
  else if (ofProp.type === "boolean") colType = "boolean[]";
6288
6344
  }
6289
- if (colType === "json") columnDefinition = `json("${colName}")`;
6290
- else if (colType === "text[]") columnDefinition = `text("${colName}").array()`;
6291
- else if (colType === "integer[]") columnDefinition = `integer("${colName}").array()`;
6292
- else if (colType === "boolean[]") columnDefinition = `boolean("${colName}").array()`;
6293
- else if (colType === "numeric[]") columnDefinition = `numeric("${colName}").array()`;
6294
- else columnDefinition = `jsonb("${colName}")`;
6345
+ if (colType === "json") columnDefinition = `json(${quote$1(colName)})`;
6346
+ else if (colType === "text[]") columnDefinition = `text(${quote$1(colName)}).array()`;
6347
+ else if (colType === "integer[]") columnDefinition = `integer(${quote$1(colName)}).array()`;
6348
+ else if (colType === "boolean[]") columnDefinition = `boolean(${quote$1(colName)}).array()`;
6349
+ else if (colType === "numeric[]") columnDefinition = `numeric(${quote$1(colName)}).array()`;
6350
+ else columnDefinition = `jsonb(${quote$1(colName)})`;
6295
6351
  break;
6296
6352
  }
6297
- case "vector":
6298
- columnDefinition = `vector("${colName}", { dimensions: ${prop.dimensions} })`;
6353
+ case "vector": {
6354
+ const vp = prop;
6355
+ columnDefinition = `vector(${quote$1(colName)}, { dimensions: ${vp.dimensions} })`;
6299
6356
  break;
6357
+ }
6300
6358
  case "binary":
6301
- columnDefinition = `customType({ dataType() { return 'bytea'; } })("${colName}")`;
6359
+ columnDefinition = `customType({ dataType() { return 'bytea'; } })(${quote$1(colName)})`;
6302
6360
  break;
6303
6361
  case "relation": {
6304
6362
  const refProp = prop;
@@ -6320,30 +6378,31 @@ var getDrizzleColumn = (propName, prop, collection, collections) => {
6320
6378
  const required = prop.validation?.required;
6321
6379
  const refOptionsParts = [onUpdate, `onDelete: \"${relation.onDelete ?? (required ? "cascade" : "set null")}\"`].filter(Boolean);
6322
6380
  const refOptions = refOptionsParts.length > 0 ? `{ ${refOptionsParts.join(", ")} }` : "";
6323
- let columnDef = `${baseColumn}.references(() => ${targetTableVar}.${targetIdField}${refOptions ? `, ${refOptions}` : ""})`;
6381
+ let columnDef = `${baseColumn}.references(() => ${member(targetTableVar, targetIdField)}${refOptions ? `, ${refOptions}` : ""})`;
6324
6382
  if (required) columnDef += ".notNull()";
6325
- return ` ${relation.localKey}: ${columnDef}`;
6383
+ return ` ${propKey(relation.localKey)}: ${columnDef}`;
6326
6384
  }
6327
6385
  case "reference": {
6328
6386
  const refProp = prop;
6329
6387
  const targetCollection = collections.find((c) => c.slug === refProp.path || getTableName$1(c) === refProp.path);
6330
6388
  if (!targetCollection) {
6331
- columnDefinition = `text("${colName}")`;
6389
+ columnDefinition = `text(${quote$1(colName)})`;
6332
6390
  break;
6333
6391
  }
6334
6392
  const pkProp = getPrimaryKeyProp(targetCollection);
6335
6393
  const targetTableVar = getTableVarName(getTableName$1(targetCollection));
6336
6394
  const targetIdField = pkProp.name;
6337
- const baseColumn = pkProp.type === "number" ? `integer("${colName}")` : pkProp.isUuid ? `uuid("${colName}")` : `text("${colName}")`;
6395
+ const baseColumn = pkProp.type === "number" ? `integer(${quote$1(colName)})` : pkProp.isUuid ? `uuid(${quote$1(colName)})` : `text(${quote$1(colName)})`;
6338
6396
  const required = prop.validation?.required;
6339
- columnDefinition = `${baseColumn}.references(() => ${targetTableVar}.${targetIdField}, ${`{ onDelete: "${required ? "cascade" : "set null"}" }`})`;
6397
+ const refOptions = `{ onDelete: "${required ? "cascade" : "set null"}" }`;
6398
+ columnDefinition = `${baseColumn}.references(() => ${member(targetTableVar, targetIdField)}, ${refOptions})`;
6340
6399
  if (required) columnDefinition += ".notNull()";
6341
- return ` ${propName}: ${columnDefinition}`;
6400
+ return ` ${propKey(propName)}: ${columnDefinition}`;
6342
6401
  }
6343
- default: return null;
6402
+ default: throw new Error(`No Postgres column mapping for property '${propName}' of type '${prop.type}' in collection '${collection.slug}'. Add a case to \`getDrizzleColumn\` (and to \`getSqlColumnType\`, which must agree).`);
6344
6403
  }
6345
6404
  if (prop.validation?.required) columnDefinition += ".notNull()";
6346
- return ` ${propName}: ${columnDefinition}`;
6405
+ return ` ${propKey(propName)}: ${columnDefinition}`;
6347
6406
  };
6348
6407
  /**
6349
6408
  * Wraps a compiled SQL clause in a Drizzle `sql\`...\`` template literal.
@@ -6376,7 +6435,7 @@ var generateSinglePolicyCode = (collection, rule, operation, policyName, resolve
6376
6435
  parts.push(`to: [${toRoles.map((r) => `"${r}"`).join(", ")}]`);
6377
6436
  if (usingClause) parts.push(`using: ${usingClause}`);
6378
6437
  if (withCheckClause) parts.push(`withCheck: ${withCheckClause}`);
6379
- return ` pgPolicy("${policyName}", { ${parts.join(", ")} }),\n`;
6438
+ return ` pgPolicy(${quote$1(policyName)}, { ${parts.join(", ")} }),\n`;
6380
6439
  };
6381
6440
  /**
6382
6441
  * Computes a deterministic shared relation name for Drizzle.
@@ -6411,11 +6470,12 @@ var computeSharedRelationName = (rel, sourceCollection, _collections) => {
6411
6470
  return fallback;
6412
6471
  };
6413
6472
  var generateSchema = async (allCollections, stripPolicies = false) => {
6414
- const collections = relationalCollections(allCollections);
6473
+ const collections = sortCollectionsBySlug(relationalCollections(allCollections));
6415
6474
  let schemaContent = "// This file is auto-generated by the Rebase Drizzle generator. Do not edit manually.\n\n";
6416
6475
  const hasUuid = collections.some((c) => c.properties && Object.values(c.properties).some((p) => p.type === "string" && (p.autoValue === "uuid" || p.isId === "uuid")));
6417
6476
  const hasVector = collections.some((c) => c.properties && Object.values(c.properties).some((p) => p.type === "vector"));
6418
6477
  const hasBinary = collections.some((c) => c.properties && Object.values(c.properties).some((p) => p.type === "binary"));
6478
+ const hasSearch = collections.some((c) => buildSearchColumnSpec(c) !== void 0);
6419
6479
  const pgCoreImports = [
6420
6480
  "primaryKey",
6421
6481
  "pgTable",
@@ -6440,7 +6500,7 @@ var generateSchema = async (allCollections, stripPolicies = false) => {
6440
6500
  ];
6441
6501
  if (hasUuid) pgCoreImports.push("uuid");
6442
6502
  if (hasVector) pgCoreImports.push("vector");
6443
- if (hasBinary) pgCoreImports.push("customType");
6503
+ if (hasBinary || hasSearch) pgCoreImports.push("customType");
6444
6504
  const uniqueSchemas = Array.from(new Set(collections.map((c) => isPostgresCollectionConfig(c) ? c.schema : void 0).filter(Boolean)));
6445
6505
  if (uniqueSchemas.length > 0) pgCoreImports.push("pgSchema");
6446
6506
  schemaContent += `import { ${pgCoreImports.join(", ")} } from 'drizzle-orm/pg-core';\n`;
@@ -6461,7 +6521,7 @@ var generateSchema = async (allCollections, stripPolicies = false) => {
6461
6521
  const enumDbName = `${collectionPath}_${resolveColumnName(propName, prop)}`;
6462
6522
  const values = Array.isArray(prop.enum) ? prop.enum.map((v) => String(typeof v === "object" && v !== null && "id" in v ? v.id : v)) : Object.keys(prop.enum);
6463
6523
  if (values.length > 0) {
6464
- schemaContent += `export const ${enumVarName} = pgEnum(\"${enumDbName}\", [${values.map((v) => `'${v}'`).join(", ")}]);\n`;
6524
+ schemaContent += `export const ${enumVarName} = pgEnum(${quote$1(enumDbName)}, [${values.map((v) => quote$1(v)).join(", ")}]);\n`;
6465
6525
  if (!exportedEnumVars.includes(enumVarName)) exportedEnumVars.push(enumVarName);
6466
6526
  }
6467
6527
  }
@@ -6522,6 +6582,11 @@ var generateSchema = async (allCollections, stripPolicies = false) => {
6522
6582
  const columnString = getDrizzleColumn(propName, prop, collection, collections);
6523
6583
  if (columnString) columns.add(columnString);
6524
6584
  });
6585
+ const searchSpec = buildSearchColumnSpec(collection);
6586
+ if (searchSpec) {
6587
+ columns.add(` ${searchSpec.column}: customType({ dataType() { return 'tsvector'; } })("${searchSpec.column}").generatedAlwaysAs(sql\`${searchSpec.expression}\`)`);
6588
+ if (searchSpec.fuzzy) columns.add(` ${searchSpec.fuzzy.column}: text("${searchSpec.fuzzy.column}").generatedAlwaysAs(sql\`${searchSpec.fuzzy.expression}\`)`);
6589
+ }
6525
6590
  if (!Array.from(columns).some((col) => col.includes(".primaryKey()"))) columns.add(" id: text(\"id\").primaryKey()");
6526
6591
  schemaContent += `${Array.from(columns).join(",\n")}`;
6527
6592
  const securityRules = getEffectiveSecurityRules(collection);
@@ -6558,9 +6623,9 @@ var generateSchema = async (allCollections, stripPolicies = false) => {
6558
6623
  break;
6559
6624
  }
6560
6625
  } catch {}
6561
- tableRelations.push(` "${relation.through.sourceColumn}": one(${sourceTableVar}, {\n fields: [${tableVarName}.${relation.through.sourceColumn}],\n references: [${sourceTableVar}.${sourceId}],\n relationName: \"${owningRelationName}\"\n })`);
6626
+ tableRelations.push(` ${quote$1(relation.through.sourceColumn)}: one(${sourceTableVar}, {\n fields: [${member(tableVarName, relation.through.sourceColumn)}],\n references: [${member(sourceTableVar, sourceId)}],\n relationName: ${quote$1(owningRelationName)}\n })`);
6562
6627
  const targetRelationName = inverseRelationName ? inverseRelationName : `${tableName}_${relation.through.targetColumn}`;
6563
- tableRelations.push(` "${relation.through.targetColumn}": one(${targetTableVar}, {\n fields: [${tableVarName}.${relation.through.targetColumn}],\n references: [${targetTableVar}.${targetId}],\n relationName: "${targetRelationName}"\n })`);
6628
+ tableRelations.push(` ${quote$1(relation.through.targetColumn)}: one(${targetTableVar}, {\n fields: [${member(tableVarName, relation.through.targetColumn)}],\n references: [${member(targetTableVar, targetId)}],\n relationName: ${quote$1(targetRelationName)}\n })`);
6564
6629
  }
6565
6630
  } else {
6566
6631
  const resolvedRelations = resolveCollectionRelations(collection);
@@ -6575,7 +6640,7 @@ var generateSchema = async (allCollections, stripPolicies = false) => {
6575
6640
  switch (rel.kind) {
6576
6641
  case "belongsTo": {
6577
6642
  const localFieldKey = resolvePropertyKeyForColumn(collection, rel.localKey);
6578
- tableRelations.push(` "${relationKey}": one(${targetTableVar}, {\n fields: [${tableVarName}.${localFieldKey}],\n references: [${targetTableVar}.${getPrimaryKeyName(target)}],\n relationName: \"${drizzleRelationName}\"\n })`);
6643
+ tableRelations.push(` ${quote$1(relationKey)}: one(${targetTableVar}, {\n fields: [${member(tableVarName, localFieldKey)}],\n references: [${member(targetTableVar, getPrimaryKeyName(target))}],\n relationName: ${quote$1(drizzleRelationName)}\n })`);
6579
6644
  break;
6580
6645
  }
6581
6646
  case "hasOne":
@@ -6606,7 +6671,7 @@ var generateSchema = async (allCollections, stripPolicies = false) => {
6606
6671
  const drizzleFieldKey = resolvePropertyKeyForColumn(collection, otherRel.foreignKeyOnTarget);
6607
6672
  const referencedKey = otherRel.sourceKey ? resolvePropertyKeyForColumn(otherCollection, otherRel.sourceKey) : getPrimaryKeyName(otherCollection);
6608
6673
  const synthKey = `_synth_${otherTableVar}_${drizzleFieldKey}`;
6609
- tableRelations.push(` "${synthKey}": one(${otherTableVar}, {\n fields: [${tableVarName}.${drizzleFieldKey}],\n references: [${otherTableVar}.${referencedKey}],\n relationName: \"${drizzleRelationName}\"\n })`);
6674
+ tableRelations.push(` ${quote$1(synthKey)}: one(${otherTableVar}, {\n fields: [${member(tableVarName, drizzleFieldKey)}],\n references: [${member(otherTableVar, referencedKey)}],\n relationName: ${quote$1(drizzleRelationName)}\n })`);
6610
6675
  emittedRelationNames.add(deduplicationKey);
6611
6676
  }
6612
6677
  }
@@ -6626,6 +6691,44 @@ var generateSchema = async (allCollections, stripPolicies = false) => {
6626
6691
  return schemaContent;
6627
6692
  };
6628
6693
  //#endregion
6694
+ //#region src/cli-output.ts
6695
+ /**
6696
+ * Terminal output for the `rebase db|schema|doctor` commands.
6697
+ *
6698
+ * These commands used to write every line through `logger`, and that is a
6699
+ * category error with three separate consequences:
6700
+ *
6701
+ * - `logger` prefixes each line with its own level, so a box-drawn report
6702
+ * arrived as `ℹ️ [INFO] ┌─ ✗ Missing Column ───` and the frame no longer
6703
+ * lined up with anything;
6704
+ * - `logger` is gated by `LOG_LEVEL`, which ships in the scaffold's own
6705
+ * `.env.example` — a developer who quietened their dev server with
6706
+ * `LOG_LEVEL=warn` got a `rebase db push` that printed almost nothing and
6707
+ * still exited non-zero, indistinguishable from a crash;
6708
+ * - under `NODE_ENV=production` `logger` emits JSON, so the whole report
6709
+ * became log records with the chalk escape codes embedded in them.
6710
+ *
6711
+ * A CLI's report *is* its return value. It goes to the terminal unconditionally
6712
+ * and unadorned. `packages/cli` has always written its output this way; this is
6713
+ * the same three functions for the plugin CLI that `rebase` delegates to.
6714
+ *
6715
+ * `logger` still belongs in this package's *runtime* — a request handler has no
6716
+ * terminal and its lines want levels, timestamps and redaction. The rule is the
6717
+ * caller, not the severity: anything a developer reads because they typed a
6718
+ * command goes here, anything a server emits while running goes to `logger`.
6719
+ *
6720
+ * Errors and warnings go to stderr so `rebase db push > plan.txt` keeps the
6721
+ * diagnosis on the terminal where it is readable.
6722
+ */
6723
+ /** One line of human-facing output on stdout. */
6724
+ var out = (line = "") => {
6725
+ console.log(line);
6726
+ };
6727
+ /** One line of human-facing error output on stderr. */
6728
+ var outError = (line = "") => {
6729
+ console.error(line);
6730
+ };
6731
+ //#endregion
6629
6732
  //#region src/schema/generate-drizzle-schema.ts
6630
6733
  var formatTerminalText = (text, options = {}) => {
6631
6734
  let codes = "";
@@ -6653,7 +6756,7 @@ var formatTerminalText = (text, options = {}) => {
6653
6756
  var runGeneration = async (collectionsFilePath, outputPath) => {
6654
6757
  try {
6655
6758
  if (!collectionsFilePath) {
6656
- logger.error("Error: No collections file path provided. Skipping schema generation.");
6759
+ outError("Error: No collections file path provided. Skipping schema generation.");
6657
6760
  return;
6658
6761
  }
6659
6762
  let collections = await loadCollectionsFromDirectory(path.resolve(collectionsFilePath));
@@ -6664,18 +6767,18 @@ var runGeneration = async (collectionsFilePath, outputPath) => {
6664
6767
  const outputDir = path.dirname(outputPath);
6665
6768
  await promises.mkdir(outputDir, { recursive: true });
6666
6769
  await promises.writeFile(outputPath, schemaContent);
6667
- logger.info(`✅ Drizzle schema generated successfully at ${outputPath}`);
6770
+ out(`✅ Drizzle schema generated successfully at ${outputPath}`);
6668
6771
  } else {
6669
- logger.info("✅ Drizzle schema generated successfully.");
6670
- logger.info(String(schemaContent));
6772
+ out("✅ Drizzle schema generated successfully.");
6773
+ out(String(schemaContent));
6671
6774
  }
6672
- logger.info(`You can now run ${formatTerminalText("rebase db generate", {
6775
+ out(`You can now run ${formatTerminalText("rebase db generate", {
6673
6776
  bold: true,
6674
6777
  backgroundColor: "blue",
6675
6778
  textColor: "black"
6676
6779
  })} to generate the SQL migration files.`);
6677
6780
  } catch (error) {
6678
- logger.error("Error generating schema", { error });
6781
+ outError(`Error generating schema: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
6679
6782
  }
6680
6783
  };
6681
6784
  var main = () => {
@@ -6685,18 +6788,18 @@ var main = () => {
6685
6788
  const outputPath = outputPathArg ? outputPathArg.split("=")[1] : void 0;
6686
6789
  const watch = process.argv.includes("--watch");
6687
6790
  if (!collectionsFilePath) {
6688
- logger.info("Usage: ts-node generate-drizzle-schema.ts <path-to-collections-file> [--output <path-to-output-file>] [--watch]");
6791
+ out("Usage: ts-node generate-drizzle-schema.ts <path-to-collections-file> [--output <path-to-output-file>] [--watch]");
6689
6792
  return;
6690
6793
  }
6691
6794
  const resolvedPath = path.resolve(process.cwd(), collectionsFilePath);
6692
6795
  const resolvedOutputPath = outputPath ? path.resolve(process.cwd(), outputPath) : void 0;
6693
6796
  if (watch) {
6694
- logger.info(`Watching for changes in ${resolvedPath}...`);
6797
+ out(`Watching for changes in ${resolvedPath}...`);
6695
6798
  chokidar.watch(resolvedPath, {
6696
6799
  persistent: true,
6697
6800
  ignoreInitial: false
6698
6801
  }).on("all", (event, filePath) => {
6699
- logger.info(`[${event}] ${filePath}. Regenerating schema...`);
6802
+ out(`[${event}] ${filePath}. Regenerating schema...`);
6700
6803
  runGeneration(resolvedPath, resolvedOutputPath);
6701
6804
  });
6702
6805
  } else runGeneration(resolvedPath, resolvedOutputPath);
@@ -6880,7 +6983,7 @@ async function provisionTriggerCdc(run, tables) {
6880
6983
  logger.warn(`⚠️ [CDC] Could not attach change-capture trigger to "${key}" — is the table migrated? Writes to it won't emit database-level events.`, { detail: reason });
6881
6984
  }
6882
6985
  }
6883
- logger.info(`📡 [CDC] Trigger-based change capture provisioned on ${installed.length} table(s)` + (skipped.length ? ` (${skipped.length} skipped)` : "") + ".");
6986
+ logger.debug(`📡 [CDC] Trigger-based change capture provisioned on ${installed.length} table(s)` + (skipped.length ? ` (${skipped.length} skipped)` : "") + ".");
6884
6987
  return {
6885
6988
  installed,
6886
6989
  skipped
@@ -6970,7 +7073,7 @@ var PgNotifyListener = class {
6970
7073
  await client.connect();
6971
7074
  await client.query(`LISTEN ${channel}`);
6972
7075
  this.client = client;
6973
- logger.info(`📡 ${logLabel} Listening on channel "${channel}".`);
7076
+ logger.debug(`📡 ${logLabel} Listening on channel "${channel}".`);
6974
7077
  } catch (err) {
6975
7078
  if (initial) throw err;
6976
7079
  logger.error(`❌ ${logLabel} Failed to connect LISTEN client`, { error: err });
@@ -7802,6 +7905,12 @@ var PG_NOTIFY_CHANNEL = "rebase_entity_changes";
7802
7905
  var RealtimeService = class RealtimeService extends EventEmitter {
7803
7906
  db;
7804
7907
  registry;
7908
+ /**
7909
+ * Declares to the multi-engine router that channel frames can be handled
7910
+ * here. Read by `createRoutedRealtimeService`, which otherwise would have to
7911
+ * guess — and guessed "the default provider", whichever engine that is.
7912
+ */
7913
+ supportsChannels = true;
7805
7914
  clients = /* @__PURE__ */ new Map();
7806
7915
  channels = /* @__PURE__ */ new Map();
7807
7916
  presence = /* @__PURE__ */ new Map();
@@ -7848,6 +7957,23 @@ var RealtimeService = class RealtimeService extends EventEmitter {
7848
7957
  * so a hot channel logs the problem once rather than once per message.
7849
7958
  */
7850
7959
  oversizedBroadcastWarned = /* @__PURE__ */ new Set();
7960
+ /**
7961
+ * Optional narrowing on top of the membership floor — see
7962
+ * {@link ChannelAuthorizer}. Unset by default, which leaves membership as
7963
+ * the whole of the rule.
7964
+ */
7965
+ channelAuthorizer;
7966
+ /**
7967
+ * Whether a notification from another instance has ever arrived.
7968
+ *
7969
+ * The entity LISTEN handler sees a foreign `sid` on every cross-instance
7970
+ * change, which is proof that this deployment runs more than one pod — the
7971
+ * one fact needed to tell "the memory bus is fine here" from "broadcast and
7972
+ * presence silently reach a fraction of your users".
7973
+ */
7974
+ foreignInstanceSeen = false;
7975
+ /** So the multi-pod memory-bus warning is emitted once, not once per join. */
7976
+ memoryBusWarned = false;
7851
7977
  presenceInterval;
7852
7978
  static PRESENCE_TIMEOUT_MS = 3e4;
7853
7979
  /** How often stale roster rows from other instances are reaped. */
@@ -7941,7 +8067,8 @@ var RealtimeService = class RealtimeService extends EventEmitter {
7941
8067
  limit: config.limit,
7942
8068
  startAfter: config.startAfter,
7943
8069
  databaseId: config.databaseId,
7944
- searchString: config.searchString
8070
+ searchString: config.searchString,
8071
+ searchExplain: config.searchExplain
7945
8072
  }
7946
8073
  });
7947
8074
  if (callback) this.subscriptionCallbacks.set(subscriptionId, callback);
@@ -8021,26 +8148,13 @@ var RealtimeService = class RealtimeService extends EventEmitter {
8021
8148
  await this.handleUnsubscribe(clientId, message.subscriptionId);
8022
8149
  break;
8023
8150
  case "join_channel":
8024
- this.joinChannel(clientId, payload?.channel);
8025
- break;
8026
8151
  case "leave_channel":
8027
- this.leaveChannel(clientId, payload?.channel);
8028
- break;
8029
8152
  case "broadcast":
8030
- this.broadcastToChannel(clientId, payload?.channel, payload?.event, payload?.payload);
8031
- break;
8032
8153
  case "channel_history":
8033
- await this.handleChannelHistoryRequest(clientId, payload?.channel, payload?.sinceSeq, payload?.limit);
8034
- break;
8035
8154
  case "presence_track":
8036
- this.joinChannel(clientId, payload?.channel);
8037
- this.trackPresence(clientId, payload?.channel, payload?.state ?? {});
8038
- break;
8039
8155
  case "presence_untrack":
8040
- this.removePresence(clientId, payload?.channel);
8041
- break;
8042
8156
  case "presence_state":
8043
- this.sendPresenceState(clientId, payload?.channel);
8157
+ await this.handleChannelMessage(clientId, message.type, payload, authContext);
8044
8158
  break;
8045
8159
  default: this.sendError(clientId, "Unknown message type " + message.type, message.subscriptionId);
8046
8160
  }
@@ -8055,7 +8169,21 @@ var RealtimeService = class RealtimeService extends EventEmitter {
8055
8169
  this.sendError(clientId, msg, subscriptionId);
8056
8170
  return;
8057
8171
  }
8058
- const boundedLimit = resolveClientListLimit(request.limit, { vectorSearch: !!request.vectorSearch });
8172
+ if (request.vectorSearch) {
8173
+ const msg = "Realtime subscriptions do not support vector search: a subscription is re-run on every matching write, and nothing here computes distances. Use `.vectorSearch(...).find()` for the query, and subscribe without it if you need live updates.";
8174
+ logger.warn(`[RealtimeService] ${msg}`);
8175
+ this.sendError(clientId, msg, subscriptionId, "VECTOR_SEARCH_NOT_LIVE");
8176
+ return;
8177
+ }
8178
+ let boundedLimit;
8179
+ try {
8180
+ boundedLimit = resolveClientListLimit(request.limit);
8181
+ } catch (e) {
8182
+ if (!(e instanceof ListLimitError)) throw e;
8183
+ logger.warn(`[RealtimeService] Refused subscription to '${request.path}': ${e.message}`);
8184
+ this.sendError(clientId, e.message, subscriptionId, "INVALID_LIMIT");
8185
+ return;
8186
+ }
8059
8187
  this._subscriptions.set(subscriptionId, {
8060
8188
  clientId,
8061
8189
  type: "collection",
@@ -8069,7 +8197,8 @@ var RealtimeService = class RealtimeService extends EventEmitter {
8069
8197
  offset: request.offset,
8070
8198
  startAfter: request.startAfter,
8071
8199
  databaseId: request.collection?.databaseId,
8072
- searchString: request.searchString
8200
+ searchString: request.searchString,
8201
+ searchExplain: request.searchExplain
8073
8202
  },
8074
8203
  authContext
8075
8204
  });
@@ -8158,7 +8287,39 @@ var RealtimeService = class RealtimeService extends EventEmitter {
8158
8287
  this.debugLog("🔔 [RealtimeService] notifyUpdate completed for path:", path);
8159
8288
  }
8160
8289
  /**
8161
- * Notify subscriptions for a specific path
8290
+ * Notify subscriptions for a specific path.
8291
+ *
8292
+ * **A subscriber only ever receives rows re-read under its own scope.**
8293
+ * `row` is used to decide *that* something changed, never to say *what* —
8294
+ * every delivery below goes through a refetch that binds the subscription's
8295
+ * own auth context.
8296
+ *
8297
+ * It used to be conditional. The CDC path already did the right thing: it
8298
+ * discards the captured tuple and emits `{_rebase_invalidated: true}`, and
8299
+ * that marker selected the refetch branch. But the marker is produced in
8300
+ * exactly two places, and the *other* side of each branch here shipped the
8301
+ * row it was handed straight to the socket. Two of the three entry paths
8302
+ * took that side — every API mutation (`PostgresBackendDriver.save` passes
8303
+ * the row it just wrote, read under the **writer's** scope) and the legacy
8304
+ * cross-instance LISTEN handler (which re-reads on the owner connection,
8305
+ * bypassing RLS altogether). Path matching was the only filter applied: the
8306
+ * subscription's own `filter`/`logical` was never evaluated, and any
8307
+ * `afterRead` redaction was the writer's rather than the reader's.
8308
+ *
8309
+ * A single-row subscription was the sharpest case. `subscribe_one` on a row
8310
+ * RLS denies is accepted and answered `null`; the next update then pushed
8311
+ * the full row with no later correction. The collection variant was merely
8312
+ * papered over ~300 ms later by the debounced refetch — after the bytes had
8313
+ * already reached the browser.
8314
+ *
8315
+ * The same defect was found and fixed on the Mongo driver in `065e2b615`
8316
+ * (see `packages/server-mongo/test/realtime-authorization.test.ts`); this is
8317
+ * the Postgres half, stated as one rule rather than three patched branches.
8318
+ *
8319
+ * The cost is the instant row-level patch that used to precede the refetch:
8320
+ * cross-tab feedback now waits for the debounce. That is the price of not
8321
+ * being able to know, without asking the database as this subscriber,
8322
+ * whether this subscriber may see the row at all.
8162
8323
  */
8163
8324
  async notifyPathUpdate(notifyPath, originalPath, id, row, _databaseId) {
8164
8325
  this.debugLog(`📡 [RealtimeService] Notifying path: ${notifyPath} (original: ${originalPath})`);
@@ -8172,12 +8333,8 @@ var RealtimeService = class RealtimeService extends EventEmitter {
8172
8333
  const webSocketSubscriptions = allSubscriptions.filter(([, sub]) => sub.clientId !== "driver" && this.clients.has(sub.clientId));
8173
8334
  const driverSubscriptions = allSubscriptions.filter(([subscriptionId, sub]) => sub.clientId === "driver" && this.subscriptionCallbacks.has(subscriptionId));
8174
8335
  for (const [subscriptionId, subscription] of webSocketSubscriptions) try {
8175
- if (subscription.type === "single" && notifyPath === originalPath) if (row && row?._rebase_invalidated) this.debouncedSingleRefetch(subscriptionId, notifyPath, id, subscription);
8176
- else this.sendSingleUpdate(subscription.clientId, subscriptionId, row);
8177
- else if (subscription.type === "collection" && subscription.collectionRequest) {
8178
- if (!row || !row?._rebase_invalidated) this.sendCollectionPatch(subscription.clientId, subscriptionId, id, row, notifyPath);
8179
- this.debouncedCollectionRefetch(subscriptionId, notifyPath, subscription);
8180
- }
8336
+ if (subscription.type === "single" && notifyPath === originalPath) this.debouncedSingleRefetch(subscriptionId, notifyPath, id, subscription);
8337
+ else if (subscription.type === "collection" && subscription.collectionRequest) this.debouncedCollectionRefetch(subscriptionId, notifyPath, subscription);
8181
8338
  } catch (error) {
8182
8339
  const sanitized = sanitizeErrorForClient(error, notifyPath);
8183
8340
  this.sendError(subscription.clientId, sanitized.message, subscriptionId, sanitized.code);
@@ -8185,8 +8342,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
8185
8342
  for (const [subscriptionId, subscription] of driverSubscriptions) try {
8186
8343
  const callback = this.subscriptionCallbacks.get(subscriptionId);
8187
8344
  if (!callback) continue;
8188
- if (subscription.type === "single" && notifyPath === originalPath) if (row && row?._rebase_invalidated) this.debouncedSingleDriverRefetch(subscriptionId, notifyPath, id, subscription, callback);
8189
- else callback(row);
8345
+ if (subscription.type === "single" && notifyPath === originalPath) this.debouncedSingleDriverRefetch(subscriptionId, notifyPath, id, subscription, callback);
8190
8346
  else if (subscription.type === "collection" && subscription.collectionRequest) this.debouncedDriverRefetch(subscriptionId, notifyPath, subscription, callback);
8191
8347
  } catch (error) {
8192
8348
  logger.error(`❌ [RealtimeService] Error processing DataDriver subscription ${subscriptionId}`, { error });
@@ -8250,10 +8406,12 @@ var RealtimeService = class RealtimeService extends EventEmitter {
8250
8406
  let fetchedEntities;
8251
8407
  if (collectionRequest.searchString) fetchedEntities = await txEntityService.searchRows(notifyPath, collectionRequest.searchString, {
8252
8408
  filter: collectionRequest.filter,
8409
+ logical: collectionRequest.logical,
8253
8410
  orderBy: collectionRequest.orderBy,
8254
8411
  order: collectionRequest.order,
8255
8412
  limit: collectionRequest.limit,
8256
- databaseId: collectionRequest.databaseId
8413
+ databaseId: collectionRequest.databaseId,
8414
+ searchExplain: collectionRequest.searchExplain
8257
8415
  });
8258
8416
  else fetchedEntities = await txEntityService.fetchCollection(notifyPath, {
8259
8417
  filter: collectionRequest.filter,
@@ -8310,13 +8468,16 @@ var RealtimeService = class RealtimeService extends EventEmitter {
8310
8468
  }
8311
8469
  if (collectionRequest.searchString) return await this.dataService.searchRows(notifyPath, collectionRequest.searchString, {
8312
8470
  filter: collectionRequest.filter,
8471
+ logical: collectionRequest.logical,
8313
8472
  orderBy: collectionRequest.orderBy,
8314
8473
  order: collectionRequest.order,
8315
8474
  limit: collectionRequest.limit,
8316
- databaseId: collectionRequest.databaseId
8475
+ databaseId: collectionRequest.databaseId,
8476
+ searchExplain: collectionRequest.searchExplain
8317
8477
  });
8318
8478
  return await this.dataService.fetchCollection(notifyPath, {
8319
8479
  filter: collectionRequest.filter,
8480
+ logical: collectionRequest.logical,
8320
8481
  orderBy: collectionRequest.orderBy,
8321
8482
  order: collectionRequest.order,
8322
8483
  limit: collectionRequest.limit,
@@ -8446,16 +8607,6 @@ var RealtimeService = class RealtimeService extends EventEmitter {
8446
8607
  * columns and no address. The SDK holds no collection config to derive one
8447
8608
  * from, so this is the only place the mapping can come from.
8448
8609
  */
8449
- sendCollectionPatch(clientId, subscriptionId, id, row, notifyPath) {
8450
- const message = {
8451
- type: "collection_patch",
8452
- subscriptionId,
8453
- id,
8454
- row,
8455
- pks: this.primaryKeysForPath(notifyPath)
8456
- };
8457
- this.sendMessage(clientId, message);
8458
- }
8459
8610
  /** The key columns of the collection at `path`, if they can be resolved. */
8460
8611
  primaryKeysForPath(path) {
8461
8612
  try {
@@ -8500,12 +8651,148 @@ var RealtimeService = class RealtimeService extends EventEmitter {
8500
8651
  }
8501
8652
  return parentPaths;
8502
8653
  }
8654
+ /**
8655
+ * Install a channel authorizer — see {@link ChannelAuthorizer}.
8656
+ *
8657
+ * Nothing in the framework calls this yet: it is the seam a rules API will
8658
+ * be built on, kept deliberately separate from the membership floor so the
8659
+ * floor holds whether or not anyone uses it.
8660
+ */
8661
+ setChannelAuthorizer(authorizer) {
8662
+ this.channelAuthorizer = authorizer;
8663
+ }
8664
+ /** Which action each channel frame is asking to perform. */
8665
+ static CHANNEL_ACTIONS = {
8666
+ join_channel: "join",
8667
+ broadcast: "broadcast",
8668
+ channel_history: "history",
8669
+ presence_track: "join",
8670
+ presence_state: "presence"
8671
+ };
8672
+ /**
8673
+ * The one door every channel frame comes through.
8674
+ *
8675
+ * Returns synchronously — and so dispatches synchronously — unless an
8676
+ * authorizer is installed. That matters: a client sends `join_channel`,
8677
+ * `presence_state` and `channel_history` back to back on connect, and the
8678
+ * socket's message handler processes each frame up to its first `await`,
8679
+ * so a gate that always yielded would let the reads overtake the join that
8680
+ * is about to authorize them.
8681
+ */
8682
+ handleChannelMessage(clientId, type, payload, authContext) {
8683
+ const channel = payload?.channel;
8684
+ if (type === "leave_channel") {
8685
+ this.leaveChannel(clientId, channel);
8686
+ return;
8687
+ }
8688
+ if (type === "presence_untrack") {
8689
+ this.removePresence(clientId, channel);
8690
+ return;
8691
+ }
8692
+ const action = RealtimeService.CHANNEL_ACTIONS[type];
8693
+ const allowed = this.authorizeChannelAction(clientId, channel, action, authContext);
8694
+ if (allowed === false) return;
8695
+ if (allowed === true) return this.dispatchChannelMessage(clientId, type, channel, payload);
8696
+ return allowed.then((ok) => {
8697
+ if (ok) return this.dispatchChannelMessage(clientId, type, channel, payload);
8698
+ });
8699
+ }
8700
+ /** Perform an already-authorized channel frame. */
8701
+ dispatchChannelMessage(clientId, type, channel, payload) {
8702
+ switch (type) {
8703
+ case "join_channel":
8704
+ this.joinChannel(clientId, channel);
8705
+ return;
8706
+ case "broadcast":
8707
+ this.broadcastToChannel(clientId, channel, payload?.event, payload?.payload);
8708
+ return;
8709
+ case "channel_history": return this.handleChannelHistoryRequest(clientId, channel, payload?.sinceSeq, payload?.limit);
8710
+ case "presence_track":
8711
+ this.joinChannel(clientId, channel);
8712
+ this.trackPresence(clientId, channel, payload?.state ?? {});
8713
+ return;
8714
+ case "presence_state":
8715
+ this.sendPresenceState(clientId, channel);
8716
+ return;
8717
+ }
8718
+ }
8719
+ /**
8720
+ * Decide whether a client may perform an action on a channel.
8721
+ *
8722
+ * **Membership is the floor.** Reading a channel's presence roster, replaying
8723
+ * its retained history and broadcasting into it all require that this client
8724
+ * has joined it. That is a low bar — joining is open to anyone who can name
8725
+ * the channel — but it is not the bar that was there before, which was none
8726
+ * at all: `channel_history` and `presence_state` answered any socket about
8727
+ * any channel, and a broadcast fanned out to members the sender had never
8728
+ * joined. Two internal tables (`rebase.channel_presence`,
8729
+ * `rebase.channel_messages`) are held outside RLS on the strength of this
8730
+ * check, so it fails closed: an authorizer that throws refuses the frame.
8731
+ *
8732
+ * Anything richer than membership belongs in a {@link ChannelAuthorizer};
8733
+ * this method is where it is consulted, and the only place.
8734
+ */
8735
+ authorizeChannelAction(clientId, channel, action, authContext) {
8736
+ if (action !== "join" && !this.channels.get(channel)?.has(clientId)) {
8737
+ this.denyChannelAction(clientId, channel, action, "not a member of the channel");
8738
+ return false;
8739
+ }
8740
+ const authorizer = this.channelAuthorizer;
8741
+ if (!authorizer) return true;
8742
+ let verdict;
8743
+ try {
8744
+ verdict = authorizer({
8745
+ channel,
8746
+ action,
8747
+ clientId,
8748
+ user: authContext
8749
+ });
8750
+ } catch (error) {
8751
+ logger.error(`❌ [Channels] Authorizer threw for ${action} on "${channel}" — refusing`, { error });
8752
+ this.denyChannelAction(clientId, channel, action, "channel authorization failed");
8753
+ return false;
8754
+ }
8755
+ if (typeof verdict === "boolean") {
8756
+ if (!verdict) this.denyChannelAction(clientId, channel, action, "refused by the channel authorizer");
8757
+ return verdict;
8758
+ }
8759
+ return verdict.then((ok) => {
8760
+ if (!ok) this.denyChannelAction(clientId, channel, action, "refused by the channel authorizer");
8761
+ return ok;
8762
+ }, (error) => {
8763
+ logger.error(`❌ [Channels] Authorizer rejected for ${action} on "${channel}" — refusing`, { error });
8764
+ this.denyChannelAction(clientId, channel, action, "channel authorization failed");
8765
+ return false;
8766
+ });
8767
+ }
8768
+ /** Tell the client why its channel frame went nowhere, and say so in the log. */
8769
+ denyChannelAction(clientId, channel, action, reason) {
8770
+ this.debugLog(`🚫 [Channels] Refused ${action} on "${channel}" for ${clientId}: ${reason}`);
8771
+ this.sendError(clientId, `Refused ${action} on channel "${channel}": ${reason}`, void 0, "CHANNEL_FORBIDDEN");
8772
+ }
8503
8773
  /** Join a broadcast channel */
8504
8774
  joinChannel(clientId, channel) {
8505
8775
  if (!this.channels.has(channel)) this.channels.set(channel, /* @__PURE__ */ new Set());
8506
8776
  this.channels.get(channel).add(clientId);
8777
+ this.warnIfMemoryBusOnMultiplePods();
8507
8778
  this.debugLog(`📡 [Broadcast] Client ${clientId} joined channel: ${channel}`);
8508
8779
  }
8780
+ /**
8781
+ * Say something the first time channels are used on a deployment that is
8782
+ * demonstrably multi-pod while the bus is still the in-memory default.
8783
+ *
8784
+ * Every other warning in this subsystem covers a *configured* bus failing —
8785
+ * the case where the operator already knew a bus mattered. The common
8786
+ * misconfiguration is the opposite one: scaled to two replicas, never
8787
+ * touched `realtime.bus`, and broadcast and presence quietly serve a
8788
+ * fraction of the room. The evidence is already in the process, so use it.
8789
+ */
8790
+ warnIfMemoryBusOnMultiplePods() {
8791
+ if (this.memoryBusWarned) return;
8792
+ if (this.bus.kind !== "memory" || !this.foreignInstanceSeen) return;
8793
+ this.memoryBusWarned = true;
8794
+ logger.warn("⚠️ [ChannelBus] Channels are in use with the in-memory bus, but notifications from another instance have been seen — this deployment runs more than one process. Broadcast and presence reach only the clients connected to this one. Set `realtime.bus` (or REBASE_REALTIME_BUS=postgres) to make channels cross-instance.");
8795
+ }
8509
8796
  /** Leave a broadcast channel */
8510
8797
  leaveChannel(clientId, channel) {
8511
8798
  const members = this.channels.get(channel);
@@ -9000,7 +9287,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
9000
9287
  throw err;
9001
9288
  }
9002
9289
  this.cdcActive = true;
9003
- logger.info(`📡 [RealtimeService] Database-level change capture ACTIVE — writes from ANY source now emit realtime events (${this.cdcTableMap.size} mapped table key(s)).`);
9290
+ logger.debug(`📡 [RealtimeService] Database-level change capture ACTIVE — writes from ANY source now emit realtime events (${this.cdcTableMap.size} mapped table key(s)).`);
9004
9291
  }
9005
9292
  /** Stop the CDC listener and clear its state. */
9006
9293
  async stopCdc() {
@@ -9183,6 +9470,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
9183
9470
  try {
9184
9471
  const { sid, p, eid, db } = JSON.parse(msg.payload);
9185
9472
  if (sid === this.instanceId) return;
9473
+ this.foreignInstanceSeen = true;
9186
9474
  this.debugLog(`📡 [RealtimeService] Received cross-instance notification: path=${p}, id=${eid}, from=${sid}`);
9187
9475
  let refetchedRow = null;
9188
9476
  try {
@@ -9373,7 +9661,7 @@ function createBackupCron(config) {
9373
9661
  enabled: config.enabled ?? true,
9374
9662
  timeoutSeconds: 3600,
9375
9663
  async handler({ log }) {
9376
- const { createDump, pruneBackups, uploadBackup, validateDump } = await import("./backup-service-Bww-Lg0s.js").then((n) => n.r);
9664
+ const { createDump, pruneBackups, uploadBackup, validateDump } = await import("./backup-service-BH0Dzo_h.js").then((n) => n.r);
9377
9665
  const { destination } = config;
9378
9666
  if (destination.kind !== "local" && !config.storage) throw new Error(`Backup destination is ${destination.kind} but no storage controller was provided. Pass the backend's configured StorageController to createBackupCron({ storage }).`);
9379
9667
  log(`Starting backup of "${dbName}"…`);
@@ -9698,7 +9986,7 @@ function buildCollectionRegistry(schema) {
9698
9986
  const registry = new PostgresCollectionRegistry();
9699
9987
  if (schema.collections) {
9700
9988
  registry.registerMultiple(schema.collections);
9701
- logger.info(`📋 [PostgresRegistry] Registered ${registry.getCollections().length} collections: [${registry.getCollections().map((c) => c.slug).join(", ")}]`);
9989
+ logger.debug(`📋 [PostgresRegistry] Registered ${registry.getCollections().length} collections: [${registry.getCollections().map((c) => c.slug).join(", ")}]`);
9702
9990
  }
9703
9991
  if (schema.tables) Object.values(schema.tables).forEach((table) => {
9704
9992
  if (isTable(table)) registry.registerTable(table, getTableName(table));
@@ -9873,7 +10161,7 @@ async function probeAuthSchema(db, authSchema) {
9873
10161
  * When omitted, a default `rebase.users` table is created.
9874
10162
  */
9875
10163
  async function ensureAuthTablesExist(db, collection) {
9876
- logger.info("🔍 Checking auth tables...");
10164
+ logger.debug("🔍 Checking auth tables...");
9877
10165
  await assertAuthSchemaCompatible(db, resolveAuthSchema(collection));
9878
10166
  try {
9879
10167
  let usersTableName = "\"rebase\".\"users\"";
@@ -9904,7 +10192,7 @@ async function ensureAuthTablesExist(db, collection) {
9904
10192
  if (dbType === "UUID") userIdType = "UUID";
9905
10193
  else if (dbType === "INTEGER" || dbType === "SMALLINT" || dbType === "BIGINT") userIdType = "INTEGER";
9906
10194
  else userIdType = "TEXT";
9907
- logger.info(`✨ Detected ${usersTableName}.id type from database: ${dbType}. Using user_id type: ${userIdType}`);
10195
+ logger.debug(`✨ Detected ${usersTableName}.id type from database: ${dbType}. Using user_id type: ${userIdType}`);
9908
10196
  }
9909
10197
  } catch (err) {
9910
10198
  logger.warn(`⚠️ Failed to introspect ${usersTableName}.id type from database, falling back to config type: ${userIdType}`, { error: err });
@@ -10191,7 +10479,7 @@ async function ensureAuthTablesExist(db, collection) {
10191
10479
  FROM information_schema.tables
10192
10480
  WHERE table_name = 'refresh_tokens'
10193
10481
  `)).rows;
10194
- logger.info(`🔍 refresh_tokens reconcile: found ${found.length} table(s): ${found.map((r) => `"${r.table_schema}"."${r.table_name}"`).join(", ") || "(none)"}`);
10482
+ logger.debug(`🔍 refresh_tokens reconcile: found ${found.length} table(s): ${found.map((r) => `"${r.table_schema}"."${r.table_name}"`).join(", ") || "(none)"}`);
10195
10483
  for (const { table_schema } of found) {
10196
10484
  const qualified = `"${table_schema}"."refresh_tokens"`;
10197
10485
  try {
@@ -10199,6 +10487,7 @@ async function ensureAuthTablesExist(db, collection) {
10199
10487
  await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS revoked BOOLEAN DEFAULT FALSE NOT NULL`);
10200
10488
  await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS rotated_at TIMESTAMP WITH TIME ZONE`);
10201
10489
  await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS session_started_at TIMESTAMP WITH TIME ZONE`);
10490
+ await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS aal TEXT`);
10202
10491
  await db.execute(sql`
10203
10492
  UPDATE ${sql.raw(qualified)}
10204
10493
  SET session_id = gen_random_uuid()::text
@@ -10218,7 +10507,7 @@ async function ensureAuthTablesExist(db, collection) {
10218
10507
  ON ${sql.raw(qualified)}(session_id)
10219
10508
  `);
10220
10509
  await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} DROP CONSTRAINT IF EXISTS unique_device_session`);
10221
- logger.info(`✅ refresh_tokens reconciled for session-scoped rotation: ${qualified}`);
10510
+ logger.debug(`✅ refresh_tokens reconciled for session-scoped rotation: ${qualified}`);
10222
10511
  } catch (perTableError) {
10223
10512
  logger.warn(`⚠️ refresh_tokens reconcile failed for ${qualified}: ${perTableError instanceof Error ? perTableError.message : String(perTableError)}`);
10224
10513
  }
@@ -10261,6 +10550,7 @@ async function ensureAuthTablesExist(db, collection) {
10261
10550
  secret_encrypted TEXT NOT NULL,
10262
10551
  friendly_name TEXT,
10263
10552
  verified BOOLEAN DEFAULT FALSE,
10553
+ last_used_counter BIGINT,
10264
10554
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
10265
10555
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
10266
10556
  )
@@ -10276,6 +10566,7 @@ async function ensureAuthTablesExist(db, collection) {
10276
10566
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
10277
10567
  verified_at TIMESTAMP WITH TIME ZONE,
10278
10568
  ip_address TEXT,
10569
+ attempts INTEGER NOT NULL DEFAULT 0,
10279
10570
  expires_at TIMESTAMP WITH TIME ZONE NOT NULL
10280
10571
  )
10281
10572
  `);
@@ -10283,6 +10574,12 @@ async function ensureAuthTablesExist(db, collection) {
10283
10574
  CREATE INDEX IF NOT EXISTS idx_mfa_challenges_factor
10284
10575
  ON ${sql.raw(mfaChallengesTableName)}(factor_id)
10285
10576
  `);
10577
+ try {
10578
+ await db.execute(sql`ALTER TABLE ${sql.raw(mfaFactorsTableName)} ADD COLUMN IF NOT EXISTS last_used_counter BIGINT`);
10579
+ await db.execute(sql`ALTER TABLE ${sql.raw(mfaChallengesTableName)} ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0`);
10580
+ } catch (mfaMigrationError) {
10581
+ logger.warn(`⚠️ MFA hardening columns skipped: ${mfaMigrationError instanceof Error ? mfaMigrationError.message : String(mfaMigrationError)}`);
10582
+ }
10286
10583
  await db.execute(sql`
10287
10584
  CREATE TABLE IF NOT EXISTS ${sql.raw(recoveryCodesTableName)} (
10288
10585
  id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
@@ -10330,7 +10627,7 @@ async function ensureAuthTablesExist(db, collection) {
10330
10627
  await revokeInternalTableAccess(async (text) => {
10331
10628
  await db.execute(sql.raw(text));
10332
10629
  }, authSchema, { onError: (table, err) => logger.warn(`🔐 Could not revoke authenticated-role access to "${authSchema}"."${table}": ` + (err instanceof Error ? err.message : String(err))) });
10333
- logger.info("✅ Auth tables ready");
10630
+ logger.debug("✅ Auth tables ready");
10334
10631
  } catch (error) {
10335
10632
  if (error instanceof AuthSchemaVersionError) throw error;
10336
10633
  logger.error("❌ Failed to create auth tables", { error });
@@ -10603,7 +10900,7 @@ var UserService = class {
10603
10900
  const conditions = [];
10604
10901
  if (roleId) conditions.push(sql`${roleId} = ANY(${sql.raw(usersTableName)}.roles)`);
10605
10902
  if (search) {
10606
- const pattern = `%${search}%`;
10903
+ const pattern = `%${escapeLikePattern(search)}%`;
10607
10904
  conditions.push(sql`(${sql.raw(usersTableName)}.${sql.raw(emailColumn)} ILIKE ${pattern} OR ${sql.raw(usersTableName)}.${sql.raw(displayNameColumn)} ILIKE ${pattern})`);
10608
10905
  }
10609
10906
  const whereClause = conditions.length > 0 ? sql`WHERE ${sql.join(conditions, sql` AND `)}` : sql``;
@@ -10779,7 +11076,8 @@ var RefreshTokenService = class {
10779
11076
  "sessionId",
10780
11077
  "rotatedAt",
10781
11078
  "revoked",
10782
- "sessionStartedAt"
11079
+ "sessionStartedAt",
11080
+ "aal"
10783
11081
  ]) if (this.has(optional)) selection[optional] = this.col(optional);
10784
11082
  return selection;
10785
11083
  }
@@ -10793,6 +11091,7 @@ var RefreshTokenService = class {
10793
11091
  };
10794
11092
  if (session && this.has("sessionId")) values.sessionId = session.id;
10795
11093
  if (session && this.has("sessionStartedAt")) values.sessionStartedAt = session.startedAt;
11094
+ if (session?.aal && this.has("aal")) values.aal = session.aal;
10796
11095
  await this.db.insert(this.refreshTokensTable).values(values);
10797
11096
  }
10798
11097
  async findByHash(tokenHash) {
@@ -11270,6 +11569,9 @@ var PostgresAuthRepository = class {
11270
11569
  async verifyMfaFactor(factorId) {
11271
11570
  return this.getMfaService().verifyMfaFactor(factorId);
11272
11571
  }
11572
+ async updateMfaFactorSecret(factorId, secretEncrypted) {
11573
+ return this.getMfaService().updateMfaFactorSecret(factorId, secretEncrypted);
11574
+ }
11273
11575
  async deleteMfaFactor(factorId, uid) {
11274
11576
  return this.getMfaService().deleteMfaFactor(factorId, uid);
11275
11577
  }
@@ -11297,6 +11599,12 @@ var PostgresAuthRepository = class {
11297
11599
  async hasVerifiedMfaFactors(uid) {
11298
11600
  return this.getMfaService().hasVerifiedMfaFactors(uid);
11299
11601
  }
11602
+ async claimMfaFactorCounter(factorId, counter) {
11603
+ return this.getMfaService().claimMfaFactorCounter(factorId, counter);
11604
+ }
11605
+ async recordMfaChallengeAttempt(challengeId) {
11606
+ return this.getMfaService().recordMfaChallengeAttempt(challengeId);
11607
+ }
11300
11608
  };
11301
11609
  /**
11302
11610
  * PostgreSQL implementation of MfaRepository.
@@ -11349,7 +11657,7 @@ var MfaService = class {
11349
11657
  async getMfaFactorById(factorId) {
11350
11658
  const tableName = this.qualify("mfa_factors");
11351
11659
  const result = await this.db.execute(sql`
11352
- SELECT id, uid, factor_type, secret_encrypted, friendly_name, verified, created_at, updated_at
11660
+ SELECT id, uid, factor_type, secret_encrypted, friendly_name, verified, last_used_counter, created_at, updated_at
11353
11661
  FROM ${sql.raw(tableName)}
11354
11662
  WHERE id = ${factorId}
11355
11663
  `);
@@ -11362,10 +11670,29 @@ var MfaService = class {
11362
11670
  secretEncrypted: row.secret_encrypted,
11363
11671
  friendlyName: row.friendly_name ?? void 0,
11364
11672
  verified: row.verified,
11673
+ lastUsedCounter: row.last_used_counter === null || row.last_used_counter === void 0 ? null : Number(row.last_used_counter),
11365
11674
  createdAt: new Date(row.created_at),
11366
11675
  updatedAt: new Date(row.updated_at)
11367
11676
  };
11368
11677
  }
11678
+ /**
11679
+ * Spend a TOTP time step, once and only once.
11680
+ *
11681
+ * One statement: the `WHERE` is the check, the `UPDATE` is the act, and
11682
+ * `RETURNING` reports which of two concurrent requests carrying the same
11683
+ * six digits won. Reading the counter and then writing it would let both
11684
+ * pass — the exact replay this closes.
11685
+ */
11686
+ async claimMfaFactorCounter(factorId, counter) {
11687
+ const tableName = this.qualify("mfa_factors");
11688
+ return (await this.db.execute(sql`
11689
+ UPDATE ${sql.raw(tableName)}
11690
+ SET last_used_counter = ${counter}, updated_at = NOW()
11691
+ WHERE id = ${factorId}
11692
+ AND (last_used_counter IS NULL OR last_used_counter < ${counter})
11693
+ RETURNING id
11694
+ `)).rows.length > 0;
11695
+ }
11369
11696
  async verifyMfaFactor(factorId) {
11370
11697
  const tableName = this.qualify("mfa_factors");
11371
11698
  await this.db.execute(sql`
@@ -11374,6 +11701,14 @@ var MfaService = class {
11374
11701
  WHERE id = ${factorId}
11375
11702
  `);
11376
11703
  }
11704
+ async updateMfaFactorSecret(factorId, secretEncrypted) {
11705
+ const tableName = this.qualify("mfa_factors");
11706
+ await this.db.execute(sql`
11707
+ UPDATE ${sql.raw(tableName)}
11708
+ SET secret_encrypted = ${secretEncrypted}, updated_at = NOW()
11709
+ WHERE id = ${factorId}
11710
+ `);
11711
+ }
11377
11712
  async deleteMfaFactor(factorId, uid) {
11378
11713
  const tableName = this.qualify("mfa_factors");
11379
11714
  await this.db.execute(sql`
@@ -11400,7 +11735,7 @@ var MfaService = class {
11400
11735
  async getMfaChallengeById(challengeId) {
11401
11736
  const tableName = this.qualify("mfa_challenges");
11402
11737
  const result = await this.db.execute(sql`
11403
- SELECT id, factor_id, created_at, verified_at, ip_address, expires_at
11738
+ SELECT id, factor_id, created_at, verified_at, ip_address, attempts, expires_at
11404
11739
  FROM ${sql.raw(tableName)}
11405
11740
  WHERE id = ${challengeId} AND expires_at > NOW() AND verified_at IS NULL
11406
11741
  `);
@@ -11411,9 +11746,28 @@ var MfaService = class {
11411
11746
  factorId: row.factor_id,
11412
11747
  createdAt: new Date(row.created_at),
11413
11748
  verifiedAt: row.verified_at ? new Date(row.verified_at) : void 0,
11414
- ipAddress: row.ip_address ?? void 0
11749
+ ipAddress: row.ip_address ?? void 0,
11750
+ attempts: Number(row.attempts ?? 0)
11415
11751
  };
11416
11752
  }
11753
+ /**
11754
+ * Count one failed guess against a challenge and report the new total.
11755
+ *
11756
+ * Incremented in the database rather than in the route so that guesses
11757
+ * arriving in parallel — the shape any real brute-force takes — cannot
11758
+ * share a single increment.
11759
+ */
11760
+ async recordMfaChallengeAttempt(challengeId) {
11761
+ const tableName = this.qualify("mfa_challenges");
11762
+ const result = await this.db.execute(sql`
11763
+ UPDATE ${sql.raw(tableName)}
11764
+ SET attempts = attempts + 1
11765
+ WHERE id = ${challengeId}
11766
+ RETURNING attempts
11767
+ `);
11768
+ if (result.rows.length === 0) return 0;
11769
+ return Number(result.rows[0].attempts);
11770
+ }
11417
11771
  async verifyMfaChallenge(challengeId) {
11418
11772
  const tableName = this.qualify("mfa_challenges");
11419
11773
  await this.db.execute(sql`
@@ -11634,7 +11988,7 @@ function findChangedFields(oldValues, newValues) {
11634
11988
  * pattern as `ensureAuthTablesExist`.
11635
11989
  */
11636
11990
  async function ensureHistoryTableExists(db) {
11637
- logger.info("🔍 Checking row history table...");
11991
+ logger.debug("🔍 Checking row history table...");
11638
11992
  try {
11639
11993
  await db.execute(sql`CREATE SCHEMA IF NOT EXISTS rebase`);
11640
11994
  await db.execute(sql`
@@ -11659,7 +12013,7 @@ async function ensureHistoryTableExists(db) {
11659
12013
  ON rebase.entity_history(table_name, entity_id, updated_at DESC)
11660
12014
  `);
11661
12015
  await db.execute(sql.raw(revokeInternalTableSql("rebase", "entity_history")));
11662
- logger.info("✅ Entity history table ready");
12016
+ logger.debug("✅ Entity history table ready");
11663
12017
  } catch (error) {
11664
12018
  logger.error("❌ Failed to create row history table", { error });
11665
12019
  logger.warn("⚠️ Continuing without creating history table.");
@@ -12279,6 +12633,43 @@ function resolveDriftCheckName(col, registeredTableNames) {
12279
12633
  return (isRelationalCollectionConfig(col) ? col.table : void 0) ?? registeredTableNames.find((k) => k === col.slug) ?? col.slug;
12280
12634
  }
12281
12635
  /**
12636
+ * Is this the local database `rebase init` scaffolds — i.e. the one case where
12637
+ * "you are connected as a superuser" is not news?
12638
+ *
12639
+ * The scaffold's own `docker-compose.yml` sets `POSTGRES_USER: rebase_app`,
12640
+ * which makes that role the cluster superuser, so the superuser advisory below
12641
+ * was the only WARN a brand-new project ever saw and it was about a decision
12642
+ * the tool had made for the developer.
12643
+ *
12644
+ * Of the two available fixes — provision a non-superuser table-owner role in
12645
+ * the scaffold, or recognise the local shape and stay quiet — this is the
12646
+ * second, because the first breaks the scaffold it is meant to improve: a
12647
+ * non-superuser owner cannot `CREATE EXTENSION` (search collections need
12648
+ * `pg_trgm`/`unaccent`, applied by `rebase db push` and again by the boot
12649
+ * schema-ensure), so the very first `pnpm run db:push` on a scaffolded project
12650
+ * with a search block would fail. Trading a working first run for a quieter log
12651
+ * line is the wrong trade.
12652
+ *
12653
+ * The condition is deliberately narrow — a *non-production* process talking to
12654
+ * a database on the loopback interface. A genuine production superuser
12655
+ * connection still warns, and so does a non-production process pointed at a
12656
+ * remote database (the usual "my dev machine writes to staging" mistake, where
12657
+ * the advisory is exactly right). NODE_ENV alone would not do: the scaffold
12658
+ * ships `NODE_ENV=development` and some deployments inherit it.
12659
+ */
12660
+ function isScaffoldedLocalDatabase(connectionString) {
12661
+ if (process.env.NODE_ENV === "production") return false;
12662
+ if (!connectionString) return false;
12663
+ let host;
12664
+ try {
12665
+ host = new URL(connectionString).hostname;
12666
+ } catch {
12667
+ return false;
12668
+ }
12669
+ const bare = host.replace(/^\[|\]$/g, "").toLowerCase();
12670
+ return bare === "localhost" || bare === "::1" || bare === "0.0.0.0" || bare === "" || /^127\./.test(bare) || bare.endsWith(".localhost");
12671
+ }
12672
+ /**
12282
12673
  * Default PostgreSQL bootstrapper.
12283
12674
  *
12284
12675
  * Use it to register Postgres with `initializeRebaseBackend()`:
@@ -12391,7 +12782,11 @@ function createPostgresBootstrapper(pgConfig) {
12391
12782
  driver.rlsUserRole = REBASE_USER_ROLE;
12392
12783
  realtimeService.rlsUserRole = REBASE_USER_ROLE;
12393
12784
  logger.info(`🔐 RLS enforcement active: authenticated requests run as "${REBASE_USER_ROLE}" (connection "${posture.role}" bypasses RLS: ${posture.superuser ? "superuser" : posture.bypassRLS ? "BYPASSRLS" : "table owner"})`);
12394
- if (posture.superuser || posture.bypassRLS) logger.warn(`⚠️ The database connection runs as ${posture.superuser ? "a superuser" : "a BYPASSRLS role"} ("${posture.role}"). User requests are isolated via SET LOCAL ROLE, but connect as a non-superuser table-owner role in production so the server/owner context is least-privilege.`);
12785
+ if (posture.superuser || posture.bypassRLS) {
12786
+ const message = `The database connection runs as ${posture.superuser ? "a superuser" : "a BYPASSRLS role"} ("${posture.role}"). User requests are isolated via SET LOCAL ROLE, but connect as a non-superuser table-owner role in production so the server/owner context is least-privilege.`;
12787
+ if (isScaffoldedLocalDatabase(pgConfig.connectionString)) logger.debug(`🔐 ${message}`);
12788
+ else logger.warn(`⚠️ ${message}`);
12789
+ }
12395
12790
  } else logger.info(`🔐 RLS enforcement: connection role "${posture.role}" is subject to RLS natively; no role switch needed.`);
12396
12791
  await validatePolicyPgRoles(runSql, registry.getCollections(), driver.rlsUserRole ?? posture.role);
12397
12792
  warnOnAnonymousGrants(registry.getCollections());
@@ -12611,12 +13006,12 @@ function createPostgresBootstrapper(pgConfig) {
12611
13006
  */
12612
13007
  async ensureCollectionSchema(collections, driverResult, log) {
12613
13008
  const internals = driverResult.internals;
12614
- const { ensureCollectionTables } = await import("./ensure-collection-tables-DSIxvLLD.js");
13009
+ const { ensureCollectionTables } = await import("./ensure-collection-tables-DWVISfcC.js");
12615
13010
  const plan = await ensureCollectionTables({ async query(text) {
12616
13011
  const result = await internals.db.execute(sql.raw(text));
12617
13012
  return { rows: result.rows ?? (Array.isArray(result) ? result : []) };
12618
13013
  } }, collections, log);
12619
- for (const failure of plan.failures) logger.warn(`🔗 [schema] Could not add foreign key "${failure.target}" — the column exists and the collection still serves, but rows are not policed by this constraint: ${failure.error}`);
13014
+ for (const failure of plan.failures) logger.warn(failure.kind === "comment-column" ? `🔍 [schema] Could not record the search fingerprint on "${failure.target}" — search works, but a later change to the \`search\` block will not be detected: ${failure.error}` : `🔗 [schema] Could not add foreign key "${failure.target}" — the column exists and the collection still serves, but rows are not policed by this constraint: ${failure.error}`);
12620
13015
  return { applied: plan.actions.length - plan.failures.length };
12621
13016
  },
12622
13017
  /**
@@ -12636,15 +13031,18 @@ function createPostgresBootstrapper(pgConfig) {
12636
13031
  */
12637
13032
  async ensureCollectionPolicies(collections, driverResult, log) {
12638
13033
  const internals = driverResult.internals;
12639
- const { ensureCollectionPolicies } = await import("./ensure-collection-policies-DMUdRQdM.js");
13034
+ const { ensureCollectionPolicies } = await import("./ensure-collection-policies-CP5_YttS.js");
12640
13035
  const outcome = await ensureCollectionPolicies({ async query(text) {
12641
13036
  const result = await internals.db.execute(sql.raw(text));
12642
13037
  return { rows: result.rows ?? (Array.isArray(result) ? result : []) };
12643
13038
  } }, collections, log);
12644
13039
  for (const skip of outcome.skipped) logger.warn(`🔐 [rls] Policies not applied to "${skip.table}": ${skip.reason}`);
12645
- for (const failure of outcome.failures) logger.warn(`🔐 [rls] Could not fully apply policies to "${failure.table}" — it stays locked (denies) until this is resolved: ${failure.error}`);
13040
+ for (const failure of outcome.failures) logger.warn(`🔐 [rls] Could not fully apply policies to "${failure.table}" — RLS is on, so it denies until this is resolved: ${failure.error}`);
13041
+ const unrevoked = outcome.unsecured.filter((u) => !u.grantWithdrawn);
13042
+ for (const u of outcome.unsecured.filter((u) => u.grantWithdrawn)) logger.error(`🔐 [rls] Could not enable row-level security on "${u.table}": ${u.error}. Its privileges have been revoked from ${REBASE_USER_ROLE}, so the table is unreachable rather than unprotected. Reads and writes to that collection will fail until RLS can be enabled.`);
13043
+ if (unrevoked.length > 0) throw new Error("Refusing to start: row-level security could not be enabled on " + unrevoked.map((u) => `"${u.table}" (${u.error})`).join(", ") + `, and the privileges granted to ${REBASE_USER_ROLE} could not be revoked either. The table would be served with no row filtering. Fix the database permissions (the connection role must own these tables, or be able to ALTER them) and boot again.`);
12646
13044
  try {
12647
- const { dropLegacyAuthSchema } = await import("./rls-bootstrap-sql-Bpv3nUZo.js").then((n) => n.n);
13045
+ const { dropLegacyAuthSchema } = await import("./rls-bootstrap-sql-69hYT8nr.js").then((n) => n.n);
12648
13046
  await dropLegacyAuthSchema(async (text) => {
12649
13047
  return (await internals.db.execute(sql.raw(text))).rows ?? [];
12650
13048
  }, {
@@ -12661,7 +13059,7 @@ function createPostgresBootstrapper(pgConfig) {
12661
13059
  },
12662
13060
  mountRoutes(app, basePath, driverResult) {},
12663
13061
  async initializeWebsockets(server, realtimeService, driver, config, adapter) {
12664
- const { createPostgresWebSocket } = await import("./websocket-D0TBU3ia.js").then((n) => n.n);
13062
+ const { createPostgresWebSocket } = await import("./websocket-C8ZqVBiV.js").then((n) => n.n);
12665
13063
  createPostgresWebSocket(server, realtimeService, driver, config, adapter);
12666
13064
  }
12667
13065
  };
@@ -12701,6 +13099,6 @@ function createPostgresAdapter(pgConfig) {
12701
13099
  };
12702
13100
  }
12703
13101
  //#endregion
12704
- export { AuthenticatedPostgresBackendDriver, BackupToolError, BranchService, CHANNEL_BUS_NOTIFY_CHANNEL, DEFAULT_BATCH_WINDOW_MS, DatabasePoolManager, DrizzleConditionBuilder, MemoryChannelBus, PG_NOTIFY_MAX_PAYLOAD_BYTES, PostgresBackendDriver, PostgresChannelBus, PostgresCollectionRegistry, PostgresConditionBuilder, PostgresRealtimeProvider, RealtimeService, appConfig, applyGlobals, backupCronConfigFromEnv, buildBackupFilename, buildPgDumpArgs, buildPgDumpallGlobalsArgs, buildPgRestoreArgs, buildPgRestoreListArgs, buildRowSecurityPgOptions, checkToolServerCompatibility, configureUnknownFilterFields, createAuthSchema, createBackupCron, createChannelBus, createDirectDatabaseConnection, createDump, createPostgresAdapter, createPostgresBootstrapper, createPostgresDatabaseConnection, createPostgresWebSocket, createReadReplicaConnection, detectToolMajor, diagnoseRowSecurityDumpFailure, ensureDatabaseExists, frameByteLength, generateSchema, getServerVersionMajor, getUnknownFilterFieldsMode, globalsFileForDump, guardPoolAgainstDirtyRelease, isChannelBusInstance, joinStorageKey, listBackups, magicLinkTokens, magicLinkTokensRelations, mfaChallenges, mfaChallengesRelations, mfaFactors, mfaFactorsRelations, parseBackupDestination, parseBackupTimestamp, parseChannelBusFrame, parseChannelBusPayload, parseDbNameFromUrl, parsePgToolMajor, passwordResetTokens, passwordResetTokensRelations, pinSearchPath, preflight, pruneBackups, recoveryCodes, recoveryCodesRelations, refreshTokens, refreshTokensRelations, resolveChannelBusSetting, resolveConnectionString, resolveDriftCheckName, resolvePgBinary, restoreDump, selectBackupsToPrune, serverVersionNumToMajor, splitGlobalsStatements, uploadBackup, userIdentities, userIdentitiesRelations, users, usersRelations, usersSchema, validateDump, withDatabaseName };
13102
+ export { AuthenticatedPostgresBackendDriver, BackupToolError, BranchService, CHANNEL_BUS_NOTIFY_CHANNEL, DEFAULT_BATCH_WINDOW_MS, DatabasePoolManager, DrizzleConditionBuilder, MemoryChannelBus, PG_NOTIFY_MAX_PAYLOAD_BYTES, PostgresBackendDriver, PostgresChannelBus, PostgresCollectionRegistry, PostgresConditionBuilder, PostgresRealtimeProvider, RealtimeService, appConfig, applyGlobals, backupCronConfigFromEnv, buildBackupFilename, buildPgDumpArgs, buildPgDumpallGlobalsArgs, buildPgRestoreArgs, buildPgRestoreListArgs, buildRowSecurityPgOptions, checkToolServerCompatibility, configureUnknownFilterFields, createAuthSchema, createBackupCron, createChannelBus, createDirectDatabaseConnection, createDump, createPostgresAdapter, createPostgresBootstrapper, createPostgresDatabaseConnection, createPostgresWebSocket, createReadReplicaConnection, detectToolMajor, diagnoseRowSecurityDumpFailure, ensureDatabaseExists, escapeLikePattern, frameByteLength, generateSchema, getDrizzleColumn, getServerVersionMajor, getUnknownFilterFieldsMode, globalsFileForDump, guardPoolAgainstDirtyRelease, isChannelBusInstance, isScaffoldedLocalDatabase, joinStorageKey, listBackups, magicLinkTokens, magicLinkTokensRelations, mfaChallenges, mfaChallengesRelations, mfaFactors, mfaFactorsRelations, parseBackupDestination, parseBackupTimestamp, parseChannelBusFrame, parseChannelBusPayload, parseDbNameFromUrl, parsePgToolMajor, passwordResetTokens, passwordResetTokensRelations, pinSearchPath, preflight, pruneBackups, recoveryCodes, recoveryCodesRelations, refreshTokens, refreshTokensRelations, resolveChannelBusSetting, resolveConnectionString, resolveDriftCheckName, resolvePgBinary, restoreDump, selectBackupsToPrune, serverVersionNumToMajor, splitGlobalsStatements, uploadBackup, userIdentities, userIdentitiesRelations, users, usersRelations, usersSchema, validateDump, withDatabaseName };
12705
13103
 
12706
13104
  //# sourceMappingURL=index.es.js.map