@rebasepro/server-postgres 0.25.1 → 0.27.0

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 (106) hide show
  1. package/README.md +1 -1
  2. package/dist/{BranchService-ClklxyAQ.js → BranchService-B9Lu8e-P.js} +25 -9
  3. package/dist/BranchService-B9Lu8e-P.js.map +1 -0
  4. package/dist/PostgresBackendDriver.d.ts +20 -0
  5. package/dist/PostgresBootstrapper.d.ts +7 -0
  6. package/dist/auth/services.d.ts +23 -2
  7. package/dist/auth/verify-auth-tables.d.ts +21 -0
  8. package/dist/{backup-cli-gijeXe0u.js → backup-cli-BZM2Fj1I.js} +4 -4
  9. package/dist/backup-cli-BZM2Fj1I.js.map +1 -0
  10. package/dist/{boot-ddl-DYH95Qeg.js → boot-ddl-yukSebLA.js} +2 -2
  11. package/dist/{boot-ddl-DYH95Qeg.js.map → boot-ddl-yukSebLA.js.map} +1 -1
  12. package/dist/branch-diff-CxE4VlxT.js +1396 -0
  13. package/dist/branch-diff-CxE4VlxT.js.map +1 -0
  14. package/dist/branch-diff-report-DpvVf7hR.js +48 -0
  15. package/dist/branch-diff-report-DpvVf7hR.js.map +1 -0
  16. package/dist/branching/branch-diff-report.d.ts +7 -0
  17. package/dist/branching/branch-diff.d.ts +115 -0
  18. package/dist/{cli-console-CQrQ0lAY.js → cli-console-BtzxzzvU.js} +38 -5
  19. package/dist/cli-console-BtzxzzvU.js.map +1 -0
  20. package/dist/cli-console.d.ts +17 -1
  21. package/dist/{cli-errors-DiA0XFIS.js → cli-errors-BBSJqlYX.js} +58 -7
  22. package/dist/cli-errors-BBSJqlYX.js.map +1 -0
  23. package/dist/cli.js +107 -127
  24. package/dist/cli.js.map +1 -1
  25. package/dist/{collections-schema-version-T6cGvrDi.js → collections-schema-version-D7bDI0PJ.js} +13 -9
  26. package/dist/collections-schema-version-D7bDI0PJ.js.map +1 -0
  27. package/dist/{column-plan-helpers-IG6uFb1s.js → column-plan-helpers-BeSztMor.js} +5 -1
  28. package/dist/{column-plan-helpers-IG6uFb1s.js.map → column-plan-helpers-BeSztMor.js.map} +1 -1
  29. package/dist/{deferred-index-build-BE0I6sYU.js → deferred-index-build-DRnoMq-O.js} +5 -5
  30. package/dist/{deferred-index-build-BE0I6sYU.js.map → deferred-index-build-DRnoMq-O.js.map} +1 -1
  31. package/dist/{doctor-BT--1kq3.js → doctor-Cs6AtizY.js} +85 -37
  32. package/dist/doctor-Cs6AtizY.js.map +1 -0
  33. package/dist/{ensure-collection-policies-BnGOURpG.js → ensure-collection-policies-H8HN1Gbd.js} +8 -8
  34. package/dist/{ensure-collection-policies-BnGOURpG.js.map → ensure-collection-policies-H8HN1Gbd.js.map} +1 -1
  35. package/dist/{ensure-collection-tables-Cet4650m.js → ensure-collection-tables-BeF1lArf.js} +7 -7
  36. package/dist/{ensure-collection-tables-Cet4650m.js.map → ensure-collection-tables-BeF1lArf.js.map} +1 -1
  37. package/dist/{ensure-tables-l_OgFQjN.js → ensure-tables-DDkNaPN2.js} +4 -4
  38. package/dist/{ensure-tables-l_OgFQjN.js.map → ensure-tables-DDkNaPN2.js.map} +1 -1
  39. package/dist/{enum-labels-kept-nheku1pB.js → enum-labels-kept-B6loB2U_.js} +3 -3
  40. package/dist/{enum-labels-kept-nheku1pB.js.map → enum-labels-kept-B6loB2U_.js.map} +1 -1
  41. package/dist/{generate-drizzle-schema-DC0BOUpn.js → generate-drizzle-schema-D_O8_iyT.js} +2 -2
  42. package/dist/{generate-drizzle-schema-DC0BOUpn.js.map → generate-drizzle-schema-D_O8_iyT.js.map} +1 -1
  43. package/dist/{generate-drizzle-schema-logic-CPzCRD-8.js → generate-drizzle-schema-logic-D0E64iwx.js} +2 -2
  44. package/dist/{generate-drizzle-schema-logic-CPzCRD-8.js.map → generate-drizzle-schema-logic-D0E64iwx.js.map} +1 -1
  45. package/dist/{generate-files-BP-4W_gm.js → generate-files-BpgyRwhU.js} +3 -3
  46. package/dist/{generate-files-BP-4W_gm.js.map → generate-files-BpgyRwhU.js.map} +1 -1
  47. package/dist/{generate-postgres-ddl-logic-DPl1oH_z.js → generate-postgres-ddl-logic-CogQBrzs.js} +3 -3
  48. package/dist/{generate-postgres-ddl-logic-DPl1oH_z.js.map → generate-postgres-ddl-logic-CogQBrzs.js.map} +1 -1
  49. package/dist/{generated-schema-diff-eZCklRZQ.js → generated-schema-diff-X9NA2Vig.js} +2 -2
  50. package/dist/{generated-schema-diff-eZCklRZQ.js.map → generated-schema-diff-X9NA2Vig.js.map} +1 -1
  51. package/dist/history/HistoryService.d.ts +7 -0
  52. package/dist/index.d.ts +20 -0
  53. package/dist/index.es.js +228 -10
  54. package/dist/index.es.js.map +1 -1
  55. package/dist/{db-subcommands-BPoHCxJR.js → migrate-baseline-Bfk1LGC6.js} +266 -41
  56. package/dist/migrate-baseline-Bfk1LGC6.js.map +1 -0
  57. package/dist/{migrate-policy-stamps-3eqfhes6.js → migrate-policy-stamps-DHxwcawC.js} +6 -6
  58. package/dist/{migrate-policy-stamps-3eqfhes6.js.map → migrate-policy-stamps-DHxwcawC.js.map} +1 -1
  59. package/dist/{open-rebase-EmqVmS14.js → open-rebase-DZ5JbZpg.js} +546 -52
  60. package/dist/open-rebase-DZ5JbZpg.js.map +1 -0
  61. package/dist/open-rebase.d.ts +9 -1
  62. package/dist/{pg-error-utils-CFEnm2m9.js → pg-error-utils-BueZEJ0S.js} +2 -2
  63. package/dist/{pg-error-utils-CFEnm2m9.js.map → pg-error-utils-BueZEJ0S.js.map} +1 -1
  64. package/dist/{plan-schema-Czf3q4-Q.js → plan-schema-YagMlmNE.js} +2 -2
  65. package/dist/{plan-schema-Czf3q4-Q.js.map → plan-schema-YagMlmNE.js.map} +1 -1
  66. package/dist/{policy-drift-X4A-xAzv.js → policy-drift-Dqp_yFeE.js} +2 -2
  67. package/dist/{policy-drift-X4A-xAzv.js.map → policy-drift-Dqp_yFeE.js.map} +1 -1
  68. package/dist/{push-index-prebuild-COd7i6wm.js → push-index-prebuild-hVRrfTi-.js} +4 -4
  69. package/dist/{push-index-prebuild-COd7i6wm.js.map → push-index-prebuild-hVRrfTi-.js.map} +1 -1
  70. package/dist/push-kept-defaults-M_ZCcXuy.js +137 -0
  71. package/dist/push-kept-defaults-M_ZCcXuy.js.map +1 -0
  72. package/dist/{push-legacy-renames-CLgYYwPE.js → push-legacy-renames-DcoAWmGt.js} +4 -4
  73. package/dist/{push-legacy-renames-CLgYYwPE.js.map → push-legacy-renames-DcoAWmGt.js.map} +1 -1
  74. package/dist/{push-policy-plan-D2gpQsdv.js → push-policy-plan-Bq1bcb3Y.js} +4 -4
  75. package/dist/{push-policy-plan-D2gpQsdv.js.map → push-policy-plan-Bq1bcb3Y.js.map} +1 -1
  76. package/dist/{render-ddl-4v88y-Gv.js → render-ddl-D5jeXKR-.js} +2 -2
  77. package/dist/{render-ddl-4v88y-Gv.js.map → render-ddl-D5jeXKR-.js.map} +1 -1
  78. package/dist/{rls-enforcement-DDyNoOSy.js → rls-enforcement-BOHuHVlc.js} +42 -3
  79. package/dist/rls-enforcement-BOHuHVlc.js.map +1 -0
  80. package/dist/schema/destructive-sql.d.ts +16 -0
  81. package/dist/schema/doctor-cli.js +4 -4
  82. package/dist/schema/generate-drizzle-schema.js +1 -1
  83. package/dist/schema/generate-postgres-ddl.js +1 -1
  84. package/dist/schema/introspect-db.js +1 -1
  85. package/dist/schema/migration-freshness.d.ts +69 -0
  86. package/dist/schema/push-kept-defaults.d.ts +57 -0
  87. package/dist/schema/rls-bootstrap-sql.d.ts +47 -10
  88. package/dist/security/rls-enforcement.d.ts +18 -0
  89. package/dist/services/FetchService.d.ts +12 -0
  90. package/dist/services/channel-bus/PostgresChannelBus.d.ts +1 -0
  91. package/dist/services/channel-presence.d.ts +3 -1
  92. package/dist/services/nested-path.d.ts +16 -0
  93. package/dist/services/realtimeService.d.ts +48 -2
  94. package/dist/{websocket-BKZwsjmf.js → websocket-C9Fx7iSx.js} +70 -15
  95. package/dist/websocket-C9Fx7iSx.js.map +1 -0
  96. package/package.json +7 -7
  97. package/dist/BranchService-ClklxyAQ.js.map +0 -1
  98. package/dist/backup-cli-gijeXe0u.js.map +0 -1
  99. package/dist/cli-console-CQrQ0lAY.js.map +0 -1
  100. package/dist/cli-errors-DiA0XFIS.js.map +0 -1
  101. package/dist/collections-schema-version-T6cGvrDi.js.map +0 -1
  102. package/dist/db-subcommands-BPoHCxJR.js.map +0 -1
  103. package/dist/doctor-BT--1kq3.js.map +0 -1
  104. package/dist/open-rebase-EmqVmS14.js.map +0 -1
  105. package/dist/rls-enforcement-DDyNoOSy.js.map +0 -1
  106. package/dist/websocket-BKZwsjmf.js.map +0 -1
