@rebasepro/server-postgres 0.29.0-canary.g0e3a0e7 → 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 (127) hide show
  1. package/dist/{BranchService-BPssiD8_.js → BranchService-BIIBF5ZL.js} +3 -3
  2. package/dist/{BranchService-BPssiD8_.js.map → BranchService-BIIBF5ZL.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +105 -9
  4. package/dist/PostgresBootstrapper.d.ts +14 -0
  5. package/dist/{backup-cli-C1wcj-rc.js → backup-cli-QcOpmRpQ.js} +3 -3
  6. package/dist/{backup-cli-C1wcj-rc.js.map → backup-cli-QcOpmRpQ.js.map} +1 -1
  7. package/dist/{boot-ddl-CIGoIGcC.js → boot-ddl-BSNpEUOS.js} +2 -2
  8. package/dist/{boot-ddl-CIGoIGcC.js.map → boot-ddl-BSNpEUOS.js.map} +1 -1
  9. package/dist/{cli-console-CJLtH58M.js → cli-console-DTsm96lW.js} +6 -6
  10. package/dist/{cli-console-CJLtH58M.js.map → cli-console-DTsm96lW.js.map} +1 -1
  11. package/dist/{cli-errors-DYets7cp.js → cli-errors-DwqFRIWz.js} +69 -6
  12. package/dist/cli-errors-DwqFRIWz.js.map +1 -0
  13. package/dist/cli-helpers.d.ts +10 -0
  14. package/dist/cli.js +90 -44
  15. package/dist/cli.js.map +1 -1
  16. package/dist/{connection-CcYqncW5.js → connection-COuS5Fm-.js} +15 -2
  17. package/dist/connection-COuS5Fm-.js.map +1 -0
  18. package/dist/connection.d.ts +6 -0
  19. package/dist/database-preflight-D5JtPt8i.js +151 -0
  20. package/dist/database-preflight-D5JtPt8i.js.map +1 -0
  21. package/dist/{databasePoolManager-XmhMczz0.js → databasePoolManager-7hXVurmG.js} +2 -2
  22. package/dist/{databasePoolManager-XmhMczz0.js.map → databasePoolManager-7hXVurmG.js.map} +1 -1
  23. package/dist/db-subcommands.d.ts +1 -1
  24. package/dist/{deferred-index-build-BwH6k1Og.js → deferred-index-build-B8feKnUj.js} +12 -8
  25. package/dist/deferred-index-build-B8feKnUj.js.map +1 -0
  26. package/dist/{doctor-TJApVglQ.js → doctor-BaR11xUe.js} +20 -6
  27. package/dist/doctor-BaR11xUe.js.map +1 -0
  28. package/dist/{ensure-collection-policies-f0LIwiwp.js → ensure-collection-policies-85HiG-k1.js} +8 -8
  29. package/dist/{ensure-collection-policies-f0LIwiwp.js.map → ensure-collection-policies-85HiG-k1.js.map} +1 -1
  30. package/dist/{ensure-collection-tables-DvaCEy6X.js → ensure-collection-tables-DR_WcxLA.js} +20 -9
  31. package/dist/ensure-collection-tables-DR_WcxLA.js.map +1 -0
  32. package/dist/{ensure-tables-CF-8zgYA.js → ensure-tables-Dh5UP_Zs.js} +4 -4
  33. package/dist/{ensure-tables-CF-8zgYA.js.map → ensure-tables-Dh5UP_Zs.js.map} +1 -1
  34. package/dist/{enum-labels-kept-DAbJ_IIl.js → enum-labels-kept-DSU8lAnd.js} +3 -3
  35. package/dist/{enum-labels-kept-DAbJ_IIl.js.map → enum-labels-kept-DSU8lAnd.js.map} +1 -1
  36. package/dist/{generate-drizzle-schema-BAIp9nKT.js → generate-drizzle-schema-5spbTyQ6.js} +2 -2
  37. package/dist/{generate-drizzle-schema-BAIp9nKT.js.map → generate-drizzle-schema-5spbTyQ6.js.map} +1 -1
  38. package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js → generate-drizzle-schema-logic-C5FB7Fpo.js} +2 -2
  39. package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js.map → generate-drizzle-schema-logic-C5FB7Fpo.js.map} +1 -1
  40. package/dist/{generate-files-DutUrsSS.js → generate-files-Bl3_D_oP.js} +11 -4
  41. package/dist/generate-files-Bl3_D_oP.js.map +1 -0
  42. package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js → generate-postgres-ddl-logic-BC3JA93M.js} +11 -4
  43. package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js.map → generate-postgres-ddl-logic-BC3JA93M.js.map} +1 -1
  44. package/dist/{generated-schema-diff-ChFg6UxI.js → generated-schema-diff-Jm93vyJB.js} +29 -6
  45. package/dist/generated-schema-diff-Jm93vyJB.js.map +1 -0
  46. package/dist/index.d.ts +2 -1
  47. package/dist/index.es.js +22 -14
  48. package/dist/index.es.js.map +1 -1
  49. package/dist/{migrate-baseline-DPawvckr.js → migrate-baseline-BfHmq3vN.js} +49 -4
  50. package/dist/{migrate-baseline-DPawvckr.js.map → migrate-baseline-BfHmq3vN.js.map} +1 -1
  51. package/dist/{migrate-policy-stamps-CdljD_y1.js → migrate-policy-stamps-B4k1ggma.js} +7 -7
  52. package/dist/{migrate-policy-stamps-CdljD_y1.js.map → migrate-policy-stamps-B4k1ggma.js.map} +1 -1
  53. package/dist/{open-rebase-DvmKIu7q.js → open-rebase-CiO_sjMT.js} +1574 -195
  54. package/dist/open-rebase-CiO_sjMT.js.map +1 -0
  55. package/dist/open-rebase.d.ts +6 -1
  56. package/dist/{pg-error-utils-BIHfsGZL.js → pg-error-utils-D1Nc0UML.js} +2 -2
  57. package/dist/{pg-error-utils-BIHfsGZL.js.map → pg-error-utils-D1Nc0UML.js.map} +1 -1
  58. package/dist/pipelined-transaction.d.ts +131 -0
  59. package/dist/{plan-schema-DMVh77yb.js → plan-schema-BYxOzflz.js} +147 -8
  60. package/dist/plan-schema-BYxOzflz.js.map +1 -0
  61. package/dist/{policy-drift-0Cp4Lc0x.js → policy-drift-DKuTJHfc.js} +2 -2
  62. package/dist/{policy-drift-0Cp4Lc0x.js.map → policy-drift-DKuTJHfc.js.map} +1 -1
  63. package/dist/{push-index-prebuild-C6wKdjYV.js → push-index-prebuild-bqXimSZz.js} +4 -4
  64. package/dist/{push-index-prebuild-C6wKdjYV.js.map → push-index-prebuild-bqXimSZz.js.map} +1 -1
  65. package/dist/{push-kept-defaults-BSqPzp0T.js → push-kept-defaults-CN9R8cHf.js} +2 -2
  66. package/dist/{push-kept-defaults-BSqPzp0T.js.map → push-kept-defaults-CN9R8cHf.js.map} +1 -1
  67. package/dist/{push-legacy-renames-BFF72tHG.js → push-legacy-renames-CU_UYPbz.js} +4 -4
  68. package/dist/{push-legacy-renames-BFF72tHG.js.map → push-legacy-renames-CU_UYPbz.js.map} +1 -1
  69. package/dist/{push-policy-plan-lOTPeQ1u.js → push-policy-plan-JcyK94bc.js} +4 -4
  70. package/dist/{push-policy-plan-lOTPeQ1u.js.map → push-policy-plan-JcyK94bc.js.map} +1 -1
  71. package/dist/{render-ddl-NpPPDACz.js → render-ddl-DCdVP-pQ.js} +95 -4
  72. package/dist/render-ddl-DCdVP-pQ.js.map +1 -0
  73. package/dist/request-role-cli-DSdRtvgH.js +260 -0
  74. package/dist/request-role-cli-DSdRtvgH.js.map +1 -0
  75. package/dist/request-role-cli.d.ts +86 -0
  76. package/dist/request-role-migration-D9BZ5Uba.js +150 -0
  77. package/dist/request-role-migration-D9BZ5Uba.js.map +1 -0
  78. package/dist/rls-enforcement-BO618rnr.js +992 -0
  79. package/dist/rls-enforcement-BO618rnr.js.map +1 -0
  80. package/dist/rls-settings-De5NoHHy.js +211 -0
  81. package/dist/rls-settings-De5NoHHy.js.map +1 -0
  82. package/dist/schema/doctor-cli.js +144 -6
  83. package/dist/schema/doctor-cli.js.map +1 -1
  84. package/dist/schema/doctor-database.d.ts +27 -0
  85. package/dist/schema/generate-drizzle-schema.js +1 -1
  86. package/dist/schema/generate-files.d.ts +2 -1
  87. package/dist/schema/generate-postgres-ddl-logic.d.ts +6 -0
  88. package/dist/schema/generate-postgres-ddl.js +1 -1
  89. package/dist/schema/introspect-db.js +2 -2
  90. package/dist/schema/introspect-runtime.d.ts +10 -1
  91. package/dist/schema/plan/diff-plan.d.ts +6 -1
  92. package/dist/schema/plan/plan-schema.d.ts +9 -1
  93. package/dist/schema/plan/render-ddl.d.ts +32 -1
  94. package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
  95. package/dist/schema/plan/types.d.ts +39 -0
  96. package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
  97. package/dist/schema/plan/view-names.d.ts +6 -0
  98. package/dist/schema/rls-bootstrap-sql.d.ts +23 -0
  99. package/dist/security/caller-sql-columns.d.ts +60 -0
  100. package/dist/security/caller-sql.d.ts +8 -0
  101. package/dist/security/database-preflight.d.ts +24 -0
  102. package/dist/security/request-role-migration.d.ts +36 -0
  103. package/dist/security/rls-enforcement.d.ts +201 -20
  104. package/dist/security/rls-settings.d.ts +177 -0
  105. package/dist/services/FetchService.d.ts +12 -12
  106. package/dist/services/PersistService.d.ts +59 -0
  107. package/dist/services/collection-helpers.d.ts +3 -1
  108. package/dist/services/dataService.d.ts +2 -0
  109. package/dist/services/realtimeService.d.ts +3 -0
  110. package/dist/services/view-access.d.ts +21 -0
  111. package/dist/view-names-Dscp6--B.js +24 -0
  112. package/dist/view-names-Dscp6--B.js.map +1 -0
  113. package/dist/{websocket-CCJnghvG.js → websocket-B33YjKhs.js} +3 -3
  114. package/dist/{websocket-CCJnghvG.js.map → websocket-B33YjKhs.js.map} +1 -1
  115. package/package.json +7 -7
  116. package/dist/cli-errors-DYets7cp.js.map +0 -1
  117. package/dist/connection-CcYqncW5.js.map +0 -1
  118. package/dist/deferred-index-build-BwH6k1Og.js.map +0 -1
  119. package/dist/doctor-TJApVglQ.js.map +0 -1
  120. package/dist/ensure-collection-tables-DvaCEy6X.js.map +0 -1
  121. package/dist/generate-files-DutUrsSS.js.map +0 -1
  122. package/dist/generated-schema-diff-ChFg6UxI.js.map +0 -1
  123. package/dist/open-rebase-DvmKIu7q.js.map +0 -1
  124. package/dist/plan-schema-DMVh77yb.js.map +0 -1
  125. package/dist/render-ddl-NpPPDACz.js.map +0 -1
  126. package/dist/rls-enforcement-BOHuHVlc.js +0 -502
  127. package/dist/rls-enforcement-BOHuHVlc.js.map +0 -1
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The columns a caller may not read, taken out of what their SQL returned.
3
+ *
4
+ * Per-field read rules (`access.read`, and `excludeFromApi`, which is
5
+ * `read: []`) are not something Postgres can hold for one request role shared
6
+ * by every user, so the SDK applies them to each row it serves
7
+ * (`stripUnreadable`). SQL run as the caller (`DataDriver.sql`) returns rows
8
+ * the SDK never walked — and `SELECT *` from a users table would hand over the
9
+ * password hash.
10
+ *
11
+ * Postgres says where each result column came from: the row description
12
+ * carries the table's oid and the column's number for every column that is a
13
+ * plain reference to one, aliased or not, `RETURNING` included. A column whose
14
+ * origin is a collection property this caller cannot read is dropped from
15
+ * every row, the way the API drops it.
16
+ *
17
+ * What it cannot see is a value computed from such a column — `md5(hash)`,
18
+ * `hash || ''` — whose origin Postgres reports as none. That is the query
19
+ * text's business, and the query text is the application's (see
20
+ * `caller-sql.ts`).
21
+ *
22
+ * A driver that reports no origins at all (PGlite) has its result columns
23
+ * matched by name instead, against every restricted column of every
24
+ * collection: it may drop a column of the same name from another table, never
25
+ * keep one it should drop.
26
+ */
27
+ import { type FieldViewer } from "@rebasepro/common";
28
+ import { type CollectionConfig } from "@rebasepro/types";
29
+ /** A result column as the driver describes it. */
30
+ export interface ResultField {
31
+ name: string;
32
+ /** The originating table's oid; 0 for a computed column. Absent when the driver does not say (PGlite). */
33
+ tableID?: number;
34
+ /** The originating column's number within it. */
35
+ columnID?: number;
36
+ }
37
+ /** The columns of a result, from a pg `QueryResult` (or the last of several). */
38
+ export declare function fieldsOfResult(result: unknown): ResultField[];
39
+ type CatalogueRunner = (text: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
40
+ interface Relation {
41
+ schema: string;
42
+ name: string;
43
+ /** `attnum` → `attname`. */
44
+ columns: Map<number, string>;
45
+ }
46
+ /**
47
+ * The relations result columns came from, by oid, read from the catalogue the
48
+ * first time an oid is seen. An oid never changes meaning: a table that is
49
+ * dropped and created again gets a new one, which is read when it appears.
50
+ */
51
+ export declare class ColumnOrigins {
52
+ private readonly relations;
53
+ describe(oids: number[], run: CatalogueRunner): Promise<Map<number, Relation | null>>;
54
+ }
55
+ /**
56
+ * `rows` without the columns `viewer` may not read, by the origins `fields`
57
+ * describe. The rows are changed in place and returned.
58
+ */
59
+ export declare function withoutUnreadableColumns(rows: Record<string, unknown>[], fields: ResultField[], viewer: FieldViewer, collections: CollectionConfig[], origins: ColumnOrigins, run: CatalogueRunner): Promise<Record<string, unknown>[]>;
60
+ export {};
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The query with every string literal, dollar-quoted body and comment
3
+ * replaced by a space. Quoted identifiers are kept, quotes and all, so a name
4
+ * written `"set_config"` still reads as one.
5
+ */
6
+ export declare function maskSqlLiterals(text: string): string;
7
+ /** Throw `SQL_NOT_ALLOWED` unless `text` may run as the caller (see the module docs). */
8
+ export declare function assertCallerSql(text: string): void;
@@ -0,0 +1,24 @@
1
+ import { type ManagedTable, type RawSqlRunner } from "./rls-enforcement.js";
2
+ import type { RlsSettings } from "./rls-settings.js";
3
+ /**
4
+ * What `rebase doctor --database` checks: whether this database can host
5
+ * Rebase's request role(s) under the project's `rls` settings, read from the
6
+ * catalogue without changing anything.
7
+ *
8
+ * Every finding that is not "ok" carries the SQL to run as an administrator, the
9
+ * `rls` setting that would adapt Rebase to the database instead, or both — the
10
+ * two ways out of any of them.
11
+ */
12
+ export interface PreflightFinding {
13
+ level: "ok" | "warn" | "fail";
14
+ check: string;
15
+ detail: string;
16
+ /** SQL that fixes it, run as a database administrator. */
17
+ sql?: string;
18
+ /** The `rls` setting that would fit Rebase to the database as it is. */
19
+ setting?: string;
20
+ }
21
+ export declare function preflightDatabase(run: RawSqlRunner, settings: RlsSettings, options: {
22
+ schemas: readonly string[];
23
+ managedTables: readonly ManagedTable[];
24
+ }): Promise<PreflightFinding[]>;
@@ -0,0 +1,36 @@
1
+ import { type RawSqlRunner } from "./rls-enforcement.js";
2
+ /**
3
+ * Move a database from one set of request roles to another — what
4
+ * `rebase db request-role migrate --to …` runs.
5
+ *
6
+ * A role belongs to the cluster, so renaming one (`ALTER ROLE … RENAME`) moves
7
+ * every database's grants at once, including another project's that shares
8
+ * it. This instead creates the new role(s) and re-issues, in THIS database
9
+ * only, every grant the old ones hold here: tables and views, columns,
10
+ * sequences, schemas, functions, the default privileges this connection set,
11
+ * and the memberships that carry other roles' policies (`rls.inheritRoles`).
12
+ * Policies that name an old role in their `TO` list are re-pointed. The old
13
+ * roles are left as they are — another database may still use them — and the
14
+ * statements to take their grants back here are returned for the operator.
15
+ */
16
+ export interface RequestRoleMigrationPlan {
17
+ /** What to run, in order, to give the new roles what the old ones hold here. */
18
+ statements: string[];
19
+ /** What would take the old roles' grants back in this database, for the operator to run once satisfied. */
20
+ revokeOld: string[];
21
+ }
22
+ /**
23
+ * Read the catalogue and plan the move. Writes nothing; {@link migrateRequestRoles}
24
+ * runs the plan.
25
+ */
26
+ export declare function planRequestRoleMigration(run: RawSqlRunner, from: readonly string[], to: readonly string[]): Promise<RequestRoleMigrationPlan>;
27
+ /**
28
+ * Provision the new role(s), run the plan, and record the new roles — in one
29
+ * transaction where the runner has one, so a failure leaves the database on
30
+ * its old roles. Returns the plan that ran.
31
+ */
32
+ export declare function migrateRequestRoles(run: RawSqlRunner, options: {
33
+ from: readonly string[];
34
+ to: readonly string[];
35
+ schemas: readonly string[];
36
+ }): Promise<RequestRoleMigrationPlan>;
@@ -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,18 @@ 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>;
438
+ /**
439
+ * {@link applyAuthContext} as one statement and its values, for a transaction
440
+ * that sends it in the same batch as its first query
441
+ * (`pipelined-transaction.ts`). `before` are settings of the transaction's own
442
+ * — what a pooled connection could not carry at connect — set ahead of the
443
+ * caller's, in the same statement.
444
+ */
445
+ export declare function authContextStatement(auth: AuthContext, userRole?: string | RequestIdentity, before?: readonly (readonly [string, string])[]): {
446
+ text: string;
447
+ values: string[];
448
+ };
275
449
  /**
276
450
  * Warn about rules that read as "signed-in users only" but admit anonymous
277
451
  * callers — `rebase.uid() IS NOT NULL`, or a comparison against another
@@ -319,8 +493,14 @@ export declare function warnOnLegacyRlsFunctions(collections: {
319
493
  * no data, so the mistake survives review and ships.
320
494
  *
321
495
  * Requests run as `rebase_user`, so a policy is only reachable if it targets
322
- * `public` or a role `rebase_user` holds. Anything else is a configuration
323
- * 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.
324
504
  */
325
505
  export declare function validatePolicyPgRoles(run: RawSqlRunner, collections: {
326
506
  slug?: string;
@@ -329,6 +509,7 @@ export declare function validatePolicyPgRoles(run: RawSqlRunner, collections: {
329
509
  pgRoles?: readonly string[];
330
510
  }[];
331
511
  }[],
332
- /** The role requests actually run as: `rebase_user` when the connection is
333
- * privileged enough to switch, otherwise the connection role itself. */
334
- 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;
@@ -1,7 +1,7 @@
1
1
  import { SQL } from "drizzle-orm";
2
2
  import { AnyPgColumn, PgTable } from "drizzle-orm/pg-core";
3
3
  import { FilterValues, OrderByTuple, LogicalCondition } from "@rebasepro/types";
4
- import type { IncludeSpec, VectorSearchParams } from "@rebasepro/types";
4
+ import type { DriverAggregate, DriverAggregateGroup, IncludeSpec, VectorSearchParams } from "@rebasepro/types";
5
5
  import { RelationService } from "./RelationService.js";
6
6
  import { DrizzleClient } from "../interfaces.js";
7
7
  import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry.js";
@@ -30,11 +30,7 @@ import { type ReadCallContextProvider } from "./read-scope.js";
30
30
  * Exported to be tested: the parsing itself needs a database, this decision
31
31
  * does not.
32
32
  */
33
- export declare function numericAggregateAliases(aggregates: {
34
- fn: "count" | "sum" | "avg" | "min" | "max";
35
- field?: string;
36
- alias: string;
37
- }[], properties: Record<string, {
33
+ export declare function numericAggregateAliases(aggregates: DriverAggregate[], properties: Record<string, {
38
34
  type?: string;
39
35
  }>): Set<string>;
40
36
  export declare class FetchService {
@@ -562,12 +558,8 @@ export declare class FetchService {
562
558
  * has to be zero.
563
559
  */
564
560
  aggregate<M extends Record<string, unknown>>(collectionPath: string, options: {
565
- aggregates: {
566
- fn: "count" | "sum" | "avg" | "min" | "max";
567
- field?: string;
568
- alias: string;
569
- }[];
570
- groupBy?: string[];
561
+ aggregates: DriverAggregate[];
562
+ groupBy?: (string | DriverAggregateGroup)[];
571
563
  filter?: FilterValues<Extract<keyof M, string>>;
572
564
  logical?: LogicalCondition;
573
565
  searchString?: string;
@@ -582,6 +574,14 @@ export declare class FetchService {
582
574
  /** See `FetchCollectionProps.withDeleted`. */
583
575
  withDeleted?: WithDeleted;
584
576
  }): Promise<Record<string, unknown>[]>;
577
+ /**
578
+ * A transformed group (`AggregateGroup`) as SQL. `lower`/`upper` read the
579
+ * column as text; `year`/`month`/`day` truncate a date or timestamp, in UTC
580
+ * when it has a time zone, to `YYYY`, `YYYY-MM` or `YYYY-MM-DD`; `unnest`
581
+ * adds a lateral join over the array's elements to `lateral` and groups by
582
+ * the element.
583
+ */
584
+ private groupExpression;
585
585
  /**
586
586
  * The `ORDER BY` of a grouped aggregate: the caller's keys, then every
587
587
  * group key they did not name.