@rebasepro/server-postgres 0.29.0 → 0.29.1

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 (109) hide show
  1. package/dist/{BranchService-JiYJ_n9E.js → BranchService-BIIBF5ZL.js} +3 -3
  2. package/dist/{BranchService-JiYJ_n9E.js.map → BranchService-BIIBF5ZL.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +27 -9
  4. package/dist/PostgresBootstrapper.d.ts +14 -0
  5. package/dist/{backup-cli-D_aKXPyX.js → backup-cli-QcOpmRpQ.js} +3 -3
  6. package/dist/{backup-cli-D_aKXPyX.js.map → backup-cli-QcOpmRpQ.js.map} +1 -1
  7. package/dist/{boot-ddl-D4W9o9xE.js → boot-ddl-BSNpEUOS.js} +2 -2
  8. package/dist/{boot-ddl-D4W9o9xE.js.map → boot-ddl-BSNpEUOS.js.map} +1 -1
  9. package/dist/{cli-console-DPdZCWTi.js → cli-console-DTsm96lW.js} +5 -5
  10. package/dist/{cli-console-DPdZCWTi.js.map → cli-console-DTsm96lW.js.map} +1 -1
  11. package/dist/{cli-errors-D8s4z_3g.js → cli-errors-DwqFRIWz.js} +49 -6
  12. package/dist/{cli-errors-D8s4z_3g.js.map → cli-errors-DwqFRIWz.js.map} +1 -1
  13. package/dist/cli.js +81 -41
  14. package/dist/cli.js.map +1 -1
  15. package/dist/database-preflight-D5JtPt8i.js +151 -0
  16. package/dist/database-preflight-D5JtPt8i.js.map +1 -0
  17. package/dist/db-subcommands.d.ts +1 -1
  18. package/dist/{deferred-index-build-F2GWu009.js → deferred-index-build-B8feKnUj.js} +12 -8
  19. package/dist/deferred-index-build-B8feKnUj.js.map +1 -0
  20. package/dist/{doctor-_g2tHRtG.js → doctor-BaR11xUe.js} +6 -6
  21. package/dist/{doctor-_g2tHRtG.js.map → doctor-BaR11xUe.js.map} +1 -1
  22. package/dist/{ensure-collection-policies-DUpWJb5D.js → ensure-collection-policies-85HiG-k1.js} +8 -8
  23. package/dist/{ensure-collection-policies-DUpWJb5D.js.map → ensure-collection-policies-85HiG-k1.js.map} +1 -1
  24. package/dist/{ensure-collection-tables-BK--gDo6.js → ensure-collection-tables-DR_WcxLA.js} +15 -10
  25. package/dist/ensure-collection-tables-DR_WcxLA.js.map +1 -0
  26. package/dist/{ensure-tables-Bx1DYarz.js → ensure-tables-Dh5UP_Zs.js} +4 -4
  27. package/dist/{ensure-tables-Bx1DYarz.js.map → ensure-tables-Dh5UP_Zs.js.map} +1 -1
  28. package/dist/{enum-labels-kept-DyFE4Gaq.js → enum-labels-kept-DSU8lAnd.js} +3 -3
  29. package/dist/{enum-labels-kept-DyFE4Gaq.js.map → enum-labels-kept-DSU8lAnd.js.map} +1 -1
  30. package/dist/{generate-drizzle-schema-taNTu3xv.js → generate-drizzle-schema-5spbTyQ6.js} +2 -2
  31. package/dist/{generate-drizzle-schema-taNTu3xv.js.map → generate-drizzle-schema-5spbTyQ6.js.map} +1 -1
  32. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js → generate-drizzle-schema-logic-C5FB7Fpo.js} +2 -2
  33. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js.map → generate-drizzle-schema-logic-C5FB7Fpo.js.map} +1 -1
  34. package/dist/{generate-files-DbwU8Btx.js → generate-files-Bl3_D_oP.js} +3 -3
  35. package/dist/{generate-files-DbwU8Btx.js.map → generate-files-Bl3_D_oP.js.map} +1 -1
  36. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js → generate-postgres-ddl-logic-BC3JA93M.js} +3 -3
  37. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js.map → generate-postgres-ddl-logic-BC3JA93M.js.map} +1 -1
  38. package/dist/{generated-schema-diff-4lOC0g1_.js → generated-schema-diff-Jm93vyJB.js} +12 -4
  39. package/dist/generated-schema-diff-Jm93vyJB.js.map +1 -0
  40. package/dist/index.d.ts +2 -1
  41. package/dist/index.es.js +20 -12
  42. package/dist/index.es.js.map +1 -1
  43. package/dist/{migrate-baseline-BeepEphh.js → migrate-baseline-BfHmq3vN.js} +49 -4
  44. package/dist/{migrate-baseline-BeepEphh.js.map → migrate-baseline-BfHmq3vN.js.map} +1 -1
  45. package/dist/{migrate-policy-stamps-cYMJ_9Ha.js → migrate-policy-stamps-B4k1ggma.js} +6 -6
  46. package/dist/{migrate-policy-stamps-cYMJ_9Ha.js.map → migrate-policy-stamps-B4k1ggma.js.map} +1 -1
  47. package/dist/{open-rebase-CTNBmmH8.js → open-rebase-CiO_sjMT.js} +465 -80
  48. package/dist/open-rebase-CiO_sjMT.js.map +1 -0
  49. package/dist/open-rebase.d.ts +6 -1
  50. package/dist/{pg-error-utils-BLOVXK67.js → pg-error-utils-D1Nc0UML.js} +2 -2
  51. package/dist/{pg-error-utils-BLOVXK67.js.map → pg-error-utils-D1Nc0UML.js.map} +1 -1
  52. package/dist/{plan-schema-CMNWvqIa.js → plan-schema-BYxOzflz.js} +89 -9
  53. package/dist/plan-schema-BYxOzflz.js.map +1 -0
  54. package/dist/{policy-drift-IjD2AUD-.js → policy-drift-DKuTJHfc.js} +2 -2
  55. package/dist/{policy-drift-IjD2AUD-.js.map → policy-drift-DKuTJHfc.js.map} +1 -1
  56. package/dist/{push-index-prebuild-CIvajIrL.js → push-index-prebuild-bqXimSZz.js} +4 -4
  57. package/dist/{push-index-prebuild-CIvajIrL.js.map → push-index-prebuild-bqXimSZz.js.map} +1 -1
  58. package/dist/{push-kept-defaults-CLbsuSmo.js → push-kept-defaults-CN9R8cHf.js} +2 -2
  59. package/dist/{push-kept-defaults-CLbsuSmo.js.map → push-kept-defaults-CN9R8cHf.js.map} +1 -1
  60. package/dist/{push-legacy-renames-DeW_HTLJ.js → push-legacy-renames-CU_UYPbz.js} +4 -4
  61. package/dist/{push-legacy-renames-DeW_HTLJ.js.map → push-legacy-renames-CU_UYPbz.js.map} +1 -1
  62. package/dist/{push-policy-plan--oRXOj4X.js → push-policy-plan-JcyK94bc.js} +4 -4
  63. package/dist/{push-policy-plan--oRXOj4X.js.map → push-policy-plan-JcyK94bc.js.map} +1 -1
  64. package/dist/{render-ddl-CzVcbbR1.js → render-ddl-DCdVP-pQ.js} +27 -10
  65. package/dist/render-ddl-DCdVP-pQ.js.map +1 -0
  66. package/dist/request-role-cli-DSdRtvgH.js +260 -0
  67. package/dist/request-role-cli-DSdRtvgH.js.map +1 -0
  68. package/dist/request-role-cli.d.ts +86 -0
  69. package/dist/request-role-migration-D9BZ5Uba.js +150 -0
  70. package/dist/request-role-migration-D9BZ5Uba.js.map +1 -0
  71. package/dist/rls-enforcement-BO618rnr.js +992 -0
  72. package/dist/rls-enforcement-BO618rnr.js.map +1 -0
  73. package/dist/rls-settings-De5NoHHy.js +211 -0
  74. package/dist/rls-settings-De5NoHHy.js.map +1 -0
  75. package/dist/schema/doctor-cli.js +144 -6
  76. package/dist/schema/doctor-cli.js.map +1 -1
  77. package/dist/schema/doctor-database.d.ts +27 -0
  78. package/dist/schema/generate-drizzle-schema.js +1 -1
  79. package/dist/schema/generate-postgres-ddl.js +1 -1
  80. package/dist/schema/introspect-db.js +1 -1
  81. package/dist/schema/plan/diff-plan.d.ts +6 -1
  82. package/dist/schema/plan/render-ddl.d.ts +10 -3
  83. package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
  84. package/dist/schema/plan/types.d.ts +15 -0
  85. package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
  86. package/dist/schema/plan/view-names.d.ts +6 -0
  87. package/dist/schema/rls-bootstrap-sql.d.ts +23 -0
  88. package/dist/security/caller-sql-columns.d.ts +60 -0
  89. package/dist/security/caller-sql.d.ts +8 -0
  90. package/dist/security/database-preflight.d.ts +24 -0
  91. package/dist/security/request-role-migration.d.ts +36 -0
  92. package/dist/security/rls-enforcement.d.ts +191 -21
  93. package/dist/security/rls-settings.d.ts +177 -0
  94. package/dist/services/dataService.d.ts +2 -0
  95. package/dist/services/realtimeService.d.ts +3 -0
  96. package/dist/services/view-access.d.ts +2 -2
  97. package/dist/view-names-Dscp6--B.js +24 -0
  98. package/dist/view-names-Dscp6--B.js.map +1 -0
  99. package/dist/{websocket-D2y88dOa.js → websocket-B33YjKhs.js} +3 -3
  100. package/dist/{websocket-D2y88dOa.js.map → websocket-B33YjKhs.js.map} +1 -1
  101. package/package.json +7 -7
  102. package/dist/deferred-index-build-F2GWu009.js.map +0 -1
  103. package/dist/ensure-collection-tables-BK--gDo6.js.map +0 -1
  104. package/dist/generated-schema-diff-4lOC0g1_.js.map +0 -1
  105. package/dist/open-rebase-CTNBmmH8.js.map +0 -1
  106. package/dist/plan-schema-CMNWvqIa.js.map +0 -1
  107. package/dist/render-ddl-CzVcbbR1.js.map +0 -1
  108. package/dist/rls-enforcement-jZTv1yci.js +0 -534
  109. package/dist/rls-enforcement-jZTv1yci.js.map +0 -1
