@rebasepro/server-postgres 0.23.0 → 0.24.1-canary.g56af4a4

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 (180) hide show
  1. package/dist/{BranchService-DGPL6G_C.js → BranchService-Bsn2wfaj.js} +36 -18
  2. package/dist/BranchService-Bsn2wfaj.js.map +1 -0
  3. package/dist/PostgresBackendDriver.d.ts +166 -13
  4. package/dist/auth/ensure-tables.d.ts +12 -0
  5. package/dist/auth/services.d.ts +78 -14
  6. package/dist/{auth-users-columns-D2LBFrMH.js → auth-users-columns-C72EMoDJ.js} +17 -1
  7. package/dist/{auth-users-columns-D2LBFrMH.js.map → auth-users-columns-C72EMoDJ.js.map} +1 -1
  8. package/dist/backup/backup-cli.d.ts +14 -0
  9. package/dist/backup/backup-service.d.ts +2 -2
  10. package/dist/backup/pg-binary.d.ts +5 -0
  11. package/dist/{backup-cli-24v4OlSp.js → backup-cli-aUfRv16h.js} +37 -29
  12. package/dist/backup-cli-aUfRv16h.js.map +1 -0
  13. package/dist/{backup-service-HQ9GC4tN.js → backup-service-BTBB7RXn.js} +60 -28
  14. package/dist/backup-service-BTBB7RXn.js.map +1 -0
  15. package/dist/boot-ddl-DVpsFN6r.js +105 -0
  16. package/dist/boot-ddl-DVpsFN6r.js.map +1 -0
  17. package/dist/cli-errors-CaI4ntyD.js +1919 -0
  18. package/dist/cli-errors-CaI4ntyD.js.map +1 -0
  19. package/dist/cli-errors.d.ts +93 -5
  20. package/dist/{cli-flags-BglvpjHv.js → cli-flags-B-Dawocl.js} +5 -2
  21. package/dist/cli-flags-B-Dawocl.js.map +1 -0
  22. package/dist/cli-helpers.d.ts +52 -12
  23. package/dist/cli-output.d.ts +16 -28
  24. package/dist/cli-push.d.ts +87 -0
  25. package/dist/cli.js +625 -190
  26. package/dist/cli.js.map +1 -1
  27. package/dist/{column-plan-helpers-DF-8dTVa.js → column-plan-helpers-drZIsSNf.js} +42 -26
  28. package/dist/column-plan-helpers-drZIsSNf.js.map +1 -0
  29. package/dist/{databasePoolManager-Bj5FbeAs.js → connection-BPoNILnD.js} +19 -110
  30. package/dist/connection-BPoNILnD.js.map +1 -0
  31. package/dist/connection.d.ts +9 -1
  32. package/dist/data-transformer.d.ts +0 -8
  33. package/dist/databasePoolManager-BkEy2w18.js +119 -0
  34. package/dist/databasePoolManager-BkEy2w18.js.map +1 -0
  35. package/dist/deferred-index-build-DP1_SNFo.js +1051 -0
  36. package/dist/deferred-index-build-DP1_SNFo.js.map +1 -0
  37. package/dist/{doctor-Cb2thZ8s.js → doctor-C4WiftHm.js} +279 -87
  38. package/dist/doctor-C4WiftHm.js.map +1 -0
  39. package/dist/ensure-collection-policies-CXpbeNag.js +541 -0
  40. package/dist/ensure-collection-policies-CXpbeNag.js.map +1 -0
  41. package/dist/ensure-collection-tables-BhsU6qUE.js +532 -0
  42. package/dist/ensure-collection-tables-BhsU6qUE.js.map +1 -0
  43. package/dist/{ensure-tables-Dhn9KM3B.js → ensure-tables-CHsgyLqg.js} +178 -75
  44. package/dist/ensure-tables-CHsgyLqg.js.map +1 -0
  45. package/dist/enum-labels-kept-D8fI1MoX.js +56 -0
  46. package/dist/enum-labels-kept-D8fI1MoX.js.map +1 -0
  47. package/dist/generate-drizzle-schema-Bz52jH2h.js +57 -0
  48. package/dist/generate-drizzle-schema-Bz52jH2h.js.map +1 -0
  49. package/dist/{generate-drizzle-schema-logic-BfzK7UQd.js → generate-drizzle-schema-logic-B74WN37S.js} +28 -10
  50. package/dist/generate-drizzle-schema-logic-B74WN37S.js.map +1 -0
  51. package/dist/generate-files-CdEckX6c.js +199 -0
  52. package/dist/generate-files-CdEckX6c.js.map +1 -0
  53. package/dist/generate-postgres-ddl-logic-B64O2oZF.js +152 -0
  54. package/dist/generate-postgres-ddl-logic-B64O2oZF.js.map +1 -0
  55. package/dist/generated-sql.d.ts +34 -0
  56. package/dist/history/HistoryService.d.ts +38 -6
  57. package/dist/history/ensure-history-table.d.ts +42 -4
  58. package/dist/index.es.js +5557 -7612
  59. package/dist/index.es.js.map +1 -1
  60. package/dist/{introspect-db-logic-WMuAfxvw.js → introspect-db-logic-C-Di8dA9.js} +562 -350
  61. package/dist/introspect-db-logic-C-Di8dA9.js.map +1 -0
  62. package/dist/introspect-db-queries-D6kAqReI.js +339 -0
  63. package/dist/introspect-db-queries-D6kAqReI.js.map +1 -0
  64. package/dist/pg-error-utils-vJezlXdI.js +388 -0
  65. package/dist/pg-error-utils-vJezlXdI.js.map +1 -0
  66. package/dist/{plan-schema-C0fxM8dY.js → plan-schema-B1YF_tYq.js} +278 -533
  67. package/dist/plan-schema-B1YF_tYq.js.map +1 -0
  68. package/dist/{policy-drift-DljYdrpW.js → policy-drift-Dm8i-s1J.js} +24 -7
  69. package/dist/policy-drift-Dm8i-s1J.js.map +1 -0
  70. package/dist/push-index-prebuild-Db4AQF4i.js +45 -0
  71. package/dist/push-index-prebuild-Db4AQF4i.js.map +1 -0
  72. package/dist/push-legacy-renames-BK6ilQq2.js +34 -0
  73. package/dist/push-legacy-renames-BK6ilQq2.js.map +1 -0
  74. package/dist/{generate-postgres-ddl-logic-Bt2d2mRH.js → render-ddl-CtC3y9Ol.js} +17 -151
  75. package/dist/render-ddl-CtC3y9Ol.js.map +1 -0
  76. package/dist/{rls-bootstrap-sql-B8EclDyM.js → rls-bootstrap-sql-RQUljnJ1.js} +125 -1046
  77. package/dist/rls-bootstrap-sql-RQUljnJ1.js.map +1 -0
  78. package/dist/{rls-enforcement-C6Xk0lA6.js → rls-enforcement-DvzqlaL1.js} +137 -17
  79. package/dist/rls-enforcement-DvzqlaL1.js.map +1 -0
  80. package/dist/schema/auth-schema.d.ts +172 -2
  81. package/dist/schema/boot-ddl.d.ts +47 -0
  82. package/dist/schema/classify-change.d.ts +29 -1
  83. package/dist/schema/collection-index.d.ts +45 -0
  84. package/dist/schema/column-plan-helpers.d.ts +38 -21
  85. package/dist/schema/deferred-index-build.d.ts +131 -0
  86. package/dist/schema/destructive-sql.d.ts +27 -1
  87. package/dist/schema/doctor-cli.js +110 -6
  88. package/dist/schema/doctor-cli.js.map +1 -1
  89. package/dist/schema/doctor-search-scale.d.ts +45 -0
  90. package/dist/schema/doctor.d.ts +53 -1
  91. package/dist/schema/ensure-collection-policies.d.ts +95 -35
  92. package/dist/schema/ensure-collection-tables.d.ts +56 -3
  93. package/dist/schema/enum-labels-kept.d.ts +26 -0
  94. package/dist/schema/generate-drizzle-schema.js +1 -1
  95. package/dist/schema/generate-files.d.ts +44 -0
  96. package/dist/schema/generate-next-step.d.ts +0 -13
  97. package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -5
  98. package/dist/schema/generate-postgres-ddl.js +10 -81
  99. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  100. package/dist/schema/generate-schema-commit.d.ts +12 -0
  101. package/dist/schema/introspect-db-logic.d.ts +43 -0
  102. package/dist/schema/introspect-db-queries.d.ts +12 -2
  103. package/dist/schema/introspect-db-search.d.ts +22 -0
  104. package/dist/schema/introspect-db-storage.d.ts +83 -0
  105. package/dist/schema/introspect-db-structure.d.ts +10 -0
  106. package/dist/schema/introspect-db.js +17 -6
  107. package/dist/schema/introspect-db.js.map +1 -1
  108. package/dist/schema/migration-post-process.d.ts +34 -0
  109. package/dist/schema/plan/diff-plan.d.ts +127 -1
  110. package/dist/schema/plan/plan-schema.d.ts +16 -8
  111. package/dist/schema/plan/render-ddl.d.ts +6 -0
  112. package/dist/schema/plan/types.d.ts +45 -11
  113. package/dist/schema/push-index-prebuild.d.ts +25 -0
  114. package/dist/schema/push-legacy-renames.d.ts +20 -0
  115. package/dist/schema/rls-bootstrap-sql.d.ts +15 -0
  116. package/dist/search-column-BM-GV6vH.js +442 -0
  117. package/dist/search-column-BM-GV6vH.js.map +1 -0
  118. package/dist/security/policy-drift.d.ts +1 -1
  119. package/dist/security/rls-enforcement.d.ts +39 -4
  120. package/dist/services/BranchService.d.ts +22 -1
  121. package/dist/services/FetchService.d.ts +63 -12
  122. package/dist/services/PersistService.d.ts +15 -0
  123. package/dist/services/RelationService.d.ts +106 -3
  124. package/dist/services/cdc/CdcListener.d.ts +26 -10
  125. package/dist/services/cdc/identity-columns.d.ts +19 -0
  126. package/dist/services/cdc/trigger-cdc.d.ts +180 -18
  127. package/dist/services/channel-bus/PostgresChannelBus.d.ts +12 -7
  128. package/dist/services/channel-history.d.ts +32 -5
  129. package/dist/services/collection-helpers.d.ts +26 -1
  130. package/dist/services/field-viewer.d.ts +15 -1
  131. package/dist/services/pg-notify-listener.d.ts +95 -6
  132. package/dist/services/realtimeService.d.ts +467 -53
  133. package/dist/services/row-pipeline.d.ts +16 -9
  134. package/dist/services/socket-liveness.d.ts +85 -0
  135. package/dist/services/soft-delete.d.ts +12 -0
  136. package/dist/services/sql-script.d.ts +275 -0
  137. package/dist/services/vector-iterative-scan.d.ts +40 -0
  138. package/dist/services/write-depth.d.ts +22 -0
  139. package/dist/services/write-transaction-scope.d.ts +15 -3
  140. package/dist/socket-liveness-D3UD5_BW.js +7570 -0
  141. package/dist/socket-liveness-D3UD5_BW.js.map +1 -0
  142. package/dist/socket-opt-ins.d.ts +64 -0
  143. package/dist/source-DBDbBTL4.js +811 -0
  144. package/dist/source-DBDbBTL4.js.map +1 -0
  145. package/dist/tsx-loader.d.ts +14 -0
  146. package/dist/utils/drizzle-conditions.d.ts +63 -3
  147. package/dist/utils/error-cause.d.ts +7 -0
  148. package/dist/utils/pg-error-utils.d.ts +2 -4
  149. package/dist/utils/result-rows.d.ts +10 -0
  150. package/dist/websocket.d.ts +63 -18
  151. package/package.json +7 -7
  152. package/dist/BranchService-DGPL6G_C.js.map +0 -1
  153. package/dist/backup-cli-24v4OlSp.js.map +0 -1
  154. package/dist/backup-service-HQ9GC4tN.js.map +0 -1
  155. package/dist/cli-errors-B8qHg02P.js +0 -798
  156. package/dist/cli-errors-B8qHg02P.js.map +0 -1
  157. package/dist/cli-flags-BglvpjHv.js.map +0 -1
  158. package/dist/cli-output-CNdMql-L.js +0 -47
  159. package/dist/cli-output-CNdMql-L.js.map +0 -1
  160. package/dist/collection-index-DdnsxiJ_.js +0 -286
  161. package/dist/collection-index-DdnsxiJ_.js.map +0 -1
  162. package/dist/column-plan-helpers-DF-8dTVa.js.map +0 -1
  163. package/dist/databasePoolManager-Bj5FbeAs.js.map +0 -1
  164. package/dist/doctor-Cb2thZ8s.js.map +0 -1
  165. package/dist/ensure-collection-policies-RHUcEp4v.js +0 -105
  166. package/dist/ensure-collection-policies-RHUcEp4v.js.map +0 -1
  167. package/dist/ensure-collection-tables-BEEjn5cn.js +0 -857
  168. package/dist/ensure-collection-tables-BEEjn5cn.js.map +0 -1
  169. package/dist/ensure-tables-Dhn9KM3B.js.map +0 -1
  170. package/dist/generate-drizzle-schema-logic-BfzK7UQd.js.map +0 -1
  171. package/dist/generate-drizzle-schema-yzY_BLhr.js +0 -123
  172. package/dist/generate-drizzle-schema-yzY_BLhr.js.map +0 -1
  173. package/dist/generate-postgres-ddl-logic-Bt2d2mRH.js.map +0 -1
  174. package/dist/introspect-db-logic-WMuAfxvw.js.map +0 -1
  175. package/dist/plan-schema-C0fxM8dY.js.map +0 -1
  176. package/dist/policy-drift-DljYdrpW.js.map +0 -1
  177. package/dist/rls-bootstrap-sql-B8EclDyM.js.map +0 -1
  178. package/dist/rls-enforcement-C6Xk0lA6.js.map +0 -1
  179. package/dist/source-Br7L7GOI.js +0 -410
  180. package/dist/source-Br7L7GOI.js.map +0 -1
