@rebasepro/server-postgres 0.29.0 → 0.29.2

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 (161) hide show
  1. package/dist/{BranchService-JiYJ_n9E.js → BranchService-X9R505mP.js} +3 -3
  2. package/dist/{BranchService-JiYJ_n9E.js.map → BranchService-X9R505mP.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +90 -12
  4. package/dist/PostgresBootstrapper.d.ts +34 -0
  5. package/dist/auth/ensure-tables.d.ts +2 -2
  6. package/dist/auth/schema-version.d.ts +5 -5
  7. package/dist/auth/services.d.ts +9 -9
  8. package/dist/{backup-cli-D_aKXPyX.js → backup-cli-CwiJEp_J.js} +3 -3
  9. package/dist/{backup-cli-D_aKXPyX.js.map → backup-cli-CwiJEp_J.js.map} +1 -1
  10. package/dist/{boot-ddl-D4W9o9xE.js → boot-ddl-CbZj9ovZ.js} +2 -2
  11. package/dist/{boot-ddl-D4W9o9xE.js.map → boot-ddl-CbZj9ovZ.js.map} +1 -1
  12. package/dist/{cli-console-DPdZCWTi.js → cli-console-DDkNetCz.js} +6 -6
  13. package/dist/{cli-console-DPdZCWTi.js.map → cli-console-DDkNetCz.js.map} +1 -1
  14. package/dist/{cli-errors-D8s4z_3g.js → cli-errors-C73Qy7WJ.js} +49 -6
  15. package/dist/{cli-errors-D8s4z_3g.js.map → cli-errors-C73Qy7WJ.js.map} +1 -1
  16. package/dist/cli.js +209 -53
  17. package/dist/cli.js.map +1 -1
  18. package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
  19. package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
  20. package/dist/data-transformer.d.ts +2 -2
  21. package/dist/database-health.d.ts +2 -1
  22. package/dist/database-preflight-DIauc8i5.js +184 -0
  23. package/dist/database-preflight-DIauc8i5.js.map +1 -0
  24. package/dist/{databasePoolManager-7hXVurmG.js → databasePoolManager-DIjzlTK4.js} +2 -2
  25. package/dist/{databasePoolManager-7hXVurmG.js.map → databasePoolManager-DIjzlTK4.js.map} +1 -1
  26. package/dist/db-subcommands.d.ts +1 -1
  27. package/dist/{deferred-index-build-F2GWu009.js → deferred-index-build-DDdnjaOW.js} +25 -9
  28. package/dist/deferred-index-build-DDdnjaOW.js.map +1 -0
  29. package/dist/{doctor-_g2tHRtG.js → doctor-DwMXljiq.js} +11 -11
  30. package/dist/doctor-DwMXljiq.js.map +1 -0
  31. package/dist/{ensure-collection-policies-DUpWJb5D.js → ensure-collection-policies-DJsOMpaI.js} +23 -13
  32. package/dist/ensure-collection-policies-DJsOMpaI.js.map +1 -0
  33. package/dist/{ensure-collection-tables-BK--gDo6.js → ensure-collection-tables-h1mUO7Uu.js} +18 -10
  34. package/dist/ensure-collection-tables-h1mUO7Uu.js.map +1 -0
  35. package/dist/{ensure-tables-Bx1DYarz.js → ensure-tables-CUqYgMvo.js} +4 -4
  36. package/dist/ensure-tables-CUqYgMvo.js.map +1 -0
  37. package/dist/{enum-labels-kept-DyFE4Gaq.js → enum-labels-kept-z7ustOl_.js} +3 -3
  38. package/dist/{enum-labels-kept-DyFE4Gaq.js.map → enum-labels-kept-z7ustOl_.js.map} +1 -1
  39. package/dist/{generate-drizzle-schema-taNTu3xv.js → generate-drizzle-schema-BIUqhSzh.js} +2 -2
  40. package/dist/{generate-drizzle-schema-taNTu3xv.js.map → generate-drizzle-schema-BIUqhSzh.js.map} +1 -1
  41. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js → generate-drizzle-schema-logic-BBXjxm5z.js} +3 -3
  42. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js.map → generate-drizzle-schema-logic-BBXjxm5z.js.map} +1 -1
  43. package/dist/{generate-files-DbwU8Btx.js → generate-files-BkiRFoV1.js} +3 -3
  44. package/dist/{generate-files-DbwU8Btx.js.map → generate-files-BkiRFoV1.js.map} +1 -1
  45. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js → generate-postgres-ddl-logic-G9PvjHrr.js} +10 -5
  46. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js.map → generate-postgres-ddl-logic-G9PvjHrr.js.map} +1 -1
  47. package/dist/{generated-schema-diff-4lOC0g1_.js → generated-schema-diff-D2soazQU.js} +18 -7
  48. package/dist/generated-schema-diff-D2soazQU.js.map +1 -0
  49. package/dist/history/HistoryService.d.ts +2 -3
  50. package/dist/history/ensure-history-table.d.ts +8 -3
  51. package/dist/index.d.ts +2 -1
  52. package/dist/index.es.js +22 -14
  53. package/dist/index.es.js.map +1 -1
  54. package/dist/interfaces.d.ts +24 -2
  55. package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
  56. package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
  57. package/dist/{migrate-baseline-BeepEphh.js → migrate-baseline-CveNQli3.js} +166 -460
  58. package/dist/migrate-baseline-CveNQli3.js.map +1 -0
  59. package/dist/{migrate-policy-stamps-cYMJ_9Ha.js → migrate-policy-stamps-C4qbQ0jK.js} +42 -13
  60. package/dist/migrate-policy-stamps-C4qbQ0jK.js.map +1 -0
  61. package/dist/{open-rebase-CTNBmmH8.js → open-rebase-Cvid3iwR.js} +1813 -689
  62. package/dist/open-rebase-Cvid3iwR.js.map +1 -0
  63. package/dist/open-rebase.d.ts +7 -2
  64. package/dist/{pg-error-utils-BLOVXK67.js → pg-error-utils-80uTIHQs.js} +2 -2
  65. package/dist/{pg-error-utils-BLOVXK67.js.map → pg-error-utils-80uTIHQs.js.map} +1 -1
  66. package/dist/pipelined-transaction.d.ts +24 -37
  67. package/dist/{plan-schema-CMNWvqIa.js → plan-schema-CMhNYEYF.js} +109 -14
  68. package/dist/plan-schema-CMhNYEYF.js.map +1 -0
  69. package/dist/{policy-drift-IjD2AUD-.js → policy-drift-Bx6663KD.js} +29 -6
  70. package/dist/policy-drift-Bx6663KD.js.map +1 -0
  71. package/dist/push-index-adoption-C-TpM445.js +22 -0
  72. package/dist/push-index-adoption-C-TpM445.js.map +1 -0
  73. package/dist/{push-index-prebuild-CIvajIrL.js → push-index-prebuild-xbpgZEJK.js} +4 -4
  74. package/dist/{push-index-prebuild-CIvajIrL.js.map → push-index-prebuild-xbpgZEJK.js.map} +1 -1
  75. package/dist/{push-kept-defaults-CLbsuSmo.js → push-kept-defaults-D-JEv0Gn.js} +2 -2
  76. package/dist/{push-kept-defaults-CLbsuSmo.js.map → push-kept-defaults-D-JEv0Gn.js.map} +1 -1
  77. package/dist/{push-legacy-renames-DeW_HTLJ.js → push-legacy-renames-7UKspspl.js} +4 -4
  78. package/dist/{push-legacy-renames-DeW_HTLJ.js.map → push-legacy-renames-7UKspspl.js.map} +1 -1
  79. package/dist/{push-policy-plan--oRXOj4X.js → push-policy-plan-BOw5PtU8.js} +14 -8
  80. package/dist/push-policy-plan-BOw5PtU8.js.map +1 -0
  81. package/dist/read-routing.d.ts +10 -30
  82. package/dist/{render-ddl-CzVcbbR1.js → render-ddl-Di-fTGti.js} +40 -10
  83. package/dist/render-ddl-Di-fTGti.js.map +1 -0
  84. package/dist/request-role-cli-Bxxskru9.js +260 -0
  85. package/dist/request-role-cli-Bxxskru9.js.map +1 -0
  86. package/dist/request-role-cli.d.ts +86 -0
  87. package/dist/request-role-migration-BCW4v0rq.js +150 -0
  88. package/dist/request-role-migration-BCW4v0rq.js.map +1 -0
  89. package/dist/rls-bootstrap-sql-CxszeSc7.js +534 -0
  90. package/dist/rls-bootstrap-sql-CxszeSc7.js.map +1 -0
  91. package/dist/rls-enforcement-CyUCPDH8.js +1195 -0
  92. package/dist/rls-enforcement-CyUCPDH8.js.map +1 -0
  93. package/dist/rls-settings-BCGMIig3.js +231 -0
  94. package/dist/rls-settings-BCGMIig3.js.map +1 -0
  95. package/dist/schema/doctor-cli.js +145 -7
  96. package/dist/schema/doctor-cli.js.map +1 -1
  97. package/dist/schema/doctor-database.d.ts +27 -0
  98. package/dist/schema/drizzle-ddl.d.ts +2 -2
  99. package/dist/schema/ensure-collection-policies.d.ts +15 -3
  100. package/dist/schema/generate-drizzle-schema.js +1 -1
  101. package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -1
  102. package/dist/schema/generate-postgres-ddl.js +1 -1
  103. package/dist/schema/index-adoption.d.ts +99 -0
  104. package/dist/schema/introspect-db-logic.d.ts +2 -1
  105. package/dist/schema/introspect-db.js +3 -3
  106. package/dist/schema/migrate-policy-stamps.d.ts +19 -1
  107. package/dist/schema/plan/diff-plan.d.ts +14 -2
  108. package/dist/schema/plan/render-ddl.d.ts +17 -3
  109. package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
  110. package/dist/schema/plan/types.d.ts +17 -0
  111. package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
  112. package/dist/schema/plan/view-names.d.ts +6 -0
  113. package/dist/schema/push-index-adoption.d.ts +10 -0
  114. package/dist/schema/push-policy-plan.d.ts +5 -1
  115. package/dist/schema/rls-bootstrap-sql.d.ts +34 -0
  116. package/dist/schema/search-column.d.ts +2 -2
  117. package/dist/search-column-BM-GV6vH.js.map +1 -1
  118. package/dist/security/caller-sql-columns.d.ts +60 -0
  119. package/dist/security/caller-sql.d.ts +8 -0
  120. package/dist/security/database-preflight.d.ts +24 -0
  121. package/dist/security/policy-drift.d.ts +19 -1
  122. package/dist/security/request-role-migration.d.ts +36 -0
  123. package/dist/security/rls-enforcement.d.ts +277 -21
  124. package/dist/security/rls-settings.d.ts +210 -0
  125. package/dist/services/FetchService.d.ts +33 -8
  126. package/dist/services/PersistService.d.ts +75 -4
  127. package/dist/services/RelationService.d.ts +1 -1
  128. package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
  129. package/dist/services/channel-bus/index.d.ts +2 -2
  130. package/dist/services/channel-history.d.ts +2 -2
  131. package/dist/services/channel-presence.d.ts +3 -3
  132. package/dist/services/dataService.d.ts +8 -2
  133. package/dist/services/realtimeService.d.ts +21 -5
  134. package/dist/services/socket-liveness.d.ts +6 -1
  135. package/dist/services/view-access.d.ts +2 -2
  136. package/dist/types.d.ts +1 -1
  137. package/dist/utils/drizzle-conditions.d.ts +12 -0
  138. package/dist/utils/positional-params.d.ts +40 -0
  139. package/dist/view-names-Dscp6--B.js +24 -0
  140. package/dist/view-names-Dscp6--B.js.map +1 -0
  141. package/dist/{websocket-D2y88dOa.js → websocket-BSYV_KSw.js} +3 -3
  142. package/dist/websocket-BSYV_KSw.js.map +1 -0
  143. package/dist/websocket.d.ts +14 -3
  144. package/package.json +7 -7
  145. package/dist/deferred-index-build-F2GWu009.js.map +0 -1
  146. package/dist/doctor-_g2tHRtG.js.map +0 -1
  147. package/dist/ensure-collection-policies-DUpWJb5D.js.map +0 -1
  148. package/dist/ensure-collection-tables-BK--gDo6.js.map +0 -1
  149. package/dist/ensure-tables-Bx1DYarz.js.map +0 -1
  150. package/dist/generated-schema-diff-4lOC0g1_.js.map +0 -1
  151. package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
  152. package/dist/migrate-baseline-BeepEphh.js.map +0 -1
  153. package/dist/migrate-policy-stamps-cYMJ_9Ha.js.map +0 -1
  154. package/dist/open-rebase-CTNBmmH8.js.map +0 -1
  155. package/dist/plan-schema-CMNWvqIa.js.map +0 -1
  156. package/dist/policy-drift-IjD2AUD-.js.map +0 -1
  157. package/dist/push-policy-plan--oRXOj4X.js.map +0 -1
  158. package/dist/render-ddl-CzVcbbR1.js.map +0 -1
  159. package/dist/rls-enforcement-jZTv1yci.js +0 -534
  160. package/dist/rls-enforcement-jZTv1yci.js.map +0 -1
  161. package/dist/websocket-D2y88dOa.js.map +0 -1
@@ -244,6 +244,10 @@ function pinSearchPath(connectionString, searchPath = "public") {
244
244
  url.search = Array.from(url.searchParams.entries()).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
245
245
  return url.toString();
246
246
  }