@@ -1,6 +1,7 @@
1
1
  import { SQL } from "drizzle-orm";
2
2
  import { SecurityRule } from "@rebasepro/types";
3
3
  import { REBASE_USER_ROLE } from "@rebasepro/common";
4
+ import type { GrantsMode, ProvisionRoleMode, RequestIdentity } from "./rls-settings.js";
4
5
  /**
5
6
  * Unified RLS enforcement — the "user context vs server context" model.
6
7
  *
@@ -117,10 +118,14 @@ export interface AuthContext {
117
118
  claims?: Record<string, unknown>;
118
119
  }
119
120
  /**
120
- * Take every privilege the user role holds on one table back — what a table
121
- * gets when RLS cannot be switched on for it, so it is unreachable rather than
122
- * unprotected. Quoted exactly: a mixed-case adopted table (`"User"`) folded to
123
- * lower case names a table that does not exist.
121
+ * Take every privilege the request roles hold on one table back — what a
122
+ * table gets when RLS cannot be switched on for it, so it is unreachable
123
+ * rather than unprotected. Quoted exactly: a mixed-case adopted table
124
+ * (`"User"`) folded to lower case names a table that does not exist.
125
+ *
126
+ * Every request role, as this database recorded them (`rls.requestRole`), and
127
+ * each only if it exists: one statement, for the boot's policies step and its
128
+ * final posture check alike, without either being handed the roles.
124
129
  */