@@ -4,7 +4,7 @@ import { r as __exportAll } from "./__vite-browser-external-BnuHet1e.js";
4
4
  import { logger } from "@rebasepro/server";
5
5
  import { sql } from "drizzle-orm";
6
6
  import { ANONYMOUS_USER_ID, REBASE_SCHEMA, usesLegacyRlsFunctions } from "@rebasepro/types";
7
- import { REBASE_USER_ROLE as REBASE_USER_ROLE$1, findAnonymousGrants, revokeInternalTableAccess, securityRuleToConditions } from "@rebasepro/common";
7
+ import { REBASE_INTERNAL_TABLES, REBASE_USER_ROLE as REBASE_USER_ROLE$1, findAnonymousGrants, revokeInternalTableAccess, securityRuleToConditions } from "@rebasepro/common";
8
8
  //#region src/security/rls-enforcement.ts
9
9
  var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
10
10
  REBASE_USER_ROLE: () => REBASE_USER_ROLE$1,
@@ -12,6 +12,9 @@ var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
12
12
  applyAuthContext: () => applyAuthContext,
13
13
  detectConnectionPosture: () => detectConnectionPosture,
14
14
  ensureAppRole: () => ensureAppRole,
15
+ ensureAppRoleGrants: () => ensureAppRoleGrants,
16
+ internalTablesGrantedToUserRole: () => internalTablesGrantedToUserRole,
17
+ revokeUserRoleSql: () => revokeUserRoleSql,
15
18
  validatePolicyPgRoles: () => validatePolicyPgRoles,
16
19
  warnOnAnonymousGrants: () => warnOnAnonymousGrants,
17
20
  warnOnLegacyRlsFunctions: () => warnOnLegacyRlsFunctions,
@@ -21,6 +24,13 @@ var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
21
24
  /** DML the user role holds on managed tables (RLS still filters per row). */
22
25
  var USER_TABLE_PRIVILEGES = "SELECT, INSERT, UPDATE, DELETE";