@@ -2,26 +2,28 @@ import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { i as createPostgresDatabaseConnection } from "./connection-czvI7TZL.js";
4
4
  import { _ as visibleColumnProjection, a as buildSearchColumnSpec, r as SEARCH_UNACCENT_FN, s as hiddenColumnsOption } from "./search-column-BM-GV6vH.js";
5
- import { a as diagnoseDbError, c as isEconnrefused, n as closedDatabaseName, nt as extractCauseMessage, r as deepestErrorMessage, u as parseHostInfo } from "./cli-errors-DiA0XFIS.js";
6
- import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-CFEnm2m9.js";
7
- import { t as BranchService } from "./BranchService-ClklxyAQ.js";
8
- import { a as ensureAppRoleGrants, d as warnOnLegacyRlsFunctions, f as warnOnRoleSchemaCollision, i as ensureAppRole, l as validatePolicyPgRoles, n as applyAuthContext, r as detectConnectionPosture, s as revokeUserRoleSql, t as REBASE_USER_ROLE$1, u as warnOnAnonymousGrants } from "./rls-enforcement-DDyNoOSy.js";
9
- import { u as resolveColumnName } from "./column-plan-helpers-IG6uFb1s.js";
10
- import { n as planSchema } from "./plan-schema-Czf3q4-Q.js";
11
- import { t as generateSchema } from "./generate-drizzle-schema-logic-CPzCRD-8.js";
12
- import { r as renderPgType } from "./render-ddl-4v88y-Gv.js";
13
- import { u as typesAgree } from "./deferred-index-build-BE0I6sYU.js";
14
- import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-DYH95Qeg.js";
15
- import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-Cet4650m.js";
5
+ import { a as diagnoseDbError, c as isEconnrefused, n as closedDatabaseName, r as deepestErrorMessage, rt as extractCauseMessage, u as parseHostInfo } from "./cli-errors-BBSJqlYX.js";
6
+ import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-BueZEJ0S.js";
7
+ import { t as BranchService } from "./BranchService-B9Lu8e-P.js";
8
+ import { a as ensureAppRoleGrants, c as revokeUserRoleSql, d as warnOnAnonymousGrants, f as warnOnLegacyRlsFunctions, i as ensureAppRole, n as applyAuthContext, o as findExposedInternalTables, p as warnOnRoleSchemaCollision, r as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as validatePolicyPgRoles } from "./rls-enforcement-BOHuHVlc.js";
9
+ import { u as resolveColumnName } from "./column-plan-helpers-BeSztMor.js";
10
+ import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-C72EMoDJ.js";
11
+ import { n as planSchema } from "./plan-schema-YagMlmNE.js";
12
+ import { t as generateSchema } from "./generate-drizzle-schema-logic-D0E64iwx.js";
13
+ import { r as renderPgType } from "./render-ddl-D5jeXKR-.js";
14
+ import { u as typesAgree } from "./deferred-index-build-DRnoMq-O.js";
15
+ import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-yukSebLA.js";
16
+ import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-BeF1lArf.js";
17
+ import { a as mergeDatabaseBranch, i as diffDatabaseBranch } from "./branch-diff-CxE4VlxT.js";
16
18
  import { t as DatabasePoolManager } from "./databasePoolManager-3stMNFL-.js";
17
- import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-l_OgFQjN.js";
18
- import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-eZCklRZQ.js";
19
+ import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-DDkNaPN2.js";
20
+ import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-X9NA2Vig.js";
19
21
  import { Client, DatabaseError, Pool } from "pg";
20
22
  import { drizzle } from "drizzle-orm/node-postgres";
21
23
  import { ApiError, assertQueryFieldsReadable, createDdlBootstrapper, createEmailService, logger, rawQueryLoggingEnabled, resolveBatchRefs, rowETag, splitFieldOps } from "@rebasepro/server";
22
24
  import { and, asc, count, desc, eq, getTableColumns, getTableName, gt, ilike, inArray, is, isNotNull, isNull, isTable, lt, lte, not, notInArray, or, relations, sql } from "drizzle-orm";
23
25
  import { PgArray, PgNumeric, PgTable, PgTimestamp, PgTimestampString, PgTransaction, bigint, boolean, getTableConfig, index, integer, jsonb, pgSchema, pgTable, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
24
- import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, ListLimitError, MAX_INCLUDE_DEPTH, Vector, encodeRelationAggregateSort, hasForeignKeyOnTarget, isChannelBusInstance, isChannelBusInstance as isChannelBusInstance$1, isManyToMany, isRelationalCollectionConfig, isSQLAdmin, parseEnvBoolean, parseRelationAggregateSort, resolveClientListLimit, resourceEnvSuffix, resourceKeyOf } from "@rebasepro/types";
26
+ import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, ListLimitError, MAX_INCLUDE_DEPTH, Vector, encodeRelationAggregateSort, hasForeignKeyOnTarget, isChannelBusInstance, isChannelBusInstance as isChannelBusInstance$1, isManyToMany, isRelationalCollectionConfig, isSQLAdmin, parseEnvBoolean, parseRelationAggregateSort, resolveClientListLimit, resourceEnvSuffix, resourceKeyOf, roleNameProblem } from "@rebasepro/types";
25
27
  import { COMPOSITE_ID_SEPARATOR, COMPOSITE_ID_SEPARATOR as COMPOSITE_ID_SEPARATOR$1, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, OrderBySpecError, REBASE_USER_ROLE, UnknownFilterOperatorError, apiHiddenFieldNames, applyDefaultValuesOnCreate, buildCompositeId, buildCompositeId as buildCompositeId$1, buildPropertyCallbacks, buildSdkData, callbackRefusal, canReadField, classifyTable, createAccessorSlugResolver, createRelationRef, createRelationRefWithData, deserializeFilter, detectJunctionTables, encodeCursor, fieldKeyForColumn, findRelation, firstSqlRow, getColumnName, getDeclaredPrimaryKeys, getJunctionConfigForRelation, getTableName as getTableName$1, getTenantConfig, hasFieldAccessRules, includableRelationNames, isAddressableId, normalizeDriverOrderBy, normalizeEmail, normalizeInclude, normalizeToEntityRelation, parseIdValues, parseIdValues as parseIdValues$1, parseOrderBySpecStrict, queryableFieldNames, requireCallbackClient, requireCallbackCollection, resolveCollectionRelations, resolveTenantWrite, restoresSoftDeletedRow, revokeInternalTableSql, softDeleteFieldOf, sqlRows, tenantBypassRoles, toCallbackError, toFilterTuples, unknownAggregateField, unknownFilterField, unknownIncludeRelation, unknownOrderByField, unknownProjectionField, unknownRelationTargetField, unknownVectorProperty, updateDateAutoValues, updateUserAutoValues, withRelationReferencesOnly } from "@rebasepro/common";
26
28
  import { camelCase, generateForeignKeyName, isPrototypePollutingKey, legacyForeignKeyName, splitSearchTerms, toSnakeCase, toWireKey, unref } from "@rebasepro/utils";
27
29
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -4403,6 +4405,38 @@ function isJunctionBackedRelation(relation) {
4403
4405
  return relation.shared;
4404
4406
  }
4405
4407
  /**
4408
+ * Reject a create or update whose body names a relation Rebase does not write
4409
+ * — a multi-hop `via` (`writable: false`) — before anything is read or written.
4410
+ *
4411
+ * A single-hop `via` is written through this door as it shipped (to-one: the
4412
+ * target's key; to-many: one junction's rows). A longer chain used to get as
4413
+ * far as the writer: a to-many one failed inside the transaction as a 500
4414
+ * RELATION_MISCONFIGURED telling the caller to regenerate a schema that was
4415
+ * fine, and a to-one one re-pointed the target at the first step's column.
4416
+ *
4417
+ * Matched the way the write path matches: a key that is a relation's own name
4418
+ * (the to-many split), or a `relation` property that resolves to one (the
4419
+ * to-one transformer). An `undefined` value is no value — the transformer skips
4420
+ * it — so it is not a write; `null` is, since it would unlink.
4421
+ */
4422
+ function assertNoReadOnlyRelationValues(values, collection) {
4423
+ const properties = collection.properties ?? {};
4424
+ let relations;
4425
+ const named = [];
4426
+ for (const [key, value] of Object.entries(values)) {
4427
+ if (value === void 0) continue;
4428
+ relations ??= resolveCollectionRelations(collection);
4429
+ const relation = relations[key] ?? (properties[key]?.type === "relation" ? findRelation(relations, key) : void 0);
4430
+ if (relation && !relation.writable) named.push(key);
4431
+ }
4432
+ if (named.length === 0) return;
4433
+ const list = named.map((key) => `'${key}'`).join(", ");
4434
+ throw ApiError.badRequest(`${list} on '${collection.slug}' ${named.length > 1 ? "are multi-hop `via` relations" : "is a multi-hop `via` relation"}, which is read-only: only single-hop via relations are writable — a to-one chain of one step, or a to-many chain through one junction table. Write the rows the chain joins directly.`, "RELATION_NOT_WRITABLE", {
4435
+ collection: collection.slug,
4436
+ fields: named
4437
+ });
4438
+ }
4439
+ /**
4406
4440
  * Reject a nested write whose final segment is a to-one relation.
4407
4441
  *
4408
4442
  * There is no column on the target row that records a to-one parent — the
@@ -4414,8 +4448,8 @@ function isJunctionBackedRelation(relation) {
4414
4448
  */
4415
4449
  function assertWritableThrough(hop, path) {
4416
4450
  const { relation } = hop;
4417
- if (relation.writable && relation.cardinality === "many") return;
4418
- if (!relation.writable) throw ApiError.badRequest(`"${path}" ends in '${hop.relationKey}', a \`via\` relation. Rebase will not infer how to write through an arbitrary join chain — write the row at "${hop.targetCollection.slug}" directly.`, "RELATION_NOT_WRITABLE");
4451
+ if (relation.kind !== "via" && relation.writable && relation.cardinality === "many") return;
4452
+ if (relation.kind === "via") throw ApiError.badRequest(`"${path}" ends in '${hop.relationKey}', a \`via\` relation, which a nested path does not write through — write the row at "${hop.targetCollection.slug}" directly` + (relation.writable ? `, and link it by setting '${hop.relationKey}' in an update of the '${hop.parentCollection.slug}' row.` : "."), "RELATION_NOT_WRITABLE");
4419
4453
  throw ApiError.badRequest(`"${path}" ends in the to-one relation '${hop.relationKey}', which cannot be written through: the foreign key for a to-one relation lives on '${hop.parentCollection.slug}', not on '${hop.targetCollection.slug}'. Write the target row at "${hop.targetCollection.slug}" and set '${hop.relationKey}' on the parent instead.`, "RELATION_NOT_WRITABLE");
4420
4454
  }