125
130
  export declare const revokeUserRoleSql: (schema: string, table: string) => string;
126
131
  /**
@@ -182,11 +187,117 @@ export declare function warnOnRoleSchemaCollision(run: RawSqlRunner): Promise<vo
182
187
  * under-reporting costs the entire authorization model.
183
188
  */
184
189
  export declare function detectConnectionPosture(run: RawSqlRunner, schemas?: string[]): Promise<ConnectionPosture>;
190
+ /**
191
+ * Raised when `rebase_user` cannot be provisioned, adopted or switched to —
192
+ * with the SQL that fixes it in {@link instructions}.
193
+ *
194
+ * Its own class so a caller that prints the instructions itself (the CLI) can
195
+ * tell they are already in the message.
196
+ */
197
+ export declare class AppRoleSetupError extends Error {
198
+ readonly instructions: string;
199
+ constructor(problem: string, instructions: string);
200
+ }
185
201
  /**
186
202
  * Human-actionable instructions for when the connection cannot provision the
187
- * user role itself (no CREATEROLE and role not pre-created by the platform).
203
+ * user role itself (no CREATEROLE and role not pre-created by the platform),
204
+ * or holds it without the right to switch to it.
205
+ *
206
+ * Every statement is safe to re-run and the same text works on Postgres 15 and
207
+ * 16+, so it can be pasted whole whatever state the database is in.
208
+ * `connectionRole` is the role the server connects as; without one, a
209
+ * placeholder Postgres will refuse until it is replaced.
210
+ */
211
+ export declare function appRoleSetupInstructions(connectionRole: string | undefined, schemas: string[], role?: string, mode?: GrantsMode): string;
212
+ /**
213
+ * Refuse a `rebase_user` that would not restrict anything.
214
+ *
215
+ * The role is cluster-wide and found by name, so the one a boot adopts may
216
+ * have been made by anybody — an earlier tool, a hand-written script, another
217
+ * application on the same cluster. Every authenticated request runs as it, so
218
+ * an attribute or a membership that lifts RLS lifts it from all of them, and
219
+ * nothing would say so: requests succeed, with every row.
220
+ *
221
+ * - LOGIN: anyone holding its password connects as the request role directly.
222
+ * - SUPERUSER, BYPASSRLS: RLS does not apply to it at all.
223
+ * - A membership in a role that owns tables here, or is itself a login,
224
+ * superuser or BYPASSRLS role: a member inheriting an owner is the owner for
225
+ * every policy check, and one that may `SET ROLE` to a privileged role is a
226
+ * statement away from it. (`GRANT app TO rebase_user` for `GRANT rebase_user
227
+ * TO app` is the easy way to get here.)
228
+ *
229
+ * A plain NOLOGIN group role is left alone: `validatePolicyPgRoles` sends a
230
+ * project with `pgRoles` to exactly that grant.
231
+ */
232
+ export declare function assertAppRoleRestricted(run: RawSqlRunner, role?: string): Promise<void>;
233
+ /**
234
+ * Run {@link roleSwitchProbe}, and on a refusal throw an
235
+ * {@link AppRoleSetupError} carrying the SQL that grants the switch.
236
+ *
237
+ * For a boot that adopts the role without provisioning it as much as for one
238
+ * that just did: either way the next thing that happens is a request running
239
+ * as it.
240
+ */
241
+ export declare function proveRoleSwitch(run: RawSqlRunner, schemas: string[], connectionRole?: string, role?: string): Promise<void>;
242
+ /** The `rebase.schema_meta` key that records which roles requests run as. */
243
+ export declare const REQUEST_ROLES_KEY = "request_roles";
244
+ /**
245
+ * The request roles this database recorded on an earlier provisioning boot, or
246
+ * `undefined` when none has — every database provisioned before the setting
247
+ * existed, which ran as `rebase_user`.
248
+ *
249
+ * Recorded in the database rather than only configured because a role belongs
250
+ * to the cluster and holds grants here: a later boot configured with another
251
+ * name would provision a second role and leave the first one holding every
252
+ * grant. Reading the record is how that boot notices.
253
+ */
254
+ export declare function readRecordedRequestRoles(run: RawSqlRunner): Promise<string[] | undefined>;
255
+ /**
256
+ * Record `roles` as this database's request roles, creating `rebase.schema_meta`
257
+ * if nothing has yet. The table is one of Rebase's internal tables, so it is
258
+ * taken back from the request roles here, as its every creator does.
259
+ */
260
+ export declare function recordRequestRoles(run: RawSqlRunner, roles: readonly string[]): Promise<void>;
261
+ /**
262
+ * Refuse a boot configured with request roles other than the ones this
263
+ * database recorded. The same set in any order is the same.
264
+ *
265
+ * Nothing recorded means `rebase_user`, as every database from before the
266
+ * setting ran — but only where `rebase_user` actually holds grants here. A
267
+ * database it has never been granted on (a fresh one) has nothing to strand,
268
+ * and a new role is simply recorded.
269
+ */
270
+ export declare function assertRecordedRequestRoles(configured: readonly string[], recorded: readonly string[] | undefined, defaultRoleHoldsGrants: boolean): void;
271
+ /** Whether `role` holds any table privilege in `schemas` — something a new role would strand. */
272
+ export declare function roleHoldsTableGrants(run: RawSqlRunner, schemas: readonly string[], role?: string): Promise<boolean>;
273
+ /**
274
+ * Login roles other than this connection that can switch into `role`, and so
275
+ * can pass this database's policies as whichever user they like: the settings the
276
+ * policies read can be set by any session.
277
+ *
278
+ * Roles belong to the cluster, so this is how two projects on one cluster
279
+ * sharing `rebase_user` shows up from inside either database. Superusers are
280
+ * left out — they can become any role, and nothing here changes that.
188
281
  */