23
26
  /**
27
+ * Take every privilege the user role holds on one table back — what a table
28
+ * gets when RLS cannot be switched on for it, so it is unreachable rather than
29
+ * unprotected. Quoted exactly: a mixed-case adopted table (`"User"`) folded to
30
+ * lower case names a table that does not exist.
31
+ */
32
+ var revokeUserRoleSql = (schema, table) => `REVOKE ALL PRIVILEGES ON ${quoteIdent(schema)}.${quoteIdent(table)} FROM ${quoteIdent(REBASE_USER_ROLE$1)}`;
33
+ /**
24
34
  * Warn when the connection role shares its name with an existing schema.
25
35
  *
26
36
  * Postgres resolves unqualified names through `search_path`, which defaults to
@@ -165,27 +175,137 @@ async function ensureAppRole(run, schemas) {
165
175
  } catch (err) {
166
176
  throw new Error(`The connection role is not a member of "${REBASE_USER_ROLE$1}" and cannot grant itself membership: ${err instanceof Error ? err.message : String(err)}\n\n` + appRoleSetupInstructions(String(memberRows[0]?.role ?? "current connection role"), uniqueSchemas));
167
177
  }
168
- const nspRows = await run("SELECT nspname FROM pg_namespace");
169
- const existing = new Set(nspRows.map((r) => String(r.nspname)));
178
+ await ensureAppRoleGrants(run, uniqueSchemas);
179
+ logger.debug(`🔐 [rls] User role "${REBASE_USER_ROLE$1}" provisioned (schemas: ${uniqueSchemas.join(", ")})`);
180
+ }
181
+ /** A string literal for a catalogue read. Names come from config and constants, never from a request. */
182
+ var sqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
183
+ var textArray = (values) => values.length === 0 ? "ARRAY[]::text[]" : `ARRAY[${values.map(sqlLiteral).join(", ")}]::text[]`;
184
+ /**
185
+ * The grant tier's state for every existing schema in `schemas`, in one read.
186
+ *
187
+ * A grant counts as present only as the statement this tier runs would record
188
+ * it — grantor the object's owner, which is what a GRANT by the owner, a member
189
+ * of the owning role or a superuser records — so skipping it leaves the ACL
190
+ * exactly as running it would. Anything else reads as missing, and the
191
+ * statement runs as it always did.
192
+ */
193
+ async function readSchemaGrants(run, schemas) {
194
+ const internal = textArray(REBASE_INTERNAL_TABLES);
195
+ const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(REBASE_USER_ROLE$1)})`;
196
+ /** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */
197
+ const held = (acl, privileges, grantor) => `(SELECT count(DISTINCT a.privilege_type) FROM aclexplode(${acl}) a WHERE a.grantee = ${target}${grantor ? ` AND a.grantor = ${grantor}` : ""} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(", ")}))`;
198
+ const DML = [
199
+ "SELECT",
200
+ "INSERT",
201
+ "UPDATE",
202
+ "DELETE"
203
+ ];
204
+ const SEQ = ["USAGE", "SELECT"];
205
+ const rows = await run(`
206
+ SELECT n.nspname AS schema,
207
+ ${held("n.nspacl", ["USAGE"], "n.nspowner")} = 1 AS usage,
208
+ NOT EXISTS (
209
+ SELECT 1 FROM pg_class c
210
+ WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')
211
+ AND NOT (c.relname = ANY(${internal}) AND NOT c.relrowsecurity)
212
+ AND ${held("c.relacl", DML, "c.relowner")} < ${DML.length}
213
+ ) AS tables,
214
+ NOT EXISTS (
215
+ SELECT 1 FROM pg_class c
216
+ WHERE c.relnamespace = n.oid AND c.relkind = 'S'
217
+ AND ${held("c.relacl", SEQ, "c.relowner")} < ${SEQ.length}
218
+ ) AS sequences,
219
+ EXISTS (
220
+ SELECT 1 FROM pg_default_acl d
221
+ WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
222
+ AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'r'
223
+ AND ${held("d.defaclacl", DML)} = ${DML.length}
224
+ ) AS default_tables,
225
+ EXISTS (
226
+ SELECT 1 FROM pg_default_acl d
227
+ WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
228
+ AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'S'
229
+ AND ${held("d.defaclacl", SEQ)} = ${SEQ.length}
230
+ ) AS default_sequences,
231
+ ARRAY(
232
+ SELECT c.relname::text FROM pg_class c
233
+ WHERE c.relnamespace = n.oid AND c.relname = ANY(${internal}) AND NOT c.relrowsecurity
234
+ AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))
235
+ ORDER BY 1
236
+ ) AS internal_granted
237
+ FROM pg_namespace n
238
+ WHERE n.nspname = ANY(${textArray(schemas)})
239
+ `);
240
+ const grants = /* @__PURE__ */ new Map();
241
+ for (const row of rows) {
242
+ const internalGranted = row.internal_granted;
243
+ grants.set(String(row.schema), {
244
+ usage: row.usage === true,
245
+ tables: row.tables === true,
246
+ sequences: row.sequences === true,
247
+ defaultTables: row.default_tables === true,
248
+ defaultSequences: row.default_sequences === true,
249
+ internalGranted: Array.isArray(internalGranted) ? internalGranted.map(String) : String(internalGranted ?? "").replace(/^\{|\}$/g, "").split(",").filter(Boolean)
250
+ });
251
+ }
252
+ return grants;
253
+ }
254
+ /**
255
+ * The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing
256
+ * schema in `schemas`, DML on its tables and `USAGE, SELECT` on its
257
+ * sequences, the default privileges that cover what this role creates later,
258
+ * and Rebase's own tables taken back — for a role and membership already
259
+ * provisioned.
260
+ *
261
+ * Every statement is issued only when the catalogue says it would change
262
+ * something. They used to run unconditionally, twice per boot (at connect, and
263
+ * again in the final posture check): a `GRANT … ON ALL TABLES` rewrites every
264
+ * table's `pg_class` row whether or not the ACL changes, which invalidates
265
+ * every table's cached plans on every connection, and the internal-table sweep
266
+ * ran 23 `REVOKE`s per schema. A boot against a database whose grants already
267
+ * hold now reads one catalogue query and writes nothing; one that is missing
268
+ * any of them runs exactly the statements it always ran.
269
+ *
270
+ * Table owners (the expected non-superuser posture) can always grant on their
271
+ * own objects, so this needs no extra privilege.
272
+ */
273
+ async function ensureAppRoleGrants(run, schemas) {
274
+ const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));
275
+ const grants = await readSchemaGrants(run, uniqueSchemas);
170
276
  for (const schema of uniqueSchemas) {
171
- if (!existing.has(schema)) continue;
277
+ const state = grants.get(schema);
278
+ if (!state) continue;
172
279
  const s = quoteIdent(schema);
173
- await run(`GRANT USAGE ON SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
174
- await run(`GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
175
- await run(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
176
- await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${REBASE_USER_ROLE$1}`);
177
- await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${REBASE_USER_ROLE$1}`);
280
+ if (!state.usage) await run(`GRANT USAGE ON SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
281
+ if (!state.tables) await run(`GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
282
+ if (!state.sequences) await run(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
283
+ if (!state.defaultTables) await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${REBASE_USER_ROLE$1}`);
284
+ if (!state.defaultSequences) await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${REBASE_USER_ROLE$1}`);
285
+ const tables = state.tables ? state.internalGranted : void 0;
286
+ if (tables && tables.length === 0) continue;
178
287
  await revokeInternalTableAccess(async (text) => {
179
288
  await run(text);
180
- }, schema, { onError: (table, error) => logger.warn(`🔐 [rls] Could not revoke "${REBASE_USER_ROLE$1}" access to "${schema}"."${table}" — it stays reachable by authenticated requests: ` + (error instanceof Error ? error.message : String(error))) });
289
+ }, schema, {
290
+ tables,
291
+ onError: (table, error) => logger.warn(`🔐 [rls] Could not revoke "${REBASE_USER_ROLE$1}" access to "${schema}"."${table}" — it stays reachable by authenticated requests: ` + (error instanceof Error ? error.message : String(error)))
292
+ });
181
293
  }
182
- logger.debug(`🔐 [rls] User role "${REBASE_USER_ROLE$1}" provisioned (schemas: ${uniqueSchemas.join(", ")})`);
294
+ }
295
+ /**
296
+ * Rebase's own RLS-off tables in `schema` that a `revokeInternalTableAccess`
297
+ * sweep would change — the user role holds a privilege on them, or their ACL
298
+ * has never been written. One read; the sweep it narrows is one `DO` per
299
+ * table name.
300
+ */
301
+ async function internalTablesGrantedToUserRole(run, schema) {
302
+ return (await readSchemaGrants(run, [schema])).get(schema)?.internalGranted ?? [];
183
303
  }
184
304
  /**
185
305
  * Apply the authenticated context to a transaction: the `app.*` GUCs that RLS
186
306
  * policies read via `rebase.uid()` / `rebase.roles()` / `rebase.jwt()`, and — when
187
- * `userRole` is set — `SET LOCAL ROLE` so RLS binds every statement in this
188
- * transaction (reads *and* writes).
307
+ * `userRole` is set — the `LOCAL` role switch, in the same statement, so RLS
308
+ * binds every statement in this transaction (reads *and* writes).
189
309
  *
190
310
  * GUCs are set with `is_local = true` and the role switch is `LOCAL`: both
191
311
  * reset at commit/rollback, so pooled connections are never polluted.
@@ -218,9 +338,9 @@ async function applyAuthContext(tx, auth, userRole) {
218
338
  sub: uid,
219
339
  roles: auth.roles,
220
340
  is_anonymous: auth.isAnonymous === true
221
- })}, true)
341
+ })}, true)${userRole ? sql`,
342
+ set_config('role', ${userRole}, true)` : sql``}
222
343
  `);
223
- if (userRole) await tx.execute(sql.raw(`SET LOCAL ROLE ${quoteIdent(userRole)}`));
224
344
  }
225
345
  /** Role names from other BaaS platforms that people reach for out of habit. */