4421
4455
  //#endregion
@@ -5338,6 +5372,38 @@ var FetchService = class FetchService {
5338
5372
  return values;
5339
5373
  }
5340
5374
  /**
5375
+ * Every row of a collection's table, as stored, a page at a time, in key
5376
+ * order — the driver's `scanStoredRows`.
5377
+ *
5378
+ * Deliberately none of the read pipeline: no `beforeQuery` (a sweep has no
5379
+ * caller to scope to, and the documented hook narrows a caller-less read to
5380
+ * the rows owned by nobody), no soft-delete filter, no `afterRead`, no
5381
+ * field stripping. The columns come back under their table names; a sweep
5382
+ * reads values, not keys. Paged by the key rather than an offset, so a row
5383
+ * deleted during the scan never shifts another past the next page.
5384
+ */
5385
+ async *scanStoredRows(collectionPath, pageSize = 500) {
5386
+ const collection = getCollectionByPath(collectionPath, this.registry);
5387
+ const table = getTableForCollection(collection, this.registry);
5388
+ const keys = primaryKeyColumns(table, requirePrimaryKeys(collection, this.registry), collectionPath);
5389
+ const keyNames = keys.map((column) => {
5390
+ const entry = Object.entries(getTableColumns(table)).find(([, candidate]) => candidate === column);
5391
+ if (!entry) throw new Error(`Key column '${column.name}' not found in table for collection '${collectionPath}'`);
5392
+ return entry[0];
5393
+ });
5394
+ const limit = Math.max(1, pageSize);
5395
+ let after;
5396
+ for (;;) {
5397
+ const past = after ? or(...keys.map((column, i) => and(...keys.slice(0, i).map((earlier, j) => eq(earlier, after[j])), gt(column, after[i])))) : void 0;
5398
+ const query = this.db.select().from(table);
5399
+ const rows = await (past ? query.where(past) : query).orderBy(...keys.map((column) => asc(column))).limit(limit);
5400
+ if (rows.length > 0) yield rows;
5401
+ if (rows.length < limit) return;
5402
+ const last = rows[rows.length - 1];
5403
+ after = keyNames.map((name) => last[name]);
5404
+ }
5405
+ }
5406
+ /**
5341
5407
  * Fetch a collection of rows
5342
5408
  */
5343
5409
  async fetchCollection(collectionPath, options = {}) {
@@ -6803,6 +6869,7 @@ var PersistService = class {
6803
6869
  }
6804
6870
  }
6805
6871
  const collection = getCollectionByPath(effectiveCollectionPath, this.registry);
6872
+ assertNoReadOnlyRelationValues(effectiveValues, collection);
6806
6873
  const table = getTableForCollection(collection, this.registry);
6807
6874
  const idInfoArray = getPrimaryKeys(collection, this.registry);
6808
6875
  idInfoArray.map((info) => info.fieldName);
@@ -9456,6 +9523,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9456
9523
  get admin() {
9457
9524
  return {
9458
9525
  executeSql: (...args) => this.executeSql(...args),
9526
+ probe: (timeoutMs) => this.probe(timeoutMs),
9459
9527
  runSqlScript: (...args) => this.runSqlScript(...args),
9460
9528
  openSqlCursor: (...args) => this.openSqlCursor(...args),
9461
9529
  fetchAvailableDatabases: () => this.fetchAvailableDatabases(),
@@ -9476,10 +9544,29 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9476
9544
  createBranch: this.branchService.createBranch.bind(this.branchService),
9477
9545
  deleteBranch: this.branchService.deleteBranch.bind(this.branchService),
9478
9546
  listBranches: this.branchService.listBranches.bind(this.branchService),
9479
- getBranchInfo: this.branchService.getBranchInfo.bind(this.branchService)
9547
+ getBranchInfo: this.branchService.getBranchInfo.bind(this.branchService),
9548
+ diffBranch: async (name, options) => this.nameDiffCollections(await diffDatabaseBranch(this.admin, name, options)),
9549
+ mergeBranch: (name, options) => mergeDatabaseBranch(this.admin, name, options)
9480
9550
  } : {}
9481
9551
  };
9482
9552
  }
9553
+ /** The diff with each table named by the collection it backs, where one does. */
9554
+ nameDiffCollections(diff) {
9555
+ const collections = this.registry?.getCollections() ?? [];
9556
+ const slugOf = (schema, table) => collections.find((collection) => {
9557
+ return ("schema" in collection && typeof collection.schema === "string" ? collection.schema : "public") === schema && getTableName$1(collection) === table;
9558
+ })?.slug;
9559
+ return {
9560
+ ...diff,
9561
+ data: diff.data.map((entry) => {
9562
+ const collection = slugOf(entry.schema, entry.table);
9563
+ return collection ? {
9564
+ ...entry,
9565
+ collection
9566
+ } : entry;
9567
+ })
9568
+ };
9569
+ }
9483
9570
  /**
9484
9571
  * `SQLAdmin.listen`: a `LISTEN` on a connection of its own, through the
9485
9572
  * listener CDC and the channel bus use, which reconnects and heartbeats.
@@ -9574,6 +9661,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9574
9661
  const client = this.client;
9575
9662
  return {
9576
9663
  user: this.user,
9664
+ ...this.user?.credential ? { credential: this.user.credential } : {},
9577
9665
  driver: this,
9578
9666
  data: this.data,
9579
9667
  get client() {
@@ -9743,6 +9831,15 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9743
9831
  return rows;
9744
9832
  }
9745
9833
  /**
9834
+ * Every stored row of a collection, past every read hook, for a whole-store
9835
+ * sweep — see `DataDriver.scanStoredRows`. Only this unscoped driver has
9836
+ * it: {@link AuthenticatedPostgresBackendDriver} reads as a caller, and a
9837
+ * caller's reads are scoped.
9838
+ */
9839
+ scanStoredRows(props) {
9840
+ return this.dataService.getFetchService().scanStoredRows(props.path, props.pageSize);
9841
+ }
9842
+ /**
9746
9843
  * Listen to a collection: the rows now, then again after every change.
9747
9844
  *
9748
9845
  * The realtime service runs every read, the first one included, as
@@ -10713,6 +10810,32 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10713
10810
  return options?.maxResultBytes === void 0 ? rows : refuseOversizedRows(rows, options.maxResultBytes);
10714
10811
  }
10715
10812
  /**
10813
+ * `SQLAdmin.probe`: `SELECT 1` on a connection opened for it, outside the
10814
+ * pool, so a pool whose connections are all serving slow requests does not
10815
+ * read as a database that is down. Without a pg pool (PGlite) there is no
10816
+ * queue to bypass, and the query runs like any other.
10817
+ */
10818
+ async probe(timeoutMs) {
10819
+ const pool = "$client" in this.db ? this.db.$client : void 0;
10820
+ if (!(pool instanceof Pool)) {
10821
+ await this.db.execute(sql.raw("SELECT 1"));
10822
+ return;
10823
+ }
10824
+ const client = new Client({
10825
+ ...pool.options,
10826
+ connectionTimeoutMillis: timeoutMs,
10827
+ query_timeout: timeoutMs,
10828
+ statement_timeout: timeoutMs
10829
+ });
10830
+ client.on("error", () => {});
10831
+ try {
10832
+ await client.connect();
10833
+ await client.query("SELECT 1");
10834
+ } finally {
10835
+ await client.end().catch(() => {});
10836
+ }
10837
+ }
10838
+ /**
10716
10839
  * Run a script a person wrote — the Studio console — and describe its
10717
10840
  * result. See `SQLAdmin.runSqlScript` and `services/sql-script.ts`.
10718
10841
  */