189
- export declare function appRoleSetupInstructions(connectionRole: string, schemas: string[]): string;
282
+ export declare function findOtherRoleMembers(run: RawSqlRunner, role: string): Promise<string[]>;
283
+ /** How {@link ensureAppRole} provisions: which role, and what it may create and grant. */
284
+ export interface EnsureAppRoleOptions {
285
+ /** The request role. Default `rebase_user`. */
286
+ role?: string;
287
+ /** `"never"`: check the role and the membership, create neither. */
288
+ provisionRole?: ProvisionRoleMode;
289
+ /** What the grant tier grants — see {@link ensureAppRoleGrants}. */
290
+ grants?: GrantsMode;
291
+ /** The tables Rebase serves, for `grants: "managed"`. */
292
+ managedTables?: readonly ManagedTable[];
293
+ /** Roles granted to the request role `WITH INHERIT TRUE` (PostgreSQL 16+). */
294
+ inheritRoles?: readonly string[];
295
+ }
296
+ /** A table Rebase serves, by schema and name. */
297
+ export interface ManagedTable {
298
+ schema: string;
299
+ table: string;
300
+ }
190
301
  /**
191
302
  * Idempotently provision the `rebase_user` role, membership for the current
192
303
  * connection role, and DML grants (+ default privileges for future tables)
@@ -200,10 +311,13 @@ export declare function appRoleSetupInstructions(connectionRole: string, schemas
200
311
  * RLS still filters every row: these grants only make the tables *reachable*
201
312
  * by the role; the policies decide which rows/commands actually pass.
202
313
  *
203
- * Throws with precise setup instructions when the role is missing and the
204
- * connection cannot create it.
314
+ * Throws {@link AppRoleSetupError}, with precise setup instructions, when the
315
+ * role is missing and the connection cannot create it, when an existing role
316
+ * would not restrict anything, and when the connection cannot switch to it.
317
+ * Boot fails then, rather than serving an API whose every signed-in request is
318
+ * refused — or, worse, allowed.
205
319
  */
206
- export declare function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promise<void>;
320
+ export declare function ensureAppRole(run: RawSqlRunner, schemas: string[], options?: EnsureAppRoleOptions): Promise<void>;
207
321
  /**
208
322
  * The framework's internal tables in `schemas` that the request role can
209
323
  * reach — `schema.table`, sorted — when nothing is left to take it back off.
@@ -221,7 +335,49 @@ export declare function ensureAppRole(run: RawSqlRunner, schemas: string[]): Pro
221
335
  * gets. A table with RLS on is somebody's collection by that same rule as the
222
336
  * sweep's, and is left out.
223
337
  */
224
- export declare function findExposedInternalTables(run: RawSqlRunner, schemas: string[]): Promise<string[]>;
338
+ export declare function findExposedInternalTables(run: RawSqlRunner, schemas: string[], role?: string): Promise<string[]>;
339
+ /**
340
+ * Tables collections are served from that the user role holds no privilege on
341
+ * and this connection cannot grant it, because another role owns them.
342
+ *
343
+ * The grant tier passes these over — it could only fail on them — so on a
344
+ * database another application shares, a collection over that application's
345
+ * table boots and then refuses every request with "permission denied". This
346
+ * names them, with the owner who can run the grant. Refusing rather than
347
+ * widening, so the boot warns instead of stopping: the rest of the project
348
+ * works, and an introspected project serves every table in the schema,
349
+ * whoever owns it.
350
+ */
351
+ export declare function findUngrantableTables(run: RawSqlRunner, tables: readonly ManagedTable[], role?: string): Promise<{
352
+ name: string;
353
+ owner: string;
354
+ grant: string;
355
+ }[]>;
356
+ /** What {@link ensureAppRoleGrants} grants, and to whom. */
357
+ export interface AppRoleGrantOptions {
358
+ /** The request role. Default `rebase_user`. */
359
+ role?: string;
360
+ /**
361
+ * `"schema"` (default): every table and sequence in the schemas that this
362
+ * connection may grant on, and default privileges for later ones.
363
+ * `"managed"`: only {@link managedTables} and the sequences they own, no
364
+ * default privileges. `"none"`: nothing, not even the revoke sweep.
365
+ */
366
+ mode?: GrantsMode;
367
+ managedTables?: readonly ManagedTable[];
368
+ }
369
+ /**
370
+ * Grant each of `inheritRoles` to the request role `WITH INHERIT TRUE`, so a
371
+ * policy written `TO` one of them — Supabase's `authenticated`, say — applies
372
+ * to requests.
373
+ *
374
+ * PostgreSQL 16 and newer only. From 16 inheritance is an option of each
375
+ * grant, so the request role takes on these roles' privileges and stays
376
+ * NOINHERIT towards every other membership. Before 16 the only lever is the
377
+ * role's own INHERIT attribute, which would hand it every role it belongs to;
378
+ * that is refused rather than done.
379
+ */
380
+ export declare function ensureInheritedRoles(run: RawSqlRunner, role: string, inheritRoles: readonly string[]): Promise<void>;
225
381
  /**
226
382
  * The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing
227
383
  * schema in `schemas`, DML on its tables and `USAGE, SELECT` on its
@@ -235,20 +391,27 @@ export declare function findExposedInternalTables(run: RawSqlRunner, schemas: st
235
391
  * table's `pg_class` row whether or not the ACL changes, which invalidates
236
392
  * every table's cached plans on every connection, and the internal-table sweep
237
393
  * ran 23 `REVOKE`s per schema. A boot against a database whose grants already
238
- * hold now reads one catalogue query and writes nothing; one that is missing
239
- * any of them runs exactly the statements it always ran.
394
+ * hold now reads one catalogue query and writes nothing.
395
+ *
396
+ * Tables and sequences are granted by name, the ones that are missing it and
397
+ * that this connection may grant on — not `ON ALL … IN SCHEMA`, which also
398
+ * tries every relation another role owns. On a schema shared with another
399
+ * application that statement fails for a table this connection holds no
400
+ * privilege on, or only warns for one it holds without grant option, and either
401
+ * way the schema never reads as granted. The ACLs this leaves are the ones the
402
+ * schema-wide statement left on everything it could reach.
240
403
  *
241
404
  * Table owners (the expected non-superuser posture) can always grant on their
242
405
  * own objects, so this needs no extra privilege.
243
406
  */