226
346
  var FOREIGN_CONVENTION_ROLES = {
@@ -338,6 +458,6 @@ async function validatePolicyPgRoles(run, collections, requestRole = REBASE_USER
338
458
  if (problems.length > 0) throw new Error(`Security rules target PostgreSQL roles this server cannot use. Requests run as "${requestRole}", so these policies would never apply and every row would be filtered out — the collections would look empty rather than error.\n\n` + problems.join("\n\n") + "\n");
339
459
  }
340
460
  //#endregion
341
- export { rls_enforcement_exports as a, warnOnLegacyRlsFunctions as c, ensureAppRole as i, warnOnRoleSchemaCollision as l, applyAuthContext as n, validatePolicyPgRoles as o, detectConnectionPosture as r, warnOnAnonymousGrants as s, REBASE_USER_ROLE$1 as t };
461
+ export { ensureAppRoleGrants as a, rls_enforcement_exports as c, warnOnLegacyRlsFunctions as d, warnOnRoleSchemaCollision as f, ensureAppRole as i, validatePolicyPgRoles as l, applyAuthContext as n, internalTablesGrantedToUserRole as o, detectConnectionPosture as r, revokeUserRoleSql as s, REBASE_USER_ROLE$1 as t, warnOnAnonymousGrants as u };
342
462
 
343
- //# sourceMappingURL=rls-enforcement-C6Xk0lA6.js.map
463
+ //# sourceMappingURL=rls-enforcement-DvzqlaL1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rls-enforcement-DvzqlaL1.js","names":[],"sources":["../src/security/rls-enforcement.ts"],"sourcesContent":["import { sql as drizzleSql, SQL } from \"drizzle-orm\";\nimport { ANONYMOUS_USER_ID, PolicyExpression, SecurityRule } from \"@rebasepro/types\";\nimport {\n AnonymousGrantRisk,\n findAnonymousGrants,\n REBASE_INTERNAL_TABLES,\n REBASE_USER_ROLE,\n revokeInternalTableAccess,\n securityRuleToConditions\n} from \"@rebasepro/common\";\nimport { REBASE_SCHEMA, usesLegacyRlsFunctions } from \"@rebasepro/types\";\nimport { logger } from \"@rebasepro/server\";\n\n/**\n * Unified RLS enforcement — the \"user context vs server context\" model.\n *\n * Every operation runs in one of two contexts:\n *\n * - **User context** — a request authenticated (or anonymous) via\n * `driver.withAuth(user)`. Runs as the restricted `rebase_user` role: a\n * non-owner, NOSUPERUSER, NOBYPASSRLS role, so Postgres RLS binds *every*\n * statement (SELECT, INSERT, UPDATE, DELETE). The collection's\n * `securityRules` are the whole authorization model; app-layer callbacks\n * are validation/side-effects, not a security boundary.\n *\n * - **Server context** — the base (owner) connection: auth flows, migrations,\n * and raw `rebase.sql`. As table owner it bypasses RLS. This is the trusted\n * plane, equivalent to Supabase's `service_role`.\n *\n * `rebase.dataAsAdmin` is **not** in it, despite the name. `init.ts` scopes\n * that driver with `withAuth(SERVICE_IDENTITY)`, so it arrives as user\n * context above — `rebase_user`, `app.uid = 'service'`, policies evaluated —\n * and clears the default policies through their admin arm rather than the\n * `rebase.uid() IS NULL` one.\n *\n * This module provides the three pieces:\n *\n * 1. {@link detectConnectionPosture} — is the connection subject to RLS at\n * all? (superuser / BYPASSRLS / table owner ⇒ no)\n * 2. {@link ensureAppRole} — idempotently provision `rebase_user` with\n * SELECT/INSERT/UPDATE/DELETE grants (+ default privileges so future\n * tables stay covered).\n * 3. {@link applyAuthContext} — per-transaction: set the `app.*` GUCs the\n * policies read (`rebase.uid()` etc.) and the transaction-local role\n * `rebase_user` so RLS binds, in one statement. Transaction-scoped, so it\n * composes with poolers.\n *\n * Provisioning runs from the framework's own bootstrap/migrate (which already\n * self-creates the `auth` schema and functions) — enforcement is default-on,\n * not an operator opt-in.\n */\n\n/**\n * The restricted role every authenticated (user-context) request runs as.\n *\n * Re-exported, not re-declared: the same name is needed by\n * `@rebasepro/common`'s internal-table revokes, and two spellings of a role name\n * fail as a silent no-op rather than an error.\n */\nexport { REBASE_USER_ROLE };\n\n/** Minimal SQL runner so callers can adapt drizzle or pg.Client. */\nexport type RawSqlRunner = (sqlText: string) => Promise<Record<string, unknown>[]>;\n\n/** Minimal transaction surface needed by {@link applyAuthContext}. */\nexport interface SqlTx {\n execute(query: SQL): Promise<unknown>;\n}\n\nexport interface ConnectionPosture {\n /** The connection's `current_user`. */\n role: string;\n superuser: boolean;\n bypassRLS: boolean;\n /**\n * Owns at least one user table — owners bypass non-FORCE RLS.\n *\n * \"Owns\" in Postgres's sense, not by name: a role that INHERITs the owner is\n * the owner for every ownership test the planner makes, including the one\n * that decides whether a policy applies at all.\n */\n ownsTables: boolean;\n /**\n * May create tables somewhere the server writes — and would then own them.\n *\n * The reason this is part of the posture rather than a separate question:\n * the posture is decided ONCE, at boot, and on a fresh database the\n * catalogue has nothing to report yet. The process that asks then goes on to\n * create every table in the schema and owns all of them for the rest of its\n * life. Asking only what is already there answers about the wrong instant.\n */\n canCreateTables: boolean;\n /** True when RLS would NOT constrain this connection. */\n privileged: boolean;\n}\n\nexport interface AuthContext {\n uid: string;\n /** Raw roles as carried on the user (strings or `{ id }` objects). */\n roles: unknown[];\n /**\n * Whether this session came from anonymous sign-in rather than an account.\n *\n * Anonymous sign-in mints a real user row and a real uid, so a guest was\n * indistinguishable from a registered account inside a policy: same\n * `rebase.uid()`, same default role. Every rule meaning \"a signed-in\n * person\" was therefore also a rule about anybody who had called\n * `POST /auth/anonymous`, which asks for no email, no password and no\n * agreement to anything.\n *\n * Optional, and absent reads as `false`: a caller that predates this — a\n * realtime subscription, a custom validator — keeps the behaviour it had\n * rather than having every one of its users reclassified as guests.\n */\n isAnonymous?: boolean;\n /**\n * The **custom** claims on the caller's token, as `rebase.jwt()` reports\n * them.\n *\n * This is how a policy reaches a fact about the session that is neither the\n * uid nor the roles — which, before this, it could not: `app.jwt` was built\n * from three fields the driver already had, so `rebase.jwt()`, documented\n * as \"full JWT claims as JSONB\", returned a three-key object that never had\n * a claim in it.\n *\n * Multi-tenancy's `claim` form is the first caller — `policy.authClaim(…)`\n * compiles to `rebase.jwt() ->> '<name>'`. Identity claims are stripped out\n * before they reach here (`AccessTokenPayload.claims`) and the identity\n * fields are written *over* them below, so nothing a hook put on a token\n * can assert a uid, roles or guest status.\n */\n claims?: Record<string, unknown>;\n}\n\nconst quoteIdent = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** DML the user role holds on managed tables (RLS still filters per row). */\nconst USER_TABLE_PRIVILEGES = \"SELECT, INSERT, UPDATE, DELETE\";\n\n/**\n * Take every privilege the user role holds on one table back — what a table\n * gets when RLS cannot be switched on for it, so it is unreachable rather than\n * unprotected. Quoted exactly: a mixed-case adopted table (`\"User\"`) folded to\n * lower case names a table that does not exist.\n */\nexport const revokeUserRoleSql = (schema: string, table: string): string =>\n `REVOKE ALL PRIVILEGES ON ${quoteIdent(schema)}.${quoteIdent(table)} FROM ${quoteIdent(REBASE_USER_ROLE)}`;\n\n/**\n * Warn when the connection role shares its name with an existing schema.\n *\n * Postgres resolves unqualified names through `search_path`, which defaults to\n * `\"$user\", public` — and `$user` is the connection ROLE. When a schema of that\n * name exists it sits ahead of `public`, so every unqualified statement\n * silently operates on it instead:\n *\n * CREATE TABLE posts (...); -- you meant public.posts; you got <role>.posts\n *\n * Nothing errors. You get a second table of the same name in the wrong schema,\n * and reads that pin `public` cannot see it — which reads as \"missing table\" and\n * sends people to re-run a push that creates a *third* copy. The bootstrapper\n * has a whole branch dedicated to recognising the symptom after the fact.\n *\n * Rebase shipped straight into this: it creates a schema named `rebase` while\n * every template named the database role `rebase` too. The scaffold uses\n * `rebase_app` now, and every pool Rebase opens pins `search_path=public`\n * (`pinSearchPath`), which covers the paths the framework controls. This covers\n * the ones it does not — `psql`, `pg_dump`, drizzle-kit, a colleague's script,\n * a hand-written migration — because the hazard is a property of the two NAMES,\n * not of any one connection.\n *\n * A warning rather than a boot failure: the database works, the framework's own\n * traffic is pinned, and refusing to start over a naming choice a user may have\n * inherited would be worse than the risk.\n */\nexport async function warnOnRoleSchemaCollision(run: RawSqlRunner): Promise<void> {\n try {\n const rows = await run(`\n SELECT current_user AS role,\n EXISTS (\n SELECT 1 FROM pg_namespace n WHERE n.nspname = current_user\n ) AS collides\n `);\n if (rows[0]?.collides !== true) return;\n const role = String(rows[0]?.role ?? \"the connection role\");\n logger.warn(\n `⚠️ The database role \"${role}\" has the same name as a schema. Postgres resolves unqualified ` +\n `names through \\`search_path\\`, which defaults to \\`\"$user\", public\\` — so \"${role}\" is searched ` +\n `BEFORE public, and any unqualified \\`CREATE TABLE\\`/\\`SELECT\\` from a tool that does not pin the ` +\n `path (psql, pg_dump, drizzle-kit, a hand-written migration) silently lands in \"${role}\" instead. ` +\n `Rebase's own connections pin \\`search_path=public\\`, so the server is unaffected. To remove the ` +\n `hazard entirely, connect as a role whose name is not also a schema — the scaffold uses ` +\n `\"rebase_app\".`\n );\n } catch {\n // A diagnostic must never be the reason a boot fails.\n }\n}\n\n/**\n * Would RLS actually constrain this connection?\n *\n * Four ways the answer is no, and only two of them are obvious. Superuser and\n * BYPASSRLS announce themselves in `pg_roles`. The other two are about\n * ownership, and both used to read as \"no bypass here\":\n *\n * - **Ownership through membership.** The old query compared\n * `pg_tables.tableowner` to `current_user` as a string. Postgres does not: a\n * role that INHERITs the owner passes every ownership test the planner makes,\n * including the one that decides whether a policy applies. So a perfectly\n * ordinary \"app role that is a member of the owner role\" setup reported\n * unprivileged and bypassed every policy — permanently, since no restart\n * changes a string comparison's answer.\n *\n * - **Ownership that has not happened yet.** The posture is decided once, at\n * boot, and on a fresh database there is nothing in the catalogue to find. The\n * same process then creates every table and owns all of them. The first boot\n * of a new deployment therefore served every request unconstrained, the log\n * said RLS was fine, and the SECOND boot silently fixed it — which is the\n * worst possible shape for a security check, because the state that reproduces\n * it is gone by the time anyone looks. Asking \"may this role create tables\n * where the server provisions?\" answers about the process's whole life rather\n * than about one instant of it.\n *\n * `schemas` narrows the CREATE question to where the server actually writes.\n * Omitted, it asks about every schema the role can see, which is the safe\n * direction: over-reporting costs a role switch that was not strictly needed,\n * under-reporting costs the entire authorization model.\n */\nexport async function detectConnectionPosture(\n run: RawSqlRunner,\n schemas?: string[]\n): Promise<ConnectionPosture> {\n // Identifiers, and they reach SQL as literals in a catalogue comparison —\n // but they arrive from collection configs, so they are quoted as string\n // literals rather than interpolated as names, and a quote inside one is\n // escaped rather than trusted.\n const schemaFilter = schemas?.length\n ? `AND n.nspname IN (${Array.from(new Set(schemas))\n .map((s) => `'${s.replace(/'/g, \"''\")}'`)\n .join(\", \")})`\n : \"\";\n\n const rows = await run(`\n SELECT current_user AS role,\n r.rolsuper AS superuser,\n r.rolbypassrls AS bypassrls,\n EXISTS (\n SELECT 1 FROM pg_tables t\n WHERE pg_has_role(current_user, t.tableowner, 'USAGE')\n AND t.schemaname NOT IN ('pg_catalog', 'information_schema')\n ) AS owns_tables,\n EXISTS (\n SELECT 1 FROM pg_namespace n\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND n.nspname NOT LIKE 'pg\\\\_toast%'\n AND n.nspname NOT LIKE 'pg\\\\_temp%'\n ${schemaFilter}\n AND has_schema_privilege(current_user, n.oid, 'CREATE')\n ) AS can_create\n FROM pg_roles r\n WHERE r.rolname = current_user\n `);\n const row = rows[0] ?? {};\n const superuser = row.superuser === true;\n const bypassRLS = row.bypassrls === true;\n const ownsTables = row.owns_tables === true;\n const canCreateTables = row.can_create === true;\n return {\n role: String(row.role ?? \"unknown\"),\n superuser,\n bypassRLS,\n ownsTables,\n canCreateTables,\n privileged: superuser || bypassRLS || ownsTables || canCreateTables\n };\n}\n\n/**\n * Human-actionable instructions for when the connection cannot provision the\n * user role itself (no CREATEROLE and role not pre-created by the platform).\n */\nexport function appRoleSetupInstructions(connectionRole: string, schemas: string[]): string {\n const grants = schemas.map((s) =>\n `GRANT USAGE ON SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};\\n` +\n `GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};\\n` +\n `GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};`\n ).join(\"\\n\");\n return (\n `Rebase enforces row-level security by running authenticated requests as ` +\n `the restricted role \"${REBASE_USER_ROLE}\", but the connection role ` +\n `\"${connectionRole}\" bypasses RLS and cannot create that role itself.\\n` +\n `Run the following as a database administrator, then restart:\\n\\n` +\n `CREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\\n` +\n `GRANT ${REBASE_USER_ROLE} TO ${quoteIdent(connectionRole)};\\n` +\n grants\n );\n}\n\n/**\n * Idempotently provision the `rebase_user` role, membership for the current\n * connection role, and DML grants (+ default privileges for future tables)\n * on every existing schema in `schemas`.\n *\n * Split into privilege tiers so it works both when the connection is a\n * superuser (creates everything) and when the platform pre-created the role\n * and membership (e.g. CNPG `postInitApplicationSQL`) and the connection is\n * merely the table owner — owners can always run the grant tier themselves.\n *\n * RLS still filters every row: these grants only make the tables *reachable*\n * by the role; the policies decide which rows/commands actually pass.\n *\n * Throws with precise setup instructions when the role is missing and the\n * connection cannot create it.\n */\nexport async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promise<void> {\n const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));\n\n // Tier 1 — role existence.\n const roleRows = await run(`SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}'`);\n if (roleRows.length === 0) {\n try {\n await run(`CREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT`);\n } catch (err) {\n throw new Error(\n `Failed to create the \"${REBASE_USER_ROLE}\" role: ${err instanceof Error ? err.message : String(err)}\\n\\n` +\n appRoleSetupInstructions(\"current connection role\", uniqueSchemas)\n );\n }\n }\n\n // Tier 2 — membership, so a non-superuser connection may SET ROLE to it.\n const memberRows = await run(`\n SELECT (pg_has_role(current_user, '${REBASE_USER_ROLE}', 'MEMBER')\n OR (SELECT rolsuper FROM pg_roles WHERE rolname = current_user)) AS can_set,\n current_user AS role\n `);\n if (memberRows[0]?.can_set !== true) {\n try {\n await run(`GRANT ${REBASE_USER_ROLE} TO CURRENT_USER`);\n } catch (err) {\n throw new Error(\n `The connection role is not a member of \"${REBASE_USER_ROLE}\" and cannot grant itself membership: ` +\n `${err instanceof Error ? err.message : String(err)}\\n\\n` +\n appRoleSetupInstructions(String(memberRows[0]?.role ?? \"current connection role\"), uniqueSchemas)\n );\n }\n }\n\n // Tier 3 — grants.\n await ensureAppRoleGrants(run, uniqueSchemas);\n\n logger.debug(`🔐 [rls] User role \"${REBASE_USER_ROLE}\" provisioned (schemas: ${uniqueSchemas.join(\", \")})`);\n}\n\n/** A string literal for a catalogue read. Names come from config and constants, never from a request. */\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[]`;\n\n/** What the grant tier would find already in place in one schema. */\ninterface SchemaGrants {\n /** `USAGE` on the schema, granted by its owner. */\n usage: boolean;\n /**\n * Every relation `GRANT … ON ALL TABLES` reaches already has all four DML\n * privileges from its owner — Rebase's own RLS-off tables aside, which the\n * sweep takes back right after and so never keep them.\n */\n tables: boolean;\n /** Every sequence already has `USAGE, SELECT` from its owner. */\n sequences: boolean;\n /** This role's default privileges in the schema already grant the table DML. */\n defaultTables: boolean;\n /** …and the sequence `USAGE, SELECT`. */\n defaultSequences: boolean;\n /**\n * Rebase's own RLS-off tables a `REVOKE` would still change: the user role\n * holds a privilege on them, or the table has never had an ACL written —\n * `NULL`, which a `REVOKE` (like the grant-and-revoke it replaces) turns\n * into the owner's explicit default. Same access either way; the same\n * catalogue only this way.\n */\n internalGranted: string[];\n}\n\n/**\n * The grant tier's state for every existing schema in `schemas`, in one read.\n *\n * A grant counts as present only as the statement this tier runs would record\n * it — grantor the object's owner, which is what a GRANT by the owner, a member\n * of the owning role or a superuser records — so skipping it leaves the ACL\n * exactly as running it would. Anything else reads as missing, and the\n * statement runs as it always did.\n */\nasync function readSchemaGrants(run: RawSqlRunner, schemas: string[]): Promise<Map<string, SchemaGrants>> {\n const internal = textArray(REBASE_INTERNAL_TABLES);\n const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(REBASE_USER_ROLE)})`;\n /** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */\n const held = (acl: string, privileges: string[], grantor?: string): string =>\n `(SELECT count(DISTINCT a.privilege_type) FROM aclexplode(${acl}) a WHERE a.grantee = ${target}` +\n `${grantor ? ` AND a.grantor = ${grantor}` : \"\"} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(\", \")}))`;\n const DML = [\"SELECT\", \"INSERT\", \"UPDATE\", \"DELETE\"];\n const SEQ = [\"USAGE\", \"SELECT\"];\n const rows = await run(`\n SELECT n.nspname AS schema,\n ${held(\"n.nspacl\", [\"USAGE\"], \"n.nspowner\")} = 1 AS usage,\n NOT EXISTS (\n SELECT 1 FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')\n AND NOT (c.relname = ANY(${internal}) AND NOT c.relrowsecurity)\n AND ${held(\"c.relacl\", DML, \"c.relowner\")} < ${DML.length}\n ) AS tables,\n NOT EXISTS (\n SELECT 1 FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relkind = 'S'\n AND ${held(\"c.relacl\", SEQ, \"c.relowner\")} < ${SEQ.length}\n ) AS sequences,\n EXISTS (\n SELECT 1 FROM pg_default_acl d\n WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'r'\n AND ${held(\"d.defaclacl\", DML)} = ${DML.length}\n ) AS default_tables,\n EXISTS (\n SELECT 1 FROM pg_default_acl d\n WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'S'\n AND ${held(\"d.defaclacl\", SEQ)} = ${SEQ.length}\n ) AS default_sequences,\n ARRAY(\n SELECT c.relname::text FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relname = ANY(${internal}) AND NOT c.relrowsecurity\n AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))\n ORDER BY 1\n ) AS internal_granted\n FROM pg_namespace n\n WHERE n.nspname = ANY(${textArray(schemas)})\n `);\n const grants = new Map<string, SchemaGrants>();\n for (const row of rows) {\n const internalGranted = row.internal_granted;\n grants.set(String(row.schema), {\n usage: row.usage === true,\n tables: row.tables === true,\n sequences: row.sequences === true,\n defaultTables: row.default_tables === true,\n defaultSequences: row.default_sequences === true,\n internalGranted: Array.isArray(internalGranted)\n ? internalGranted.map(String)\n // A driver that hands arrays back as text: `{a,b}`.\n : String(internalGranted ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean)\n });\n }\n return grants;\n}\n\n/**\n * The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing\n * schema in `schemas`, DML on its tables and `USAGE, SELECT` on its\n * sequences, the default privileges that cover what this role creates later,\n * and Rebase's own tables taken back — for a role and membership already\n * provisioned.\n *\n * Every statement is issued only when the catalogue says it would change\n * something. They used to run unconditionally, twice per boot (at connect, and\n * again in the final posture check): a `GRANT … ON ALL TABLES` rewrites every\n * table's `pg_class` row whether or not the ACL changes, which invalidates\n * every table's cached plans on every connection, and the internal-table sweep\n * ran 23 `REVOKE`s per schema. A boot against a database whose grants already\n * hold now reads one catalogue query and writes nothing; one that is missing\n * any of them runs exactly the statements it always ran.\n *\n * Table owners (the expected non-superuser posture) can always grant on their\n * own objects, so this needs no extra privilege.\n */\nexport async function ensureAppRoleGrants(run: RawSqlRunner, schemas: string[]): Promise<void> {\n const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));\n const grants = await readSchemaGrants(run, uniqueSchemas);\n for (const schema of uniqueSchemas) {\n const state = grants.get(schema);\n // Not there (yet): a later call, once provisioning has created it, grants it.\n if (!state) continue;\n const s = quoteIdent(schema);\n if (!state.usage) await run(`GRANT USAGE ON SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n if (!state.tables) await run(`GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n if (!state.sequences) await run(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n // Cover objects created later by the CURRENT role (the role that runs\n // migrations), so a migrate can never strand the user role.\n if (!state.defaultTables) {\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${REBASE_USER_ROLE}`);\n }\n if (!state.defaultSequences) {\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${REBASE_USER_ROLE}`);\n }\n\n // The grants above are deliberately schema-wide — a project's own\n // collections may live in `rebase`, and future tables must be reachable\n // or a migration strands the role. Rebase's OWN tables are the exception:\n // refresh tokens, MFA secrets, API keys and the rest carry no RLS and no\n // row an end user should ever address. Taking the privilege back here\n // covers every table that already exists; each creator revokes on the\n // table it just made, for the boot that creates them for the first time.\n //\n // All of them right after the schema-wide grant, which has just handed\n // them out; otherwise only the ones the catalogue says still hold one.\n const tables = state.tables ? state.internalGranted : undefined;\n if (tables && tables.length === 0) continue;\n await revokeInternalTableAccess(async (text) => { await run(text); }, schema, {\n tables,\n onError: (table, error) => logger.warn(\n `🔐 [rls] Could not revoke \"${REBASE_USER_ROLE}\" access to \"${schema}\".\"${table}\" — ` +\n \"it stays reachable by authenticated requests: \" +\n (error instanceof Error ? error.message : String(error))\n )\n });\n }\n}\n\n/**\n * Rebase's own RLS-off tables in `schema` that a `revokeInternalTableAccess`\n * sweep would change — the user role holds a privilege on them, or their ACL\n * has never been written. One read; the sweep it narrows is one `DO` per\n * table name.\n */\nexport async function internalTablesGrantedToUserRole(run: RawSqlRunner, schema: string): Promise<string[]> {\n return (await readSchemaGrants(run, [schema])).get(schema)?.internalGranted ?? [];\n}\n\n/**\n * Apply the authenticated context to a transaction: the `app.*` GUCs that RLS\n * policies read via `rebase.uid()` / `rebase.roles()` / `rebase.jwt()`, and — when\n * `userRole` is set — the `LOCAL` role switch, in the same statement, so RLS\n * binds every statement in this transaction (reads *and* writes).\n *\n * GUCs are set with `is_local = true` and the role switch is `LOCAL`: both\n * reset at commit/rollback, so pooled connections are never polluted.\n *\n * Fails closed by construction: if the role switch errors, the transaction\n * aborts instead of proceeding privileged.\n *\n * SECURITY: this function is only ever called on the **user** path (the server\n * context uses the base/owner driver and never calls it). The default policies\n * treat `rebase.uid() IS NULL` as the trusted server context, and `rebase.uid()`\n * is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would\n * be read as NULL and silently escalate a user request to server privileges.\n * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,\n * rather than trusting every caller (e.g. realtime subscription auth) to do it.\n * That sentinel is exported from `@rebasepro/types` because it leaks into rule\n * semantics: it is why `rebase.uid() IS NOT NULL` is true for anonymous requests.\n */\nexport async function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void> {\n const uid = typeof auth.uid === \"string\" && auth.uid.trim() !== \"\" ? auth.uid : ANONYMOUS_USER_ID;\n const normalizedRoles = auth.roles.map((r: unknown) =>\n typeof r === \"string\" ? r : (r as Record<string, unknown>)?.id ?? String(r)\n );\n // `app.user_id` is the pre-rename spelling, still written because policies\n // are data: a database provisioned before the rename holds rules compiled\n // to `current_setting('app.user_id')`, and those predicates would evaluate\n // to NULL — failing open or locking out — if we stopped setting it. Drop\n // the alias only once no live database carries a legacy policy.\n // A guest is a signed-in caller with no account behind them, and until this\n // the database could not tell the difference — see `rebase.is_anonymous()`.\n // Written as a string because that is what `set_config` takes.\n const isAnonymous = auth.isAnonymous === true ? \"true\" : \"false\";\n\n await tx.execute(drizzleSql`\n SELECT\n set_config('app.uid', ${uid}, true),\n set_config('app.user_id', ${uid}, true),\n set_config('app.user_roles', ${normalizedRoles.join(\",\")}, true),\n set_config('app.is_anonymous', ${isAnonymous}, true),\n set_config('app.jwt', ${JSON.stringify({\n // The caller's custom claims, FIRST, so the identity keys below\n // overwrite them rather than the other way round. Same ordering, and\n // the same reason, as `generateAccessToken`: a claims hook is a place\n // to add facts about a session, not the place its subject is decided.\n // `verifyAccessToken` already strips the identity claims out of this\n // object; the ordering is the second lock on the same door.\n ...(auth.claims ?? {}),\n sub: uid,\n roles: auth.roles,\n // In the claims too, so a policy reading `rebase.jwt()` — which is\n // how a rule reaches anything that is not uid or roles — sees the\n // same fact as `rebase.is_anonymous()`. Two sources that could\n // disagree would be worse than one.\n is_anonymous: auth.isAnonymous === true\n })}, true)${userRole\n // The role switch, in the same statement rather than a `SET LOCAL ROLE`\n // round trip of its own on every transaction. Postgres implements\n // `SET ROLE` as the `role` setting: `set_config('role', name, true)`\n // runs the same membership check, fails with the same SQLSTATE and\n // message (42501 \"permission denied to set role\", 22023 for an unknown\n // role — `isRoleSwitchingPermissionError` still reads it), takes the\n // name verbatim as the quoted identifier did, and resets at COMMIT and\n // ROLLBACK like `LOCAL`. Last in the list, after the GUCs; a refusal\n // fails the whole statement, so the transaction aborts rather than\n // running on as the connection owner. auth-context-one-statement.test.ts.\n ? drizzleSql`,\n set_config('role', ${userRole}, true)`\n : drizzleSql``}\n `);\n}\n\n/** Role names from other BaaS platforms that people reach for out of habit. */\nconst FOREIGN_CONVENTION_ROLES: Record<string, string> = {\n authenticated: \"Supabase\",\n anon: \"Supabase\",\n service_role: \"Supabase\"\n};\n\n/**\n * Warn about rules that read as \"signed-in users only\" but admit anonymous\n * callers — `rebase.uid() IS NOT NULL`, or a comparison against another\n * platform's magic user id such as `'anon'`.\n *\n * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling\n * of the same habit. A foreign `pgRoles` value makes a policy unreachable and\n * the table reads empty — loud, and that guard throws. These do the opposite:\n * the rule compiles to a grant, and nothing looks wrong until the data is\n * already public.\n *\n * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are\n * serving traffic today: refusing to boot would take an app offline to report a\n * problem it already has, and on the read path it would take it offline\n * *because* its data was exposed. Rewriting the author's SQL is not an option\n * either — this is the escape hatch whose whole promise is that it means what it\n * says. So: say so, loudly, and leave the rule alone.\n */\nexport function warnOnAnonymousGrants(\n collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]\n): void {\n // Grouped by the mistake, not by the rule: one habit typically repeats\n // across every collection an author wrote, and a per-rule list would repeat\n // the same paragraph dozens of times and get skimmed.\n const byRisk = new Map<string, { risk: AnonymousGrantRisk; sites: string[] }>();\n\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n const risks = [usingExpr, withCheckExpr]\n .filter((e): e is PolicyExpression => e !== null)\n .flatMap(findAnonymousGrants);\n\n for (const risk of risks) {\n const key = `${risk.pattern}:${risk.detail}`;\n const site = `${collection.slug ?? \"(unnamed)\"} → \"${rule.name ?? \"(unnamed rule)\"}\"`;\n const entry = byRisk.get(key) ?? { risk, sites: [] };\n if (!entry.sites.includes(site)) entry.sites.push(site);\n byRisk.set(key, entry);\n }\n }\n }\n\n if (byRisk.size === 0) return;\n\n const problems = [...byRisk.values()].map(({ risk, sites }) =>\n ` • ${risk.explanation}\\n ${sites.length} rule(s): ${sites.join(\", \")}`\n );\n\n logger.warn(\n `Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a ` +\n `client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are ` +\n `true for everyone:\\n\\n` +\n problems.join(\"\\n\\n\") + \"\\n\"\n );\n}\n\n/**\n * Name the collections whose raw policy SQL still calls the pre-1.0 helpers.\n *\n * The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the\n * database, so nothing is broken and no policy is wrong — which is exactly why\n * this has to be said out loud. A silent rewrite that works forever is not a\n * migration, it is a second supported spelling nobody wrote down, and the next\n * person to read those rules will copy the old one.\n *\n * Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,\n * `policy.rolesOverlap(...)`) compile from the model and were never affected.\n */\nexport function warnOnLegacyRlsFunctions(\n collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]\n): void {\n const sites: string[] = [];\n\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n const carriesLegacy = [usingExpr, withCheckExpr]\n .filter((e): e is PolicyExpression => e !== null)\n .some(containsLegacyRlsCall);\n if (!carriesLegacy) continue;\n\n const site = `${collection.slug ?? \"(unnamed)\"} → \"${rule.name ?? \"(unnamed rule)\"}\"`;\n if (!sites.includes(site)) sites.push(site);\n }\n }\n\n if (sites.length === 0) return;\n\n logger.warn(\n `These security rules call the pre-1.0 RLS helpers (\\`auth.uid()\\`, \\`auth.roles()\\`, \\`auth.jwt()\\`). ` +\n `They still work — the compiler rewrites them — but the functions now live in the \\`rebase\\` schema, ` +\n `and the \\`auth\\` one is Supabase's. Update the raw SQL in these rules to \\`${REBASE_SCHEMA}.uid()\\` ` +\n `and friends, or switch them to the structured helpers (\\`policy.authUid()\\`, \\`policy.rolesOverlap()\\`), ` +\n `which never had to be spelled by hand:\\n\\n` +\n sites.map(s => ` • ${s}`).join(\"\\n\") + \"\\n\"\n );\n}\n\n/** Whether any `raw` expression in the tree calls a pre-1.0 helper. */\nfunction containsLegacyRlsCall(expr: PolicyExpression): boolean {\n switch (expr.kind) {\n case \"raw\":\n return usesLegacyRlsFunctions(expr.sql);\n case \"and\":\n case \"or\":\n return expr.operands.some(containsLegacyRlsCall);\n case \"not\":\n return containsLegacyRlsCall(expr.operand);\n case \"existsIn\":\n return containsLegacyRlsCall(expr.where);\n default:\n return false;\n }\n}\n\n/**\n * Reject `pgRoles` that this server can never satisfy.\n *\n * `pgRoles` sets the `TO` clause of a generated policy, so a policy naming a\n * role the request never runs as simply never applies — and RLS then filters\n * every row. The table reads as empty, which is indistinguishable from having\n * no data, so the mistake survives review and ships.\n *\n * Requests run as `rebase_user`, so a policy is only reachable if it targets\n * `public` or a role `rebase_user` holds. Anything else is a configuration\n * error worth failing the boot for.\n */\nexport async function validatePolicyPgRoles(\n run: RawSqlRunner,\n collections: { slug?: string; securityRules?: readonly { name?: string; pgRoles?: readonly string[] }[] }[],\n /** The role requests actually run as: `rebase_user` when the connection is\n * privileged enough to switch, otherwise the connection role itself. */\n requestRole: string = REBASE_USER_ROLE\n): Promise<void> {\n const wanted = new Map<string, string[]>();\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n for (const role of rule.pgRoles ?? []) {\n if (role === \"public\") continue;\n wanted.set(role, [...(wanted.get(role) ?? []), collection.slug ?? \"(unnamed)\"]);\n }\n }\n }\n if (wanted.size === 0) return;\n\n const names = [...wanted.keys()].map((r) => `'${r.replace(/'/g, \"''\")}'`).join(\",\");\n const escapedRequestRole = requestRole.replace(/'/g, \"''\");\n const rows = await run(`\n SELECT r.rolname AS role,\n COALESCE(pg_has_role(to_regrole('${escapedRequestRole}'), r.oid, 'MEMBER'), false) AS reachable\n FROM pg_roles r\n WHERE r.rolname IN (${names})\n `);\n\n const reachable = new Map(rows.map((row) => [String(row.role), row.reachable === true]));\n const problems: string[] = [];\n\n for (const [role, slugs] of wanted) {\n if (reachable.get(role) === true) continue;\n\n const why = reachable.has(role)\n ? `\"${requestRole}\" is not a member of it`\n : \"no such role exists in this database\";\n const platform = FOREIGN_CONVENTION_ROLES[role];\n const hint = platform\n ? `\"${role}\" is a ${platform} convention, not a PostgreSQL role. Application roles belong in \\`roles: [\"${role === \"service_role\" ? \"admin\" : role}\"]\\`, which is checked inside the policy via rebase.roles().`\n : `Either grant it (GRANT ${role} TO ${requestRole}) or drop \\`pgRoles\\` so the policy targets \\`public\\`.`;\n\n problems.push(\n ` • pgRoles: [\"${role}\"] on ${slugs.join(\", \")} — ${why}.\\n ${hint}`\n );\n }\n\n if (problems.length > 0) {\n throw new Error(\n `Security rules target PostgreSQL roles this server cannot use. Requests run as ` +\n `\"${requestRole}\", so these policies would never apply and every row would be ` +\n `filtered out — the collections would look empty rather than error.\\n\\n` +\n problems.join(\"\\n\\n\") + \"\\n\"\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsIA,IAAM,cAAc,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;;AAG5E,IAAM,wBAAwB;;;;;;;AAQ9B,IAAa,qBAAqB,QAAgB,UAC9C,4BAA4B,WAAW,MAAM,EAAE,GAAG,WAAW,KAAK,EAAE,QAAQ,WAAW,kBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6B3G,eAAsB,0BAA0B,KAAkC;CAC9E,IAAI;EACA,MAAM,OAAO,MAAM,IAAI;;;;;SAKtB;EACD,IAAI,KAAK,EAAE,EAAE,aAAa,MAAM;EAChC,MAAM,OAAO,OAAO,KAAK,EAAE,EAAE,QAAQ,qBAAqB;EAC1D,OAAO,KACH,0BAA0B,KAAK,4IAC+C,KAAK,gMAED,KAAK,gNAI3F;CACJ,QAAQ,CAER;AACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,eAAs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I,cAAc,IAAI,CAAC,CAAC;CACvF,MAAM,WAAqB,CAAC;CAE5B,KAAK,MAAM,CAAC,MAAM,UAAU,QAAQ;EAChC,IAAI,UAAU,IAAI,IAAI,MAAM,MAAM;EAElC,MAAM,MAAM,UAAU,IAAI,IAAI,IACxB,IAAI,YAAY,2BAChB;EACN,MAAM,WAAW,yBAAyB;EAC1C,MAAM,OAAO,WACP,IAAI,KAAK,SAAS,SAAS,6EAA6E,SAAS,iBAAiB,UAAU,KAAK,gEACjJ,0BAA0B,KAAK,MAAM,YAAY;EAEvD,SAAS,KACL,kBAAkB,KAAK,QAAQ,MAAM,KAAK,IAAI,EAAE,KAAK,IAAI,SAAS,MACtE;CACJ;CAEA,IAAI,SAAS,SAAS,GAClB,MAAM,IAAI,MACN,mFACI,YAAY,wIAEhB,SAAS,KAAK,MAAM,IAAI,IAC5B;AAER"}
@@ -204,6 +204,7 @@ export declare function createAuthSchema(usersSchemaName?: string): {
204
204
  identity: undefined;
205
205
  generated: undefined;
206
206
  }, {}, {
207
+ size: undefined;
207
208
  baseBuilder: import("drizzle-orm/pg-core").PgColumnBuilder<{
208
209
  name: "roles";
209
210
  dataType: "string";
@@ -212,7 +213,6 @@ export declare function createAuthSchema(usersSchemaName?: string): {
212
213
  enumValues: [string, ...string[]];
213
214
  driverParam: string;
214
215
  }, {}, {}, import("drizzle-orm").ColumnBuilderExtraConfig>;
215
- size: undefined;
216
216
  }>;
217
217
  metadata: import("drizzle-orm/pg-core").PgColumn<{
218
218
  name: "metadata";
@@ -250,6 +250,74 @@ export declare function createAuthSchema(usersSchemaName?: string): {
250
250
  identity: undefined;
251
251
  generated: undefined;
252
252
  }, {}, {}>;
253
+ disabledAt: import("drizzle-orm/pg-core").PgColumn<{
254
+ name: "disabled_at";
255
+ tableName: "users";
256
+ dataType: "date";
257
+ columnType: "PgTimestamp";
258
+ data: Date;
259
+ driverParam: string;
260
+ notNull: false;
261
+ hasDefault: false;
262
+ isPrimaryKey: false;
263
+ isAutoincrement: false;
264
+ hasRuntimeDefault: false;
265
+ enumValues: undefined;
266
+ baseColumn: never;
267
+ identity: undefined;
268
+ generated: undefined;
269
+ }, {}, {}>;
270
+ pendingEmail: import("drizzle-orm/pg-core").PgColumn<{
271
+ name: "pending_email";
272
+ tableName: "users";
273
+ dataType: "string";
274
+ columnType: "PgText";
275
+ data: string;
276
+ driverParam: string;
277
+ notNull: false;
278
+ hasDefault: false;
279
+ isPrimaryKey: false;
280
+ isAutoincrement: false;
281
+ hasRuntimeDefault: false;
282
+ enumValues: [string, ...string[]];
283
+ baseColumn: never;
284
+ identity: undefined;
285
+ generated: undefined;
286
+ }, {}, {}>;
287
+ emailChangeToken: import("drizzle-orm/pg-core").PgColumn<{
288
+ name: "email_change_token";
289
+ tableName: "users";
290
+ dataType: "string";
291
+ columnType: "PgText";
292
+ data: string;
293
+ driverParam: string;
294
+ notNull: false;
295
+ hasDefault: false;
296
+ isPrimaryKey: false;
297
+ isAutoincrement: false;
298
+ hasRuntimeDefault: false;
299
+ enumValues: [string, ...string[]];
300
+ baseColumn: never;
301
+ identity: undefined;
302
+ generated: undefined;
303
+ }, {}, {}>;
304
+ emailChangeSentAt: import("drizzle-orm/pg-core").PgColumn<{
305
+ name: "email_change_sent_at";
306
+ tableName: "users";
307
+ dataType: "date";
308
+ columnType: "PgTimestamp";
309
+ data: Date;
310
+ driverParam: string;
311
+ notNull: false;
312
+ hasDefault: false;
313
+ isPrimaryKey: false;
314
+ isAutoincrement: false;
315
+ hasRuntimeDefault: false;
316
+ enumValues: undefined;
317
+ baseColumn: never;
318
+ identity: undefined;
319
+ generated: undefined;
320
+ }, {}, {}>;
253
321
  createdAt: import("drizzle-orm/pg-core").PgColumn<{
254
322
  name: "created_at";
255
323
  tableName: "users";
@@ -444,6 +512,23 @@ export declare function createAuthSchema(usersSchemaName?: string): {
444
512
  identity: undefined;
445
513
  generated: undefined;
446
514
  }, {}, {}>;
515
+ method: import("drizzle-orm/pg-core").PgColumn<{
516
+ name: "method";
517
+ tableName: "refresh_tokens";
518
+ dataType: "string";
519
+ columnType: "PgText";
520
+ data: string;
521
+ driverParam: string;
522
+ notNull: false;
523
+ hasDefault: false;
524
+ isPrimaryKey: false;
525
+ isAutoincrement: false;
526
+ hasRuntimeDefault: false;
527
+ enumValues: [string, ...string[]];
528
+ baseColumn: never;
529
+ identity: undefined;
530
+ generated: undefined;
531
+ }, {}, {}>;
447
532
  userAgent: import("drizzle-orm/pg-core").PgColumn<{
448
533
  name: "user_agent";
449
534
  tableName: "refresh_tokens";
@@ -1470,6 +1555,7 @@ export declare const users: import("drizzle-orm/pg-core").PgTableWithColumns<{
1470
1555
  identity: undefined;
1471
1556
  generated: undefined;
1472
1557
  }, {}, {
1558
+ size: undefined;
1473
1559
  baseBuilder: import("drizzle-orm/pg-core").PgColumnBuilder<{
1474
1560
  name: "roles";
1475
1561
  dataType: "string";
@@ -1478,7 +1564,6 @@ export declare const users: import("drizzle-orm/pg-core").PgTableWithColumns<{
1478
1564
  enumValues: [string, ...string[]];
1479
1565
  driverParam: string;
1480
1566
  }, {}, {}, import("drizzle-orm").ColumnBuilderExtraConfig>;
1481
- size: undefined;
1482
1567
  }>;
1483
1568
  metadata: import("drizzle-orm/pg-core").PgColumn<{
1484
1569
  name: "metadata";
@@ -1516,6 +1601,74 @@ export declare const users: import("drizzle-orm/pg-core").PgTableWithColumns<{
1516
1601
  identity: undefined;
1517
1602
  generated: undefined;
1518
1603
  }, {}, {}>;
1604
+ disabledAt: import("drizzle-orm/pg-core").PgColumn<{
1605
+ name: "disabled_at";
1606
+ tableName: "users";
1607
+ dataType: "date";
1608
+ columnType: "PgTimestamp";
1609
+ data: Date;
1610
+ driverParam: string;
1611
+ notNull: false;
1612
+ hasDefault: false;
1613
+ isPrimaryKey: false;
1614
+ isAutoincrement: false;
1615
+ hasRuntimeDefault: false;
1616
+ enumValues: undefined;
1617
+ baseColumn: never;
1618
+ identity: undefined;
1619
+ generated: undefined;
1620
+ }, {}, {}>;
1621
+ pendingEmail: import("drizzle-orm/pg-core").PgColumn<{
1622
+ name: "pending_email";
1623
+ tableName: "users";
1624
+ dataType: "string";
1625
+ columnType: "PgText";
1626
+ data: string;
1627
+ driverParam: string;
1628
+ notNull: false;
1629
+ hasDefault: false;
1630
+ isPrimaryKey: false;
1631
+ isAutoincrement: false;
1632
+ hasRuntimeDefault: false;
1633
+ enumValues: [string, ...string[]];
1634
+ baseColumn: never;
1635
+ identity: undefined;
1636
+ generated: undefined;
1637
+ }, {}, {}>;
1638
+ emailChangeToken: import("drizzle-orm/pg-core").PgColumn<{
1639
+ name: "email_change_token";
1640
+ tableName: "users";
1641
+ dataType: "string";
1642
+ columnType: "PgText";
1643
+ data: string;
1644
+ driverParam: string;
1645
+ notNull: false;
1646
+ hasDefault: false;
1647
+ isPrimaryKey: false;
1648
+ isAutoincrement: false;
1649
+ hasRuntimeDefault: false;
1650
+ enumValues: [string, ...string[]];
1651
+ baseColumn: never;
1652
+ identity: undefined;
1653
+ generated: undefined;
1654
+ }, {}, {}>;
1655
+ emailChangeSentAt: import("drizzle-orm/pg-core").PgColumn<{
1656
+ name: "email_change_sent_at";
1657
+ tableName: "users";
1658
+ dataType: "date";
1659
+ columnType: "PgTimestamp";
1660
+ data: Date;
1661
+ driverParam: string;
1662
+ notNull: false;
1663
+ hasDefault: false;
1664
+ isPrimaryKey: false;
1665
+ isAutoincrement: false;
1666
+ hasRuntimeDefault: false;
1667
+ enumValues: undefined;
1668
+ baseColumn: never;
1669
+ identity: undefined;
1670
+ generated: undefined;
1671
+ }, {}, {}>;
1519
1672
  createdAt: import("drizzle-orm/pg-core").PgColumn<{
1520
1673
  name: "created_at";
1521
1674
  tableName: "users";
@@ -1710,6 +1863,23 @@ export declare const refreshTokens: import("drizzle-orm/pg-core").PgTableWithCol
1710
1863
  identity: undefined;
1711
1864
  generated: undefined;
1712
1865
  }, {}, {}>;
1866
+ method: import("drizzle-orm/pg-core").PgColumn<{
1867
+ name: "method";
1868
+ tableName: "refresh_tokens";
1869
+ dataType: "string";
1870
+ columnType: "PgText";
1871
+ data: string;
1872
+ driverParam: string;
1873
+ notNull: false;
1874
+ hasDefault: false;
1875
+ isPrimaryKey: false;
1876
+ isAutoincrement: false;
1877
+ hasRuntimeDefault: false;
1878
+ enumValues: [string, ...string[]];
1879
+ baseColumn: never;
1880
+ identity: undefined;
1881
+ generated: undefined;
1882
+ }, {}, {}>;
1713
1883
  userAgent: import("drizzle-orm/pg-core").PgColumn<{
1714
1884
  name: "user_agent";
1715
1885
  tableName: "refresh_tokens";
@@ -0,0 +1,47 @@
1
+ /** `lock_timeout` for each attempt at a boot DDL statement or batch. See the module comment. */
2
+ export declare const BOOT_LOCK_TIMEOUT_MS = 1000;
3
+ /** Attempts per table, including the first, before a contended table is given up on. */
4
+ export declare const BOOT_LOCK_ATTEMPTS = 3;
5
+ /**
6
+ * The most lock waiting one boot step spends on *retries*, in total.
7
+ *
8
+ * Without a cap, a holder that covers the whole database — a `pg_dump` takes
9
+ * `ACCESS SHARE` on every table it dumps, for as long as it runs — costs
10
+ * tables × attempts × timeout: four minutes at 240 tables. Retrying is for the
11
+ * holder that is about to finish (a report, a transaction), and ten seconds is
12
+ * plenty to wait that out; past it, waiting longer only delays the boot.
13
+ */
14
+ export declare const BOOT_LOCK_RETRY_BUDGET_MS = 10000;
15
+ export interface BootLockOptions {
16
+ /** Per-attempt `lock_timeout`, ms. Default {@link BOOT_LOCK_TIMEOUT_MS}. */
17
+ lockTimeoutMs?: number;
18
+ /** Attempts per table, including the first. Default {@link BOOT_LOCK_ATTEMPTS}. */
19
+ attempts?: number;
20
+ /** Total retry waiting per step, ms. Default {@link BOOT_LOCK_RETRY_BUDGET_MS}. */
21
+ retryBudgetMs?: number;
22
+ /** Pause before retry round `round` (1-based), ms. Default: jittered, growing. */
23
+ backoffMs?: (round: number) => number;
24
+ }
25
+ export interface ResolvedBootLockOptions {
26
+ lockTimeoutMs: number;
27
+ attempts: number;
28
+ retryBudgetMs: number;
29
+ backoffMs: (round: number) => number;
30
+ }
31
+ export declare const resolveBootLockOptions: (options?: BootLockOptions) => ResolvedBootLockOptions;
32
+ /** `55P03 lock_not_available` — what `lock_timeout` raises. */
33
+ export declare const isLockTimeout: (err: unknown) => boolean;
34
+ /**
35
+ * `42601` "cannot insert multiple commands into a prepared statement": the
36
+ * handle runs every query over the extended protocol, which carries exactly one
37
+ * statement. Raised before anything runs, so nothing needs undoing.
38
+ */
39
+ export declare const isMultiStatementRefusal: (err: unknown) => boolean;
40
+ /**
41
+ * `SET LOCAL lock_timeout`, then the statements: one string, one implicit
42
+ * transaction. See the module comment for why this and not `BEGIN … COMMIT`.
43
+ */
44
+ export declare const atomicBatch: (statements: readonly string[], lockTimeoutMs: number) => string;
45
+ /** Statements as one multi-statement string — one implicit transaction — each `;`-terminated. */
46
+ export declare const joinStatements: (statements: readonly string[]) => string;
47
+ export declare const sleep: (ms: number) => Promise<void>;
@@ -30,6 +30,23 @@
30
30
  * `diverges` is the whole point of this module: an editor that reports them as
31
31
  * safe is worse than one that refuses them.
32
32
  *
33
+ * ## Read from the plan, not from the properties
34
+ *
35
+ * Whether an edit changes the database is decided by comparing what
36
+ * `planSchema` — the one reading of a `Property` every emitter renders — makes
37
+ * of the collections before and after it: each table's columns, their types,
38
+ * nullability, defaults, uniqueness and foreign keys, the junction tables,
39
+ * indexes and triggers. It used to be decided by a hand-picked list of property
40
+ * fields, which knew nothing of `validation.integer`, of a string becoming an
41
+ * enum, of an array's element type or of anything about a relation beyond its
42
+ * name — and every one of those was reported "safe, no change", committed, and
43
+ * never applied. A difference in the plan cannot be missed that way: a new kind
44
+ * of edit either changes the plan, and is classified here from the difference,
45
+ * or it does not change the database.
46
+ *
47
+ * The property-level reading is still here, for the parts only it can name: a
48
+ * property added or removed, a required flag, an enum's values, a key renamed.
49
+ *
33
50
  * ## Why refusing is the right default for the rest
34
51
  *
35
52
  * Dropping a column, narrowing a type, changing a primary key: each is
@@ -37,7 +54,7 @@
37
54
  * somebody wrote and read. `needs-migration` says exactly that, and naming the
38
55
  * change is more useful than attempting it.
39
56
  */
40
- import type { CollectionConfig, SchemaChange, SchemaChangeKind, SchemaChangeVerdict, ClassifiedSchemaChanges } from "@rebasepro/types";
57
+ import { type CollectionConfig, type SchemaChange, type SchemaChangeKind, type SchemaChangeVerdict, type ClassifiedSchemaChanges } from "@rebasepro/types";
41
58
  /**
42
59
  * The vocabulary lives in `@rebasepro/types` so that `@rebasepro/server`, which
43
60
  * cannot import this package, can still describe a change. Re-exported here
@@ -66,6 +83,10 @@ export interface SchemaFacts {
66
83
  notNullColumns?: Set<string>;
67
84
  /** `schema.typename` → the values that type currently holds. */
68
85
  enumValues?: Map<string, string[]>;
86
+ /** `schema.table.column` → the type Postgres reports for it (`udt_name`). */
87
+ columnTypes?: Map<string, string>;
88
+ /** `schema.table.column` of every column that has a DEFAULT. */
89
+ columnDefaults?: Set<string>;
69
90
  }
70
91
  /**
71
92
  * Classify the difference between two collection sets.
@@ -78,5 +99,12 @@ export interface SchemaFacts {
78
99
  * get the conservative reading.
79
100
  */
80
101
  export declare function classifyCollectionChanges(before: CollectionConfig[], after: CollectionConfig[], facts?: SchemaFacts): ClassifiedChanges;
102
+ /**
103
+ * The statements a default change needs that the additive ensure does not
104
+ * plan: it sets a DEFAULT only on a column that has none, and never changes or
105
+ * drops one. Both are metadata-only — a DEFAULT binds future writes and touches
106
+ * no row — so a reviewed change may make them.
107
+ */
108
+ export declare function defaultChangeStatements(before: CollectionConfig[], after: CollectionConfig[], existingTables: Map<string, Set<string>>): string[];
81
109
  /** A one-line summary, for a log or a refusal message. */
82
110
  export declare function summarizeChanges(classified: ClassifiedChanges): string;