247
+ /** pg-pool's private set of expired clients: a WeakSet today, anything with `add`/`has` tomorrow. */
248
+ function isClientSet(value) {
249
+ return typeof value === "object" && value !== null && "add" in value && typeof value.add === "function" && "has" in value && typeof value.has === "function";
250
+ }
247
251
  /**
248
252
  * Destroy pool clients that are released while still inside a transaction.
249
253
  *
@@ -269,8 +273,8 @@ function guardPoolAgainstDirtyRelease(pool, label) {
269
273
  if (err) return;
270
274
  const txStatus = client?._txStatus;
271
275
  if (typeof txStatus !== "string" || txStatus === TX_IDLE) return;
272
- const expired = pool._expired;
273
- if (expired && typeof expired.add === "function" && typeof expired.has === "function" && client && typeof client === "object") {
276
+ const expired = Reflect.get(pool, "_expired");
277
+ if (isClientSet(expired) && client && typeof client === "object") {
274
278
  expired.add(client);
275
279
  logger.error(`[${label}] Client released back to the pool while still in a transaction (status '${txStatus}') — destroying it so the open transaction and its session state (RLS GUCs) cannot leak into the next request.`);
276
280
  } else logger.error(`[${label}] Client released mid-transaction (status '${txStatus}') but the pool's internal expiry set is unavailable (pg-pool internals changed?). The connection may leak its open transaction into subsequent requests.`);
@@ -395,4 +399,4 @@ function closeWithPool(pool, companions) {
395
399
  //#endregion
396
400
  export { createPostgresDatabaseConnection as a, guardPoolAgainstDirtyRelease as c, poolMaxCeiling as d, pooledTransactionSettings as f, reportPoolError as g, transactionSettingsStatements as h, createDirectDatabaseConnection as i, isPooledPool as l, transactionSettingsConfig as m, closeWithPool as n, createReadReplicaConnection as o, searchPathList as p, connection_exports as r, defaultPoolTimeouts as s, cappedPoolMax as t, pinSearchPath as u };
397
401
 
398
- //# sourceMappingURL=connection-COuS5Fm-.js.map
402
+ //# sourceMappingURL=connection-C1zXTPJq.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"connection-COuS5Fm-.js","names":[],"sources":["../src/pool-disconnects.ts","../src/connection.ts"],"sourcesContent":["/**\n * What a pool says when the server ends its idle connections.\n *\n * `pg_terminate_backend` ends every connection to a database at once, and an\n * idle pool client hears it as an `error` event: one per connection, from\n * every pool the process holds. `rebase db branch create --force` does exactly\n * that to the database it copies, so fifteen forced creates beside a running\n * `rebase dev` printed 220 `❌ [ERROR] [pg-pool] Unexpected pool error\n * {\"detail\":\"terminating connection due to administrator command\"}` lines. It\n * read as an outage, and nothing was wrong: the pool opens new connections on\n * the next query. A database restart looks the same.\n */\nimport { logger } from \"@rebasepro/server\";\n\n/** SQLSTATEs of a connection the server ended: admin_shutdown, crash_shutdown, cannot_connect_now. */\nconst SERVER_ENDED_CODES = new Set([\"57P01\", \"57P02\", \"57P03\"]);\n\n/** Did the server end this connection, rather than something go wrong with it? */\nexport function serverEndedConnection(err: Error): boolean {\n const code = \"code\" in err ? err.code : undefined;\n return (typeof code === \"string\" && SERVER_ENDED_CODES.has(code))\n || /terminating connection due to administrator command/i.test(err.message);\n}\n\n/** How long one line stands for every server-ended connection after it, across all pools. */\nexport const DISCONNECT_BURST_MS = 10_000;\n\n/** When the current burst's line stops covering further disconnects. */\nlet burstUntil = 0;\n\n/** The logger methods a pool's error listener writes through. */\nexport type PoolErrorLog = Pick<typeof logger, \"warn\" | \"error\" | \"debug\">;\n\n/**\n * Say a pool's `error` event: a connection the server ended is one WARN line\n * per burst for the whole process, and the rest of the burst is at debug;\n * anything else is the ERROR it always was.\n *\n * The window is fixed from the first disconnect, not extended by each, so a\n * second burst ten seconds later is said again.\n */\nexport function reportPoolError(label: string, err: Error, log: PoolErrorLog = logger, now: () => number = Date.now): void {\n if (!serverEndedConnection(err)) {\n log.error(`[${label}] Unexpected pool error`, { detail: err.message });\n return;\n }\n const at = now();\n if (at < burstUntil) {\n log.debug(`[${label}] The database ended another idle connection`, { detail: err.message });\n return;\n }\n burstUntil = at + DISCONNECT_BURST_MS;\n const code = \"code\" in err && typeof err.code === \"string\" ? `, ${err.code}` : \"\";\n log.warn(\n `[${label}] The database ended this server's idle connections (${err.message}${code}). ` +\n \"New ones open on the next query. A database restart does this, and so does \" +\n \"`rebase db branch create --force`, which closes the database it copies.\"\n );\n}\n","import { Pool, PoolConfig } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { reportPoolError } from \"./pool-disconnects\";\n\n/**\n * Configuration for the Postgres connection pool.\n *\n * Sensible defaults are provided for production Cloud Run / single-instance\n * deployments. Override via environment variables or explicit config.\n */\nexport interface PostgresPoolConfig {\n /** Maximum number of connections in the pool (default: 20) */\n max?: number;\n /** Close idle connections after this many ms (default: 30 000) */\n idleTimeoutMillis?: number;\n /** Abort connection attempts after this many ms (default: 10 000) */\n connectionTimeoutMillis?: number;\n /** Per-query timeout in ms (default: 30 000) */\n queryTimeout?: number;\n /** Per-statement timeout in ms (default: 30 000) */\n statementTimeout?: number;\n /** Enable TCP keep-alive (default: true) */\n keepAlive?: boolean;\n /**\n * `search_path` pinned on every connection (default: `\"public\"`).\n *\n * Pass `false` to send no `search_path` at all and inherit whatever the\n * server/role defaults to. See {@link pinSearchPath} for why the default\n * is not \"inherit\".\n */\n searchPath?: string | false;\n /**\n * The URL reaches the database through a transaction-mode pooler such as\n * PgBouncer (`DATABASE_POOLED=true`).\n *\n * A transaction-mode pooler hands each transaction whatever server\n * connection is free, so nothing set for a *session* survives to the next\n * statement — and the startup packet's parameters are either refused by\n * the pooler or dropped by it (`ignore_startup_parameters`). So a pooled\n * pool sends neither `statement_timeout` nor `options=-c search_path` at\n * connect; {@link pooledTransactionSettings} says what to `SET LOCAL` at\n * the start of each transaction instead, and the boot sets the role's\n * default `search_path` (see `ensurePooledRoleDefaults`).\n *\n * Explicit rather than sniffed from the URL: a pooler's address looks like\n * any other database's.\n */\n pooled?: boolean;\n}\n\n/**\n * Ceiling on pool size, from the environment.\n *\n * Exists for the managed development database. PGlite is a single session\n * behind a multiplexing socket server, and two pooled clients holding\n * overlapping transactions deadlock there — which a request-per-transaction\n * server produces the moment two requests overlap. One connection turns that\n * deadlock into ordinary queueing.\n *\n * A ceiling rather than a value, so it constrains every pool in the process\n * without any of them having to know why. Ignored when unset or unparseable,\n * because a malformed limit must not silently serialize a production server.\n */\nexport function poolMaxCeiling(env: NodeJS.ProcessEnv = process.env): number | null {\n const raw = env.REBASE_DB_POOL_MAX;\n if (typeof raw !== \"string\") return null;\n\n // Plain decimal digits only. `Number` would also accept `1e3`, `0x10` and\n // ` 4 ` — none of which anyone writes on purpose in a config value, and all\n // of which would mean this silently did something other than it appears to.\n if (!/^[0-9]+$/.test(raw.trim())) return null;\n\n const parsed = Number(raw.trim());\n\n return parsed >= 1 ? parsed : null;\n}\n\n/** Apply {@link poolMaxCeiling} to a requested pool size. */\nexport function cappedPoolMax(requested: number, env: NodeJS.ProcessEnv = process.env): number {\n const ceiling = poolMaxCeiling(env);\n\n return ceiling === null ? requested : Math.min(requested, ceiling);\n}\n\nconst DEFAULT_POOL: Required<PostgresPoolConfig> = {\n max: 20,\n searchPath: \"public\",\n pooled: false,\n idleTimeoutMillis: 30_000,\n connectionTimeoutMillis: 10_000,\n // The client-side read timeout MUST be comfortably above the server-side\n // statement_timeout. When the client timer fires first, node-postgres\n // abandons the in-flight statement but keeps the connection — inside a\n // transaction that leaves the tx open (and any pending ROLLBACK is\n // spliced out of the client queue before it ever reaches the wire), so\n // the pooled connection is returned still in-transaction with its RLS\n // GUCs set. The server abort (SQLSTATE 57014) is the clean path; the\n // client timeout is only a backstop for a dead network.\n queryTimeout: 60_000,\n statementTimeout: 30_000,\n keepAlive: true\n};\n\n/**\n * The time limits every pool to this server shares: how long to wait for a\n * connection (then 503), the server-side statement timeout, the client-side\n * read backstop above it, and TCP keep-alive. Exported for the per-database\n * pools (`DatabasePoolManager`), which had none of them — pg's default\n * `connectionTimeoutMillis` is 0, wait forever.\n */\nexport function defaultPoolTimeouts(): Pick<PoolConfig,\n \"connectionTimeoutMillis\" | \"query_timeout\" | \"statement_timeout\" | \"keepAlive\" | \"keepAliveInitialDelayMillis\"> {\n return {\n connectionTimeoutMillis: DEFAULT_POOL.connectionTimeoutMillis,\n query_timeout: DEFAULT_POOL.queryTimeout,\n statement_timeout: DEFAULT_POOL.statementTimeout,\n keepAlive: DEFAULT_POOL.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n}\n\n/** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */\nconst TX_IDLE = \"I\";\n\n/**\n * What a pool behind a transaction-mode pooler would have sent at connect, and\n * must instead set inside each transaction. See {@link PostgresPoolConfig.pooled}.\n */\nexport interface PooledTransactionSettings {\n /** `false` when the pool was told to inherit the server's `search_path`. */\n searchPath: string | false;\n statementTimeoutMs: number;\n}\n\nconst pooledPools = new WeakMap<object, PooledTransactionSettings>();\n\n/**\n * The settings a transaction on `pool` must `SET LOCAL` for itself, or\n * `undefined` when the pool talks to the database directly and sent them at\n * connect.\n */\nexport function pooledTransactionSettings(pool: unknown): PooledTransactionSettings | undefined {\n return pool !== null && typeof pool === \"object\" ? pooledPools.get(pool) : undefined;\n}\n\n/** Whether `pool` reaches its database through a transaction-mode pooler. */\nexport function isPooledPool(pool: unknown): boolean {\n return pooledTransactionSettings(pool) !== undefined;\n}\n\n/**\n * The `SET LOCAL` statements that give a transaction on a pooled connection\n * what a direct connection got from its startup packet. Empty for a direct\n * pool. `SET LOCAL` ends with the transaction, so nothing reaches the next\n * client the pooler hands that server connection to.\n */\nexport function transactionSettingsStatements(settings: PooledTransactionSettings | undefined): string[] {\n if (!settings) return [];\n const statements: string[] = [];\n if (settings.searchPath !== false) {\n statements.push(`SET LOCAL search_path TO ${searchPathList(settings.searchPath)}`);\n }\n if (settings.statementTimeoutMs > 0) {\n statements.push(`SET LOCAL statement_timeout = ${Math.floor(settings.statementTimeoutMs)}`);\n }\n return statements;\n}\n\n/**\n * {@link transactionSettingsStatements} as `set_config` name/value pairs, for\n * a transaction that sets them in one statement with the caller's context\n * (`authContextStatement`). Empty for a direct pool.\n */\nexport function transactionSettingsConfig(settings: PooledTransactionSettings | undefined): [string, string][] {\n if (!settings) return [];\n const config: [string, string][] = [];\n if (settings.searchPath !== false) config.push([\"search_path\", searchPathList(settings.searchPath)]);\n if (settings.statementTimeoutMs > 0) config.push([\"statement_timeout\", String(Math.floor(settings.statementTimeoutMs))]);\n return config;\n}\n\n/**\n * A `search_path` value as a list of quoted identifiers, so a schema name can\n * never be read as SQL. `\"$user\"` keeps its meaning quoted.\n */\nexport function searchPathList(searchPath: string): string {\n return searchPath\n .split(\",\")\n .map(part => part.trim().replace(/^\"(.*)\"$/, \"$1\"))\n .filter(part => part.length > 0)\n .map(part => `\"${part.replace(/\"/g, \"\\\"\\\"\")}\"`)\n .join(\", \");\n}\n\n/**\n * The `pg.Pool` settings shared by every pool this module opens, with the\n * startup parameters a transaction-mode pooler cannot carry left out when\n * `pooled`. The pool is registered so {@link pooledTransactionSettings} can\n * answer for it.\n */\nfunction poolOptions(\n connectionString: string,\n opts: Required<PostgresPoolConfig>,\n max: number\n): PoolConfig {\n return {\n connectionString: opts.pooled ? connectionString : pinSearchPath(connectionString, opts.searchPath),\n max,\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n ...(opts.pooled ? {} : { statement_timeout: opts.statementTimeout }),\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n}\n\nfunction registerPooled(pool: Pool, opts: Required<PostgresPoolConfig>): void {\n if (!opts.pooled) return;\n pooledPools.set(pool, { searchPath: opts.searchPath, statementTimeoutMs: opts.statementTimeout });\n}\n\n/**\n * Pin `search_path` into a connection string, so unqualified SQL resolves to a\n * schema this framework chose rather than to one Postgres inferred.\n *\n * Postgres defaults `search_path` to `\"$user\", public`: the *first* candidate\n * is a schema named after the connecting role. Rebase creates a schema called\n * `rebase` (auth, history, api keys), and every template, compose file and\n * deployment doc names the database role `rebase` too — so `$user` resolves to\n * a schema that exists, and every unqualified statement lands there instead of\n * in `public`. The generated Drizzle schema emits bare `pgTable(\"posts\", …)`\n * for any collection without an explicit `schema`, which makes the *runtime's*\n * own reads and writes unqualified; a developer's raw `rebase.sql(...)`, the\n * Studio SQL editor and any hand-written migration are unqualified too. The\n * result is collection tables created in, and served from, `rebase`.\n *\n * Drizzle cannot express the fix on its side: `pgSchema(\"public\")` throws by\n * design (\"just use pgTable() instead\"), so there is no way to emit a\n * public-qualified table from the generator. The pin has to live on the\n * connection.\n *\n * Precedence is deliberate and verified against node-postgres: `options` in\n * the connection string wins over the `options` field passed to `Pool`, so\n * rewriting the URL — rather than setting the field — is what makes this\n * authoritative. Two escape hatches survive it:\n *\n * - an `options` that already mentions `search_path` is left untouched, so a\n * deployment that deliberately pins something else keeps it;\n * - `searchPath: false` (or an unparseable, non-URL connection string) sends\n * nothing and inherits the server default.\n *\n * Anything else in `options` (a `statement_timeout`, say) is preserved and the\n * `search_path` flag is appended to it.\n */\nexport function pinSearchPath(connectionString: string, searchPath: string | false = \"public\"): string {\n if (searchPath === false) return connectionString;\n\n let url: URL;\n try {\n url = new URL(connectionString);\n } catch {\n // Key/value DSNs and anything else we cannot parse are returned as\n // given: a connection that works unpinned beats one we corrupted.\n return connectionString;\n }\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return connectionString;\n\n const existing = url.searchParams.get(\"options\");\n if (existing && /(^|\\s)-c\\s*search_path\\s*=/.test(existing)) return connectionString;\n\n const flag = `-c search_path=${searchPath}`;\n url.searchParams.set(\"options\", existing ? `${existing} ${flag}` : flag);\n // Re-serialize by hand. `URLSearchParams` writes a space as `+`, which\n // node-postgres happens to decode but libpq does not — and this same string\n // is handed to `pg_dump`/`psql` for backups. Percent-encoding is the form\n // both agree on, and is what the scaffolded `.env` already ships.\n url.search = Array.from(url.searchParams.entries())\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n return url.toString();\n}\n\n/**\n * Destroy pool clients that are released while still inside a transaction.\n *\n * pg-pool returns a client to the idle list whenever `release()` is called\n * without an error — even if the connection is still mid-transaction (status\n * `T`/`E`). That happens in practice: drizzle's pool transaction releases in\n * a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails\n * (e.g. it was queued behind a statement that hit the client-side\n * query_timeout), the client goes back dirty. The next checkout then runs\n * its statements inside the zombie transaction — with the previous request's\n * `app.*` RLS GUCs still applied, which turns unrelated queries into\n * RLS-scoped ones (observed in production as registration failing with\n * SQLSTATE 42501 under a leaked anonymous context).\n *\n * pg-pool emits `release` before it consults its private `_expired` set, so\n * marking the client expired here makes `_release()` destroy it instead of\n * pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are\n * private APIs — feature-detect and fall back to loud logging so an upstream\n * change degrades to observability, never to silent corruption.\n */\nexport function guardPoolAgainstDirtyRelease(pool: Pool, label: string): void {\n pool.on(\"release\", (err: Error | undefined, client: unknown) => {\n if (err) return; // errored clients are already destroyed by pg-pool\n const txStatus = (client as { _txStatus?: string | null })?._txStatus;\n if (typeof txStatus !== \"string\" || txStatus === TX_IDLE) return;\n\n // pg-pool keeps expired clients in a WeakSet (a plain object works too\n // if upstream ever changes it — duck-type on add/has).\n const expired = (pool as unknown as { _expired?: { add(c: object): unknown; has(c: object): boolean } })._expired;\n if (expired && typeof expired.add === \"function\" && typeof expired.has === \"function\" && client && typeof client === \"object\") {\n expired.add(client);\n logger.error(\n `[${label}] Client released back to the pool while still in a transaction ` +\n `(status '${txStatus}') — destroying it so the open transaction and its ` +\n `session state (RLS GUCs) cannot leak into the next request.`\n );\n } else {\n logger.error(\n `[${label}] Client released mid-transaction (status '${txStatus}') but the ` +\n `pool's internal expiry set is unavailable (pg-pool internals changed?). ` +\n `The connection may leak its open transaction into subsequent requests.`\n );\n }\n });\n}\n\n/**\n * Create a Drizzle-backed Postgres connection with a production-grade\n * connection pool.\n *\n * @param connectionString Postgres connection URL\n * @param schema Optional Drizzle schema for the relational API\n * @param poolConfig Optional pool tuning (merged over defaults)\n * @param env Where the pool-size ceiling `REBASE_DB_POOL_MAX`\n * is read from (see {@link poolMaxCeiling}); pass\n * `{}` to read none.\n *\n * @returns `{ db, pool, connectionString }` — the `pool` is exposed so\n * callers can register shutdown hooks (`pool.end()`) or monitor\n * pool metrics.\n */\nexport function createPostgresDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig,\n env: NodeJS.ProcessEnv = process.env\n) {\n const opts = { ...DEFAULT_POOL,\n...poolConfig };\n const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max, env));\n connectionString = pgPoolConfig.connectionString ?? connectionString;\n\n const pool = new Pool(pgPoolConfig);\n registerPooled(pool, opts);\n\n // ── Pool event logging ────────────────────────────────────────────────\n // Uses console.* because the structured logger lives in server\n // (a separate package). The caller can replace these with the structured\n // logger if desired via pool.on() after creation.\n pool.on(\"error\", (err) => {\n reportPoolError(\"pg-pool\", err);\n if (err.message.includes(\"ETIMEDOUT\")) {\n logger.warn(\"[pg-pool] Connection timeout detected — pool will auto-retry\");\n }\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-pool\");\n\n // Create drizzle instance — pass schema when available to enable db.query relational API\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a direct (non-pooled) connection for operations that require\n * session-level features incompatible with PgBouncer transaction mode,\n * such as LISTEN/NOTIFY, prepared statements, or advisory locks.\n *\n * Uses a smaller pool since this is only for specific use cases.\n */\nexport function createDirectDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 5,\n ...poolConfig\n };\n const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max));\n connectionString = pgPoolConfig.connectionString ?? connectionString;\n\n const pool = new Pool(pgPoolConfig);\n registerPooled(pool, opts);\n\n pool.on(\"error\", (err) => reportPoolError(\"pg-direct-pool\", err));\n guardPoolAgainstDirtyRelease(pool, \"pg-direct-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a read-only connection for routing read queries to replicas.\n * Uses a moderate pool size since reads are distributed across replicas.\n */\nexport function createReadReplicaConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 10,\n ...poolConfig\n };\n const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max));\n connectionString = pgPoolConfig.connectionString ?? connectionString;\n\n const pool = new Pool(pgPoolConfig);\n registerPooled(pool, opts);\n\n pool.on(\"error\", (err) => reportPoolError(\"pg-replica-pool\", err));\n guardPoolAgainstDirtyRelease(pool, \"pg-replica-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Close `companions` whenever `pool` is closed, before it.\n *\n * The pools a driver opens for itself — a read replica's, a direct session\n * pool, the per-database pools — are invisible to whoever opened the main\n * pool, and closing the main pool is the one shutdown signal every server\n * version sends a driver. So the main pool's `end` is wrapped: companions\n * first, then the pool, once however many times it is called (`pg.Pool`\n * throws on a second `end`). A pool without `end`, or no pool, is left alone.\n */\nexport function closeWithPool(pool: unknown, companions: () => Promise<void>): void {\n if (pool === null || typeof pool !== \"object\" || !(\"end\" in pool) || typeof pool.end !== \"function\") return;\n const end: (...args: unknown[]) => unknown = pool.end.bind(pool);\n let closing: Promise<void> | undefined;\n const wrapped = (callback?: (err?: Error) => void): Promise<void> | void => {\n closing ??= (async () => {\n try {\n await companions();\n } finally {\n await end();\n }\n })();\n if (typeof callback === \"function\") {\n closing.then(() => callback(), (err: unknown) => callback(err instanceof Error ? err : new Error(String(err))));\n return;\n }\n return closing;\n };\n Object.defineProperty(pool, \"end\", { value: wrapped, configurable: true, writable: true });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAeA,IAAM,qCAAqB,IAAI,IAAI;CAAC;CAAS;CAAS;AAAO,CAAC;;AAG9D,SAAgB,sBAAsB,KAAqB;CACvD,MAAM,OAAO,UAAU,MAAM,IAAI,OAAO,KAAA;CACxC,OAAQ,OAAO,SAAS,YAAY,mBAAmB,IAAI,IAAI,K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,YACF;CACE,MAAM,OAAO;EACT,GAAG;EACH,KAAK;EACL,GAAG;CACP;CACA,MAAM,eAAe,YAAY,kBAAkB,MAAM,cAAc,KAAK,GAAG,CAAC;CAChF,mBAAmB,aAAa,oBAAoB;CAEpD,MAAM,OAAO,IAAI,KAAK,YAAY;CAClC,eAAe,MAAM,IAAI;CAEzB,KAAK,GAAG,UAAU,QAAQ,gBAAgB,mBAAmB,GAAG,CAAC;CACjE,6BAA6B,MAAM,iBAAiB;CAIpD,OAAO;EAAE,IAFE,SAAS,QAAQ,MAAM,EAAE,OAAO,CAAC,IAAI,QAAQ,IAAI;EAGhE;EACA;CAAiB;AACjB;;;;;;;;;;;AAYA,SAAgB,cAAc,MAAe,YAAuC;CAChF,IAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,EAAE,SAAS,SAAS,OAAO,KAAK,QAAQ,YAAY;CACrG,MAAM,MAAuC,KAAK,IAAI,KAAK,IAAI;CAC/D,IAAI;CACJ,MAAM,WAAW,aAA2D;EACxE,aAAa,YAAY;GACrB,IAAI;IACA,MAAM,WAAW;GACrB,UAAU;IACN,MAAM,IAAI;GACd;EACJ,EAAA,CAAG;EACH,IAAI,OAAO,aAAa,YAAY;GAChC,QAAQ,WAAW,SAAS,IAAI,QAAiB,SAAS,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC;GAC9G;EACJ;EACA,OAAO;CACX;CACA,OAAO,eAAe,MAAM,OAAO;EAAE,OAAO;EAAS,cAAc;EAAM,UAAU;CAAK,CAAC;AAC7F"}
1
+ {"version":3,"file":"connection-C1zXTPJq.js","names":[],"sources":["../src/pool-disconnects.ts","../src/connection.ts"],"sourcesContent":["/**\n * What a pool says when the server ends its idle connections.\n *\n * `pg_terminate_backend` ends every connection to a database at once, and an\n * idle pool client hears it as an `error` event: one per connection, from\n * every pool the process holds. `rebase db branch create --force` does exactly\n * that to the database it copies, so fifteen forced creates beside a running\n * `rebase dev` printed 220 `❌ [ERROR] [pg-pool] Unexpected pool error\n * {\"detail\":\"terminating connection due to administrator command\"}` lines. It\n * read as an outage, and nothing was wrong: the pool opens new connections on\n * the next query. A database restart looks the same.\n */\nimport { logger } from \"@rebasepro/server\";\n\n/** SQLSTATEs of a connection the server ended: admin_shutdown, crash_shutdown, cannot_connect_now. */\nconst SERVER_ENDED_CODES = new Set([\"57P01\", \"57P02\", \"57P03\"]);\n\n/** Did the server end this connection, rather than something go wrong with it? */\nexport function serverEndedConnection(err: Error): boolean {\n const code = \"code\" in err ? err.code : undefined;\n return (typeof code === \"string\" && SERVER_ENDED_CODES.has(code))\n || /terminating connection due to administrator command/i.test(err.message);\n}\n\n/** How long one line stands for every server-ended connection after it, across all pools. */\nexport const DISCONNECT_BURST_MS = 10_000;\n\n/** When the current burst's line stops covering further disconnects. */\nlet burstUntil = 0;\n\n/** The logger methods a pool's error listener writes through. */\nexport type PoolErrorLog = Pick<typeof logger, \"warn\" | \"error\" | \"debug\">;\n\n/**\n * Say a pool's `error` event: a connection the server ended is one WARN line\n * per burst for the whole process, and the rest of the burst is at debug;\n * anything else is the ERROR it always was.\n *\n * The window is fixed from the first disconnect, not extended by each, so a\n * second burst ten seconds later is said again.\n */\nexport function reportPoolError(label: string, err: Error, log: PoolErrorLog = logger, now: () => number = Date.now): void {\n if (!serverEndedConnection(err)) {\n log.error(`[${label}] Unexpected pool error`, { detail: err.message });\n return;\n }\n const at = now();\n if (at < burstUntil) {\n log.debug(`[${label}] The database ended another idle connection`, { detail: err.message });\n return;\n }\n burstUntil = at + DISCONNECT_BURST_MS;\n const code = \"code\" in err && typeof err.code === \"string\" ? `, ${err.code}` : \"\";\n log.warn(\n `[${label}] The database ended this server's idle connections (${err.message}${code}). ` +\n \"New ones open on the next query. A database restart does this, and so does \" +\n \"`rebase db branch create --force`, which closes the database it copies.\"\n );\n}\n","import { Pool, PoolConfig } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { reportPoolError } from \"./pool-disconnects\";\n\n/**\n * Configuration for the Postgres connection pool.\n *\n * Sensible defaults are provided for production Cloud Run / single-instance\n * deployments. Override via environment variables or explicit config.\n */\nexport interface PostgresPoolConfig {\n /** Maximum number of connections in the pool (default: 20) */\n max?: number;\n /** Close idle connections after this many ms (default: 30 000) */\n idleTimeoutMillis?: number;\n /** Abort connection attempts after this many ms (default: 10 000) */\n connectionTimeoutMillis?: number;\n /** Per-query timeout in ms (default: 30 000) */\n queryTimeout?: number;\n /** Per-statement timeout in ms (default: 30 000) */\n statementTimeout?: number;\n /** Enable TCP keep-alive (default: true) */\n keepAlive?: boolean;\n /**\n * `search_path` pinned on every connection (default: `\"public\"`).\n *\n * Pass `false` to send no `search_path` at all and inherit whatever the\n * server/role defaults to. See {@link pinSearchPath} for why the default\n * is not \"inherit\".\n */\n searchPath?: string | false;\n /**\n * The URL reaches the database through a transaction-mode pooler such as\n * PgBouncer (`DATABASE_POOLED=true`).\n *\n * A transaction-mode pooler hands each transaction whatever server\n * connection is free, so nothing set for a *session* survives to the next\n * statement — and the startup packet's parameters are either refused by\n * the pooler or dropped by it (`ignore_startup_parameters`). So a pooled\n * pool sends neither `statement_timeout` nor `options=-c search_path` at\n * connect; {@link pooledTransactionSettings} says what to `SET LOCAL` at\n * the start of each transaction instead, and the boot sets the role's\n * default `search_path` (see `ensurePooledRoleDefaults`).\n *\n * Explicit rather than sniffed from the URL: a pooler's address looks like\n * any other database's.\n */\n pooled?: boolean;\n}\n\n/**\n * Ceiling on pool size, from the environment.\n *\n * Exists for the managed development database. PGlite is a single session\n * behind a multiplexing socket server, and two pooled clients holding\n * overlapping transactions deadlock there — which a request-per-transaction\n * server produces the moment two requests overlap. One connection turns that\n * deadlock into ordinary queueing.\n *\n * A ceiling rather than a value, so it constrains every pool in the process\n * without any of them having to know why. Ignored when unset or unparseable,\n * because a malformed limit must not silently serialize a production server.\n */\nexport function poolMaxCeiling(env: NodeJS.ProcessEnv = process.env): number | null {\n const raw = env.REBASE_DB_POOL_MAX;\n if (typeof raw !== \"string\") return null;\n\n // Plain decimal digits only. `Number` would also accept `1e3`, `0x10` and\n // ` 4 ` — none of which anyone writes on purpose in a config value, and all\n // of which would mean this silently did something other than it appears to.\n if (!/^[0-9]+$/.test(raw.trim())) return null;\n\n const parsed = Number(raw.trim());\n\n return parsed >= 1 ? parsed : null;\n}\n\n/** Apply {@link poolMaxCeiling} to a requested pool size. */\nexport function cappedPoolMax(requested: number, env: NodeJS.ProcessEnv = process.env): number {\n const ceiling = poolMaxCeiling(env);\n\n return ceiling === null ? requested : Math.min(requested, ceiling);\n}\n\nconst DEFAULT_POOL: Required<PostgresPoolConfig> = {\n max: 20,\n searchPath: \"public\",\n pooled: false,\n idleTimeoutMillis: 30_000,\n connectionTimeoutMillis: 10_000,\n // The client-side read timeout MUST be comfortably above the server-side\n // statement_timeout. When the client timer fires first, node-postgres\n // abandons the in-flight statement but keeps the connection — inside a\n // transaction that leaves the tx open (and any pending ROLLBACK is\n // spliced out of the client queue before it ever reaches the wire), so\n // the pooled connection is returned still in-transaction with its RLS\n // GUCs set. The server abort (SQLSTATE 57014) is the clean path; the\n // client timeout is only a backstop for a dead network.\n queryTimeout: 60_000,\n statementTimeout: 30_000,\n keepAlive: true\n};\n\n/**\n * The time limits every pool to this server shares: how long to wait for a\n * connection (then 503), the server-side statement timeout, the client-side\n * read backstop above it, and TCP keep-alive. Exported for the per-database\n * pools (`DatabasePoolManager`), which had none of them — pg's default\n * `connectionTimeoutMillis` is 0, wait forever.\n */\nexport function defaultPoolTimeouts(): Pick<PoolConfig,\n \"connectionTimeoutMillis\" | \"query_timeout\" | \"statement_timeout\" | \"keepAlive\" | \"keepAliveInitialDelayMillis\"> {\n return {\n connectionTimeoutMillis: DEFAULT_POOL.connectionTimeoutMillis,\n query_timeout: DEFAULT_POOL.queryTimeout,\n statement_timeout: DEFAULT_POOL.statementTimeout,\n keepAlive: DEFAULT_POOL.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n}\n\n/** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */\nconst TX_IDLE = \"I\";\n\n/**\n * What a pool behind a transaction-mode pooler would have sent at connect, and\n * must instead set inside each transaction. See {@link PostgresPoolConfig.pooled}.\n */\nexport interface PooledTransactionSettings {\n /** `false` when the pool was told to inherit the server's `search_path`. */\n searchPath: string | false;\n statementTimeoutMs: number;\n}\n\nconst pooledPools = new WeakMap<object, PooledTransactionSettings>();\n\n/**\n * The settings a transaction on `pool` must `SET LOCAL` for itself, or\n * `undefined` when the pool talks to the database directly and sent them at\n * connect.\n */\nexport function pooledTransactionSettings(pool: unknown): PooledTransactionSettings | undefined {\n return pool !== null && typeof pool === \"object\" ? pooledPools.get(pool) : undefined;\n}\n\n/** Whether `pool` reaches its database through a transaction-mode pooler. */\nexport function isPooledPool(pool: unknown): boolean {\n return pooledTransactionSettings(pool) !== undefined;\n}\n\n/**\n * The `SET LOCAL` statements that give a transaction on a pooled connection\n * what a direct connection got from its startup packet. Empty for a direct\n * pool. `SET LOCAL` ends with the transaction, so nothing reaches the next\n * client the pooler hands that server connection to.\n */\nexport function transactionSettingsStatements(settings: PooledTransactionSettings | undefined): string[] {\n if (!settings) return [];\n const statements: string[] = [];\n if (settings.searchPath !== false) {\n statements.push(`SET LOCAL search_path TO ${searchPathList(settings.searchPath)}`);\n }\n if (settings.statementTimeoutMs > 0) {\n statements.push(`SET LOCAL statement_timeout = ${Math.floor(settings.statementTimeoutMs)}`);\n }\n return statements;\n}\n\n/**\n * {@link transactionSettingsStatements} as `set_config` name/value pairs, for\n * a transaction that sets them in one statement with the caller's context\n * (`authContextStatement`). Empty for a direct pool.\n */\nexport function transactionSettingsConfig(settings: PooledTransactionSettings | undefined): [string, string][] {\n if (!settings) return [];\n const config: [string, string][] = [];\n if (settings.searchPath !== false) config.push([\"search_path\", searchPathList(settings.searchPath)]);\n if (settings.statementTimeoutMs > 0) config.push([\"statement_timeout\", String(Math.floor(settings.statementTimeoutMs))]);\n return config;\n}\n\n/**\n * A `search_path` value as a list of quoted identifiers, so a schema name can\n * never be read as SQL. `\"$user\"` keeps its meaning quoted.\n */\nexport function searchPathList(searchPath: string): string {\n return searchPath\n .split(\",\")\n .map(part => part.trim().replace(/^\"(.*)\"$/, \"$1\"))\n .filter(part => part.length > 0)\n .map(part => `\"${part.replace(/\"/g, \"\\\"\\\"\")}\"`)\n .join(\", \");\n}\n\n/**\n * The `pg.Pool` settings shared by every pool this module opens, with the\n * startup parameters a transaction-mode pooler cannot carry left out when\n * `pooled`. The pool is registered so {@link pooledTransactionSettings} can\n * answer for it.\n */\nfunction poolOptions(\n connectionString: string,\n opts: Required<PostgresPoolConfig>,\n max: number\n): PoolConfig {\n return {\n connectionString: opts.pooled ? connectionString : pinSearchPath(connectionString, opts.searchPath),\n max,\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n ...(opts.pooled ? {} : { statement_timeout: opts.statementTimeout }),\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n}\n\nfunction registerPooled(pool: Pool, opts: Required<PostgresPoolConfig>): void {\n if (!opts.pooled) return;\n pooledPools.set(pool, { searchPath: opts.searchPath, statementTimeoutMs: opts.statementTimeout });\n}\n\n/**\n * Pin `search_path` into a connection string, so unqualified SQL resolves to a\n * schema this framework chose rather than to one Postgres inferred.\n *\n * Postgres defaults `search_path` to `\"$user\", public`: the *first* candidate\n * is a schema named after the connecting role. Rebase creates a schema called\n * `rebase` (auth, history, api keys), and every template, compose file and\n * deployment doc names the database role `rebase` too — so `$user` resolves to\n * a schema that exists, and every unqualified statement lands there instead of\n * in `public`. The generated Drizzle schema emits bare `pgTable(\"posts\", …)`\n * for any collection without an explicit `schema`, which makes the *runtime's*\n * own reads and writes unqualified; a developer's raw `rebase.sql(...)`, the\n * Studio SQL editor and any hand-written migration are unqualified too. The\n * result is collection tables created in, and served from, `rebase`.\n *\n * Drizzle cannot express the fix on its side: `pgSchema(\"public\")` throws by\n * design (\"just use pgTable() instead\"), so there is no way to emit a\n * public-qualified table from the generator. The pin has to live on the\n * connection.\n *\n * Precedence is deliberate and verified against node-postgres: `options` in\n * the connection string wins over the `options` field passed to `Pool`, so\n * rewriting the URL — rather than setting the field — is what makes this\n * authoritative. Two escape hatches survive it:\n *\n * - an `options` that already mentions `search_path` is left untouched, so a\n * deployment that deliberately pins something else keeps it;\n * - `searchPath: false` (or an unparseable, non-URL connection string) sends\n * nothing and inherits the server default.\n *\n * Anything else in `options` (a `statement_timeout`, say) is preserved and the\n * `search_path` flag is appended to it.\n */\nexport function pinSearchPath(connectionString: string, searchPath: string | false = \"public\"): string {\n if (searchPath === false) return connectionString;\n\n let url: URL;\n try {\n url = new URL(connectionString);\n } catch {\n // Key/value DSNs and anything else we cannot parse are returned as\n // given: a connection that works unpinned beats one we corrupted.\n return connectionString;\n }\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return connectionString;\n\n const existing = url.searchParams.get(\"options\");\n if (existing && /(^|\\s)-c\\s*search_path\\s*=/.test(existing)) return connectionString;\n\n const flag = `-c search_path=${searchPath}`;\n url.searchParams.set(\"options\", existing ? `${existing} ${flag}` : flag);\n // Re-serialize by hand. `URLSearchParams` writes a space as `+`, which\n // node-postgres happens to decode but libpq does not — and this same string\n // is handed to `pg_dump`/`psql` for backups. Percent-encoding is the form\n // both agree on, and is what the scaffolded `.env` already ships.\n url.search = Array.from(url.searchParams.entries())\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n return url.toString();\n}\n\n/** pg-pool's private set of expired clients: a WeakSet today, anything with `add`/`has` tomorrow. */\nfunction isClientSet(value: unknown): value is { add(c: object): unknown; has(c: object): boolean } {\n return typeof value === \"object\" && value !== null\n && \"add\" in value && typeof value.add === \"function\"\n && \"has\" in value && typeof value.has === \"function\";\n}\n\n/**\n * Destroy pool clients that are released while still inside a transaction.\n *\n * pg-pool returns a client to the idle list whenever `release()` is called\n * without an error — even if the connection is still mid-transaction (status\n * `T`/`E`). That happens in practice: drizzle's pool transaction releases in\n * a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails\n * (e.g. it was queued behind a statement that hit the client-side\n * query_timeout), the client goes back dirty. The next checkout then runs\n * its statements inside the zombie transaction — with the previous request's\n * `app.*` RLS GUCs still applied, which turns unrelated queries into\n * RLS-scoped ones (observed in production as registration failing with\n * SQLSTATE 42501 under a leaked anonymous context).\n *\n * pg-pool emits `release` before it consults its private `_expired` set, so\n * marking the client expired here makes `_release()` destroy it instead of\n * pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are\n * private APIs — feature-detect and fall back to loud logging so an upstream\n * change degrades to observability, never to silent corruption.\n */\nexport function guardPoolAgainstDirtyRelease(pool: Pool, label: string): void {\n pool.on(\"release\", (err: Error | undefined, client: unknown) => {\n if (err) return; // errored clients are already destroyed by pg-pool\n const txStatus = (client as { _txStatus?: string | null })?._txStatus;\n if (typeof txStatus !== \"string\" || txStatus === TX_IDLE) return;\n\n // pg-pool keeps expired clients in a WeakSet (a plain object works too\n // if upstream ever changes it — duck-type on add/has).\n const expired: unknown = Reflect.get(pool, \"_expired\");\n if (isClientSet(expired) && client && typeof client === \"object\") {\n expired.add(client);\n logger.error(\n `[${label}] Client released back to the pool while still in a transaction ` +\n `(status '${txStatus}') — destroying it so the open transaction and its ` +\n `session state (RLS GUCs) cannot leak into the next request.`\n );\n } else {\n logger.error(\n `[${label}] Client released mid-transaction (status '${txStatus}') but the ` +\n `pool's internal expiry set is unavailable (pg-pool internals changed?). ` +\n `The connection may leak its open transaction into subsequent requests.`\n );\n }\n });\n}\n\n/**\n * Create a Drizzle-backed Postgres connection with a production-grade\n * connection pool.\n *\n * @param connectionString Postgres connection URL\n * @param schema Optional Drizzle schema for the relational API\n * @param poolConfig Optional pool tuning (merged over defaults)\n * @param env Where the pool-size ceiling `REBASE_DB_POOL_MAX`\n * is read from (see {@link poolMaxCeiling}); pass\n * `{}` to read none.\n *\n * @returns `{ db, pool, connectionString }` — the `pool` is exposed so\n * callers can register shutdown hooks (`pool.end()`) or monitor\n * pool metrics.\n */\nexport function createPostgresDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig,\n env: NodeJS.ProcessEnv = process.env\n) {\n const opts = { ...DEFAULT_POOL,\n...poolConfig };\n const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max, env));\n connectionString = pgPoolConfig.connectionString ?? connectionString;\n\n const pool = new Pool(pgPoolConfig);\n registerPooled(pool, opts);\n\n // ── Pool event logging ────────────────────────────────────────────────\n // Uses console.* because the structured logger lives in server\n // (a separate package). The caller can replace these with the structured\n // logger if desired via pool.on() after creation.\n pool.on(\"error\", (err) => {\n reportPoolError(\"pg-pool\", err);\n if (err.message.includes(\"ETIMEDOUT\")) {\n logger.warn(\"[pg-pool] Connection timeout detected — pool will auto-retry\");\n }\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-pool\");\n\n // Create drizzle instance — pass schema when available to enable db.query relational API\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a direct (non-pooled) connection for operations that require\n * session-level features incompatible with PgBouncer transaction mode,\n * such as LISTEN/NOTIFY, prepared statements, or advisory locks.\n *\n * Uses a smaller pool since this is only for specific use cases.\n */\nexport function createDirectDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 5,\n ...poolConfig\n };\n const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max));\n connectionString = pgPoolConfig.connectionString ?? connectionString;\n\n const pool = new Pool(pgPoolConfig);\n registerPooled(pool, opts);\n\n pool.on(\"error\", (err) => reportPoolError(\"pg-direct-pool\", err));\n guardPoolAgainstDirtyRelease(pool, \"pg-direct-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a read-only connection for routing read queries to replicas.\n * Uses a moderate pool size since reads are distributed across replicas.\n */\nexport function createReadReplicaConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 10,\n ...poolConfig\n };\n const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max));\n connectionString = pgPoolConfig.connectionString ?? connectionString;\n\n const pool = new Pool(pgPoolConfig);\n registerPooled(pool, opts);\n\n pool.on(\"error\", (err) => reportPoolError(\"pg-replica-pool\", err));\n guardPoolAgainstDirtyRelease(pool, \"pg-replica-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Close `companions` whenever `pool` is closed, before it.\n *\n * The pools a driver opens for itself — a read replica's, a direct session\n * pool, the per-database pools — are invisible to whoever opened the main\n * pool, and closing the main pool is the one shutdown signal every server\n * version sends a driver. So the main pool's `end` is wrapped: companions\n * first, then the pool, once however many times it is called (`pg.Pool`\n * throws on a second `end`). A pool without `end`, or no pool, is left alone.\n */\nexport function closeWithPool(pool: unknown, companions: () => Promise<void>): void {\n if (pool === null || typeof pool !== \"object\" || !(\"end\" in pool) || typeof pool.end !== \"function\") return;\n const end: (...args: unknown[]) => unknown = pool.end.bind(pool);\n let closing: Promise<void> | undefined;\n const wrapped = (callback?: (err?: Error) => void): Promise<void> | void => {\n closing ??= (async () => {\n try {\n await companions();\n } finally {\n await end();\n }\n })();\n if (typeof callback === \"function\") {\n closing.then(() => callback(), (err: unknown) => callback(err instanceof Error ? err : new Error(String(err))));\n return;\n }\n return closing;\n };\n Object.defineProperty(pool, \"end\", { value: wrapped, configurable: true, writable: true });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAeA,IAAM,qCAAqB,IAAI,IAAI;CAAC;C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CAAC;AAC7F"}
@@ -1,6 +1,6 @@
1
- import { NodePgDatabase } from "drizzle-orm/node-postgres";
2
1
  import { CollectionConfig, Properties, Property, ResolvedRelation, type ResolvedVia } from "@rebasepro/types";
3
2
  import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry.js";
3
+ import type { DrizzleClient } from "./interfaces.js";
4
4
  /**
5
5
  * Data transformation utilities for converting between frontend and database formats.
6
6
  */
@@ -55,7 +55,7 @@ export declare function serializePropertyToServer(value: unknown, property: Prop
55
55
  /**
56
56
  * Transform IDs back to relation objects for frontend
57
57
  */
58
- export declare function parseDataFromServer<M extends Record<string, unknown>>(data: M, collection: CollectionConfig, db?: NodePgDatabase<Record<string, unknown>>, registry?: PostgresCollectionRegistry): Promise<M>;
58
+ export declare function parseDataFromServer<M extends Record<string, unknown>>(data: M, collection: CollectionConfig, db?: DrizzleClient, registry?: PostgresCollectionRegistry): Promise<M>;
59
59
  export declare function parsePropertyFromServer(value: unknown, property: Property, collection: CollectionConfig, propertyKey?: string): unknown;
60
60
  /**
61
61
  * Lightweight value normalization for db.query results.
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import type { Pool } from "pg";
14
14
  import type { DatabaseHealthSample, DatabasePoolStats } from "@rebasepro/types";
15
+ import { type RowsQueryable } from "./read-routing.js";
15
16
  /** The three counts `pg.Pool` keeps, as a stats row for `pool`. */
16
17
  export declare function poolStatsOf(pool: Pick<Pool, "totalCount" | "idleCount" | "waitingCount">, name: string): DatabasePoolStats;
17
18
  /**
@@ -20,4 +21,4 @@ export declare function poolStatsOf(pool: Pick<Pool, "totalCount" | "idleCount"
20
21
  * answer still reports the others, and the part it could not read is left
21
22
  * out rather than reported as zero.
22
23
  */
23
- export declare function sampleDatabaseHealth(primary: Pick<Pool, "query">, replica?: Pick<Pool, "query">): Promise<DatabaseHealthSample>;
24
+ export declare function sampleDatabaseHealth(primary: RowsQueryable, replica?: RowsQueryable): Promise<DatabaseHealthSample>;
@@ -0,0 +1,184 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ __createRequire(import.meta.url);
3
+ import { f as findOtherRoleMembers, g as readRecordedRequestRoles, i as assertAppRoleRestricted, n as appRoleSetupInstructions } from "./rls-enforcement-CyUCPDH8.js";
4
+ import { REBASE_ADMIN_ROLE } from "@rebasepro/types";
5
+ //#region src/security/database-preflight.ts
6
+ var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
7
+ var sqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
8
+ var textArray = (values) => values.length === 0 ? "ARRAY[]::text[]" : `ARRAY[${values.map(sqlLiteral).join(", ")}]::text[]`;
9
+ var managedPairs = (tables) => `(SELECT * FROM unnest(${textArray(tables.map((t) => t.schema))}, ${textArray(tables.map((t) => t.table))}))`;
10
+ async function preflightDatabase(run, settings, options) {
11
+ const findings = [];
12
+ const schemas = (await run(`SELECT nspname FROM pg_namespace WHERE nspname = ANY(${textArray(Array.from(new Set(options.schemas)))})`)).map((row) => String(row.nspname));
13
+ const [who] = await run(`
14
+ SELECT current_user AS role, current_database() AS database,
15
+ (SELECT rolsuper FROM pg_roles WHERE rolname = current_user) AS superuser,
16
+ current_setting('server_version_num')::int >= 160000 AS per_grant
17
+ `);
18
+ const connection = String(who?.role ?? "");
19
+ const perGrant = who?.per_grant === true;
20
+ const recorded = await readRecordedRequestRoles(run);
21
+ if (recorded && (recorded.length !== settings.roles.length || !settings.roles.every((r) => recorded.includes(r)))) findings.push({
22
+ level: "fail",
23
+ check: "Recorded request roles",
24
+ detail: `This database records ${recorded.join(", ")}, but the settings name ${settings.roles.join(", ")}. A boot refuses until they agree.`,
25
+ sql: `-- from the project: rebase db request-role migrate --to ${settings.roles.join(",")}`
26
+ });
27
+ for (const role of settings.roles) {
28
+ const [state] = await run(`
29
+ SELECT to_regrole(${sqlLiteral(role)}) IS NOT NULL AS present,
30
+ COALESCE(pg_has_role(current_user, to_regrole(${sqlLiteral(role)}), '${perGrant ? "SET" : "MEMBER"}'), false) AS can_switch,
31
+ (SELECT rolcreaterole FROM pg_roles WHERE rolname = current_user) AS can_create
32
+ `);
33
+ if (state?.present !== true) {
34
+ const creates = settings.provisionRole === "auto" && (state?.can_create === true || who?.superuser === true);
35
+ findings.push({
36
+ level: creates ? "ok" : "fail",
37
+ check: `Request role "${role}"`,
38
+ detail: creates ? "Does not exist yet; the first boot creates it." : settings.provisionRole === "never" ? "Does not exist, and rls.provisionRole is \"never\"." : `Does not exist, and "${connection}" cannot create roles.`,
39
+ sql: creates ? void 0 : appRoleSetupInstructions(connection, [...schemas], role, settings.grants)
40
+ });
41
+ continue;
42
+ }
43
+ try {
44
+ await assertAppRoleRestricted(run, role);
45
+ } catch (err) {
46
+ findings.push({
47
+ level: "fail",
48
+ check: `Request role "${role}"`,
49
+ detail: err instanceof Error ? err.message.split("\n\n")[0] : String(err),
50
+ sql: err instanceof Error && "instructions" in err ? String(err.instructions) : void 0
51
+ });
52
+ continue;
53
+ }
54
+ if (state?.can_switch !== true && who?.superuser !== true) findings.push({
55
+ level: settings.provisionRole === "auto" ? "warn" : "fail",
56
+ check: `Switching to "${role}"`,
57
+ detail: `"${connection}" may not switch to it${perGrant ? " (no membership WITH SET TRUE)" : ""}.` + (settings.provisionRole === "auto" ? " A boot grants that to itself when it can." : ""),
58
+ sql: appRoleSetupInstructions(connection, [...schemas], role, settings.grants)
59
+ });
60
+ else findings.push({
61
+ level: "ok",
62
+ check: `Request role "${role}"`,
63
+ detail: "Exists, restricted, and this connection can switch to it."
64
+ });
65
+ const others = await findOtherRoleMembers(run, role);
66
+ if (others.length > 0) findings.push({
67
+ level: settings.sharedRole === "refuse" ? "fail" : "warn",
68
+ check: `Who else can use "${role}"`,
69
+ detail: `${others.join(", ")} can switch into it, and so can pass this database's policies as whichever user they like.`,
70
+ setting: "rls.requestRole (a role of this project's own), then `rebase db request-role migrate`"
71
+ });
72
+ }
73
+ const [database] = await run(`
74
+ SELECT d.datacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(d.datacl) a WHERE a.grantee = 0 AND a.privilege_type = 'CONNECT') AS public_connect
75
+ FROM pg_database d WHERE d.datname = current_database()
76
+ `);
77
+ if (database?.public_connect === true) findings.push({
78
+ level: "warn",
79
+ check: "Who can connect",
80
+ detail: "Every role on the cluster may connect to this database (PUBLIC holds CONNECT, the default).",
81
+ sql: `REVOKE CONNECT ON DATABASE ${quoteIdent(String(who?.database ?? ""))} FROM PUBLIC;\nGRANT CONNECT ON DATABASE ${quoteIdent(String(who?.database ?? ""))} TO ${quoteIdent(connection)};`
82
+ });
83
+ const [unmanaged] = await run(`
84
+ SELECT count(*)::int AS count, string_agg(n.nspname || '.' || c.relname, ', ' ORDER BY n.nspname, c.relname) AS sample
85
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
86
+ WHERE n.nspname = ANY(${textArray(schemas)}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
87
+ AND (n.nspname, c.relname::text) NOT IN ${managedPairs(options.managedTables)}
88
+ AND n.nspname <> 'rebase'
89
+ `);
90
+ const unmanagedCount = Number(unmanaged?.count ?? 0);
91
+ if (unmanagedCount > 0 && settings.grants === "schema") findings.push({
92
+ level: "warn",
93
+ check: "Tables Rebase does not serve",
94
+ detail: `${unmanagedCount} table(s) in ${schemas.join(", ")} back no collection (${String(unmanaged?.sample ?? "").split(", ").slice(0, 5).join(", ")}${unmanagedCount > 5 ? ", …" : ""}). With grants: "schema" the request role gets DML on every one this connection may grant on.`,
95
+ setting: "rls.grants = \"managed\""
96
+ });
97
+ const foreign = await run(`
98
+ SELECT DISTINCT g.rolname AS grantee
99
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
100
+ CROSS JOIN LATERAL aclexplode(c.relacl) a
101
+ JOIN pg_roles g ON g.oid = a.grantee
102
+ WHERE (n.nspname, c.relname::text) IN ${managedPairs(options.managedTables)}
103
+ AND g.rolname <> ALL(${textArray([...settings.roles, connection])})
104
+ AND a.grantee <> c.relowner
105
+ ORDER BY 1
106
+ `);
107
+ if (foreign.length > 0 && settings.policyTarget === "public") findings.push({
108
+ level: "warn",
109
+ check: "Other roles on Rebase's tables",
110
+ detail: `${foreign.map((r) => r.grantee).join(", ")} hold privileges on tables Rebase serves. Its permissive policies apply TO public, so a session of theirs that never sets Rebase's identity passes the server-context arm and sees every row.`,
111
+ setting: "rls.policyTarget = \"requestRole\""
112
+ });
113
+ for (const [role, adminRole] of settings.adminRoles) {
114
+ const [state] = await run(`
115
+ SELECT to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS marker,
116
+ to_regrole(${sqlLiteral(adminRole)}) IS NOT NULL AS present,
117
+ COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole(${sqlLiteral(role)}), 'USAGE'), false)
118
+ AND COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false) AS inherits,
119
+ (SELECT rolcreaterole FROM pg_roles WHERE rolname = current_user) AS can_create
120
+ `);
121
+ if (state?.marker === true && state?.present === true && state?.inherits === true) {
122
+ findings.push({
123
+ level: "ok",
124
+ check: `Admin request role "${adminRole}"`,
125
+ detail: `Inherits "${role}" and "${REBASE_ADMIN_ROLE}".`
126
+ });
127
+ continue;
128
+ }
129
+ const boots = settings.provisionRole === "auto" && (state?.can_create === true || who?.superuser === true);
130
+ const grant = (granted) => perGrant ? `GRANT ${quoteIdent(granted)} TO ${adminRole} WITH INHERIT TRUE, SET FALSE;` : `GRANT ${quoteIdent(granted)} TO ${adminRole};`;
131
+ findings.push({
132
+ level: boots ? "ok" : "warn",
133
+ check: `Admin request role "${adminRole}"`,
134
+ detail: (state?.marker === true ? "" : `"${REBASE_ADMIN_ROLE}" does not exist. `) + (state?.present === true ? `It does not inherit "${role}" and "${REBASE_ADMIN_ROLE}".` : "Does not exist.") + (boots ? " The next boot provisions it." : " Until it does, admin requests run as the request role and the server-or-admin policies refuse them."),
135
+ sql: boots ? void 0 : [
136
+ ...state?.marker === true ? [] : [`CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;`],
137
+ ...state?.present === true ? [] : [`CREATE ROLE ${adminRole} NOLOGIN NOSUPERUSER NOBYPASSRLS ${perGrant ? "NOINHERIT" : "INHERIT"};`],
138
+ grant(role),
139
+ grant(REBASE_ADMIN_ROLE),
140
+ `GRANT ${adminRole} TO ${quoteIdent(connection)}${perGrant ? " WITH SET TRUE, INHERIT FALSE" : ""};`
141
+ ].join("\n"),
142
+ setting: "rls.adminPolicies = \"public\""
143
+ });
144
+ }
145
+ const unreachable = await run(`
146
+ SELECT p.schemaname || '.' || p.tablename AS name, p.policyname AS policy, r.role AS role
147
+ FROM pg_policies p CROSS JOIN LATERAL unnest(p.roles::text[]) AS r(role)
148
+ WHERE (p.schemaname, p.tablename::text) IN ${managedPairs(options.managedTables)}
149
+ AND r.role <> 'public' AND r.role <> '${REBASE_ADMIN_ROLE}' AND r.role <> ALL(${textArray(settings.roles)})
150
+ AND NOT EXISTS (SELECT 1 FROM unnest(${textArray(settings.roles)}) AS q(name)
151
+ WHERE COALESCE(pg_has_role(to_regrole(q.name), to_regrole(r.role), 'USAGE'), false))
152
+ ORDER BY 1, 2
153
+ `);
154
+ if (unreachable.length > 0) {
155
+ const roles = Array.from(new Set(unreachable.map((r) => String(r.role))));
156
+ findings.push({
157
+ level: "warn",
158
+ check: "Policies that never apply to requests",
159
+ detail: `${unreachable.length} polic${unreachable.length === 1 ? "y" : "ies"} on Rebase's tables target ${roles.join(", ")}, whose privileges the request role does not have (e.g. ${unreachable[0].policy} on ${unreachable[0].name}).`,
160
+ setting: perGrant ? `rls.inheritRoles = [${roles.map((r) => `"${r}"`).join(", ")}]` : "move them into the collection's securityRules (PostgreSQL 15 cannot inherit per grant)"
161
+ });
162
+ }
163
+ const defaults = await run(`
164
+ SELECT DISTINCT g.rolname AS grantee, n.nspname AS schema
165
+ FROM pg_default_acl d
166
+ JOIN pg_namespace n ON n.oid = d.defaclnamespace
167
+ CROSS JOIN LATERAL aclexplode(d.defaclacl) a
168
+ JOIN pg_roles g ON g.oid = a.grantee
169
+ WHERE n.nspname = ANY(${textArray(schemas)}) AND d.defaclobjtype = 'r'
170
+ AND g.rolname <> ALL(${textArray([...settings.roles, connection])})
171
+ ORDER BY 2, 1
172
+ `);
173
+ if (defaults.length > 0) findings.push({
174
+ level: "warn",
175
+ check: "Default privileges for other roles",
176
+ detail: `New tables in ${Array.from(new Set(defaults.map((d) => d.schema))).join(", ")} are granted to ${Array.from(new Set(defaults.map((d) => d.grantee))).join(", ")} as they are created — Rebase's collection tables included.`,
177
+ setting: settings.policyTarget === "public" ? "rls.policyTarget = \"requestRole\"" : void 0
178
+ });
179
+ return findings;
180
+ }
181
+ //#endregion
182
+ export { preflightDatabase };
183
+
184
+ //# sourceMappingURL=database-preflight-DIauc8i5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database-preflight-DIauc8i5.js","names":[],"sources":["../src/security/database-preflight.ts"],"sourcesContent":["import {\n appRoleSetupInstructions,\n assertAppRoleRestricted,\n findOtherRoleMembers,\n readRecordedRequestRoles,\n type ManagedTable,\n type RawSqlRunner\n} from \"./rls-enforcement\";\nimport { REBASE_ADMIN_ROLE } from \"@rebasepro/types\";\nimport type { RlsSettings } from \"./rls-settings\";\n\n/**\n * What `rebase doctor --database` checks: whether this database can host\n * Rebase's request role(s) under the project's `rls` settings, read from the\n * catalogue without changing anything.\n *\n * Every finding that is not \"ok\" carries the SQL to run as an administrator, the\n * `rls` setting that would adapt Rebase to the database instead, or both — the\n * two ways out of any of them.\n */\nexport interface PreflightFinding {\n level: \"ok\" | \"warn\" | \"fail\";\n check: string;\n detail: string;\n /** SQL that fixes it, run as a database administrator. */\n sql?: string;\n /** The `rls` setting that would fit Rebase to the database as it is. */\n setting?: string;\n}\n\nconst quoteIdent = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\nconst sqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\nconst textArray = (values: readonly string[]): string =>\n values.length === 0 ? \"ARRAY[]::text[]\" : `ARRAY[${values.map(sqlLiteral).join(\", \")}]::text[]`;\nconst managedPairs = (tables: readonly ManagedTable[]): string =>\n `(SELECT * FROM unnest(${textArray(tables.map((t) => t.schema))}, ${textArray(tables.map((t) => t.table))}))`;\n\nexport async function preflightDatabase(\n run: RawSqlRunner,\n settings: RlsSettings,\n options: { schemas: readonly string[]; managedTables: readonly ManagedTable[] }\n): Promise<PreflightFinding[]> {\n const findings: PreflightFinding[] = [];\n // Only schemas that exist: a GRANT on a missing one breaks the setup SQL\n // these findings hand out.\n const existing = await run(`SELECT nspname FROM pg_namespace WHERE nspname = ANY(${textArray(Array.from(new Set(options.schemas)))})`);\n const schemas = existing.map((row) => String(row.nspname));\n const [who] = await run(`\n SELECT current_user AS role, current_database() AS database,\n (SELECT rolsuper FROM pg_roles WHERE rolname = current_user) AS superuser,\n current_setting('server_version_num')::int >= 160000 AS per_grant\n `);\n const connection = String(who?.role ?? \"\");\n const perGrant = who?.per_grant === true;\n\n const recorded = await readRecordedRequestRoles(run);\n if (recorded && (recorded.length !== settings.roles.length || !settings.roles.every((r) => recorded.includes(r)))) {\n findings.push({\n level: \"fail\",\n check: \"Recorded request roles\",\n detail: `This database records ${recorded.join(\", \")}, but the settings name ${settings.roles.join(\", \")}. A boot refuses until they agree.`,\n sql: `-- from the project: rebase db request-role migrate --to ${settings.roles.join(\",\")}`\n });\n }\n\n for (const role of settings.roles) {\n const [state] = await run(`\n SELECT to_regrole(${sqlLiteral(role)}) IS NOT NULL AS present,\n COALESCE(pg_has_role(current_user, to_regrole(${sqlLiteral(role)}), '${perGrant ? \"SET\" : \"MEMBER\"}'), false) AS can_switch,\n (SELECT rolcreaterole FROM pg_roles WHERE rolname = current_user) AS can_create\n `);\n if (state?.present !== true) {\n const creates = settings.provisionRole === \"auto\" && (state?.can_create === true || who?.superuser === true);\n findings.push({\n level: creates ? \"ok\" : \"fail\",\n check: `Request role \"${role}\"`,\n detail: creates\n ? \"Does not exist yet; the first boot creates it.\"\n : settings.provisionRole === \"never\"\n ? \"Does not exist, and rls.provisionRole is \\\"never\\\".\"\n : `Does not exist, and \"${connection}\" cannot create roles.`,\n sql: creates ? undefined : appRoleSetupInstructions(connection, [...schemas], role, settings.grants)\n });\n continue;\n }\n try {\n await assertAppRoleRestricted(run, role);\n } catch (err) {\n findings.push({\n level: \"fail\",\n check: `Request role \"${role}\"`,\n detail: err instanceof Error ? err.message.split(\"\\n\\n\")[0] : String(err),\n sql: err instanceof Error && \"instructions\" in err ? String((err as { instructions: unknown }).instructions) : undefined\n });\n continue;\n }\n if (state?.can_switch !== true && who?.superuser !== true) {\n findings.push({\n level: settings.provisionRole === \"auto\" ? \"warn\" : \"fail\",\n check: `Switching to \"${role}\"`,\n detail: `\"${connection}\" may not switch to it${perGrant ? \" (no membership WITH SET TRUE)\" : \"\"}.` +\n (settings.provisionRole === \"auto\" ? \" A boot grants that to itself when it can.\" : \"\"),\n sql: appRoleSetupInstructions(connection, [...schemas], role, settings.grants)\n });\n } else {\n findings.push({ level: \"ok\", check: `Request role \"${role}\"`, detail: \"Exists, restricted, and this connection can switch to it.\" });\n }\n\n const others = await findOtherRoleMembers(run, role);\n if (others.length > 0) {\n findings.push({\n level: settings.sharedRole === \"refuse\" ? \"fail\" : \"warn\",\n check: `Who else can use \"${role}\"`,\n detail: `${others.join(\", \")} can switch into it, and so can pass this database's policies as whichever user they like.`,\n setting: \"rls.requestRole (a role of this project's own), then `rebase db request-role migrate`\"\n });\n }\n }\n\n const [database] = await run(`\n SELECT d.datacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(d.datacl) a WHERE a.grantee = 0 AND a.privilege_type = 'CONNECT') AS public_connect\n FROM pg_database d WHERE d.datname = current_database()\n `);\n if (database?.public_connect === true) {\n findings.push({\n level: \"warn\",\n check: \"Who can connect\",\n detail: \"Every role on the cluster may connect to this database (PUBLIC holds CONNECT, the default).\",\n sql: `REVOKE CONNECT ON DATABASE ${quoteIdent(String(who?.database ?? \"\"))} FROM PUBLIC;\\nGRANT CONNECT ON DATABASE ${quoteIdent(String(who?.database ?? \"\"))} TO ${quoteIdent(connection)};`\n });\n }\n\n const [unmanaged] = await run(`\n SELECT count(*)::int AS count, string_agg(n.nspname || '.' || c.relname, ', ' ORDER BY n.nspname, c.relname) AS sample\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY(${textArray(schemas)}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f')\n AND (n.nspname, c.relname::text) NOT IN ${managedPairs(options.managedTables)}\n AND n.nspname <> 'rebase'\n `);\n const unmanagedCount = Number(unmanaged?.count ?? 0);\n if (unmanagedCount > 0 && settings.grants === \"schema\") {\n findings.push({\n level: \"warn\",\n check: \"Tables Rebase does not serve\",\n detail: `${unmanagedCount} table(s) in ${schemas.join(\", \")} back no collection (${String(unmanaged?.sample ?? \"\").split(\", \").slice(0, 5).join(\", \")}${unmanagedCount > 5 ? \", …\" : \"\"}). With grants: \"schema\" the request role gets DML on every one this connection may grant on.`,\n setting: \"rls.grants = \\\"managed\\\"\"\n });\n }\n\n const foreign = await run(`\n SELECT DISTINCT g.rolname AS grantee\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n CROSS JOIN LATERAL aclexplode(c.relacl) a\n JOIN pg_roles g ON g.oid = a.grantee\n WHERE (n.nspname, c.relname::text) IN ${managedPairs(options.managedTables)}\n AND g.rolname <> ALL(${textArray([...settings.roles, connection])})\n AND a.grantee <> c.relowner\n ORDER BY 1\n `);\n if (foreign.length > 0 && settings.policyTarget === \"public\") {\n findings.push({\n level: \"warn\",\n check: \"Other roles on Rebase's tables\",\n detail: `${foreign.map((r) => r.grantee).join(\", \")} hold privileges on tables Rebase serves. Its permissive policies apply TO public, so a session of theirs that never sets Rebase's identity passes the server-context arm and sees every row.`,\n setting: \"rls.policyTarget = \\\"requestRole\\\"\"\n });\n }\n\n // `rls.adminPolicies: \"adminRole\"`: the server-or-admin policies are `TO\n // rebase_admin`, and admin requests switch to `<role>_admin`. A missing\n // piece fails closed — admins are refused, nobody gains — so a warning.\n for (const [role, adminRole] of settings.adminRoles) {\n const [state] = await run(`\n SELECT to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS marker,\n to_regrole(${sqlLiteral(adminRole)}) IS NOT NULL AS present,\n COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole(${sqlLiteral(role)}), 'USAGE'), false)\n AND COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false) AS inherits,\n (SELECT rolcreaterole FROM pg_roles WHERE rolname = current_user) AS can_create\n `);\n if (state?.marker === true && state?.present === true && state?.inherits === true) {\n findings.push({ level: \"ok\", check: `Admin request role \"${adminRole}\"`, detail: `Inherits \"${role}\" and \"${REBASE_ADMIN_ROLE}\".` });\n continue;\n }\n const boots = settings.provisionRole === \"auto\" && (state?.can_create === true || who?.superuser === true);\n const grant = (granted: string) => perGrant\n ? `GRANT ${quoteIdent(granted)} TO ${adminRole} WITH INHERIT TRUE, SET FALSE;`\n : `GRANT ${quoteIdent(granted)} TO ${adminRole};`;\n findings.push({\n level: boots ? \"ok\" : \"warn\",\n check: `Admin request role \"${adminRole}\"`,\n detail: (state?.marker === true ? \"\" : `\"${REBASE_ADMIN_ROLE}\" does not exist. `) +\n (state?.present === true ? `It does not inherit \"${role}\" and \"${REBASE_ADMIN_ROLE}\".` : \"Does not exist.\") +\n (boots ? \" The next boot provisions it.\" : \" Until it does, admin requests run as the request role and the server-or-admin policies refuse them.\"),\n sql: boots ? undefined : [\n ...(state?.marker === true ? [] : [`CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;`]),\n ...(state?.present === true ? [] : [`CREATE ROLE ${adminRole} NOLOGIN NOSUPERUSER NOBYPASSRLS ${perGrant ? \"NOINHERIT\" : \"INHERIT\"};`]),\n grant(role),\n grant(REBASE_ADMIN_ROLE),\n `GRANT ${adminRole} TO ${quoteIdent(connection)}${perGrant ? \" WITH SET TRUE, INHERIT FALSE\" : \"\"};`\n ].join(\"\\n\"),\n setting: \"rls.adminPolicies = \\\"public\\\"\"\n });\n }\n\n const unreachable = await run(`\n SELECT p.schemaname || '.' || p.tablename AS name, p.policyname AS policy, r.role AS role\n FROM pg_policies p CROSS JOIN LATERAL unnest(p.roles::text[]) AS r(role)\n WHERE (p.schemaname, p.tablename::text) IN ${managedPairs(options.managedTables)}\n AND r.role <> 'public' AND r.role <> '${REBASE_ADMIN_ROLE}' AND r.role <> ALL(${textArray(settings.roles)})\n AND NOT EXISTS (SELECT 1 FROM unnest(${textArray(settings.roles)}) AS q(name)\n WHERE COALESCE(pg_has_role(to_regrole(q.name), to_regrole(r.role), 'USAGE'), false))\n ORDER BY 1, 2\n `);\n if (unreachable.length > 0) {\n const roles = Array.from(new Set(unreachable.map((r) => String(r.role))));\n findings.push({\n level: \"warn\",\n check: \"Policies that never apply to requests\",\n detail: `${unreachable.length} polic${unreachable.length === 1 ? \"y\" : \"ies\"} on Rebase's tables target ${roles.join(\", \")}, whose privileges the request role does not have (e.g. ${unreachable[0].policy} on ${unreachable[0].name}).`,\n setting: perGrant ? `rls.inheritRoles = [${roles.map((r) => `\"${r}\"`).join(\", \")}]` : \"move them into the collection's securityRules (PostgreSQL 15 cannot inherit per grant)\"\n });\n }\n\n const defaults = await run(`\n SELECT DISTINCT g.rolname AS grantee, n.nspname AS schema\n FROM pg_default_acl d\n JOIN pg_namespace n ON n.oid = d.defaclnamespace\n CROSS JOIN LATERAL aclexplode(d.defaclacl) a\n JOIN pg_roles g ON g.oid = a.grantee\n WHERE n.nspname = ANY(${textArray(schemas)}) AND d.defaclobjtype = 'r'\n AND g.rolname <> ALL(${textArray([...settings.roles, connection])})\n ORDER BY 2, 1\n `);\n if (defaults.length > 0) {\n findings.push({\n level: \"warn\",\n check: \"Default privileges for other roles\",\n detail: `New tables in ${Array.from(new Set(defaults.map((d) => d.schema))).join(\", \")} are granted to ${Array.from(new Set(defaults.map((d) => d.grantee))).join(\", \")} as they are created — Rebase's collection tables included.`,\n setting: settings.policyTarget === \"public\" ? \"rls.policyTarget = \\\"requestRole\\\"\" : undefined\n });\n }\n\n return findings;\n}\n"],"mappings":";;;;;AA8BA,IAAM,cAAc,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;AAC5E,IAAM,cAAc,UAA0B,IAAI,MAAM,QAAQ,MAAM,IAAI,EAAE;AAC5E,IAAM,aAAa,WACf,OAAO,WAAW,IAAI,oBAAoB,SAAS,OAAO,IAAI,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE;AACzF,IAAM,gBAAgB,WAClB,yBAAyB,UAAU,OAAO,KAAK,MAAM,EAAE,MAAM,CAAC,EAAE,IAAI,UAAU,OAAO,KAAK,MAAM,EAAE,KAAK,CAAC,EAAE;AAE9G,eAAsB,kBAClB,KACA,UACA,SAC2B;CAC3B,MAAM,WAA+B,CAAC;CAItC,MAAM,WAAU,MADO,IAAI,wDAAwD,UAAU,MAAM,KAAK,IAAI,IAAI,QAAQ,OAAO,CAAC,CAAC,EAAE,EAAE,EAAA,CAC5G,KAAK,QAAQ,OAAO,IAAI,OAAO,CAAC;CACzD,MAAM,CAAC,OAAO,MAAM,IAAI;;;;KAIvB;CACD,MAAM,aAAa,OAAO,KAAK,QAAQ,EAAE;CACzC,MAAM,WAAW,KAAK,cAAc;CAEpC,MAAM,WAAW,MAAM,yBAAyB,GAAG;CACnD,IAAI,aAAa,SAAS,WAAW,SAAS,MAAM,UAAU,CAAC,SAAS,MAAM,OAAO,MAAM,SAAS,SAAS,CAAC,CAAC,IAC3G,SAAS,KAAK;EACV,OAAO;EACP,OAAO;EACP,QAAQ,yBAAyB,SAAS,KAAK,IAAI,EAAE,0BAA0B,SAAS,MAAM,KAAK,IAAI,EAAE;E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AAa,EAAE;kDACvC,kBAAkB,sBAAsB,UAAU,SAAS,KAAK,EAAE;iDACnE,UAAU,SAAS,KAAK,EAAE;;;KAGtE;CACD,IAAI,YAAY,SAAS,GAAG;EACxB,MAAM,QAAQ,MAAM,KAAK,IAAI,IAAI,YAAY,KAAK,MAAM,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;EACxE,SAAS,KAAK;GACV,OAAO;GACP,OAAO;GACP,QAAQ,GAAG,YAAY,OAAO,QAAQ,YAAY,WAAW,IAAI,MAAM,MAAM,6BAA6B,MAAM,KAAK,IAAI,EAAE,0DAA0D,YAAY,EAAE,CAAC,OAAO,MAAM,YAAY,EAAE,CAAC,KAAK;GACrO,SAAS,WAAW,uBAAuB,MAAM,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,KAAK;EAC1F,CAAC;CACL;CAEA,MAAM,WAAW,MAAM,IAAI;;;;;;gCAMC,UAAU,OAAO,EAAE;iCAClB,UAAU,CAAC,GAAG,SAAS,OAAO,UAAU,CAAC,EAAE;;KAEvE;CACD,IAAI,SAAS,SAAS,GAClB,SAAS,KAAK;EACV,OAAO;EACP,OAAO;EACP,QAAQ,iBAAiB,MAAM,KAAK,IAAI,IAAI,SAAS,KAAK,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,kBAAkB,MAAM,KAAK,IAAI,IAAI,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE;EACxK,SAAS,SAAS,iBAAiB,WAAW,uCAAuC,KAAA;CACzF,CAAC;CAGL,OAAO;AACX"}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
- import { c as guardPoolAgainstDirtyRelease, g as reportPoolError, s as defaultPoolTimeouts, t as cappedPoolMax, u as pinSearchPath } from "./connection-COuS5Fm-.js";
4
+ import { c as guardPoolAgainstDirtyRelease, g as reportPoolError, s as defaultPoolTimeouts, t as cappedPoolMax, u as pinSearchPath } from "./connection-C1zXTPJq.js";
5
5
  import { Pool } from "pg";
6
6
  import { drizzle } from "drizzle-orm/node-postgres";
7
7
  import { logger } from "@rebasepro/server";
@@ -114,4 +114,4 @@ var DatabasePoolManager = class {
114
114
  //#endregion
115
115
  export { databasePoolManager_exports as n, DatabasePoolManager as t };
116
116
 
117
- //# sourceMappingURL=databasePoolManager-7hXVurmG.js.map
117
+ //# sourceMappingURL=databasePoolManager-DIjzlTK4.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"databasePoolManager-7hXVurmG.js","names":[],"sources":["../src/databasePoolManager.ts"],"sourcesContent":["import { Pool } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\nimport { guardPoolAgainstDirtyRelease, pinSearchPath, cappedPoolMax, defaultPoolTimeouts } from \"./connection\";\nimport { reportPoolError } from \"./pool-disconnects\";\n\nexport class DatabasePoolManager {\n private pools: Map<string, Pool> = new Map();\n private drizzleInstances: Map<string, NodePgDatabase> = new Map();\n public readonly defaultDatabaseName: string;\n private readonly rootConnectionString: string;\n\n constructor(adminConnectionString: string) {\n this.rootConnectionString = adminConnectionString;\n try {\n const url = new URL(adminConnectionString);\n // Decoded as pg decodes it to connect (`decodeURI`): the URL holds\n // `caf%C3%A9` for the database `café`, and this name is used as an\n // SQL identifier and as the key of the pool `getPool` builds back\n // from it.\n this.defaultDatabaseName = decodeURI(url.pathname.slice(1));\n } catch (e) {\n throw new Error(`Invalid adminConnectionString provided: ${e}`);\n }\n }\n\n public getDrizzle(databaseName: string): NodePgDatabase<Record<string, never>> {\n const existing = this.drizzleInstances.get(databaseName);\n if (existing) {\n return existing;\n }\n\n const pool = this.getPool(databaseName);\n const db = drizzle(pool);\n this.drizzleInstances.set(databaseName, db);\n return db;\n }\n\n public getPool(databaseName: string): Pool {\n if (this.pools.has(databaseName)) {\n return this.pools.get(databaseName)!;\n }\n\n const url = new URL(this.rootConnectionString);\n url.pathname = `/${databaseName}`;\n\n const pool = new Pool({\n // Same pin as the primary pool: these are branch/multi-database\n // connections to the *same* server, so they inherit the same\n // `\"$user\"` hazard. See `pinSearchPath`.\n connectionString: pinSearchPath(url.toString()),\n // Capped by REBASE_DB_POOL_MAX, which the managed development\n // database sets to 1: PGlite multiplexes onto a single session and\n // overlapping transactions deadlock there.\n max: cappedPoolMax(10),\n idleTimeoutMillis: 10000, // Reduced from 30000 for aggressive cleanup\n allowExitOnIdle: true, // Prevent idle clients from hanging the Node.js process\n // The main pool's limits: a full pool answers 503 after 10 s rather\n // than queueing forever, and a statement stops at 30 s server-side.\n ...defaultPoolTimeouts()\n });\n\n // Prevent idle client errors from crashing the Node.js process\n pool.on(\"error\", (err) => reportPoolError(`DatabasePoolManager:${databaseName}`, err));\n guardPoolAgainstDirtyRelease(pool, `pg-pool:${databaseName}`);\n\n this.pools.set(databaseName, pool);\n return pool;\n }\n\n /**\n * Disconnect and remove the pool for a specific database.\n * Required before `CREATE DATABASE ... TEMPLATE` or `DROP DATABASE`,\n * which need exclusive access to the target database.\n */\n public async disconnectDatabase(databaseName: string): Promise<void> {\n const pool = this.pools.get(databaseName);\n if (pool) {\n await pool.end();\n this.pools.delete(databaseName);\n this.drizzleInstances.delete(databaseName);\n }\n }\n\n /** Check if a pool exists for a given database name. */\n public hasPool(databaseName: string): boolean {\n return this.pools.has(databaseName);\n }\n\n /**\n * Does this server serve exactly one database?\n *\n * The managed development database is PGlite, and PGlite serves exactly\n * one. `CREATE DATABASE \"rb_feature\" TEMPLATE \"postgres\"` there writes a\n * `pg_database` catalogue row and nothing else: nothing errors, the row is\n * listable, `pg_database_size` answers — and connecting to the \"branch\"\n * lands you in the parent. Every write made in the belief that it is\n * sandboxed goes to the developer's real development database.\n *\n * The CLI already refuses `rebase db branch` on this ground, but it does it\n * by parsing argv, so Studio — which reaches `BranchService` over the\n * websocket — walked straight past it. The connection is the only thing\n * both callers share, so the answer belongs here.\n *\n * Measured, not assumed: `select version()` over the PGlite socket returns\n * `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`, which is how a wasm build\n * announces itself and what `dev-db/constraints.ts` documents. A real\n * Postgres never carries `(PGlite `.\n *\n * Cached, because a live connection cannot change engine underneath us, and\n * a `PostgresBackendDriver` — which builds a `BranchService` — is\n * constructed per transaction.\n */\n public servesOneDatabase(): Promise<boolean> {\n this.oneDatabaseProbe ??= this.probeOneDatabase();\n return this.oneDatabaseProbe;\n }\n\n private oneDatabaseProbe?: Promise<boolean>;\n\n private async probeOneDatabase(): Promise<boolean> {\n try {\n const result = await this.getPool(this.defaultDatabaseName)\n .query<{ version: string }>(\"SELECT version() AS version\");\n return /\\(PGlite\\b/i.test(result.rows[0]?.version ?? \"\");\n } catch (err) {\n // Fail open, and do not cache the failure. The cost of a wrong\n // \"yes\" is refusing branching on a real Postgres that momentarily\n // could not answer; the cost of a wrong \"no\" is one fake branch,\n // which is what this exists to prevent — but a server that cannot\n // run `select version()` is not one we can conclude anything about.\n this.oneDatabaseProbe = undefined;\n logger.warn(\"[DatabasePoolManager] Could not read the server version\", { error: err });\n return false;\n }\n }\n\n public async shutdown(): Promise<void> {\n const promises = [];\n for (const [dbName, pool] of this.pools.entries()) {\n // Debug: every CLI command that reaches a database ends here, and\n // the reader of `rebase db branch create` did not ask about pools.\n logger.debug(`[DatabasePoolManager] Shutting down pool for ${dbName}`);\n promises.push(pool.end());\n }\n await Promise.all(promises);\n this.pools.clear();\n this.drizzleInstances.clear();\n }\n}\n"],"mappings":";;;;;;;;;AAOA,IAAa,sBAAb,MAAiC;CAC7B,wBAAmC,IAAI,IAAI;CAC3C,mCAAwD,IAAI,IAAI;CAChE;CACA;CAEA,YAAY,uBAA+B;EACvC,KAAK,uBAAuB;EAC5B,IAAI;GACA,MAAM,MAAM,IAAI,IAA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AAK,QAAQ,KAAK,mBAAmB,CAAC,CACtD,MAA2B,6BAA6B;GAC7D,OAAO,cAAc,KAAK,OAAO,KAAK,EAAE,EAAE,WAAW,EAAE;EAC3D,SAAS,KAAK;GAMV,KAAK,mBAAmB,KAAA;GACxB,OAAO,KAAK,2DAA2D,EAAE,OAAO,IAAI,CAAC;GACrF,OAAO;EACX;CACJ;CAEA,MAAa,WAA0B;EACnC,MAAM,WAAW,CAAC;EAClB,KAAK,MAAM,CAAC,QAAQ,SAAS,KAAK,MAAM,QAAQ,GAAG;GAG/C,OAAO,MAAM,gDAAgD,QAAQ;GACrE,SAAS,KAAK,KAAK,IAAI,CAAC;EAC5B;EACA,MAAM,QAAQ,IAAI,QAAQ;EAC1B,KAAK,MAAM,MAAM;EACjB,KAAK,iBAAiB,MAAM;CAChC;AACJ"}
1
+ {"version":3,"file":"databasePoolManager-DIjzlTK4.js","names":[],"sources":["../src/databasePoolManager.ts"],"sourcesContent":["import { Pool } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\nimport { guardPoolAgainstDirtyRelease, pinSearchPath, cappedPoolMax, defaultPoolTimeouts } from \"./connection\";\nimport { reportPoolError } from \"./pool-disconnects\";\n\nexport class DatabasePoolManager {\n private pools: Map<string, Pool> = new Map();\n private drizzleInstances: Map<string, NodePgDatabase> = new Map();\n public readonly defaultDatabaseName: string;\n private readonly rootConnectionString: string;\n\n constructor(adminConnectionString: string) {\n this.rootConnectionString = adminConnectionString;\n try {\n const url = new URL(adminConnectionString);\n // Decoded as pg decodes it to connect (`decodeURI`): the URL holds\n // `caf%C3%A9` for the database `café`, and this name is used as an\n // SQL identifier and as the key of the pool `getPool` builds back\n // from it.\n this.defaultDatabaseName = decodeURI(url.pathname.slice(1));\n } catch (e) {\n throw new Error(`Invalid adminConnectionString provided: ${e}`);\n }\n }\n\n public getDrizzle(databaseName: string): NodePgDatabase<Record<string, never>> {\n const existing = this.drizzleInstances.get(databaseName);\n if (existing) {\n return existing;\n }\n\n const pool = this.getPool(databaseName);\n const db = drizzle(pool);\n this.drizzleInstances.set(databaseName, db);\n return db;\n }\n\n public getPool(databaseName: string): Pool {\n if (this.pools.has(databaseName)) {\n return this.pools.get(databaseName)!;\n }\n\n const url = new URL(this.rootConnectionString);\n url.pathname = `/${databaseName}`;\n\n const pool = new Pool({\n // Same pin as the primary pool: these are branch/multi-database\n // connections to the *same* server, so they inherit the same\n // `\"$user\"` hazard. See `pinSearchPath`.\n connectionString: pinSearchPath(url.toString()),\n // Capped by REBASE_DB_POOL_MAX, which the managed development\n // database sets to 1: PGlite multiplexes onto a single session and\n // overlapping transactions deadlock there.\n max: cappedPoolMax(10),\n idleTimeoutMillis: 10000, // Reduced from 30000 for aggressive cleanup\n allowExitOnIdle: true, // Prevent idle clients from hanging the Node.js process\n // The main pool's limits: a full pool answers 503 after 10 s rather\n // than queueing forever, and a statement stops at 30 s server-side.\n ...defaultPoolTimeouts()\n });\n\n // Prevent idle client errors from crashing the Node.js process\n pool.on(\"error\", (err) => reportPoolError(`DatabasePoolManager:${databaseName}`, err));\n guardPoolAgainstDirtyRelease(pool, `pg-pool:${databaseName}`);\n\n this.pools.set(databaseName, pool);\n return pool;\n }\n\n /**\n * Disconnect and remove the pool for a specific database.\n * Required before `CREATE DATABASE ... TEMPLATE` or `DROP DATABASE`,\n * which need exclusive access to the target database.\n */\n public async disconnectDatabase(databaseName: string): Promise<void> {\n const pool = this.pools.get(databaseName);\n if (pool) {\n await pool.end();\n this.pools.delete(databaseName);\n this.drizzleInstances.delete(databaseName);\n }\n }\n\n /** Check if a pool exists for a given database name. */\n public hasPool(databaseName: string): boolean {\n return this.pools.has(databaseName);\n }\n\n /**\n * Does this server serve exactly one database?\n *\n * The managed development database is PGlite, and PGlite serves exactly\n * one. `CREATE DATABASE \"rb_feature\" TEMPLATE \"postgres\"` there writes a\n * `pg_database` catalogue row and nothing else: nothing errors, the row is\n * listable, `pg_database_size` answers — and connecting to the \"branch\"\n * lands you in the parent. Every write made in the belief that it is\n * sandboxed goes to the developer's real development database.\n *\n * The CLI already refuses `rebase db branch` on this ground, but it does it\n * by parsing argv, so Studio — which reaches `BranchService` over the\n * websocket — walked straight past it. The connection is the only thing\n * both callers share, so the answer belongs here.\n *\n * Measured, not assumed: `select version()` over the PGlite socket returns\n * `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`, which is how a wasm build\n * announces itself and what `dev-db/constraints.ts` documents. A real\n * Postgres never carries `(PGlite `.\n *\n * Cached, because a live connection cannot change engine underneath us, and\n * a `PostgresBackendDriver` — which builds a `BranchService` — is\n * constructed per transaction.\n */\n public servesOneDatabase(): Promise<boolean> {\n this.oneDatabaseProbe ??= this.probeOneDatabase();\n return this.oneDatabaseProbe;\n }\n\n private oneDatabaseProbe?: Promise<boolean>;\n\n private async probeOneDatabase(): Promise<boolean> {\n try {\n const result = await this.getPool(this.defaultDatabaseName)\n .query<{ version: string }>(\"SELECT version() AS version\");\n return /\\(PGlite\\b/i.test(result.rows[0]?.version ?? \"\");\n } catch (err) {\n // Fail open, and do not cache the failure. The cost of a wrong\n // \"yes\" is refusing branching on a real Postgres that momentarily\n // could not answer; the cost of a wrong \"no\" is one fake branch,\n // which is what this exists to prevent — but a server that cannot\n // run `select version()` is not one we can conclude anything about.\n this.oneDatabaseProbe = undefined;\n logger.warn(\"[DatabasePoolManager] Could not read the server version\", { error: err });\n return false;\n }\n }\n\n public async shutdown(): Promise<void> {\n const promises = [];\n for (const [dbName, pool] of this.pools.entries()) {\n // Debug: every CLI command that reaches a database ends here, and\n // the reader of `rebase db branch create` did not ask about pools.\n logger.debug(`[DatabasePoolManager] Shutting down pool for ${dbName}`);\n promises.push(pool.end());\n }\n await Promise.all(promises);\n this.pools.clear();\n this.drizzleInstances.clear();\n }\n}\n"],"mappings":";;;;;;;;;AAOA,IAAa,sBAAb,MAAiC;CAC7B,wBAAmC,IAAI,IAAI;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C,KAAK,qBAAqB,KAAK,iBAAiB;EAChD,OAAO,KAAK;CAChB;CAEA;CAEA,MAAc,mBAAqC;EAC/C,IAAI;GACA,MAAM,SAAS,MAAM,KAAK,QAAQ,KAAK,mBAAmB,CAAC,CACtD,MAA2B,6BAA6B;GAC7D,OAAO,cAAc,KAAK,OAAO,KAAK,EAAE,EAAE,WAAW,EAAE;EAC3D,SAAS,KAAK;GAMV,KAAK,mBAAmB,KAAA;GACxB,OAAO,KAAK,2DAA2D,EAAE,OAAO,IAAI,CAAC;GACrF,OAAO;EACX;CACJ;CAEA,MAAa,WAA0B;EACnC,MAAM,WAAW,CAAC;EAClB,KAAK,MAAM,CAAC,QAAQ,SAAS,KAAK,MAAM,QAAQ,GAAG;GAG/C,OAAO,MAAM,gDAAgD,QAAQ;GACrE,SAAS,KAAK,KAAK,IAAI,CAAC;EAC5B;EACA,MAAM,QAAQ,IAAI,QAAQ;EAC1B,KAAK,MAAM,MAAM;EACjB,KAAK,iBAAiB,MAAM;CAChC;AACJ"}
@@ -5,7 +5,7 @@
5
5
  * what judges their lines (`db-command-line.ts` reaches the backup module,
6
6
  * which `cli.ts` imports only when a backup command runs).
7
7
  */
8
- export declare const DRIVER_DB_SUBCOMMANDS: readonly ["push", "generate", "migrate", "branch", "backup", "restore", "backups"];
8
+ export declare const DRIVER_DB_SUBCOMMANDS: readonly ["push", "generate", "migrate", "branch", "backup", "restore", "backups", "request-role", "provision"];
9
9
  export type DriverDbSubcommand = typeof DRIVER_DB_SUBCOMMANDS[number];
10
10
  /** Is `word` a `db` subcommand this driver answers? */
11
11
  export declare function isDriverDbSubcommand(word: string | undefined): word is DriverDbSubcommand;
@@ -2,12 +2,13 @@ import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
4
  import { h as searchIndexStatements, n as SEARCH_TEXT_FN, r as SEARCH_UNACCENT_FN, u as searchColumnStamps } from "./search-column-BM-GV6vH.js";
5
- import { n as extractPgError } from "./pg-error-utils-BLOVXK67.js";
5
+ import { n as extractPgError } from "./pg-error-utils-80uTIHQs.js";
6
6
  import { u as vectorIndexStatement } from "./vector-index-DsQ3V2d2.js";
7
7
  import { _ as sortIndexSpecs, l as collectionIndexStatement } from "./source-fZb92pN8.js";
8
- import { a as triggerStatements, i as SET_UPDATED_AT_FN, r as quoteSqlLiteral } from "./plan-schema-CMNWvqIa.js";
9
- import { c as renderPrimaryKeyConstraint, i as renderPgType, r as renderEnableRls, t as renderColumnDefinition } from "./render-ddl-CzVcbbR1.js";
10
- import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, o as isMultiStatementRefusal, r as atomicBatch } from "./boot-ddl-D4W9o9xE.js";
8
+ import { a as triggerStatements, i as SET_UPDATED_AT_FN, o as KEEP_TENANT_FN, r as quoteSqlLiteral, s as keepTenantArguments } from "./plan-schema-CMhNYEYF.js";
9
+ import { c as renderPrimaryKeyConstraint, i as renderPgType, r as renderEnableRls, t as renderColumnDefinition } from "./render-ddl-Di-fTGti.js";
10
+ import { T as planIndexAdoptions, w as indexAdoptionStatement } from "./migrate-baseline-CveNQli3.js";
11
+ import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, o as isMultiStatementRefusal, r as atomicBatch } from "./boot-ddl-CbZj9ovZ.js";
11
12
  import { logger } from "@rebasepro/server";
12
13
  //#region src/schema/column-type-drift.ts
13
14
  /**
@@ -165,8 +166,11 @@ function assertSafeIdentifier(value, what) {
165
166
  var HELPER_FUNCTIONS = [
166
167
  SEARCH_TEXT_FN,
167
168
  SEARCH_UNACCENT_FN,
168
- SET_UPDATED_AT_FN
169
+ SET_UPDATED_AT_FN,
170
+ KEEP_TENANT_FN
169
171
  ];
172
+ /** A trigger's catalogue key with the arguments it is bound with. */
173
+ var triggerArgumentsKey = (key, args) => `${key}(${JSON.stringify(args)})`;
170
174
  var helperFunctionKey = (schema, name, args) => `${schema}.${name}(${args.replace(/\s+/g, " ").trim().toLowerCase()})`;
171
175
  var describeHelperFunction = (facts) => JSON.stringify([
172
176
  facts.returns.toLowerCase(),
@@ -630,7 +634,18 @@ function diffPlanAgainstCatalogue(plan, existing, options = {}) {
630
634
  }
631
635
  vectorIndexSkipped.push(...table.vector.skipped);
632
636
  }
633
- for (const spec of sortIndexSpecs([...collectionTables, ...junctionTables].flatMap((t) => t.indexes))) {
637
+ const declaredIndexes = sortIndexSpecs([...collectionTables, ...junctionTables].flatMap((t) => t.indexes));
638
+ const adopted = /* @__PURE__ */ new Set();
639
+ for (const adoption of planIndexAdoptions(declaredIndexes, existing.indexShapes ?? [])) {
640
+ adopted.add(`${adoption.schema}.${adoption.to}`);
641
+ actions.push({
642
+ kind: "rename-index",
643
+ target: `${adoption.schema}.${adoption.table}`,
644
+ sql: indexAdoptionStatement(adoption)
645
+ });
646
+ }
647
+ for (const spec of declaredIndexes) {
648
+ if (adopted.has(`${spec.schema}.${spec.indexName}`)) continue;
634
649
  if (toBuilder(spec.schema, spec.table, spec.derived === "foreign-key")) {
635
650
  deferIndex({
636
651
  schema: spec.schema,
@@ -655,7 +670,8 @@ function diffPlanAgainstCatalogue(plan, existing, options = {}) {
655
670
  });
656
671
  }
657
672
  for (const table of collectionTables) for (const trigger of table.triggers) {
658
- if (existing.triggers?.has(`${table.qualified}.${trigger.name}`)) continue;
673
+ const key = `${table.qualified}.${trigger.name}`;
674
+ if (trigger.kind === "keep-tenant" ? existing.triggers?.has(triggerArgumentsKey(key, keepTenantArguments(trigger))) : existing.triggers?.has(key)) continue;
659
675
  for (const statement of triggerStatements(trigger)) actions.push({
660
676
  kind: "create-trigger",
661
677
  target: `${table.qualified}.${trigger.name}`,
@@ -1075,6 +1091,6 @@ function scheduleDeferredIndexBuild(openSession, indexes, options = {}) {
1075
1091
  };
1076
1092
  }
1077
1093
  //#endregion
1078
- export { assertSafeIdentifier as a, helperFunctionKey as c, HELPER_FUNCTIONS as i, columnTypeDriftMessage as l, buildDeferredIndexes as n, describeHelperFunction as o, deferred_index_build_exports as r, diffPlanAgainstCatalogue as s, TABLE_BUSY_REASON as t, typesAgree as u };
1094
+ export { assertSafeIdentifier as a, helperFunctionKey as c, typesAgree as d, HELPER_FUNCTIONS as i, triggerArgumentsKey as l, buildDeferredIndexes as n, describeHelperFunction as o, deferred_index_build_exports as r, diffPlanAgainstCatalogue as s, TABLE_BUSY_REASON as t, columnTypeDriftMessage as u };
1079
1095
 
1080
- //# sourceMappingURL=deferred-index-build-F2GWu009.js.map
1096
+ //# sourceMappingURL=deferred-index-build-DDdnjaOW.js.map