244
- export declare function ensureAppRoleGrants(run: RawSqlRunner, schemas: string[]): Promise<void>;
407
+ export declare function ensureAppRoleGrants(run: RawSqlRunner, schemas: string[], options?: AppRoleGrantOptions): Promise<void>;
245
408
  /**
246
409
  * Rebase's own RLS-off tables in `schema` that a `revokeInternalTableAccess`
247
410
  * sweep would change — the user role holds a privilege on them, or their ACL
248
411
  * has never been written. One read; the sweep it narrows is one `DO` per
249
412
  * table name.
250
413
  */
251
- export declare function internalTablesGrantedToUserRole(run: RawSqlRunner, schema: string): Promise<string[]>;
414
+ export declare function internalTablesGrantedToUserRole(run: RawSqlRunner, schema: string, role?: string): Promise<string[]>;
252
415
  /**
253
416
  * Apply the authenticated context to a transaction: the `app.*` GUCs that RLS
254
417
  * policies read via `rebase.uid()` / `rebase.roles()` / `rebase.jwt()`, and — when
@@ -271,7 +434,7 @@ export declare function internalTablesGrantedToUserRole(run: RawSqlRunner, schem
271
434
  * That sentinel is exported from `@rebasepro/types` because it leaks into rule
272
435
  * semantics: it is why `rebase.uid() IS NOT NULL` is true for anonymous requests.
273
436
  */
274
- export declare function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void>;
437
+ export declare function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string | RequestIdentity): Promise<void>;
275
438
  /**
276
439
  * {@link applyAuthContext} as one statement and its values, for a transaction
277
440
  * that sends it in the same batch as its first query
@@ -279,7 +442,7 @@ export declare function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?
279
442
  * — what a pooled connection could not carry at connect — set ahead of the
280
443
  * caller's, in the same statement.
281
444
  */