@@ -11082,6 +11205,7 @@ var AuthenticatedPostgresBackendDriver = class {
11082
11205
  const client = this.delegate.client;
11083
11206
  writeScope?.setSettledContext({
11084
11207
  user: this.user,
11208
+ ...this.user?.credential ? { credential: this.user.credential } : {},
11085
11209
  driver: this,
11086
11210
  data: this.data,
11087
11211
  get client() {
@@ -13042,9 +13166,13 @@ var ChannelPresenceStore = class {
13042
13166
  * `tablesReady` is now set from a probe of what exists, not from having been
13043
13167
  * the instance that created it.
13044
13168
  */
13045
- async ensureTables() {
13046
- if (this.tablesReady) return;
13169
+ async ensureTables(options = {}) {
13170
+ if (this.tablesReady) return true;
13047
13171
  const ddl = drizzleDdlBootstrapper(this.db, "channel-presence");
13172
+ if (options.provision === false) {
13173
+ this.tablesReady = await ddl.isReadable("rebase.channel_presence");
13174
+ return this.tablesReady;
13175
+ }
13048
13176
  await ddl.ensureObject("rebase schema", "CREATE SCHEMA IF NOT EXISTS rebase");
13049
13177
  await ddl.ensureObject("channel_presence table", `
13050
13178
  CREATE TABLE IF NOT EXISTS rebase.channel_presence (
@@ -13068,6 +13196,7 @@ var ChannelPresenceStore = class {
13068
13196
  await ddl.step("channel_presence revoke", () => this.db.execute(sql.raw(revokeInternalTableSql("rebase", "channel_presence"))));
13069
13197
  this.tablesReady = true;
13070
13198
  }
13199
+ return this.tablesReady;
13071
13200
  }
13072
13201
  /** Record (or refresh) a client's presence. */
13073
13202
  async track(channel, clientId, state) {
@@ -13211,6 +13340,7 @@ var PostgresChannelBus = class {
13211
13340
  connectionString;
13212
13341
  kind = "postgres";
13213
13342
  maxFrameBytes = PG_NOTIFY_MAX_PAYLOAD_BYTES;
13343
+ publishesOnDemand = true;
13214
13344
  listener;
13215
13345
  batchWindowMs;
13216
13346
  /**
@@ -13393,6 +13523,15 @@ function coerceFrame(value) {
13393
13523
  from: typeof obj.from === "string" ? obj.from : void 0,
13394
13524
  seq: obj.seq
13395
13525
  };
13526
+ case "channels": return {
13527
+ kind: "channels",
13528
+ sid,
13529
+ channel,
13530
+ add: Array.isArray(obj.add) ? obj.add.filter((c) => typeof c === "string") : void 0,
13531
+ list: Array.isArray(obj.list) ? obj.list.filter((c) => typeof c === "string") : void 0,
13532
+ done: obj.done === true,
13533
+ hello: obj.hello === true
13534
+ };
13396
13535
  case "presence_diff": return {
13397
13536
  kind: "presence_diff",
13398
13537
  sid,
@@ -13670,6 +13809,17 @@ var RealtimeService = class RealtimeService extends EventEmitter {
13670
13809
  */
13671
13810
  bus = new MemoryChannelBus();
13672
13811
  /**
13812
+ * The other instances on an on-demand bus, and the channels each serves
13813
+ * (`null`: it hasn't said, so assume all of them). See {@link hasRemoteMembers}.
13814
+ */
13815
+ busPeers = /* @__PURE__ */ new Map();
13816
+ /** Frames the bus took, by kind. See {@link counts}. */
13817
+ busFramesPublished = /* @__PURE__ */ new Map();
13818
+ /** Frames not sent because no other instance had members. See {@link counts}. */
13819
+ busFramesSkipped = 0;
13820
+ busStartedAt = 0;
13821
+ busGossipInterval;
13822
+ /**
13673
13823
  * The shared presence roster, present only when a real bus is active.
13674
13824
  *
13675
13825
  * Fan-out alone is not enough for presence: `presence_state` has to answer
@@ -13750,6 +13900,14 @@ var RealtimeService = class RealtimeService extends EventEmitter {
13750
13900
  refetchQueue = /* @__PURE__ */ new Set();
13751
13901
  /** Group refetches running now — at most {@link maxConcurrentRefetches}. */
13752
13902
  refetchesRunning = 0;
13903
+ /**
13904
+ * What a group refetch runs inside — see {@link setScopeRunner}. A refetch
13905
+ * runs on a timer armed by whatever announced the change; one armed by a
13906
+ * change-capture notification inherits the LISTEN connection's context,
13907
+ * which is no backend's, so a hook the read reached saw the process
13908
+ * default as `rebase`.
13909
+ */
13910
+ runInScope = (fn) => fn();
13753
13911
  /** See {@link refetchConcurrencyFor}. */
13754
13912
  maxConcurrentRefetches;
13755
13913
  /**
@@ -14018,6 +14176,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
14018
14176
  if (group.pending !== "all") group.pending.delete(key);
14019
14177
  if (group.members.size > 0) return;
14020
14178
  if (group.timer) clearTimeout(group.timer);
14179
+ if (group.recountTimer) clearTimeout(group.recountTimer);
14021
14180
  this.refetchQueue.delete(group);
14022
14181
  this.groups.delete(group.key);
14023
14182
  const [index, address] = group.type === "collection" ? [this.collectionGroupsByPath, group.path] : [this.singleGroupsByAddress, `${group.path}\u0000${group.id}`];
@@ -14091,7 +14250,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
14091
14250
  this.refetchQueue.delete(group);
14092
14251
  if (this.groups.get(group.key) !== group) continue;
14093
14252
  this.refetchesRunning++;
14094
- this.refetchGroup(group).finally(() => {
14253
+ this.runInScope(() => this.refetchGroup(group)).finally(() => {
14095
14254
  this.refetchesRunning--;
14096
14255
  this.drainRefetchQueue();
14097
14256
  });
@@ -14865,6 +15024,17 @@ var RealtimeService = class RealtimeService extends EventEmitter {
14865
15024
  });
14866
15025
  }
14867
15026
  /**
15027
+ * Refetch `group` — and so count it again — at `at`, when the total its
15028
+ * last frame reused expires. One pending at a time per group.
15029
+ */
15030
+ scheduleRecount(group, at) {
15031
+ if (group.recountTimer) return;
15032
+ group.recountTimer = setTimeout(() => {
15033
+ group.recountTimer = void 0;
15034
+ if (this.groups.get(group.key) === group) this.scheduleGroupRefetch(group);
15035
+ }, Math.max(0, at - Date.now()) + 1);
15036
+ }
15037
+ /**
14868
15038
  * The `meta` a `collection_update` frame carries beside its rows, counted
14869
15039
  * through `service` — the subscriber's own transaction, read only, with
14870
15040
  * its auth context and `beforeQuery` narrowing already bound.
@@ -14893,6 +15063,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
14893
15063
  else if (reusable && this.recountIntervalMs !== void 0 && reusable.total >= this.recountMinRows && Date.now() - reusable.at < this.recountIntervalMs) {
14894
15064
  total = reusable.total;
14895
15065
  totalAsOf = new Date(reusable.at).toISOString();
15066
+ if (group) this.scheduleRecount(group, reusable.at + this.recountIntervalMs);
14896
15067
  } else {
14897
15068
  try {
14898
15069
  total = await service.count(notifyPath, {
@@ -15304,7 +15475,10 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15304
15475
  }
15305
15476
  /** Join a broadcast channel */
15306
15477
  joinChannel(clientId, channel) {
15307
- if (!this.channels.has(channel)) this.channels.set(channel, /* @__PURE__ */ new Set());
15478
+ if (!this.channels.has(channel)) {
15479
+ this.channels.set(channel, /* @__PURE__ */ new Set());
15480
+ this.announceChannel(channel);
15481
+ }
15308
15482
  this.channels.get(channel).add(clientId);
15309
15483
  this.indexClientChannel(this.channelsByClient, clientId, channel);
15310
15484
  this.warnIfMemoryBusOnMultiplePods();
@@ -15471,7 +15645,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15471
15645
  * what it was before this existed, whereas refusing to boot takes the whole
15472
15646
  * backend down for it.
15473
15647
  */
15474
- async configureChannelBus(bus) {
15648
+ async configureChannelBus(bus, options = {}) {
15475
15649
  if (bus.kind === "memory") {
15476
15650
  this.bus = bus;
15477
15651
  return;
@@ -15485,9 +15659,10 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15485
15659
  return;
15486
15660
  }
15487
15661
  this.bus = bus;
15662
+ this.startBusGossip();
15488
15663
  try {
15489
15664
  const store = new ChannelPresenceStore(this.db, this.instanceId);
15490
- await store.ensureTables();
15665
+ if (!await store.ensureTables({ provision: options.provision }) && options.provision === false) throw new Error("rebase.channel_presence does not exist, and this backend changes nothing in its database. A provisioning run with the same channel bus configured creates it.");
15491
15666
  this.presenceStore = store;
15492
15667
  this.ensurePresenceSweep();
15493
15668
  } catch (error) {
@@ -15509,6 +15684,10 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15509
15684
  */
15510
15685
  publishBroadcast(clientId, channel, event, payload, seq) {
15511
15686
  if (this.bus.kind === "memory") return;
15687
+ if (seq === void 0 && !this.hasRemoteMembers(channel)) {
15688
+ this.busFramesSkipped++;
15689
+ return;
15690
+ }
15512
15691
  const frame = {
15513
15692
  kind: "broadcast",
15514
15693
  sid: this.instanceId,
@@ -15537,6 +15716,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15537
15716
  async publishFrame(frame) {
15538
15717
  try {
15539
15718
  await this.bus.publish(frame);
15719
+ this.busFramesPublished.set(frame.kind, (this.busFramesPublished.get(frame.kind) ?? 0) + 1);
15540
15720
  } catch (error) {
15541
15721
  logger.error("❌ [ChannelBus] Failed to publish frame — other instances did not receive it", {
15542
15722
  detail: `${frame.kind} on "${frame.channel}"`,
@@ -15569,6 +15749,11 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15569
15749
  * its own `sid`.
15570
15750
  */
15571
15751
  async handleBusFrame(frame) {
15752
+ if (frame.sid !== this.instanceId) this.notePeer(frame.sid);
15753
+ if (frame.kind === "channels") {
15754
+ if (frame.sid !== this.instanceId) this.readPeerChannels(frame);
15755
+ return;
15756
+ }
15572
15757
  const retained = (frame.kind === "broadcast" || frame.kind === "broadcast_ref") && frame.seq !== void 0;
15573
15758
  if (frame.sid === this.instanceId && !(retained && this.bus instanceof PostgresChannelBus)) return;
15574
15759
  if (!retained) return this.deliverBusFrame(frame);
@@ -15745,6 +15930,10 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15745
15930
  /** Tell the other instances about a presence change. */
15746
15931
  publishPresenceDiff(channel, joins, leaves) {
15747
15932
  if (this.bus.kind === "memory") return;
15933
+ if (!this.hasRemoteMembers(channel)) {
15934
+ this.busFramesSkipped++;
15935
+ return;
15936
+ }
15748
15937
  this.publishFrame({
15749
15938
  kind: "presence_diff",
15750
15939
  sid: this.instanceId,
@@ -15753,6 +15942,110 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15753
15942
  leaves
15754
15943
  });
15755
15944
  }
15945
+ static BUS_GOSSIP_INTERVAL_MS = 15e3;
15946
+ static BUS_PEER_TTL_MS = 45e3;
15947
+ static BUS_WARMUP_MS = 6e4;
15948
+ /** The frames' `channel`: a transport drops a frame without one. */
15949
+ static BUS_PEERS_CHANNEL = "__peers";
15950
+ /** Whether a frame on `channel` may have a reader on another instance. */
15951
+ hasRemoteMembers(channel) {
15952
+ if (!this.bus.publishesOnDemand) return true;
15953
+ const now = Date.now();
15954
+ if (now - this.busStartedAt < RealtimeService.BUS_WARMUP_MS) return true;
15955
+ for (const [sid, peer] of this.busPeers) {
15956
+ if (now - peer.heardAt > RealtimeService.BUS_PEER_TTL_MS) {
15957
+ this.busPeers.delete(sid);
15958
+ continue;
15959
+ }
15960
+ if (peer.channels === null || peer.channels.has(channel)) return true;
15961
+ }
15962
+ return false;
15963
+ }
15964
+ /** Tell the others about a channel's first member here. */
15965
+ announceChannel(channel) {
15966
+ if (!this.bus.publishesOnDemand) return;
15967
+ if (!this.busPeers.size && Date.now() - this.busStartedAt >= RealtimeService.BUS_WARMUP_MS) return;
15968
+ this.publishFrame({
15969
+ kind: "channels",
15970
+ sid: this.instanceId,
15971
+ channel: RealtimeService.BUS_PEERS_CHANNEL,
15972
+ add: [channel]
15973
+ });
15974
+ }
15975
+ /** Every channel served here, in as many parts as the transport needs. */
15976
+ announceChannels() {
15977
+ if (!this.bus.publishesOnDemand) return;
15978
+ const channel = RealtimeService.BUS_PEERS_CHANNEL;
15979
+ const limit = Math.min(this.bus.maxFrameBytes, 7e3) - 200;
15980
+ let list = [], bytes = 0;
15981
+ for (const name of this.channels.keys()) {
15982
+ const size = Buffer.byteLength(name, "utf8") + 3;
15983
+ if (bytes + size > limit) {
15984
+ this.publishFrame({
15985
+ kind: "channels",
15986
+ sid: this.instanceId,
15987
+ channel,
15988
+ list
15989
+ });
15990
+ list = [];
15991
+ bytes = 0;
15992
+ }
15993
+ list.push(name);
15994
+ bytes += size;
15995
+ }
15996
+ this.publishFrame({
15997
+ kind: "channels",
15998
+ sid: this.instanceId,
15999
+ channel,
16000
+ list,
16001
+ done: true
16002
+ });
16003
+ }
16004
+ /** Any frame from another instance: it's alive, and a new one needs to hear what's served here. */
16005
+ notePeer(sid) {
16006
+ const peer = this.busPeers.get(sid);
16007
+ if (peer) {
16008
+ peer.heardAt = Date.now();
16009
+ return;
16010
+ }
16011
+ this.busPeers.set(sid, {
16012
+ heardAt: Date.now(),
16013
+ channels: null
16014
+ });
16015
+ this.announceChannels();
16016
+ }
16017
+ readPeerChannels(frame) {
16018
+ const peer = this.busPeers.get(frame.sid);
16019
+ if (!peer) return;
16020
+ if (frame.hello) this.announceChannels();
16021
+ if (frame.add) {
16022
+ peer.channels ??= /* @__PURE__ */ new Set();
16023
+ for (const channel of frame.add) peer.channels.add(channel);
16024
+ }
16025
+ if (frame.list) {
16026
+ peer.incoming ??= /* @__PURE__ */ new Set();
16027
+ for (const channel of frame.list) peer.incoming.add(channel);
16028
+ if (frame.done) {
16029
+ peer.channels = peer.incoming;
16030
+ peer.incoming = void 0;
16031
+ }
16032
+ }
16033
+ }
16034
+ /** Start gossiping on a bus that publishes on demand. */
16035
+ startBusGossip() {
16036
+ if (!this.bus.publishesOnDemand) return;
16037
+ this.busStartedAt = Date.now();
16038
+ this.publishFrame({
16039
+ kind: "channels",
16040
+ sid: this.instanceId,
16041
+ channel: RealtimeService.BUS_PEERS_CHANNEL,
16042
+ hello: true
16043
+ });
16044
+ this.busGossipInterval = setInterval(() => {
16045
+ if (this.busPeers.size) this.announceChannels();
16046
+ }, RealtimeService.BUS_GOSSIP_INTERVAL_MS);
16047
+ unref(this.busGossipInterval);
16048
+ }
15756
16049
  /** Run a roster write when there is a roster, and never let it throw. */
15757
16050
  async presenceStoreOp(op, label) {
15758
16051
  if (!this.presenceStore) return;
@@ -15818,6 +16111,8 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15818
16111
  for (const group of this.groups.values()) {
15819
16112
  if (group.timer) clearTimeout(group.timer);
15820
16113
  group.timer = void 0;
16114
+ if (group.recountTimer) clearTimeout(group.recountTimer);
16115
+ group.recountTimer = void 0;
15821
16116
  }
15822
16117
  this.unscheduledListGroups.clear();
15823
16118
  this.listPathChangedAt.clear();
@@ -15848,6 +16143,10 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15848
16143
  clearInterval(this.presenceSweepInterval);
15849
16144
  this.presenceSweepInterval = void 0;
15850
16145
  }
16146
+ if (this.busGossipInterval) {
16147
+ clearInterval(this.busGossipInterval);
16148
+ this.busGossipInterval = void 0;
16149
+ }
15851
16150
  this.oversizedBroadcastWarned.clear();
15852
16151
  if (this.presenceStore) {
15853
16152
  try {
@@ -15877,6 +16176,19 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15877
16176
  isCdcActive() {
15878
16177
  return this.cdcActive && this.cdcListener?.connected === true;
15879
16178
  }
16179
+ /** See `RealtimeProvider.setScopeRunner`. */
16180
+ setScopeRunner(run) {
16181
+ this.runInScope = run;
16182
+ }
16183
+ /** What this instance is carrying — see `RealtimeProvider.counts`. */
16184
+ counts() {
16185
+ return {
16186
+ sockets: this.clients.size,
16187
+ channels: this.channels.size,
16188
+ busFramesPublished: Object.fromEntries(this.busFramesPublished),
16189
+ busFramesSkipped: this.busFramesSkipped
16190
+ };
16191
+ }
15880
16192
  /** The LISTEN connections this service depends on — see `RealtimeProvider.health`. */
15881
16193
  health() {
15882
16194
  const listeners = [];
@@ -16411,7 +16723,7 @@ function columnNames(table) {
16411
16723
  }
16412
16724
  return names;
16413
16725
  }
16414
- var quote = (xs) => Array.from(xs).map((s) => `\`${s}\``).join(", ");
16726
+ var quote$1 = (xs) => Array.from(xs).map((s) => `\`${s}\``).join(", ");
16415
16727
  /** `on.from` / `on.to` accept a single column or a composite tuple. */
16416
16728
  var asColumns = (value) => Array.isArray(value) ? value : [value];
16417
16729
  /**
@@ -16433,7 +16745,7 @@ function compositeKeyDefect(relation, source, target, registry) {
16433
16745
  const keys = getPrimaryKeys(keyed, registry);
16434
16746
  if (keys.length < 2) return void 0;
16435
16747
  return {
16436
- problem: `${linkColumn} is one column, and \`${keyed.slug}\` is keyed on ${quote(keys.map((key) => key.fieldName))} together — one column cannot reference a composite key`,
16748
+ problem: `${linkColumn} is one column, and \`${keyed.slug}\` is keyed on ${quote$1(keys.map((key) => key.fieldName))} together — one column cannot reference a composite key`,
16437
16749
  fix
16438
16750
  };
16439
16751
  };
@@ -16562,7 +16874,7 @@ function findRelationDefects(collections, registry, given) {
16562
16874
  } : {
16563
16875
  ...at,
16564
16876
  problem: `\`localKey: "${relation.localKey}"\` is not a column on \`${sourceTableName}\``,
16565
- fix: `add the column, or set \`localKey\` to one of: ${quote(sourceColumns)}`
16877
+ fix: `add the column, or set \`localKey\` to one of: ${quote$1(sourceColumns)}`
16566
16878
  });
16567
16879
  }
16568
16880
  break;
@@ -16576,13 +16888,13 @@ function findRelationDefects(collections, registry, given) {
16576
16888
  } : {
16577
16889
  ...at,
16578
16890
  problem: `\`foreignKeyOnTarget: "${relation.foreignKeyOnTarget}"\` is not a column on the target table \`${targetTableName}\``,
16579
- fix: `add the column, or set \`foreignKeyOnTarget\` to one of: ${quote(targetColumns)}`
16891
+ fix: `add the column, or set \`foreignKeyOnTarget\` to one of: ${quote$1(targetColumns)}`
16580
16892
  });
16581
16893
  }
16582
16894
  if (relation.sourceKey && !sourceColumns.has(relation.sourceKey)) defects.push({
16583
16895
  ...at,
16584
16896
  problem: `\`sourceKey: "${relation.sourceKey}"\` is not a column on \`${sourceTableName}\``,
16585
- fix: targetColumns.has(relation.sourceKey) ? `it is a column on the *target* table \`${targetTableName}\` — \`sourceKey\` names the column on this collection that the target's foreign key points at, so it must be one of: ${quote(sourceColumns)}` : `add the column, or set \`sourceKey\` to one of: ${quote(sourceColumns)}`
16897
+ fix: targetColumns.has(relation.sourceKey) ? `it is a column on the *target* table \`${targetTableName}\` — \`sourceKey\` names the column on this collection that the target's foreign key points at, so it must be one of: ${quote$1(sourceColumns)}` : `add the column, or set \`sourceKey\` to one of: ${quote$1(sourceColumns)}`
16586
16898
  });
16587
16899
  break;
16588
16900
  case "manyToMany": {
@@ -16609,7 +16921,7 @@ function findRelationDefects(collections, registry, given) {
16609
16921
  } : {
16610
16922
  ...at,
16611
16923
  problem: `\`through.${label}: "${column}"\` is not a column on the junction table \`${table}\``,
16612
- fix: `set \`through.${label}\` to one of: ${quote(junctionColumns)}` + (label === "sourceColumn" ? " — it is the column naming *this* collection" : "")
16924
+ fix: `set \`through.${label}\` to one of: ${quote$1(junctionColumns)}` + (label === "sourceColumn" ? " — it is the column naming *this* collection" : "")
16613
16925
  });
16614
16926
  }
16615
16927
  break;
@@ -16641,12 +16953,12 @@ function findRelationDefects(collections, registry, given) {
16641
16953
  for (const column of asColumns(step.on.from)) if (!prevColumns.has(column)) defects.push({
16642
16954
  ...at,
16643
16955
  problem: `step ${i + 1} joins \`${prevName}.${column}\` → \`${step.table}\`, but \`${column}\` is not a column on \`${prevName}\``,
16644
- fix: `\`joinPath[${i}].on.from\` names columns on ${i === 0 ? "this collection's table" : `the previous step's table (\`${prevName}\`)`}: ${quote(prevColumns)}`
16956
+ fix: `\`joinPath[${i}].on.from\` names columns on ${i === 0 ? "this collection's table" : `the previous step's table (\`${prevName}\`)`}: ${quote$1(prevColumns)}`
16645
16957
  });
16646
16958
  for (const column of asColumns(step.on.to)) if (!stepColumns.has(column)) defects.push({
16647
16959
  ...at,
16648
16960
  problem: `step ${i + 1} joins into \`${step.table}.${column}\`, but \`${column}\` is not a column on \`${step.table}\``,
16649
- fix: `\`joinPath[${i}].on.to\` names columns on \`${step.table}\`: ${quote(stepColumns)}`
16961
+ fix: `\`joinPath[${i}].on.to\` names columns on \`${step.table}\`: ${quote$1(stepColumns)}`
16650
16962
  });
16651
16963
  if (asColumns(step.on.from).length !== asColumns(step.on.to).length) defects.push({
16652
16964
  ...at,
@@ -17075,6 +17387,60 @@ var UserService = class {
17075
17387
  };
17076
17388
  }
17077
17389
  /**
17390
+ * @see UserRepository.listGuests — what a guest is, as SQL. The list and the
17391
+ * delete both read this, so nothing can be listed for deletion that the
17392
+ * delete would not call a guest. A column name falls back to its physical
17393
+ * name and never to no condition: a table without the column fails the
17394
+ * statement rather than widening it.
17395
+ */
17396
+ isGuest() {
17397
+ const users = sql.raw(this.getQualifiedUsersTableName());
17398
+ const column = (key, physical) => sql.identifier(getColumn(this.usersTable, key, physical)?.name ?? physical);
17399
+ const identities = sql.raw(qualifiedTableName(this.userIdentitiesTable));
17400
+ return sql`${users}.${column("isAnonymous", "is_anonymous")} = TRUE
17401
+ AND ${users}.${column("passwordHash", "password_hash")} IS NULL
17402
+ AND NOT EXISTS (SELECT 1 FROM ${identities} ui WHERE ui.uid = ${users}.${column("id", "id")})`;
17403
+ }
17404
+ /** @see UserRepository.listGuests */
17405
+ async listGuests(options) {
17406
+ const limit = options?.limit ?? 25;
17407
+ const offset = options?.offset ?? 0;
17408
+ const users = sql.raw(this.getQualifiedUsersTableName());
17409
+ const idColumn = sql.identifier(getColumn(this.usersTable, "id")?.name ?? "id");
17410
+ const createdAt = sql`${users}.${sql.identifier(getColumn(this.usersTable, "createdAt", "created_at")?.name ?? "created_at")}`;
17411
+ const lastSeenAt = sql`GREATEST(${createdAt}, (SELECT MAX(rt.created_at) FROM ${sql.raw(qualifiedTableName(this.refreshTokensTable))} rt WHERE rt.uid = ${users}.${idColumn}))`;
17412
+ const where = options?.lastSeenBefore ? sql`${this.isGuest()} AND ${lastSeenAt} < ${options.lastSeenBefore.toISOString()}::timestamptz` : this.isGuest();
17413
+ const counted = await this.db.execute(sql`SELECT count(*)::int AS total FROM ${users} WHERE ${where}`);
17414
+ return {
17415
+ guests: (await this.db.execute(sql`
17416
+ SELECT ${users}.${idColumn} AS id, ${createdAt} AS created_at, ${lastSeenAt} AS last_seen_at
17417
+ FROM ${users}
17418
+ WHERE ${where}
17419
+ ORDER BY last_seen_at ASC, id ASC
17420
+ LIMIT ${limit} OFFSET ${offset}
17421
+ `)).rows.map((row) => ({
17422
+ id: row.id,
17423
+ createdAt: new Date(row.created_at),
17424
+ lastSeenAt: new Date(row.last_seen_at)
17425
+ })),
17426
+ total: counted.rows[0].total
17427
+ };
17428
+ }
17429
+ /** @see UserRepository.deleteGuest */
17430
+ async deleteGuest(id) {
17431
+ const users = sql.raw(this.getQualifiedUsersTableName());
17432
+ const idColumn = sql.identifier(getColumn(this.usersTable, "id")?.name ?? "id");
17433
+ try {
17434
+ return (await this.withServerContext((db) => db.execute(sql`
17435
+ DELETE FROM ${users} WHERE ${users}.${idColumn} = ${id} AND ${this.isGuest()} RETURNING 1
17436
+ `))).rows.length > 0;
17437
+ } catch (error) {
17438
+ const code = extractPgError(error)?.code;
17439
+ if (code === "23503" || code === "23001") throw ApiError.conflict("A row of this project's own requires this guest, so it was not deleted.", "GUEST_REFERENCED");
17440
+ throw error;
17441
+ }
17442
+ }
17443
+ /**
17078
17444
  * Update user's password hash; `null` removes the password.
17079
17445
  */
17080
17446
  async updatePassword(id, passwordHash) {
@@ -17138,14 +17504,26 @@ var UserService = class {
17138
17504
  return result.rows[0].roles ?? [];
17139
17505
  }
17140
17506
  /**
17141
- * Set roles for a user (replaces existing roles)
17507
+ * Set roles for a user (replaces existing roles).
17508
+ *
17509
+ * Each role is its own bound parameter. The array used to be spelled as a
17510
+ * literal, `{${roles.join(",")}}`, so the database parsed what the caller
17511
+ * had only checked as strings: `"support,admin"` was stored as two roles,
17512
+ * one of them `admin`, and `"NULL"` as a SQL NULL. A name that would be read
17513
+ * back as other roles is refused (`roleNameProblem`) — RLS splits the
17514
+ * comma-joined `app.user_roles` the same way.
17142
17515
  */
17143
17516
  async setUserRoles(uid, roleIds) {
17517
+ const problems = roleIds.flatMap((role) => {
17518
+ const problem = roleNameProblem(role);
17519
+ return problem ? [`${JSON.stringify(role)} ${problem}`] : [];
17520
+ });
17521
+ if (problems.length > 0) throw ApiError.badRequest(`Not valid role names: ${problems.join("; ")}`, "INVALID_ROLE");
17144
17522
  const usersTableName = this.getQualifiedUsersTableName();
17145
- const rolesArray = `{${roleIds.join(",")}}`;
17523
+ const rolesArray = roleIds.length === 0 ? sql`'{}'::text[]` : sql`ARRAY[${sql.join(roleIds.map((role) => sql`${role}`), sql`, `)}]::text[]`;
17146
17524
  await this.withServerContext(async (db) => db.execute(sql`
17147
17525
  UPDATE ${sql.raw(usersTableName)}
17148
- SET roles = ${rolesArray}::text[], updated_at = NOW()
17526
+ SET roles = ${rolesArray}, updated_at = NOW()
17149
17527
  WHERE id = ${uid}
17150
17528
  `));
17151
17529
  }
@@ -17789,6 +18167,12 @@ var PostgresAuthRepository = class {
17789
18167
  async listUsersPaginated(options) {
17790
18168
  return this.userService.listUsersPaginated(options);
17791
18169
  }
18170
+ async listGuests(options) {
18171
+ return this.userService.listGuests(options);
18172
+ }
18173
+ async deleteGuest(id) {
18174
+ return this.userService.deleteGuest(id);
18175
+ }
17792
18176
  async firstUserIds(limit) {
17793
18177
  return this.userService.firstUserIds(limit);
17794
18178
  }
@@ -18167,6 +18551,59 @@ var MfaService = class {
18167
18551
  }
18168
18552
  };
18169
18553
  //#endregion
18554
+ //#region src/auth/verify-auth-tables.ts
18555
+ /**
18556
+ * Whether the auth tables a backend reads are there, on a backend that may not
18557
+ * create them.
18558
+ *
18559
+ * A driver opened without provisioning skips `ensureAuthTablesExist` — the
18560
+ * tables are another process's to make — and before this nothing took its
18561
+ * place. A database that lacked `rebase.refresh_tokens`, or had a users table
18562
+ * from a release before `disabled_at`, booted green and then failed every
18563
+ * sign-in with a 500 whose cause was one missing relation. Auth cannot run on
18564
+ * part of its schema, so this is a refusal at boot, naming each table.
18565
+ *
18566
+ * Asked by reading, not by the catalogue: a `SELECT` of every column the auth
18567
+ * services name, `WHERE false`. That answers "missing", "out of date" and "this
18568
+ * role may not read it" in one statement per table, with the database's own
18569
+ * words for whichever it is.
18570
+ */
18571
+ var quote = (identifier) => `"${identifier.replace(/"/g, "\"\"")}"`;
18572
+ /** What a Drizzle table definition says auth will query. */
18573
+ function expectationOf(table) {
18574
+ const config = getTableConfig(table);
18575
+ return {
18576
+ table: config.schema ? `${quote(config.schema)}.${quote(config.name)}` : quote(config.name),
18577
+ columns: Object.values(getTableColumns(table)).map((column) => column.name)
18578
+ };
18579
+ }
18580
+ /**
18581
+ * The users table, which is the project's own when it declares an auth
18582
+ * collection: only the columns the auth bootstrap guarantees on it are
18583
+ * expected, never the collection's other fields — those are the collection
18584
+ * schema's business, checked where collections are.
18585
+ */
18586
+ function usersExpectation(qualifiedTable) {
18587
+ return {
18588
+ table: qualifiedTable,
18589
+ columns: ["id", ...AUTH_USERS_COLUMNS.map((spec) => spec.column)]
18590
+ };
18591
+ }
18592
+ /** Each table that cannot be read as expected, with the database's reason. */
18593
+ async function findUnusableAuthTables(db, expectations) {
18594
+ const problems = [];
18595
+ for (const { table, columns } of expectations) try {
18596
+ await db.execute(sql.raw(`SELECT ${columns.map(quote).join(", ")} FROM ${table} WHERE false`));
18597
+ } catch (err) {
18598
+ problems.push(`${table}: ${deepestErrorMessage(err)}`);
18599
+ }
18600
+ return problems;
18601
+ }
18602
+ /** The refusal, phrased as what to run. */
18603
+ function unusableAuthTablesError(problems) {
18604
+ return /* @__PURE__ */ new Error("Auth cannot run on this database, and this backend changes nothing in it (provisioning is off):\n" + problems.map((problem) => ` - ${problem}`).join("\n") + "\nCreate them with a provisioning run against this database (REBASE_PROVISION_ONLY=true, without REBASE_PROVISION=false), or apply the SQL such a run recorded (REBASE_PROVISION_SQL_OUT).");
18605
+ }
18606
+ //#endregion
18170
18607
  //#region src/history/ensure-history-table.ts
18171
18608
  /** How a history entry gets written from inside the write it records. */
18172
18609
  var RECORD_HISTORY_FUNCTION = "rebase.record_history";
@@ -18570,6 +19007,28 @@ var HistoryService = class {
18570
19007
  `)) ?? null;
18571
19008
  }
18572
19009
  /**
19010
+ * Every entry's `values` and `previous_values`, of every row, a page at a
19011
+ * time in id order — for a whole-store sweep. `rebase storage orphans`
19012
+ * reads it because a history revert restores the values an entry holds,
19013
+ * so a file only an entry names is still in use.
19014
+ */
19015
+ async *scanStoredValues(pageSize = 1e3) {
19016
+ const limit = Math.max(1, pageSize);
19017
+ let after;
19018
+ for (;;) {
19019
+ const rows = sqlRows(await this.db.execute(sql`
19020
+ SELECT id, "values", previous_values
19021
+ FROM rebase.entity_history
19022
+ ${after === void 0 ? sql`` : sql`WHERE id > ${after}`}
19023
+ ORDER BY id
19024
+ LIMIT ${limit}
19025
+ `));
19026
+ if (rows.length > 0) yield rows.map((row) => [row.values, row.previous_values]);
19027
+ if (rows.length < limit) return;
19028
+ after = rows[rows.length - 1].id;
19029
+ }
19030
+ }
19031
+ /**
18573
19032
  * Each entry's `format`. A table without the column holds only entries
18574
19033
  * that store the whole previous row, which is what `1` says.
18575
19034
  */
@@ -19105,6 +19564,7 @@ async function openPostgresDriver(pgConfig, config) {
19105
19564
  const rlsStatus = await readRlsStatus(rawClient, pgSchemaName);
19106
19565
  const unprotected = [...schema.tablesMap.keys()].filter((t) => !schema.joinTables.has(t) && !rlsStatus.get(t)?.rlsEnabled);
19107
19566
  const policyless = [...schema.tablesMap.keys()].filter((t) => !schema.joinTables.has(t) && rlsStatus.get(t)?.rlsEnabled && rlsStatus.get(t)?.policyCount === 0);
19567
+ const unprotectedJoinTables = [...schema.joinTables].filter((t) => !rlsStatus.get(t)?.rlsEnabled);
19108
19568
  if (unprotected.length > 0) if (unprotectedTables === "serve") logger.warn(`🔓 [rls] Serving ${unprotected.length} table(s) with row-level security DISABLED: ${unprotected.join(", ")}. Every authenticated request can read and write every row of these. This is baas.unprotectedTables: "serve".`);
19109
19569
  else {
19110
19570
  logger.warn(`🔒 [rls] Not serving ${unprotected.length} table(s) — row-level security is disabled, so they have no authorization model: ${unprotected.join(", ")}\n` + unprotected.map((t) => ` ALTER TABLE "${pgSchemaName}"."${t}" ENABLE ROW LEVEL SECURITY; -- then add a policy`).join("\n") + "\n To serve them without RLS anyway, pass baas: { unprotectedTables: \"serve\" } to the server entry: an option `rebase eject` gives you, which the managed runtime does not read from config/ or the environment.");
@@ -19114,6 +19574,10 @@ async function openPostgresDriver(pgConfig, config) {
19114
19574
  table
19115
19575
  }));
19116
19576
  }
19577
+ if (unprotectedJoinTables.length > 0) {
19578
+ logger.warn(`🔒 [rls] ${unprotectedJoinTables.length} join table(s) have row-level security disabled: ${unprotectedJoinTables.join(", ")}. The API does not serve a join table, with RLS or without, but ${REBASE_USER_ROLE$1} keeps its grants on these, so SQL your own code runs as a caller reaches every row.`);
19579
+ for (const t of unprotectedJoinTables) schema.tablesMap.delete(t);
19580
+ }
19117
19581
  if (policyless.length > 0) logger.warn(`🔒 [rls] ${policyless.length} table(s) have RLS enabled but no policies, so they will return no rows: ${policyless.join(", ")}`);
19118
19582
  introspectedCollections = buildCollectionsFromSchema(schema, pgSchemaName);
19119
19583
  ({tables: introspectedTables, relations: introspectedRelations} = buildBaasSchema(schema.tablesMap, pgSchemaName, introspectedCollections));
@@ -19206,6 +19670,7 @@ async function openPostgresDriver(pgConfig, config) {
19206
19670
  driver.listenConnectionString = directUrl;
19207
19671
  realtimeService.setDataDriver(driver);
19208
19672
  let rlsEnforcement;
19673
+ let exposedInternalTables;
19209
19674
  {
19210
19675
  const runSql = async (text) => {
19211
19676
  return (await schemaAwareDb.execute(sql.raw(text))).rows ?? [];
@@ -19223,6 +19688,10 @@ async function openPostgresDriver(pgConfig, config) {
19223
19688
  if (!provision) {
19224
19689
  const roleExists = (await runSql(`SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE$1}'`)).length > 0;
19225
19690
  switched = roleExists || bypassesNow;
19691
+ if (roleExists) {
19692
+ exposedInternalTables = await findExposedInternalTables(runSql, managedSchemas);
19693
+ if (exposedInternalTables.length > 0) logger.warn(`⚠️ RLS enforcement: the request role "${REBASE_USER_ROLE$1}" can reach framework tables no user should: ${exposedInternalTables.join(", ")}. A provisioning boot revokes this; this driver was opened without provisioning, so nothing does.`);
19694
+ }
19226
19695
  if (!roleExists && bypassesNow) logger.warn(`⚠️ RLS enforcement: connection role "${posture.role}" bypasses row-level security and the restricted role "${REBASE_USER_ROLE$1}" does not exist yet — this driver was opened without provisioning, so it was not created. Requests made as a user will fail until a server boot (or \`rebase db push\`) creates it; requests as the connection itself are unaffected.`);
19227
19696
  } else try {
19228
19697
  await ensureAppRole(runSql, managedSchemas);
@@ -19262,7 +19731,7 @@ async function openPostgresDriver(pgConfig, config) {
19262
19731
  if (!realtimeOff && (isChannelBusInstance(busSetting) || busSetting.type !== "memory")) await realtimeService.configureChannelBus(createChannelBus(busSetting, {
19263
19732
  db: schemaAwareDb,
19264
19733
  directUrl
19265
- }));
19734
+ }), { provision });
19266
19735
  } catch (err) {
19267
19736
  logger.warn("⚠️ [ChannelBus] Could not configure the channel bus — channel broadcast and presence stay per-instance", { error: err });
19268
19737
  }
@@ -19397,6 +19866,7 @@ async function openPostgresDriver(pgConfig, config) {
19397
19866
  poolManager,
19398
19867
  provisioned: provision,
19399
19868
  rlsEnforcement,
19869
+ exposedInternalTables,
19400
19870
  provisionCdcForTables
19401
19871
  };
19402
19872
  return {
@@ -19467,7 +19937,7 @@ function createPostgresBootstrapper(pgConfig) {
19467
19937
  const openIndexBuildSession = (driverResult) => async () => {
19468
19938
  const db = requireProvisioningDb(driverResult);
19469
19939
  const pool = "$client" in db ? db.$client : void 0;
19470
- const { isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-BE0I6sYU.js").then((n) => n.r);
19940
+ const { isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-DRnoMq-O.js").then((n) => n.r);
19471
19941
  if (isPgPool(pool)) return poolIndexBuildSession(pool)();
19472
19942
  const queryable = provisioningQueryable(driverResult);
19473
19943
  return {
@@ -19493,7 +19963,7 @@ function createPostgresBootstrapper(pgConfig) {
19493
19963
  */
19494
19964
  const provisionRlsRuntime = async (driverResult) => {
19495
19965
  const db = requireProvisioningDb(driverResult);
19496
- const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./db-subcommands-BPoHCxJR.js").then((n) => n.v);
19966
+ const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./migrate-baseline-Bfk1LGC6.js").then((n) => n.w);
19497
19967
  const run = async (text) => sqlRows(await db.execute(sql.raw(text)));
19498
19968
  if (await rlsRuntimeIsCurrent(run).catch(() => false)) return;
19499
19969
  await db.transaction(async (tx) => {
@@ -19526,6 +19996,9 @@ function createPostgresBootstrapper(pgConfig) {
19526
19996
  const init = config;
19527
19997
  const opened = await openPostgresDriver(effectiveConfig(init.dataSourceKey), init);
19528
19998
  if (opened.internals.rlsEnforcement) logger.info(opened.internals.rlsEnforcement);
19999
+ const exposed = opened.internals.exposedInternalTables ?? [];
20000
+ if (exposed.length > 0) throw new Error(`The request role "${REBASE_USER_ROLE$1}" can read or write framework tables that hold sessions, key hashes and job payloads: ${exposed.join(", ")}.\nA provisioning boot revokes this, and this backend changes nothing in its database (provisioning is off). Revoke it as part of your change process:
20001
+ ` + exposed.map((table) => ` REVOKE ALL ON ${table.split(".").map((part) => `"${part}"`).join(".")} FROM ${REBASE_USER_ROLE$1};`).join("\n"));
19529
20002
  return opened;
19530
20003
  },
19531
20004
  async initializeAuth(config, driverResult) {
@@ -19536,7 +20009,23 @@ function createPostgresBootstrapper(pgConfig) {
19536
20009
  const registry = internals.registry;
19537
20010
  const authCollection = authConfig.collection;
19538
20011
  if (internals.provisioned !== false) await ensureAuthTablesExist(db, authCollection);
19539
- else await assertAuthSchemaCompatible(db, resolveAuthSchema(authCollection));
20012
+ else {
20013
+ await assertAuthSchemaCompatible(db, resolveAuthSchema(authCollection));
20014
+ const usersSchema = authCollection ? "schema" in authCollection && typeof authCollection.schema === "string" ? authCollection.schema : "public" : "rebase";
20015
+ const usersTableName = authCollection ? "table" in authCollection && typeof authCollection.table === "string" ? authCollection.table : authCollection.slug : "users";
20016
+ const expected = createAuthSchema(usersSchema === "public" ? "rebase" : usersSchema);
20017
+ const problems = await findUnusableAuthTables(db, [usersExpectation(usersSchema === "public" ? `"${usersTableName}"` : `"${usersSchema}"."${usersTableName}"`), ...[
20018
+ expected.refreshTokens,
20019
+ expected.passwordResetTokens,
20020
+ expected.appConfig,
20021
+ expected.userIdentities,
20022
+ expected.mfaFactors,
20023
+ expected.mfaChallenges,
20024
+ expected.recoveryCodes,
20025
+ expected.magicLinkTokens
20026
+ ].map(expectationOf)]);
20027
+ if (problems.length > 0) throw unusableAuthTablesError(problems);
20028
+ }
19540
20029
  if (authCollection && internals.provisionCdcForTables) {
19541
20030
  const authSchema = "schema" in authCollection && typeof authCollection.schema === "string" ? authCollection.schema : "rebase";
19542
20031
  const authTable = "table" in authCollection && typeof authCollection.table === "string" ? authCollection.table : authCollection.slug;
@@ -19587,11 +20076,11 @@ function createPostgresBootstrapper(pgConfig) {
19587
20076
  unavailable: historyUnavailableReason(state, { requireTransaction: false })
19588
20077
  }) };
19589
20078
  }
19590
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-DYH95Qeg.js").then((n) => n.i);
20079
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-yukSebLA.js").then((n) => n.i);
19591
20080
  const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
19592
20081
  const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
19593
20082
  if (historyIndexes.length > 0) {
19594
- const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-BE0I6sYU.js").then((n) => n.r);
20083
+ const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-DRnoMq-O.js").then((n) => n.r);
19595
20084
  const indexOptions = {
19596
20085
  log: (message) => logger.info(`[history] ${message}`),
19597
20086
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
@@ -19647,9 +20136,9 @@ function createPostgresBootstrapper(pgConfig) {
19647
20136
  * proved it can bootstrap with.
19648
20137
  */
19649
20138
  async ensureCollectionSchema(collections, driverResult, log) {
19650
- const { ensureCollectionTables } = await import("./ensure-collection-tables-Cet4650m.js").then((n) => n.n);
20139
+ const { ensureCollectionTables } = await import("./ensure-collection-tables-BeF1lArf.js").then((n) => n.n);
19651
20140
  const queryable = provisioningQueryable(driverResult);
19652
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-DYH95Qeg.js").then((n) => n.i);
20141
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-yukSebLA.js").then((n) => n.i);
19653
20142
  const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
19654
20143
  const plan = await ensureCollectionTables(queryable, collections, log, {
19655
20144
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS,
@@ -19661,7 +20150,7 @@ function createPostgresBootstrapper(pgConfig) {
19661
20150
  pendingIndexBuild?.cancel();
19662
20151
  pendingIndexBuild = void 0;
19663
20152
  if (!provisionOnly && plan.deferredIndexes.length > 0) {
19664
- const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-BE0I6sYU.js").then((n) => n.r);
20153
+ const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-DRnoMq-O.js").then((n) => n.r);
19665
20154
  logger.info(`[schema] ${plan.deferredIndexes.length} index(es) are missing, or were left INVALID, on tables that already exist. They are built in the background once the server is serving, one at a time, without blocking reads or writes.`);
19666
20155
  pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
19667
20156
  log: (message) => logger.info(`[schema] ${message}`),
@@ -19701,7 +20190,7 @@ function createPostgresBootstrapper(pgConfig) {
19701
20190
  await provisionRlsRuntime(driverResult);
19702
20191
  },
19703
20192
  async ensureCollectionPolicies(collections, driverResult, log) {
19704
- const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-BnGOURpG.js");
20193
+ const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-H8HN1Gbd.js");
19705
20194
  const queryable = provisioningQueryable(driverResult);
19706
20195
  const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
19707
20196
  if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
@@ -19726,7 +20215,7 @@ function createPostgresBootstrapper(pgConfig) {
19726
20215
  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$1}, so the table is unreachable rather than unprotected. Reads and writes to that collection will fail until RLS can be enabled.`);
19727
20216
  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$1} 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.`);
19728
20217
  try {
19729
- const { dropLegacyAuthSchema } = await import("./db-subcommands-BPoHCxJR.js").then((n) => n.v);
20218
+ const { dropLegacyAuthSchema } = await import("./migrate-baseline-Bfk1LGC6.js").then((n) => n.w);
19730
20219
  await dropLegacyAuthSchema(async (text) => (await queryable.query(text)).rows, {
19731
20220
  info: (m) => logger.info(m),
19732
20221
  warn: (m) => logger.warn(m)
@@ -19746,14 +20235,14 @@ function createPostgresBootstrapper(pgConfig) {
19746
20235
  async readCollectionsSchemaVersion(driverResult) {
19747
20236
  const db = provisioningDb(driverResult);
19748
20237
  if (!db) return null;
19749
- const { readCollectionsSchemaVersion } = await import("./collections-schema-version-T6cGvrDi.js");
20238
+ const { readCollectionsSchemaVersion } = await import("./collections-schema-version-D7bDI0PJ.js");
19750
20239
  return readCollectionsSchemaVersion(db, SCHEMA_META_SCHEMA);
19751
20240
  },
19752
20241
  /** Record what this process just applied. Only the provisioning process calls this. */
19753
20242
  async stampCollectionsSchemaVersion(version, driverResult) {
19754
20243
  const db = provisioningDb(driverResult);
19755
20244
  if (!db) return;
19756
- const { stampCollectionsSchemaVersion } = await import("./collections-schema-version-T6cGvrDi.js");
20245
+ const { stampCollectionsSchemaVersion } = await import("./collections-schema-version-D7bDI0PJ.js");
19757
20246
  await stampCollectionsSchemaVersion(db, SCHEMA_META_SCHEMA, version);
19758
20247
  },
19759
20248
  /**
@@ -19817,7 +20306,7 @@ function createPostgresBootstrapper(pgConfig) {
19817
20306
  return driverResult.internals.driver.admin;
19818
20307
  },
19819
20308
  async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
19820
- const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-BKZwsjmf.js").then((n) => n.c);
20309
+ const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-C9Fx7iSx.js").then((n) => n.c);
19821
20310
  if (!isSocketRealtimeService(realtimeService)) throw new Error(`The realtime service handed to the Postgres socket cannot serve it — it has no ${socketRealtimeMissing(realtimeService).join(", ")}. Every socket would fail on its first frame.`);
19822
20311
  const realtimeConfig = effectiveConfig().realtime;
19823
20312
  const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
@@ -19891,6 +20380,7 @@ async function openRebase(options) {
19891
20380
  const hint = extractPgError(error)?.hint;
19892
20381
  throw new Error(`Cannot connect to PostgreSQL at ${parseHostInfo(connectionString ?? "")}: ${deepestErrorMessage(error) ?? "the connection failed"}.${hint ? ` ${hint}` : ""}`, { cause: error });
19893
20382
  }
20383
+ const ownKey = options.dataSourceKey ?? DEFAULT_DATA_SOURCE_KEY;
19894
20384
  let opened;
19895
20385
  try {
19896
20386
  opened = await openPostgresDriver({
@@ -19898,7 +20388,7 @@ async function openRebase(options) {
19898
20388
  connectionString
19899
20389
  }, {
19900
20390
  collections: options.collections,
19901
- dataSourceKey: options.dataSourceKey ?? DEFAULT_DATA_SOURCE_KEY,
20391
+ dataSourceKey: ownKey,
19902
20392
  introspectCollections: options.collections.length === 0,
19903
20393
  provision: false,
19904
20394
  realtime: false,
@@ -19913,6 +20403,7 @@ async function openRebase(options) {
19913
20403
  }
19914
20404
  const driver = opened.internals.driver;
19915
20405
  const registry = opened.internals.registry;
20406
+ if (options.callbacks) registry.setGlobalCallbacks(options.callbacks);
19916
20407
  if (opened.internals.rlsEnforcement) logger.debug(opened.internals.rlsEnforcement);
19917
20408
  const collections = opened.collections ?? options.collections;
19918
20409
  if (collections.some((collection) => collection.history)) try {
@@ -19937,10 +20428,13 @@ async function openRebase(options) {
19937
20428
  collections,
19938
20429
  async sql(query, sqlOptions) {
19939
20430
  if (!isSQLAdmin(admin)) throw new Error("This driver cannot run raw SQL.");
20431
+ if (sqlOptions?.database !== void 0) {
20432
+ const asked = resourceKeyOf(sqlOptions.database);
20433
+ if (asked !== ownKey) throw new Error(`openRebase opened the "${ownKey}" data source only, so it cannot run SQL on "${asked}". Open that one with its own openRebase({ databaseUrl, dataSourceKey: "${asked}" }).`);
20434
+ }
19940
20435
  return admin.executeSql(query, sqlOptions && {
19941
20436
  role: sqlOptions.role,
19942
- params: sqlOptions.params,
19943
- ...sqlOptions.database !== void 0 ? { database: resourceKeyOf(sqlOptions.database) } : {}
20437
+ params: sqlOptions.params
19944
20438
  });
19945
20439
  },
19946
20440
  async withAuth(user) {
@@ -19956,4 +20450,4 @@ async function openRebase(options) {
19956
20450
  //#endregion
19957
20451
  export { AuthenticatedPostgresBackendDriver as $, budgetSendBuffers as A, mfaFactors as B, PG_NOTIFY_MAX_PAYLOAD_BYTES as C, MemoryChannelBus as D, parseChannelBusPayload as E, createAuthSchema as F, recoveryCodesRelations as G, passwordResetTokens as H, magicLinkTokens as I, userIdentities as J, refreshTokens as K, magicLinkTokensRelations as L, terminateIfBacklogged as M, assertReadRequestReadable as N, frameByteLength as O, appConfig as P, usersSchema as Q, mfaChallenges as R, DEFAULT_BATCH_WINDOW_MS as S, parseChannelBusFrame as T, passwordResetTokensRelations as U, mfaFactorsRelations as V, recoveryCodes as W, users as X, userIdentitiesRelations as Y, usersRelations as Z, parseRealtimeTuning as _, listedColumnKeys as _t, openPostgresDriver as a, isRoleSwitchingOptedOut as at, resolveChannelBusSetting as b, resolveSourceUrls as c, SqlResultTooLargeError as ct, DEFAULT_RECOUNT_MIN_ROWS as d, DrizzleConditionBuilder as dt, CONNECTION_OWNER as et, PostgresRealtimeProvider as f, PostgresConditionBuilder as ft, parseMaxSubscriptionsPerSocket as g, joinColumn as gt, parseMaxSocketsPerUser as h, getUnknownFilterFieldsMode as ht, isScaffoldedLocalDatabase as i, effectiveSqlRole as it, reapSilentSockets as j, isChannelBusInstance$1 as k, PostgresCollectionRegistry as l, isNestedPath as lt, packEntityChanges as m, escapeLikePattern as mt, createPostgresBootstrapper as n, RoleSwitchUnavailableError as nt, postgresDriverConfigFromEnv as o, sqlRoleRanAs as ot, RealtimeService as p, configureUnknownFilterFields as pt, refreshTokensRelations as q, describeSchemaDriftCause as r, branchParentDatabase as rt, resolveDriftCheckName as s, SQL_RESULT_BYTE_BUDGET as st, openRebase as t, PostgresBackendDriver as tt, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET as u, resolveNestedPath as ut, refetchConcurrencyFor as v, PostgresChannelBus as w, CHANNEL_BUS_NOTIFY_CHANNEL as x, createChannelBus as y, mfaChallengesRelations as z };
19958
20452
 
19959
- //# sourceMappingURL=open-rebase-EmqVmS14.js.map
20453
+ //# sourceMappingURL=open-rebase-DZ5JbZpg.js.map