282
- export declare function authContextStatement(auth: AuthContext, userRole?: string, before?: readonly (readonly [string, string])[]): {
445
+ export declare function authContextStatement(auth: AuthContext, userRole?: string | RequestIdentity, before?: readonly (readonly [string, string])[]): {
283
446
  text: string;
284
447
  values: string[];
285
448
  };
@@ -330,8 +493,14 @@ export declare function warnOnLegacyRlsFunctions(collections: {
330
493
  * no data, so the mistake survives review and ships.
331
494
  *
332
495
  * Requests run as `rebase_user`, so a policy is only reachable if it targets
333
- * `public` or a role `rebase_user` holds. Anything else is a configuration
334
- * error worth failing the boot for.
496
+ * `public` or a role whose privileges `rebase_user` has. Anything else is a
497
+ * configuration error worth failing the boot for.
498
+ *
499
+ * Privileges, not membership: Postgres applies a policy `TO r` to a role that
500
+ * has `r`'s privileges, which a member only gets by inheriting them, and
501
+ * `rebase_user` is `NOINHERIT`. This used to ask `pg_has_role(…, 'MEMBER')`, so
502
+ * `GRANT authenticated TO rebase_user` — the grant its own hint suggested —
503
+ * passed here and still read every collection as empty.
335
504
  */
336
505
  export declare function validatePolicyPgRoles(run: RawSqlRunner, collections: {
337
506
  slug?: string;
@@ -340,6 +509,7 @@ export declare function validatePolicyPgRoles(run: RawSqlRunner, collections: {
340
509
  pgRoles?: readonly string[];
341
510
  }[];
342
511
  }[],
343
- /** The role requests actually run as: `rebase_user` when the connection is
344
- * privileged enough to switch, otherwise the connection role itself. */
345
- requestRole?: string): Promise<void>;
512
+ /** The role(s) requests actually run as: `rebase_user` (or the `rls.requestRole`
513
+ * roles) when the connection is privileged enough to switch, otherwise the
514
+ * connection role itself. With several, a role is usable when any reaches it. */
515
+ requestRoles?: string | readonly string[]): Promise<void>;
@@ -0,0 +1,177 @@
1
+ import type { AuthContext } from "./rls-enforcement.js";
2
+ /**
3
+ * The escape hatches for the request role — every choice Rebase makes about
4
+ * the roles, grants, policy targets and session settings that row-level
5
+ * security runs on, as a setting.
6
+ *
7
+ * Each one defaults to what Rebase did before it existed, so a project that
8
+ * sets nothing gets exactly that. The point is the other values: a database
9
+ * someone already runs has its own roles, its own grants and sometimes its own
10
+ * policies, and Rebase should fit them rather than demand a database of its
11
+ * own. See docs/design/rebase-user-on-existing-databases.md.
12
+ *
13
+ * Set in code on the driver (`rls`), and — for the ones an operator may need to
14
+ * change per deployment — from the environment, which wins, as it does for the
15
+ * realtime settings. Function-valued settings are code only.
16
+ */
17
+ export interface PostgresRlsConfig {
18
+ /**
19
+ * The role signed-in and anonymous requests run as. Default `"rebase_user"`.
20
+ *
21
+ * - A name: every request runs as it. Give each project on a shared cluster
22
+ * its own, because a role belongs to the whole cluster and any login that
23
+ * can switch into it passes this database's policies.
24
+ * - `{ anonymous, signedIn }`: a caller with no session runs as one, anyone
25
+ * signed in (guests and `rebase.dataAsAdmin` included) as the other —
26
+ * the `anon` / `authenticated` split of Supabase and PostgREST.
27
+ * - A function of the request's identity, for anything else. Declare every
28
+ * name it can return in {@link requestRoles}; a name outside that list
29
+ * fails the request.
30
+ *
31
+ * Env: `REBASE_RLS_REQUEST_ROLE` (a name).
32
+ */
33
+ requestRole?: string | RequestRoleMap | ((auth: AuthContext) => string);
34
+ /**
35
+ * Every role a function-valued {@link requestRole} can return, so they can
36
+ * be provisioned, granted, recorded and checked. Derived for the other forms.
37
+ */
38
+ requestRoles?: readonly string[];
39
+ /**
40
+ * Whether Rebase creates the request role and the membership that lets the
41
+ * connection switch into it. `"auto"` (default) does; `"never"` leaves both
42
+ * to the operator — roles managed in Terraform, a DBA who creates every role
43
+ * by hand — and only checks them, failing the boot with the SQL to run.
44
+ *
45
+ * Env: `REBASE_RLS_PROVISION_ROLE`.
46
+ */
47
+ provisionRole?: ProvisionRoleMode;
48
+ /**
49
+ * What Rebase grants the request role.
50
+ *
51
+ * - `"schema"` (default): every table and sequence in the schemas it serves
52
+ * that the connection may grant on, plus default privileges so tables
53
+ * created later are covered.
54
+ * - `"managed"`: only the tables Rebase serves — collections, junctions, its
55
+ * own row-secured tables — and their sequences; no default privileges.
56
+ * For a schema shared with tables Rebase should not reach.
57
+ * - `"none"`: nothing. Grants are yours; a table you have not granted is
58
+ * refused, never widened.
59
+ *
60
+ * Env: `REBASE_RLS_GRANTS`.
61
+ */
62
+ grants?: GrantsMode;
63
+ /**
64
+ * Whom permissive policies apply to. `"public"` (default) is every role
65
+ * with a grant on the table. `"requestRole"` narrows them to the request
66
+ * role(s), so another application's role reading the same table gets
67
+ * nothing from Rebase's policies. Restrictive policies always apply to
68
+ * everyone: they can only take access away.
69
+ *
70
+ * Env: `REBASE_RLS_POLICY_TARGET`.
71
+ */
72
+ policyTarget?: PolicyTargetMode;
73
+ /**
74
+ * `false` drops the injected server-or-admin baseline from every
75
+ * collection, as `disableDefaultPolicies` does for one. Default `true`.
76
+ * A collection's own `disableDefaultPolicies` still decides for it.
77
+ */
78
+ defaultPolicies?: boolean;
79
+ /**
80
+ * Roles whose policies should apply to requests: each is granted to the
81
+ * request role(s) `WITH INHERIT TRUE`, so a policy written `TO
82
+ * authenticated` applies. PostgreSQL 16 and newer only — before 16 the only
83
+ * way is to make the request role inherit from every role it belongs to,
84
+ * which this refuses to do.
85
+ */
86
+ inheritRoles?: readonly string[];
87
+ /**
88
+ * The session settings a request carries its identity in, besides the
89
+ * `app.*` settings Rebase's own policies read (always set).
90
+ *
91
+ * - `"rebase"` (default): nothing more.
92
+ * - `"supabase"`: also `request.jwt.claims`, `request.jwt.claim.sub` and
93
+ * `request.jwt.claim.role`, so policies written with Supabase's
94
+ * `auth.uid()` / `auth.jwt()` see the caller.
95
+ * - A function returning `[name, value]` pairs, for any other convention.
96
+ *
97
+ * Env: `REBASE_RLS_IDENTITY` (a named form).
98
+ */
99
+ identity?: IdentityMode | ((auth: AuthContext, role: string) => readonly (readonly [string, string])[]);
100
+ /**
101
+ * What to do when a login other than this connection can switch into the
102
+ * request role — which lets it pass this database's policies as anyone.
103
+ * `"warn"` (default), `"refuse"` to fail the boot, `"ignore"` for a role
104
+ * shared on purpose.
105
+ *
106
+ * Env: `REBASE_RLS_SHARED_ROLE`.
107
+ */
108
+ sharedRole?: SharedRoleMode;
109
+ }
110
+ export interface RequestRoleMap {
111
+ /** The role a caller with no session runs as. */
112
+ anonymous: string;
113
+ /** The role every signed-in caller runs as, guests included. */
114
+ signedIn: string;
115
+ }
116
+ export type ProvisionRoleMode = "auto" | "never";
117
+ export type GrantsMode = "schema" | "managed" | "none";
118
+ export type PolicyTargetMode = "public" | "requestRole";
119
+ export type IdentityMode = "rebase" | "supabase";
120
+ export type SharedRoleMode = "warn" | "refuse" | "ignore";
121
+ /**
122
+ * How one request runs: the role to switch to, and any session settings beyond
123
+ * `app.*`. What the driver and the realtime refetch hand to `applyAuthContext`.
124
+ */
125
+ export interface RequestIdentity {
126
+ roleFor(auth: AuthContext): string;
127
+ settingsFor(auth: AuthContext, role: string): readonly (readonly [string, string])[];
128
+ }
129
+ /** {@link PostgresRlsConfig}, resolved: every setting decided, every name checked. */
130
+ export interface RlsSettings {
131
+ /** Every role a request can run as, the default first. */
132
+ roles: readonly string[];
133
+ /** The role a request runs as when the setting is a single name — the first of {@link roles} otherwise. */
134
+ defaultRole: string;
135
+ request: RequestIdentity;
136
+ provisionRole: ProvisionRoleMode;
137
+ grants: GrantsMode;
138
+ policyTarget: PolicyTargetMode;
139
+ defaultPolicies: boolean;
140
+ inheritRoles: readonly string[];
141
+ /**
142
+ * The request roles {@link inheritRoles} are granted to: the one role, or
143
+ * only the signed-in one of a `{ anonymous, signedIn }` pair — granting
144
+ * `authenticated` to `anon` would hand every caller with no session the
145
+ * signed-in policies.
146
+ */
147
+ inheritTo: readonly string[];
148
+ sharedRole: SharedRoleMode;
149
+ /** Every setting that is not at its default, as `name=value`, for the boot line. */
150
+ nonDefaults: readonly string[];
151
+ }
152
+ /**
153
+ * The driver's `rls` block with the environment applied over it — what
154
+ * `postgresDriverConfigFromEnv` does for every other setting. A variable that
155
+ * is set wins over the code; the rest of the block is kept as written.
156
+ */
157
+ export declare function rlsConfigFromEnv(config: PostgresRlsConfig | undefined, read: (name: string) => string | undefined): PostgresRlsConfig | undefined;
158
+ /**
159
+ * Decide every setting from the driver's `rls` block (environment already
160
+ * applied — {@link rlsConfigFromEnv}). Throws on a value it cannot use: a
161
+ * mistyped mode or an unusable role name fails the boot, not the first request.
162
+ */
163
+ export declare function resolveRlsSettings(config: PostgresRlsConfig | undefined): RlsSettings;
164
+ /**
165
+ * What each non-default setting hands to the operator, said once at boot. A
166
+ * hatch that takes a safety job away from Rebase says which job it took.
167
+ */
168
+ export declare function rlsHandoverNotes(settings: RlsSettings): string[];
169
+ /**
170
+ * The request settings for a command that runs outside the server — `db push`,
171
+ * `db migrate`, a restore — which sees the database declaration and the
172
+ * environment but not the backend's code. The roles are the environment's or
173
+ * the declaration's when either names them; otherwise the ones a server boot
174
+ * recorded in this database (which covers a role configured in code);
175
+ * otherwise the default.
176
+ */
177
+ export declare function cliRlsSettings(recordedRoles: readonly string[] | undefined, env?: NodeJS.ProcessEnv): RlsSettings;
@@ -133,6 +133,8 @@ export declare class DataService implements DataRepository {
133
133
  * Execute raw SQL
134
134
  */
135
135
  executeSql(sqlText: string, params?: unknown[]): Promise<Record<string, unknown>[]>;
136
+ /** {@link executeSql}, answering with the driver's whole result: its rows and its column descriptions. */
137
+ executeSqlResult(sqlText: string, params?: unknown[]): Promise<unknown>;
136
138
  /**
137
139
  * Get the underlying FetchService for advanced use
138
140
  */
@@ -4,6 +4,7 @@ import { DataDriver, IncludeSpec, WebSocketMessage, LogicalCondition, OrderByTup
4
4
  import { NodePgDatabase } from "drizzle-orm/node-postgres";
5
5
  import { RealtimeProvider, CollectionSubscriptionConfig, SingleSubscriptionConfig } from "../interfaces.js";
6
6
  import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry.js";
7
+ import type { RequestIdentity } from "../security/rls-settings.js";
7
8
  import type { CdcTableRef } from "./cdc/trigger-cdc.js";
8
9
  import { ChannelBus } from "./channel-bus/index.js";
9
10
  import type { ChannelRetentionRule, RealtimeCounts, RealtimeListenerHealth } from "@rebasepro/types";
@@ -511,6 +512,8 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
511
512
  * would leak rows the initial (isolated) fetch correctly hid.
512
513
  */
513
514
  rlsUserRole?: string;
515
+ /** How a request picks its role and identity settings (`rls`), set with {@link rlsUserRole}. */
516
+ rlsRequest?: RequestIdentity;
514
517
  /**
515
518
  * Verbose subscription tracing.
516
519
  *
@@ -11,8 +11,8 @@
11
11
  * with no viewer at all.
12
12
  */
13
13
  import { type CollectionConfig } from "@rebasepro/types";
14
- /** The roles a materialized view is served to when it names none. */
15
- export declare const DEFAULT_VIEW_ROLES: readonly string[];
14
+ import { DEFAULT_VIEW_ROLES } from "../schema/plan/view-names.js";
15
+ export { DEFAULT_VIEW_ROLES };
16
16
  /** Whether a collection serves a view rather than a table. */
17
17
  export declare function isViewCollection(collection: CollectionConfig | undefined): boolean;
18
18
  /** Refuse a caller who holds none of a materialized view's roles. A no-op for anything else. */
@@ -0,0 +1,24 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ __createRequire(import.meta.url);
3
+ import { toPostgresIdentifier } from "@rebasepro/utils";
4
+ //#region src/schema/plan/view-names.ts
5
+ /**
6
+ * The names a materialized-view collection lives under.
7
+ *
8
+ * Postgres puts no row-level security on a materialized view, and the request
9
+ * role can read anything it holds `SELECT` on. So the stored rows live under
10
+ * {@link viewRowsName}, which only the owner may read, and the collection's
11
+ * own name is a view over them that serves them to the collection's roles
12
+ * (`view.roles`) and to the server itself — a gate in the database, so SQL run
13
+ * as a caller meets it as the SDK does.
14
+ */
15
+ /** The roles a materialized view is served to when it names none. */
16
+ var DEFAULT_VIEW_ROLES = ["admin"];
17
+ /** Where a materialized view's rows are stored. A frozen derived name. */
18
+ var viewRowsName = (name) => toPostgresIdentifier(`${name}_rebase_rows`);
19
+ /** The comment the stored rows carry, beside the gate's `rebase:view:<hash>`. */
20
+ var VIEW_ROWS_COMMENT_PREFIX = "rebase:view-rows:";
21
+ //#endregion
22
+ export { VIEW_ROWS_COMMENT_PREFIX as n, viewRowsName as r, DEFAULT_VIEW_ROLES as t };
23
+
24
+ //# sourceMappingURL=view-names-Dscp6--B.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"view-names-Dscp6--B.js","names":[],"sources":["../src/schema/plan/view-names.ts"],"sourcesContent":["/**\n * The names a materialized-view collection lives under.\n *\n * Postgres puts no row-level security on a materialized view, and the request\n * role can read anything it holds `SELECT` on. So the stored rows live under\n * {@link viewRowsName}, which only the owner may read, and the collection's\n * own name is a view over them that serves them to the collection's roles\n * (`view.roles`) and to the server itself — a gate in the database, so SQL run\n * as a caller meets it as the SDK does.\n */\nimport { toPostgresIdentifier } from \"@rebasepro/utils\";\n\n/** The roles a materialized view is served to when it names none. */\nexport const DEFAULT_VIEW_ROLES: readonly string[] = [\"admin\"];\n\n/** Where a materialized view's rows are stored. A frozen derived name. */\nexport const viewRowsName = (name: string): string => toPostgresIdentifier(`${name}_rebase_rows`);\n\n/** The comment the stored rows carry, beside the gate's `rebase:view:<hash>`. */\nexport const VIEW_ROWS_COMMENT_PREFIX = \"rebase:view-rows:\";\n"],"mappings":";;;;;;;;;;;;;;;AAaA,IAAa,qBAAwC,CAAC,OAAO;;AAG7D,IAAa,gBAAgB,SAAyB,qBAAqB,GAAG,KAAK,aAAa;;AAGhG,IAAa,2BAA2B"}
@@ -1,8 +1,8 @@
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 { A as budgetSendBuffers, M as terminateIfBacklogged, N as assertReadRequestReadable, ct as SqlResultTooLargeError, it as effectiveSqlRole, j as reapSilentSockets, lt as isNestedPath, ot as sqlRoleRanAs, st as SQL_RESULT_BYTE_BUDGET, ut as resolveNestedPath } from "./open-rebase-CTNBmmH8.js";
5
- import { r as BranchingUnsupportedError } from "./BranchService-JiYJ_n9E.js";
4
+ import { A as budgetSendBuffers, M as terminateIfBacklogged, N as assertReadRequestReadable, ct as SqlResultTooLargeError, it as effectiveSqlRole, j as reapSilentSockets, lt as isNestedPath, ot as sqlRoleRanAs, st as SQL_RESULT_BYTE_BUDGET, ut as resolveNestedPath } from "./open-rebase-CiO_sjMT.js";
5
+ import { r as BranchingUnsupportedError } from "./BranchService-BIIBF5ZL.js";
6
6
  import { ApiError, DATABASE_UNAVAILABLE_MESSAGE, RUNTIME_DEFAULT_MAX_BODY_SIZE, assertFieldOpsValid, assertNestedWriteAllowed, assertNoFieldOpsOnCreate, assertNoUserUpsert, assertUserCreationBodyValid, assertWriteRequestValid, createUserThroughAuthCollection, decideImpersonation, declaredErrorAnswer, extractUserFromToken, getAccessModel, isDatabaseUnreachable, logger, resolveConflictTarget, resolveRequireAuth, safeCompare } from "@rebasepro/server";
7
7
  import { ANONYMOUS_USER_ID, ListLimitError, hasAdminRole, isSQLAdmin, isSchemaAdmin, resolveClientListLimit, scopeGrants, scopesForRoles } from "@rebasepro/types";
8
8
  import { UnknownFilterOperatorError, deserializeFilter, redactSqlLiterals } from "@rebasepro/common";
@@ -1698,4 +1698,4 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1698
1698
  //#endregion
1699
1699
  export { createPostgresWebSocket as a, websocket_exports as c, TOO_MANY_SOCKETS_CLOSE_CODE as i, PUBLIC_TYPES as n, isSocketRealtimeService as o, SESSION_ENDED_CLOSE_CODE as r, socketRealtimeMissing as s, ADMIN_PLANE_TYPES as t };
1700
1700
 
1701
- //# sourceMappingURL=websocket-D2y88dOa.js.map
1701
+ //# sourceMappingURL=websocket-B33YjKhs.js.map