@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
@@ -0,0 +1,992 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ __createRequire(import.meta.url);
3
+ import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
+ import { n as VIEW_ROWS_COMMENT_PREFIX } from "./view-names-Dscp6--B.js";
5
+ import { ot as extractCauseMessage } from "./cli-errors-DwqFRIWz.js";
6
+ import { logger } from "@rebasepro/server";
7
+ import { sql } from "drizzle-orm";
8
+ import { ANONYMOUS_USER_ID, REBASE_SCHEMA, usesLegacyRlsFunctions } from "@rebasepro/types";
9
+ import { LOAD_REQUEST_ROLES_PLPGSQL, REBASE_INTERNAL_TABLES, REBASE_USER_ROLE as REBASE_USER_ROLE$1, findAnonymousGrants, revokeInternalTableAccess, revokeInternalTableSql, securityRuleToConditions } from "@rebasepro/common";
10
+ //#region src/security/rls-enforcement.ts
11
+ var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
12
+ AppRoleSetupError: () => AppRoleSetupError,
13
+ REBASE_USER_ROLE: () => REBASE_USER_ROLE$1,
14
+ REQUEST_ROLES_KEY: () => REQUEST_ROLES_KEY,
15
+ appRoleSetupInstructions: () => appRoleSetupInstructions,
16
+ applyAuthContext: () => applyAuthContext,
17
+ assertAppRoleRestricted: () => assertAppRoleRestricted,
18
+ assertRecordedRequestRoles: () => assertRecordedRequestRoles,
19
+ authContextStatement: () => authContextStatement,
20
+ detectConnectionPosture: () => detectConnectionPosture,
21
+ ensureAppRole: () => ensureAppRole,
22
+ ensureAppRoleGrants: () => ensureAppRoleGrants,
23
+ ensureInheritedRoles: () => ensureInheritedRoles,
24
+ findExposedInternalTables: () => findExposedInternalTables,
25
+ findOtherRoleMembers: () => findOtherRoleMembers,
26
+ findUngrantableTables: () => findUngrantableTables,
27
+ internalTablesGrantedToUserRole: () => internalTablesGrantedToUserRole,
28
+ proveRoleSwitch: () => proveRoleSwitch,
29
+ readRecordedRequestRoles: () => readRecordedRequestRoles,
30
+ recordRequestRoles: () => recordRequestRoles,
31
+ revokeUserRoleSql: () => revokeUserRoleSql,
32
+ roleHoldsTableGrants: () => roleHoldsTableGrants,
33
+ validatePolicyPgRoles: () => validatePolicyPgRoles,
34
+ warnOnAnonymousGrants: () => warnOnAnonymousGrants,
35
+ warnOnLegacyRlsFunctions: () => warnOnLegacyRlsFunctions,
36
+ warnOnRoleSchemaCollision: () => warnOnRoleSchemaCollision
37
+ });
38
+ var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
39
+ /** A string literal for a catalogue read. Names come from config and constants, never from a request. */
40
+ var sqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
41
+ var textArray = (values) => values.length === 0 ? "ARRAY[]::text[]" : `ARRAY[${values.map(sqlLiteral).join(", ")}]::text[]`;
42
+ /** A `text[]` column as read back — an array, or `{a,b}` from a driver that hands arrays back as text. */
43
+ var textArrayValue = (value) => Array.isArray(value) ? value.map(String) : String(value ?? "").replace(/^\{|\}$/g, "").split(",").filter(Boolean);
44
+ /** DML the user role holds on managed tables (RLS still filters per row). */
45
+ var USER_TABLE_PRIVILEGES = "SELECT, INSERT, UPDATE, DELETE";
46
+ /**
47
+ * Take every privilege the request roles hold on one table back — what a
48
+ * table gets when RLS cannot be switched on for it, so it is unreachable
49
+ * rather than unprotected. Quoted exactly: a mixed-case adopted table
50
+ * (`"User"`) folded to lower case names a table that does not exist.
51
+ *
52
+ * Every request role, as this database recorded them (`rls.requestRole`), and
53
+ * each only if it exists: one statement, for the boot's policies step and its
54
+ * final posture check alike, without either being handed the roles.
55
+ */
56
+ var revokeUserRoleSql = (schema, table) => `
57
+ DO $rebase_withhold$
58
+ DECLARE
59
+ request_roles text[];
60
+ request_role text;
61
+ BEGIN
62
+ ${LOAD_REQUEST_ROLES_PLPGSQL}
63
+ FOREACH request_role IN ARRAY request_roles LOOP
64
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = request_role) THEN
65
+ EXECUTE format('REVOKE ALL PRIVILEGES ON %I.%I FROM %I', ${sqlLiteral(schema)}, ${sqlLiteral(table)}, request_role);
66
+ END IF;
67
+ END LOOP;
68
+ END
69
+ $rebase_withhold$
70
+ `.trim();
71
+ /**
72
+ * Warn when the connection role shares its name with an existing schema.
73
+ *
74
+ * Postgres resolves unqualified names through `search_path`, which defaults to
75
+ * `"$user", public` — and `$user` is the connection ROLE. When a schema of that
76
+ * name exists it sits ahead of `public`, so every unqualified statement
77
+ * silently operates on it instead:
78
+ *
79
+ * CREATE TABLE posts (...); -- you meant public.posts; you got <role>.posts
80
+ *
81
+ * Nothing errors. You get a second table of the same name in the wrong schema,
82
+ * and reads that pin `public` cannot see it — which reads as "missing table" and
83
+ * sends people to re-run a push that creates a *third* copy. The bootstrapper
84
+ * has a whole branch dedicated to recognising the symptom after the fact.
85
+ *
86
+ * Rebase shipped straight into this: it creates a schema named `rebase` while
87
+ * every template named the database role `rebase` too. The scaffold uses
88
+ * `rebase_app` now, and every pool Rebase opens pins `search_path=public`
89
+ * (`pinSearchPath`), which covers the paths the framework controls. This covers
90
+ * the ones it does not — `psql`, `pg_dump`, drizzle-kit, a colleague's script,
91
+ * a hand-written migration — because the hazard is a property of the two NAMES,
92
+ * not of any one connection.
93
+ *
94
+ * A warning rather than a boot failure: the database works, the framework's own
95
+ * traffic is pinned, and refusing to start over a naming choice a user may have
96
+ * inherited would be worse than the risk.
97
+ */
98
+ async function warnOnRoleSchemaCollision(run) {
99
+ try {
100
+ const rows = await run(`
101
+ SELECT current_user AS role,
102
+ EXISTS (
103
+ SELECT 1 FROM pg_namespace n WHERE n.nspname = current_user
104
+ ) AS collides
105
+ `);
106
+ if (rows[0]?.collides !== true) return;
107
+ const role = String(rows[0]?.role ?? "the connection role");
108
+ logger.warn(`⚠️ The database role "${role}" has the same name as a schema. Postgres resolves unqualified names through \`search_path\`, which defaults to \`"$user", public\` — so "${role}" is searched BEFORE public, and any unqualified \`CREATE TABLE\`/\`SELECT\` from a tool that does not pin the path (psql, pg_dump, drizzle-kit, a hand-written migration) silently lands in "${role}" instead. Rebase's own connections pin \`search_path=public\`, so the server is unaffected. To remove the hazard entirely, connect as a role whose name is not also a schema — the scaffold uses "rebase_app".`);
109
+ } catch {}
110
+ }
111
+ /**
112
+ * Would RLS actually constrain this connection?
113
+ *
114
+ * Four ways the answer is no, and only two of them are obvious. Superuser and
115
+ * BYPASSRLS announce themselves in `pg_roles`. The other two are about
116
+ * ownership, and both used to read as "no bypass here":
117
+ *
118
+ * - **Ownership through membership.** The old query compared
119
+ * `pg_tables.tableowner` to `current_user` as a string. Postgres does not: a
120
+ * role that INHERITs the owner passes every ownership test the planner makes,
121
+ * including the one that decides whether a policy applies. So a perfectly
122
+ * ordinary "app role that is a member of the owner role" setup reported
123
+ * unprivileged and bypassed every policy — permanently, since no restart
124
+ * changes a string comparison's answer.
125
+ *
126
+ * - **Ownership that has not happened yet.** The posture is decided once, at
127
+ * boot, and on a fresh database there is nothing in the catalogue to find. The
128
+ * same process then creates every table and owns all of them. The first boot
129
+ * of a new deployment therefore served every request unconstrained, the log
130
+ * said RLS was fine, and the SECOND boot silently fixed it — which is the
131
+ * worst possible shape for a security check, because the state that reproduces
132
+ * it is gone by the time anyone looks. Asking "may this role create tables
133
+ * where the server provisions?" answers about the process's whole life rather
134
+ * than about one instant of it.
135
+ *
136
+ * `schemas` narrows the CREATE question to where the server actually writes.
137
+ * Omitted, it asks about every schema the role can see, which is the safe
138
+ * direction: over-reporting costs a role switch that was not strictly needed,
139
+ * under-reporting costs the entire authorization model.
140
+ */
141
+ async function detectConnectionPosture(run, schemas) {
142
+ const row = (await run(`
143
+ SELECT current_user AS role,
144
+ r.rolsuper AS superuser,
145
+ r.rolbypassrls AS bypassrls,
146
+ EXISTS (
147
+ SELECT 1 FROM pg_tables t
148
+ WHERE pg_has_role(current_user, t.tableowner, 'USAGE')
149
+ AND t.schemaname NOT IN ('pg_catalog', 'information_schema')
150
+ ) AS owns_tables,
151
+ EXISTS (
152
+ SELECT 1 FROM pg_namespace n
153
+ WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
154
+ AND n.nspname NOT LIKE 'pg\\_toast%'
155
+ AND n.nspname NOT LIKE 'pg\\_temp%'
156
+ ${schemas?.length ? `AND n.nspname IN (${Array.from(new Set(schemas)).map((s) => `'${s.replace(/'/g, "''")}'`).join(", ")})` : ""}
157
+ AND has_schema_privilege(current_user, n.oid, 'CREATE')
158
+ ) AS can_create
159
+ FROM pg_roles r
160
+ WHERE r.rolname = current_user
161
+ `))[0] ?? {};
162
+ const superuser = row.superuser === true;
163
+ const bypassRLS = row.bypassrls === true;
164
+ const ownsTables = row.owns_tables === true;
165
+ const canCreateTables = row.can_create === true;
166
+ return {
167
+ role: String(row.role ?? "unknown"),
168
+ superuser,
169
+ bypassRLS,
170
+ ownsTables,
171
+ canCreateTables,
172
+ privileged: superuser || bypassRLS || ownsTables || canCreateTables
173
+ };
174
+ }
175
+ /**
176
+ * The Postgres major from which a role membership carries a separate SET
177
+ * option, as `server_version_num` spells it.
178
+ *
179
+ * From 16, `pg_has_role(…, 'MEMBER')` no longer answers "may this connection
180
+ * `SET ROLE` to it": a membership can be held with `SET FALSE`. That is exactly
181
+ * what a non-superuser with CREATEROLE gets for a role it creates — Postgres
182
+ * records the creator as a member `WITH ADMIN TRUE, SET FALSE, INHERIT FALSE`
183
+ * (unless `createrole_self_grant` says otherwise). RDS's master user, Cloud
184
+ * SQL's `postgres`, Neon's owner and most managed "admin" users are that kind
185
+ * of role. Asking MEMBER said yes, the grant was skipped, boot logged RLS as
186
+ * active, and every signed-in request then failed with 42501 "permission
187
+ * denied to set role". A plain `GRANT` on top changes nothing — Postgres reports
188
+ * the membership as already granted — so the grant has to name the option.
189
+ */
190
+ var SET_OPTION_SINCE = 16e4;
191
+ /**
192
+ * Raised when `rebase_user` cannot be provisioned, adopted or switched to —
193
+ * with the SQL that fixes it in {@link instructions}.
194
+ *
195
+ * Its own class so a caller that prints the instructions itself (the CLI) can
196
+ * tell they are already in the message.
197
+ */
198
+ var AppRoleSetupError = class extends Error {
199
+ instructions;
200
+ constructor(problem, instructions) {
201
+ super(`${problem}\n\n${instructions}`);
202
+ this.name = "AppRoleSetupError";
203
+ this.instructions = instructions;
204
+ }
205
+ };
206
+ /**
207
+ * What a failed statement said, without the statement.
208
+ *
209
+ * A Drizzle runner throws `Failed query: <sql>\nparams: <values>` and keeps
210
+ * Postgres's own sentence in `.cause`. The logger redacts from that marker to
211
+ * the next stack frame — the params have no terminator — so any text appended
212
+ * after a Drizzle message is redacted with it. That is how the setup SQL below
213
+ * used to vanish from a production log. Postgres's messages carry no statement
214
+ * and no row values, and they are the part that says what is wrong.
215
+ */
216
+ function failureReason(err) {
217
+ return extractCauseMessage(err) ?? (err instanceof Error ? err.message : String(err));
218
+ }
219
+ /**
220
+ * The statement that lets `connectionRole` switch to the user role, as one
221
+ * statement that works on any Postgres the driver supports.
222
+ *
223
+ * Version-adaptive rather than two alternatives for the reader to choose
224
+ * between: `WITH SET TRUE` is a syntax error before 16, and a plain `GRANT`
225
+ * from 16 on is a no-op on a membership that exists without SET.
226
+ * `INHERIT FALSE` keeps the connection from picking up the user role's
227
+ * privileges as its own; the switch is all it needs.
228
+ */
229
+ function membershipGrantSql(connectionRole, role = REBASE_USER_ROLE$1) {
230
+ const member = sqlLiteral(connectionRole);
231
+ const target = sqlLiteral(role);
232
+ return `DO \$rebase_grant\$
233
+ BEGIN
234
+ IF current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} THEN\n EXECUTE format('GRANT %I TO %I WITH SET TRUE, INHERIT FALSE', ${target}, ${member});\n ELSE\n EXECUTE format('GRANT %I TO %I', ${target}, ${member});\n END IF;\nEND\n$rebase_grant$;`;
235
+ }
236
+ /**
237
+ * Human-actionable instructions for when the connection cannot provision the
238
+ * user role itself (no CREATEROLE and role not pre-created by the platform),
239
+ * or holds it without the right to switch to it.
240
+ *
241
+ * Every statement is safe to re-run and the same text works on Postgres 15 and
242
+ * 16+, so it can be pasted whole whatever state the database is in.
243
+ * `connectionRole` is the role the server connects as; without one, a
244
+ * placeholder Postgres will refuse until it is replaced.
245
+ */
246
+ function appRoleSetupInstructions(connectionRole, schemas, role = REBASE_USER_ROLE$1, mode = "schema") {
247
+ const member = connectionRole ?? "<your database user>";
248
+ const grants = mode !== "schema" ? "" : schemas.map((s) => `GRANT USAGE ON SCHEMA ${quoteIdent(s)} TO ${role};\nGRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${quoteIdent(s)} TO ${role};\nGRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${quoteIdent(s)} TO ${role};`).join("\n");
249
+ return `Rebase enforces row-level security by running authenticated requests as the restricted role "${role}", but the connection role "${member}" bypasses RLS and cannot set that role up itself.\nRun the following as a database administrator (a superuser, or the role that created "${role}"), then restart:\n\nDO $rebase_role$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${sqlLiteral(role)}) THEN\n CREATE ROLE ${role} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\nEND\n$rebase_role$;\n${membershipGrantSql(member, role)}\n` + grants;
250
+ }
251
+ /**
252
+ * Refuse a `rebase_user` that would not restrict anything.
253
+ *
254
+ * The role is cluster-wide and found by name, so the one a boot adopts may
255
+ * have been made by anybody — an earlier tool, a hand-written script, another
256
+ * application on the same cluster. Every authenticated request runs as it, so
257
+ * an attribute or a membership that lifts RLS lifts it from all of them, and
258
+ * nothing would say so: requests succeed, with every row.
259
+ *
260
+ * - LOGIN: anyone holding its password connects as the request role directly.
261
+ * - SUPERUSER, BYPASSRLS: RLS does not apply to it at all.
262
+ * - A membership in a role that owns tables here, or is itself a login,
263
+ * superuser or BYPASSRLS role: a member inheriting an owner is the owner for
264
+ * every policy check, and one that may `SET ROLE` to a privileged role is a
265
+ * statement away from it. (`GRANT app TO rebase_user` for `GRANT rebase_user
266
+ * TO app` is the easy way to get here.)
267
+ *
268
+ * A plain NOLOGIN group role is left alone: `validatePolicyPgRoles` sends a
269
+ * project with `pgRoles` to exactly that grant.
270
+ */
271
+ async function assertAppRoleRestricted(run, role = REBASE_USER_ROLE$1) {
272
+ const row = (await run(`
273
+ SELECT r.rolcanlogin AS can_login,
274
+ r.rolsuper AS superuser,
275
+ r.rolbypassrls AS bypassrls,
276
+ ARRAY(
277
+ SELECT g.rolname::text FROM pg_roles g
278
+ WHERE g.oid <> r.oid
279
+ AND pg_has_role(r.oid, g.oid, 'MEMBER')
280
+ AND (g.rolsuper OR g.rolbypassrls OR g.rolcanlogin
281
+ OR EXISTS (SELECT 1 FROM pg_class c
282
+ WHERE c.relowner = g.oid AND c.relkind IN ('r', 'p', 'v', 'm', 'f')))
283
+ ORDER BY 1
284
+ ) AS privileged_memberships
285
+ FROM pg_roles r
286
+ WHERE r.rolname = ${sqlLiteral(role)}
287
+ `))[0];
288
+ if (!row) return;
289
+ const memberships = textArrayValue(row.privileged_memberships);
290
+ const problems = [];
291
+ const fixes = [];
292
+ const attributes = [];
293
+ if (row.can_login === true) {
294
+ problems.push("it can log in (LOGIN)");
295
+ attributes.push("NOLOGIN");
296
+ }
297
+ if (row.superuser === true) {
298
+ problems.push("it is a superuser, so RLS does not apply to it");
299
+ attributes.push("NOSUPERUSER");
300
+ }
301
+ if (row.bypassrls === true) {
302
+ problems.push("it has BYPASSRLS, so RLS does not apply to it");
303
+ attributes.push("NOBYPASSRLS");
304
+ }
305
+ if (attributes.length > 0) fixes.push(`ALTER ROLE ${role} ${attributes.join(" ")};`);
306
+ if (memberships.length > 0) {
307
+ problems.push(`it is a member of ${memberships.map((m) => `"${m}"`).join(", ")} — a role that owns tables or logs in, or is a superuser or BYPASSRLS — so requests can act as that role`);
308
+ for (const m of memberships) fixes.push(`REVOKE ${quoteIdent(m)} FROM ${role};`);
309
+ }
310
+ if (problems.length === 0) return;
311
+ throw new AppRoleSetupError(`Refusing to use the existing "${role}" role: every authenticated request runs as it, and ${problems.join("; ")}. Row-level security would not restrict those requests.`, `Run the following as a database administrator, then restart. If another application on this cluster relies on "${role}" being this way, the two cannot share it.\n\n` + fixes.join("\n"));
312
+ }
313
+ /**
314
+ * Prove the connection can switch to the user role, the way every request
315
+ * will, and leave nothing behind.
316
+ *
317
+ * Catalogue answers are only a model of what Postgres will allow. This is the
318
+ * switch itself — `set_config('role', …, true)` is what `applyAuthContext`
319
+ * sends — followed, in the same statement, by switching back to the role the
320
+ * session had, so nothing outlives the probe even when the runner is inside a
321
+ * transaction of its own. A refusal escapes as Postgres's own 42501.
322
+ *
323
+ * Each step is its own subquery level, so the order is the plan's, not the
324
+ * order of a target list: the innermost reads the role the session has, the
325
+ * middle switches, the outer switches back. `OFFSET 0` keeps the levels from
326
+ * being flattened, and a volatile column is never pruned as unused.
327
+ *
328
+ * A `SELECT`, not a `DO` block with a rolled-back subtransaction: the
329
+ * provisioning recorder and the provisioning-off guard both read a leading
330
+ * `DO` as a schema change, and this changes nothing.
331
+ */
332
+ var roleSwitchProbe = (role) => `
333
+ SELECT set_config('role', switched.previous, true) AS restored
334
+ FROM (
335
+ SELECT session.previous, set_config('role', ${sqlLiteral(role)}, true) AS probe
336
+ FROM (SELECT current_setting('role') AS previous OFFSET 0) session
337
+ OFFSET 0
338
+ ) switched
339
+ `;
340
+ /**
341
+ * Run {@link roleSwitchProbe}, and on a refusal throw an
342
+ * {@link AppRoleSetupError} carrying the SQL that grants the switch.
343
+ *
344
+ * For a boot that adopts the role without provisioning it as much as for one
345
+ * that just did: either way the next thing that happens is a request running
346
+ * as it.
347
+ */
348
+ async function proveRoleSwitch(run, schemas, connectionRole, role = REBASE_USER_ROLE$1) {
349
+ try {
350
+ await run(roleSwitchProbe(role));
351
+ } catch (err) {
352
+ const member = connectionRole ?? String((await run("SELECT current_user AS role").catch(() => []))[0]?.role ?? "");
353
+ throw new AppRoleSetupError(`The connection role "${member}" cannot switch to "${role}", so every authenticated request would fail: ${failureReason(err)}`, appRoleSetupInstructions(member || void 0, Array.from(new Set(schemas.filter(Boolean))), role));
354
+ }
355
+ }
356
+ /** The `rebase.schema_meta` key that records which roles requests run as. */
357
+ var REQUEST_ROLES_KEY = "request_roles";
358
+ /**
359
+ * The request roles this database recorded on an earlier provisioning boot, or
360
+ * `undefined` when none has — every database provisioned before the setting
361
+ * existed, which ran as `rebase_user`.
362
+ *
363
+ * Recorded in the database rather than only configured because a role belongs
364
+ * to the cluster and holds grants here: a later boot configured with another
365
+ * name would provision a second role and leave the first one holding every
366
+ * grant. Reading the record is how that boot notices.
367
+ */
368
+ async function readRecordedRequestRoles(run) {
369
+ const [present] = await run(`SELECT to_regclass('"${REBASE_SCHEMA}"."schema_meta"') IS NOT NULL AS present`);
370
+ if (present?.present !== true) return void 0;
371
+ const [row] = await run(`SELECT value FROM "${REBASE_SCHEMA}"."schema_meta" WHERE key = ${sqlLiteral(REQUEST_ROLES_KEY)}`);
372
+ const value = row?.value === void 0 ? "" : String(row.value).trim();
373
+ return value === "" ? void 0 : value.split(",").map((r) => r.trim()).filter(Boolean);
374
+ }
375
+ /**
376
+ * Record `roles` as this database's request roles, creating `rebase.schema_meta`
377
+ * if nothing has yet. The table is one of Rebase's internal tables, so it is
378
+ * taken back from the request roles here, as its every creator does.
379
+ */
380
+ async function recordRequestRoles(run, roles) {
381
+ const [schema] = await run(`SELECT to_regnamespace('${REBASE_SCHEMA}') IS NOT NULL AS present`);
382
+ if (schema?.present !== true) await run(`CREATE SCHEMA IF NOT EXISTS "${REBASE_SCHEMA}"`);
383
+ await run(`
384
+ CREATE TABLE IF NOT EXISTS "${REBASE_SCHEMA}"."schema_meta" (
385
+ key TEXT PRIMARY KEY,
386
+ value TEXT NOT NULL,
387
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL
388
+ )
389
+ `);
390
+ await run(`
391
+ INSERT INTO "${REBASE_SCHEMA}"."schema_meta" (key, value)
392
+ VALUES (${sqlLiteral(REQUEST_ROLES_KEY)}, ${sqlLiteral(roles.join(","))})
393
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
394
+ WHERE "schema_meta".value IS DISTINCT FROM EXCLUDED.value
395
+ `);
396
+ await run(revokeInternalTableSql(REBASE_SCHEMA, "schema_meta"));
397
+ }
398
+ /**
399
+ * Refuse a boot configured with request roles other than the ones this
400
+ * database recorded. The same set in any order is the same.
401
+ *
402
+ * Nothing recorded means `rebase_user`, as every database from before the
403
+ * setting ran — but only where `rebase_user` actually holds grants here. A
404
+ * database it has never been granted on (a fresh one) has nothing to strand,
405
+ * and a new role is simply recorded.
406
+ */
407
+ function assertRecordedRequestRoles(configured, recorded, defaultRoleHoldsGrants) {
408
+ if (!recorded && !defaultRoleHoldsGrants) return;
409
+ const effective = recorded ?? [REBASE_USER_ROLE$1];
410
+ if (configured.length === effective.length && configured.every((r) => effective.includes(r))) return;
411
+ throw new AppRoleSetupError(`This database's requests run as ${effective.map((r) => `"${r}"`).join(", ")}${recorded ? "" : " (the default, which holds grants here)"}, but this server is configured for ${configured.map((r) => `"${r}"`).join(", ")} (rls.requestRole / REBASE_RLS_REQUEST_ROLE). Booting would provision new roles and leave the old ones holding every grant.`, `Move this database to the new role(s) — it re-creates each grant in this database only and records them:
412
+
413
+ rebase db request-role migrate --to ${configured.join(",")}\n\nOr set the setting back to ${effective.join(",")}.`);
414
+ }
415
+ /** Whether `role` holds any table privilege in `schemas` — something a new role would strand. */
416
+ async function roleHoldsTableGrants(run, schemas, role = REBASE_USER_ROLE$1) {
417
+ const [row] = await run(`
418
+ SELECT to_regrole(${sqlLiteral(role)}) IS NOT NULL AND EXISTS (
419
+ SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
420
+ WHERE n.nspname = ANY(${textArray(schemas)}) AND c.relkind IN ('r', 'v', 'm', 'f', 'p')
421
+ AND EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = to_regrole(${sqlLiteral(role)}))
422
+ ) AS holds
423
+ `);
424
+ return row?.holds === true;
425
+ }
426
+ /**
427
+ * Login roles other than this connection that can switch into `role`, and so
428
+ * can pass this database's policies as whichever user they like: the settings the
429
+ * policies read can be set by any session.
430
+ *
431
+ * Roles belong to the cluster, so this is how two projects on one cluster
432
+ * sharing `rebase_user` shows up from inside either database. Superusers are
433
+ * left out — they can become any role, and nothing here changes that.
434
+ */
435
+ async function findOtherRoleMembers(run, role) {
436
+ return (await run(`
437
+ SELECT r.rolname AS name
438
+ FROM pg_roles r
439
+ WHERE r.rolcanlogin AND NOT r.rolsuper AND r.rolname <> current_user
440
+ AND to_regrole(${sqlLiteral(role)}) IS NOT NULL
441
+ AND pg_has_role(r.oid, to_regrole(${sqlLiteral(role)}),
442
+ CASE WHEN current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} THEN 'SET' ELSE 'MEMBER' END)
443
+ ORDER BY 1
444
+ `)).map((row) => String(row.name));
445
+ }
446
+ /**
447
+ * Idempotently provision the `rebase_user` role, membership for the current
448
+ * connection role, and DML grants (+ default privileges for future tables)
449
+ * on every existing schema in `schemas`.
450
+ *
451
+ * Split into privilege tiers so it works both when the connection is a
452
+ * superuser (creates everything) and when the platform pre-created the role
453
+ * and membership (e.g. CNPG `postInitApplicationSQL`) and the connection is
454
+ * merely the table owner — owners can always run the grant tier themselves.
455
+ *
456
+ * RLS still filters every row: these grants only make the tables *reachable*
457
+ * by the role; the policies decide which rows/commands actually pass.
458
+ *
459
+ * Throws {@link AppRoleSetupError}, with precise setup instructions, when the
460
+ * role is missing and the connection cannot create it, when an existing role
461
+ * would not restrict anything, and when the connection cannot switch to it.
462
+ * Boot fails then, rather than serving an API whose every signed-in request is
463
+ * refused — or, worse, allowed.
464
+ */
465
+ async function ensureAppRole(run, schemas, options = {}) {
466
+ const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));
467
+ const role = options.role ?? REBASE_USER_ROLE$1;
468
+ const provision = options.provisionRole !== "never";
469
+ const [who] = await run(`
470
+ SELECT current_user AS role,
471
+ (SELECT rolsuper FROM pg_roles WHERE rolname = current_user) AS superuser,
472
+ current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS set_option,
473
+ EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${sqlLiteral(role)}) AS role_exists
474
+ `);
475
+ const connectionRole = String(who?.role ?? "");
476
+ const superuser = who?.superuser === true;
477
+ const setOption = who?.set_option === true;
478
+ const instructions = () => appRoleSetupInstructions(connectionRole || void 0, uniqueSchemas, role, options.grants);
479
+ if (who?.role_exists !== true && !provision) throw new AppRoleSetupError(`The request role "${role}" does not exist, and rls.provisionRole is "never", so Rebase does not create it.`, instructions());
480
+ if (who?.role_exists !== true) try {
481
+ await run(`
482
+ DO $rebase_role$
483
+ BEGIN
484
+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${role}') THEN
485
+ CREATE ROLE ${role} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;
486
+ END IF;
487
+ END
488
+ $rebase_role$
489
+ `);
490
+ } catch (err) {
491
+ throw new AppRoleSetupError(`Failed to create the "${role}" role: ${failureReason(err)}`, instructions());
492
+ }
493
+ else await assertAppRoleRestricted(run, role);
494
+ if (!superuser) {
495
+ const [membership] = await run(`SELECT pg_has_role(current_user, ${sqlLiteral(role)}, '${setOption ? "SET" : "MEMBER"}') AS can_set`);
496
+ if (membership?.can_set !== true && !provision) throw new AppRoleSetupError(`The connection role "${connectionRole}" may not switch to "${role}", and rls.provisionRole is "never", so Rebase does not grant itself that.`, instructions());
497
+ if (membership?.can_set !== true) try {
498
+ await run(setOption ? `GRANT ${role} TO CURRENT_USER WITH SET TRUE, INHERIT FALSE` : `GRANT ${role} TO CURRENT_USER`);
499
+ } catch (err) {
500
+ throw new AppRoleSetupError(`The connection role "${connectionRole}" may not switch to "${role}" ${setOption ? "(no membership WITH SET TRUE)" : "(not a member)"} and cannot grant that to itself: ${failureReason(err)}`, instructions());
501
+ }
502
+ }
503
+ await proveRoleSwitch(run, uniqueSchemas, connectionRole || void 0, role);
504
+ if (options.inheritRoles?.length) await ensureInheritedRoles(run, role, options.inheritRoles);
505
+ await ensureAppRoleGrants(run, uniqueSchemas, {
506
+ role,
507
+ mode: options.grants,
508
+ managedTables: options.managedTables
509
+ });
510
+ logger.debug(`🔐 [rls] User role "${role}" provisioned (schemas: ${uniqueSchemas.join(", ")})`);
511
+ }
512
+ /**
513
+ * The framework's internal tables in `schemas` that the request role can
514
+ * reach — `schema.table`, sorted — when nothing is left to take it back off.
515
+ *
516
+ * Every provisioning boot repairs this: each store revokes on its own table
517
+ * and {@link ensureAppRole}'s sweep revokes on the rest, because the grant
518
+ * tier hands the request role DML on whole schemas. A backend that changes
519
+ * nothing in its database runs neither, so a database whose `rebase_user` can
520
+ * read `refresh_tokens` or `api_keys` would stay that way for as long as it
521
+ * served. This is the question the sweep would have answered, asked instead.
522
+ *
523
+ * "Can reach" is what the role can actually do — through a grant to it, to a
524
+ * role it inherits, or to PUBLIC, on the table or on any of its columns —
525
+ * because that, not how the ACL is spelled, is what a request running as it
526
+ * gets. A table with RLS on is somebody's collection by that same rule as the
527
+ * sweep's, and is left out.
528
+ */
529
+ async function findExposedInternalTables(run, schemas, role = REBASE_USER_ROLE$1) {
530
+ return (await run(`
531
+ SELECT n.nspname || '.' || c.relname AS name
532
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
533
+ WHERE n.nspname = ANY(${textArray(Array.from(new Set(schemas)))})
534
+ AND c.relname = ANY(${textArray(REBASE_INTERNAL_TABLES)})
535
+ AND c.relkind IN ('r', 'p')
536
+ AND NOT c.relrowsecurity
537
+ AND (has_table_privilege(${sqlLiteral(role)}, c.oid, 'SELECT, INSERT, UPDATE, DELETE')
538
+ OR has_any_column_privilege(${sqlLiteral(role)}, c.oid, 'SELECT, INSERT, UPDATE'))
539
+ ORDER BY 1
540
+ `)).map((row) => String(row.name));
541
+ }
542
+ /** The connection role's oid, for a catalogue read. */
543
+ var CURRENT_ROLE_OID = "(SELECT oid FROM pg_roles WHERE rolname = current_user)";
544
+ /**
545
+ * SQL: may this connection grant every one of `privileges` on an object?
546
+ *
547
+ * Its owner, a role that inherits the owner, or a superuser — `pg_has_role`
548
+ * answers yes for all three — or a role holding each privilege `WITH GRANT
549
+ * OPTION`. Every one, because a grant short of one only warns and leaves the
550
+ * object reading as missing, which is the boot-after-boot re-grant this exists
551
+ * to stop.
552
+ */
553
+ function mayGrant(kind, oid, owner, privileges) {
554
+ return `(pg_has_role(current_user, ${owner}, 'USAGE') OR (${privileges.map((p) => `has_${kind}_privilege(current_user, ${oid}, ${sqlLiteral(`${p} WITH GRANT OPTION`)})`).join(" AND ")}))`;
555
+ }
556
+ /**
557
+ * Tables collections are served from that the user role holds no privilege on
558
+ * and this connection cannot grant it, because another role owns them.
559
+ *
560
+ * The grant tier passes these over — it could only fail on them — so on a
561
+ * database another application shares, a collection over that application's
562
+ * table boots and then refuses every request with "permission denied". This
563
+ * names them, with the owner who can run the grant. Refusing rather than
564
+ * widening, so the boot warns instead of stopping: the rest of the project
565
+ * works, and an introspected project serves every table in the schema,
566
+ * whoever owns it.
567
+ */
568
+ async function findUngrantableTables(run, tables, role = REBASE_USER_ROLE$1) {
569
+ if (tables.length === 0) return [];
570
+ return (await run(`
571
+ SELECT n.nspname AS schema, c.relname AS table, pg_get_userbyid(c.relowner) AS owner
572
+ FROM unnest(${textArray(tables.map((t) => t.schema))}, ${textArray(tables.map((t) => t.table))}) AS w(s, t)
573
+ JOIN pg_namespace n ON n.nspname = w.s
574
+ JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = w.t
575
+ WHERE NOT ${mayGrant("table", "c.oid", "c.relowner", USER_TABLE_PRIVILEGES.split(", "))}
576
+ AND NOT has_table_privilege(to_regrole(${sqlLiteral(role)}), c.oid, 'SELECT, INSERT, UPDATE, DELETE')
577
+ ORDER BY 1, 2
578
+ `)).map((row) => {
579
+ const name = `${quoteIdent(String(row.schema))}.${quoteIdent(String(row.table))}`;
580
+ return {
581
+ name,
582
+ owner: String(row.owner),
583
+ grant: `GRANT ${USER_TABLE_PRIVILEGES} ON ${name} TO ${role};`
584
+ };
585
+ });
586
+ }
587
+ /**
588
+ * The grant tier's state for every existing schema in `schemas`, in one read.
589
+ *
590
+ * A grant counts as present only as the statement this tier runs would record
591
+ * it — grantor the object's owner, which is what a GRANT by the owner, a member
592
+ * of the owning role or a superuser records, or this connection itself, which
593
+ * is what a GRANT on its grant option records — so skipping it leaves the ACL
594
+ * exactly as running it would. Anything else reads as missing, and the
595
+ * statement runs as it always did.
596
+ */
597
+ async function readSchemaGrants(run, schemas, role = REBASE_USER_ROLE$1, managedTables) {
598
+ const managed = managedTables ? `(SELECT * FROM unnest(${textArray(managedTables.map((t) => t.schema))}, ${textArray(managedTables.map((t) => t.table))}))` : void 0;
599
+ const onlyManagedTables = managed ? `AND (n.nspname, c.relname::text) IN ${managed}` : "";
600
+ const onlyManagedSequences = managed ? `AND EXISTS (SELECT 1 FROM pg_depend d JOIN pg_class t ON t.oid = d.refobjid
601
+ WHERE d.objid = c.oid AND d.deptype IN ('a', 'i')
602
+ AND (n.nspname, t.relname::text) IN ${managed})` : "";
603
+ const internal = textArray(REBASE_INTERNAL_TABLES);
604
+ const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(role)})`;
605
+ /** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */
606
+ const held = (acl, privileges, grantor) => `(SELECT count(DISTINCT a.privilege_type) FROM aclexplode(${acl}) a WHERE a.grantee = ${target}${grantor ? ` AND a.grantor IN (${grantor}, ${CURRENT_ROLE_OID})` : ""} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(", ")}))`;
607
+ const DML = [
608
+ "SELECT",
609
+ "INSERT",
610
+ "UPDATE",
611
+ "DELETE"
612
+ ];
613
+ const SEQ = ["USAGE", "SELECT"];
614
+ const viewRows = (alias) => `(${alias}.relkind = 'm' AND COALESCE(obj_description(${alias}.oid, 'pg_class'), '') LIKE '${VIEW_ROWS_COMMENT_PREFIX}%')`;
615
+ const rows = await run(`
616
+ SELECT n.nspname AS schema,
617
+ -- Settled as well when this connection cannot grant it: a schema
618
+ -- another role owns (a shared database's \`public\`) only warned,
619
+ -- and was re-granted on every boot. PUBLIC's own USAGE covers it there.
620
+ (${held("n.nspacl", ["USAGE"], "n.nspowner")} = 1
621
+ OR NOT ${mayGrant("schema", "n.oid", "n.nspowner", ["USAGE"])}) AS usage,
622
+ ARRAY(
623
+ SELECT c.relname::text FROM pg_class c
624
+ WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')
625
+ AND NOT (c.relname = ANY(${internal}) AND NOT c.relrowsecurity)
626
+ AND ${mayGrant("table", "c.oid", "c.relowner", DML)}
627
+ ${onlyManagedTables}
628
+ AND NOT ${viewRows("c")}
629
+ AND ${held("c.relacl", DML, "c.relowner")} < ${DML.length}
630
+ ORDER BY 1
631
+ ) AS tables,
632
+ ARRAY(
633
+ SELECT c.relname::text FROM pg_class c
634
+ WHERE c.relnamespace = n.oid AND c.relkind = 'S'
635
+ AND ${mayGrant("sequence", "c.oid", "c.relowner", SEQ)}
636
+ ${onlyManagedSequences}
637
+ AND ${held("c.relacl", SEQ, "c.relowner")} < ${SEQ.length}
638
+ ORDER BY 1
639
+ ) AS sequences,
640
+ EXISTS (
641
+ SELECT 1 FROM pg_default_acl d
642
+ WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
643
+ AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'r'
644
+ AND ${held("d.defaclacl", DML)} = ${DML.length}
645
+ ) AS default_tables,
646
+ EXISTS (
647
+ SELECT 1 FROM pg_default_acl d
648
+ WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
649
+ AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'S'
650
+ AND ${held("d.defaclacl", SEQ)} = ${SEQ.length}
651
+ ) AS default_sequences,
652
+ ARRAY(
653
+ SELECT c.relname::text FROM pg_class c
654
+ WHERE c.relnamespace = n.oid AND c.relname = ANY(${internal}) AND NOT c.relrowsecurity
655
+ AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))
656
+ ORDER BY 1
657
+ ) AS internal_granted,
658
+ ARRAY(
659
+ SELECT c.relname::text FROM pg_class c
660
+ WHERE c.relnamespace = n.oid AND ${viewRows("c")}
661
+ AND EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target})
662
+ ORDER BY 1
663
+ ) AS view_rows_granted
664
+ FROM pg_namespace n
665
+ WHERE n.nspname = ANY(${textArray(schemas)})
666
+ `);
667
+ const grants = /* @__PURE__ */ new Map();
668
+ for (const row of rows) {
669
+ const internalGranted = row.internal_granted;
670
+ const viewRowsGranted = row.view_rows_granted;
671
+ grants.set(String(row.schema), {
672
+ usage: row.usage === true,
673
+ tables: textArrayValue(row.tables),
674
+ sequences: textArrayValue(row.sequences),
675
+ defaultTables: row.default_tables === true,
676
+ defaultSequences: row.default_sequences === true,
677
+ internalGranted: textArrayValue(internalGranted),
678
+ viewRowsGranted: textArrayValue(viewRowsGranted)
679
+ });
680
+ }
681
+ return grants;
682
+ }
683
+ /**
684
+ * Grant each of `inheritRoles` to the request role `WITH INHERIT TRUE`, so a
685
+ * policy written `TO` one of them — Supabase's `authenticated`, say — applies
686
+ * to requests.
687
+ *
688
+ * PostgreSQL 16 and newer only. From 16 inheritance is an option of each
689
+ * grant, so the request role takes on these roles' privileges and stays
690
+ * NOINHERIT towards every other membership. Before 16 the only lever is the
691
+ * role's own INHERIT attribute, which would hand it every role it belongs to;
692
+ * that is refused rather than done.
693
+ */
694
+ async function ensureInheritedRoles(run, role, inheritRoles) {
695
+ const [server] = await run(`SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant`);
696
+ if (server?.per_grant !== true) throw new AppRoleSetupError(`rls.inheritRoles (${inheritRoles.join(", ")}) needs PostgreSQL 16 or newer: before 16 the request role "${role}" can only inherit by inheriting from every role it belongs to.`, "Upgrade to PostgreSQL 16+, or drop rls.inheritRoles and express those policies as the collection's securityRules.");
697
+ const rows = await run(`
698
+ SELECT w.name, r.oid IS NOT NULL AS present,
699
+ COALESCE(pg_has_role(to_regrole(${sqlLiteral(role)}), r.oid, 'USAGE'), false) AS inherits
700
+ FROM unnest(${textArray(inheritRoles)}) AS w(name)
701
+ LEFT JOIN pg_roles r ON r.rolname = w.name
702
+ `);
703
+ const missing = rows.filter((row) => row.present !== true).map((row) => String(row.name));
704
+ if (missing.length > 0) throw new AppRoleSetupError(`rls.inheritRoles names ${missing.map((m) => `"${m}"`).join(", ")}, which ${missing.length === 1 ? "does" : "do"} not exist in this cluster.`, "Create the role(s), or remove them from rls.inheritRoles.");
705
+ for (const row of rows) {
706
+ if (row.inherits === true) continue;
707
+ const name = String(row.name);
708
+ const grant = `GRANT ${quoteIdent(name)} TO ${quoteIdent(role)} WITH INHERIT TRUE, SET FALSE`;
709
+ try {
710
+ await run(grant);
711
+ } catch (err) {
712
+ throw new AppRoleSetupError(`Could not grant "${name}" to the request role "${role}" for rls.inheritRoles: ${failureReason(err)}`, `Run as a database administrator, then restart:\n\n${grant};`);
713
+ }
714
+ }
715
+ }
716
+ /**
717
+ * The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing
718
+ * schema in `schemas`, DML on its tables and `USAGE, SELECT` on its
719
+ * sequences, the default privileges that cover what this role creates later,
720
+ * and Rebase's own tables taken back — for a role and membership already
721
+ * provisioned.
722
+ *
723
+ * Every statement is issued only when the catalogue says it would change
724
+ * something. They used to run unconditionally, twice per boot (at connect, and
725
+ * again in the final posture check): a `GRANT … ON ALL TABLES` rewrites every
726
+ * table's `pg_class` row whether or not the ACL changes, which invalidates
727
+ * every table's cached plans on every connection, and the internal-table sweep
728
+ * ran 23 `REVOKE`s per schema. A boot against a database whose grants already
729
+ * hold now reads one catalogue query and writes nothing.
730
+ *
731
+ * Tables and sequences are granted by name, the ones that are missing it and
732
+ * that this connection may grant on — not `ON ALL … IN SCHEMA`, which also
733
+ * tries every relation another role owns. On a schema shared with another
734
+ * application that statement fails for a table this connection holds no
735
+ * privilege on, or only warns for one it holds without grant option, and either
736
+ * way the schema never reads as granted. The ACLs this leaves are the ones the
737
+ * schema-wide statement left on everything it could reach.
738
+ *
739
+ * Table owners (the expected non-superuser posture) can always grant on their
740
+ * own objects, so this needs no extra privilege.
741
+ */
742
+ async function ensureAppRoleGrants(run, schemas, options = {}) {
743
+ const role = options.role ?? REBASE_USER_ROLE$1;
744
+ const mode = options.mode ?? "schema";
745
+ if (mode === "none") return;
746
+ const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));
747
+ const grants = await readSchemaGrants(run, uniqueSchemas, role, mode === "managed" ? options.managedTables ?? [] : void 0);
748
+ for (const schema of uniqueSchemas) {
749
+ const state = grants.get(schema);
750
+ if (!state) continue;
751
+ const s = quoteIdent(schema);
752
+ if (!state.usage) await run(`GRANT USAGE ON SCHEMA ${s} TO ${role}`);
753
+ const named = (relations) => relations.map((r) => `${s}.${quoteIdent(r)}`).join(", ");
754
+ if (state.tables.length > 0) await run(`GRANT ${USER_TABLE_PRIVILEGES} ON TABLE ${named(state.tables)} TO ${role}`);
755
+ if (state.sequences.length > 0) await run(`GRANT USAGE, SELECT ON SEQUENCE ${named(state.sequences)} TO ${role}`);
756
+ for (const rows of state.viewRowsGranted) await run(`REVOKE ALL ON ${s}.${quoteIdent(rows)} FROM ${role}`);
757
+ if (!state.defaultTables && mode === "schema") await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${role}`);
758
+ if (!state.defaultSequences && mode === "schema") await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${role}`);
759
+ if (state.internalGranted.length === 0) continue;
760
+ await revokeInternalTableAccess(async (text) => {
761
+ await run(text);
762
+ }, schema, {
763
+ tables: state.internalGranted,
764
+ onError: (table, error) => logger.warn(`🔐 [rls] Could not revoke "${role}" access to "${schema}"."${table}" — it stays reachable by authenticated requests: ` + (error instanceof Error ? error.message : String(error)))
765
+ });
766
+ }
767
+ }
768
+ /**
769
+ * Rebase's own RLS-off tables in `schema` that a `revokeInternalTableAccess`
770
+ * sweep would change — the user role holds a privilege on them, or their ACL
771
+ * has never been written. One read; the sweep it narrows is one `DO` per
772
+ * table name.
773
+ */
774
+ async function internalTablesGrantedToUserRole(run, schema, role = REBASE_USER_ROLE$1) {
775
+ return (await readSchemaGrants(run, [schema], role)).get(schema)?.internalGranted ?? [];
776
+ }
777
+ /**
778
+ * Apply the authenticated context to a transaction: the `app.*` GUCs that RLS
779
+ * policies read via `rebase.uid()` / `rebase.roles()` / `rebase.jwt()`, and — when
780
+ * `userRole` is set — the `LOCAL` role switch, in the same statement, so RLS
781
+ * binds every statement in this transaction (reads *and* writes).
782
+ *
783
+ * GUCs are set with `is_local = true` and the role switch is `LOCAL`: both
784
+ * reset at commit/rollback, so pooled connections are never polluted.
785
+ *
786
+ * Fails closed by construction: if the role switch errors, the transaction
787
+ * aborts instead of proceeding privileged.
788
+ *
789
+ * SECURITY: this function is only ever called on the **user** path (the server
790
+ * context uses the base/owner driver and never calls it). The default policies
791
+ * treat `rebase.uid() IS NULL` as the trusted server context, and `rebase.uid()`
792
+ * is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would
793
+ * be read as NULL and silently escalate a user request to server privileges.
794
+ * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
795
+ * rather than trusting every caller (e.g. realtime subscription auth) to do it.
796
+ * That sentinel is exported from `@rebasepro/types` because it leaks into rule
797
+ * semantics: it is why `rebase.uid() IS NOT NULL` is true for anonymous requests.
798
+ */
799
+ async function applyAuthContext(tx, auth, userRole) {
800
+ const settings = authContextSettings(auth, userRole);
801
+ await tx.execute(sql`SELECT ${sql.join(settings.map(([name, value]) => sql`${sql.raw(`set_config(${settingNameLiteral(name)}, `)}${value}, true)`), sql`, `)}`);
802
+ }
803
+ /**
804
+ * {@link applyAuthContext} as one statement and its values, for a transaction
805
+ * that sends it in the same batch as its first query
806
+ * (`pipelined-transaction.ts`). `before` are settings of the transaction's own
807
+ * — what a pooled connection could not carry at connect — set ahead of the
808
+ * caller's, in the same statement.
809
+ */
810
+ function authContextStatement(auth, userRole, before = []) {
811
+ const settings = [...before, ...authContextSettings(auth, userRole)];
812
+ return {
813
+ text: `SELECT ${settings.map(([name], i) => `set_config(${settingNameLiteral(name)}, $${i + 1}, true)`).join(", ")}`,
814
+ values: settings.map(([, value]) => value)
815
+ };
816
+ }
817
+ /**
818
+ * A setting's name as a SQL literal. Names are this module's constants (and
819
+ * the pooled settings' two), never a caller's value, which is a bound
820
+ * parameter; written into the text so a statement log reads as the settings
821
+ * it sets.
822
+ */
823
+ function settingNameLiteral(name) {
824
+ return `'${name.replace(/'/g, "''")}'`;
825
+ }
826
+ /**
827
+ * The transaction-local settings that make a transaction the caller's, in the
828
+ * order they are set: the `app.*` GUCs, then the role.
829
+ *
830
+ * `userRole` is the role to switch to — or, for a project whose requests do not
831
+ * all run as one role or carry their identity in more than `app.*`, the
832
+ * resolved `rls` settings ({@link RequestIdentity}), which choose the role for
833
+ * this caller and add their own settings ahead of the switch.
834
+ */
835
+ function authContextSettings(auth, userRole) {
836
+ const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
837
+ const normalizedRoles = auth.roles.map((r) => typeof r === "string" ? r : r?.id ?? String(r));
838
+ const isAnonymous = auth.isAnonymous === true ? "true" : "false";
839
+ const settings = [
840
+ ["app.uid", uid],
841
+ ["app.user_id", uid],
842
+ ["app.user_roles", normalizedRoles.join(",")],
843
+ ["app.is_anonymous", isAnonymous],
844
+ ["app.jwt", JSON.stringify({
845
+ ...auth.claims ?? {},
846
+ sub: uid,
847
+ roles: auth.roles,
848
+ is_anonymous: auth.isAnonymous === true
849
+ })]
850
+ ];
851
+ const role = typeof userRole === "object" ? userRole.roleFor(auth) : userRole;
852
+ if (typeof userRole === "object" && role) for (const [name, value] of userRole.settingsFor(auth, role)) settings.push([name, value]);
853
+ if (role) settings.push(["role", role]);
854
+ return settings;
855
+ }
856
+ /** Role names from other BaaS platforms that people reach for out of habit. */
857
+ var FOREIGN_CONVENTION_ROLES = {
858
+ authenticated: "Supabase",
859
+ anon: "Supabase",
860
+ service_role: "Supabase"
861
+ };
862
+ /**
863
+ * Warn about rules that read as "signed-in users only" but admit anonymous
864
+ * callers — `rebase.uid() IS NOT NULL`, or a comparison against another
865
+ * platform's magic user id such as `'anon'`.
866
+ *
867
+ * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling
868
+ * of the same habit. A foreign `pgRoles` value makes a policy unreachable and
869
+ * the table reads empty — loud, and that guard throws. These do the opposite:
870
+ * the rule compiles to a grant, and nothing looks wrong until the data is
871
+ * already public.
872
+ *
873
+ * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are
874
+ * serving traffic today: refusing to boot would take an app offline to report a
875
+ * problem it already has, and on the read path it would take it offline
876
+ * *because* its data was exposed. Rewriting the author's SQL is not an option
877
+ * either — this is the escape hatch whose whole promise is that it means what it
878
+ * says. So: say so, loudly, and leave the rule alone.
879
+ */
880
+ function warnOnAnonymousGrants(collections) {
881
+ const byRisk = /* @__PURE__ */ new Map();
882
+ for (const collection of collections) for (const rule of collection.securityRules ?? []) {
883
+ const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
884
+ const risks = [usingExpr, withCheckExpr].filter((e) => e !== null).flatMap(findAnonymousGrants);
885
+ for (const risk of risks) {
886
+ const key = `${risk.pattern}:${risk.detail}`;
887
+ const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
888
+ const entry = byRisk.get(key) ?? {
889
+ risk,
890
+ sites: []
891
+ };
892
+ if (!entry.sites.includes(site)) entry.sites.push(site);
893
+ byRisk.set(key, entry);
894
+ }
895
+ }
896
+ if (byRisk.size === 0) return;
897
+ const problems = [...byRisk.values()].map(({ risk, sites }) => ` • ${risk.explanation}\n ${sites.length} rule(s): ${sites.join(", ")}`);
898
+ logger.warn(`Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are true for everyone:\n\n` + problems.join("\n\n") + "\n");
899
+ }
900
+ /**
901
+ * Name the collections whose raw policy SQL still calls the pre-1.0 helpers.
902
+ *
903
+ * The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the
904
+ * database, so nothing is broken and no policy is wrong — which is exactly why
905
+ * this has to be said out loud. A silent rewrite that works forever is not a
906
+ * migration, it is a second supported spelling nobody wrote down, and the next
907
+ * person to read those rules will copy the old one.
908
+ *
909
+ * Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,
910
+ * `policy.rolesOverlap(...)`) compile from the model and were never affected.
911
+ */
912
+ function warnOnLegacyRlsFunctions(collections) {
913
+ const sites = [];
914
+ for (const collection of collections) for (const rule of collection.securityRules ?? []) {
915
+ const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
916
+ if (![usingExpr, withCheckExpr].filter((e) => e !== null).some(containsLegacyRlsCall)) continue;
917
+ const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
918
+ if (!sites.includes(site)) sites.push(site);
919
+ }
920
+ if (sites.length === 0) return;
921
+ logger.warn(`These security rules call the pre-1.0 RLS helpers (\`auth.uid()\`, \`auth.roles()\`, \`auth.jwt()\`). They still work — the compiler rewrites them — but the functions now live in the \`rebase\` schema, and the \`auth\` one is Supabase's. Update the raw SQL in these rules to \`${REBASE_SCHEMA}.uid()\` and friends, or switch them to the structured helpers (\`policy.authUid()\`, \`policy.rolesOverlap()\`), which never had to be spelled by hand:\n\n` + sites.map((s) => ` • ${s}`).join("\n") + "\n");
922
+ }
923
+ /** Whether any `raw` expression in the tree calls a pre-1.0 helper. */
924
+ function containsLegacyRlsCall(expr) {
925
+ switch (expr.kind) {
926
+ case "raw": return usesLegacyRlsFunctions(expr.sql);
927
+ case "and":
928
+ case "or": return expr.operands.some(containsLegacyRlsCall);
929
+ case "not": return containsLegacyRlsCall(expr.operand);
930
+ case "existsIn": return containsLegacyRlsCall(expr.where);
931
+ default: return false;
932
+ }
933
+ }
934
+ /**
935
+ * Reject `pgRoles` that this server can never satisfy.
936
+ *
937
+ * `pgRoles` sets the `TO` clause of a generated policy, so a policy naming a
938
+ * role the request never runs as simply never applies — and RLS then filters
939
+ * every row. The table reads as empty, which is indistinguishable from having
940
+ * no data, so the mistake survives review and ships.
941
+ *
942
+ * Requests run as `rebase_user`, so a policy is only reachable if it targets
943
+ * `public` or a role whose privileges `rebase_user` has. Anything else is a
944
+ * configuration error worth failing the boot for.
945
+ *
946
+ * Privileges, not membership: Postgres applies a policy `TO r` to a role that
947
+ * has `r`'s privileges, which a member only gets by inheriting them, and
948
+ * `rebase_user` is `NOINHERIT`. This used to ask `pg_has_role(…, 'MEMBER')`, so
949
+ * `GRANT authenticated TO rebase_user` — the grant its own hint suggested —
950
+ * passed here and still read every collection as empty.
951
+ */
952
+ async function validatePolicyPgRoles(run, collections, requestRoles = REBASE_USER_ROLE$1) {
953
+ const candidates = typeof requestRoles === "string" ? [requestRoles] : [...requestRoles];
954
+ const requestRole = candidates[0] ?? REBASE_USER_ROLE$1;
955
+ const wanted = /* @__PURE__ */ new Map();
956
+ for (const collection of collections) for (const rule of collection.securityRules ?? []) for (const role of rule.pgRoles ?? []) {
957
+ if (role === "public" || candidates.includes(role)) continue;
958
+ wanted.set(role, [...wanted.get(role) ?? [], collection.slug ?? "(unnamed)"]);
959
+ }
960
+ if (wanted.size === 0) return;
961
+ const names = [...wanted.keys()].map((r) => `'${r.replace(/'/g, "''")}'`).join(",");
962
+ const escapedRequestRole = requestRole.replace(/'/g, "''");
963
+ const rows = await run(`
964
+ SELECT r.rolname AS role,
965
+ COALESCE(bool_or(pg_has_role(to_regrole(req.name), r.oid, 'USAGE')), false) AS reachable,
966
+ COALESCE(bool_or(pg_has_role(to_regrole(req.name), r.oid, 'MEMBER')), false) AS member
967
+ FROM pg_roles r CROSS JOIN unnest(${textArray(candidates)}) AS req(name)
968
+ WHERE r.rolname IN (${names})
969
+ GROUP BY r.rolname
970
+ `);
971
+ const [server] = await run(`
972
+ SELECT current_setting('server_version_num')::int >= 160000 AS per_grant_inherit,
973
+ (SELECT rolinherit FROM pg_roles WHERE oid = to_regrole('${escapedRequestRole}')) AS inherits
974
+ `);
975
+ const grantThatWorks = (role) => server?.per_grant_inherit === true ? `GRANT ${role} TO ${requestRole} WITH INHERIT TRUE` : server?.inherits === true ? `GRANT ${role} TO ${requestRole}` : void 0;
976
+ const found = new Map(rows.map((row) => [String(row.role), row]));
977
+ const problems = [];
978
+ for (const [role, slugs] of wanted) {
979
+ const row = found.get(role);
980
+ if (row?.reachable === true) continue;
981
+ const why = !row ? "no such role exists in this database" : row.member === true ? `"${requestRole}" is a member of it but does not inherit its privileges, so its policies do not apply` : `"${requestRole}" is not a member of it`;
982
+ const platform = FOREIGN_CONVENTION_ROLES[role];
983
+ const grant = grantThatWorks(role);
984
+ const hint = platform && !row ? `"${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().` : grant ? `Either grant it (${grant}) or drop \`pgRoles\` so the policy targets \`public\`.` : `"${requestRole}" is NOINHERIT, and before PostgreSQL 16 a NOINHERIT role takes on no other role's policies. Drop \`pgRoles\` so the policy targets \`public\`.`;
985
+ problems.push(` • pgRoles: ["${role}"] on ${slugs.join(", ")} — ${why}.\n ${hint}`);
986
+ }
987
+ 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");
988
+ }
989
+ //#endregion
990
+ export { warnOnRoleSchemaCollision as C, warnOnLegacyRlsFunctions as S, revokeUserRoleSql as _, assertRecordedRequestRoles as a, validatePolicyPgRoles as b, ensureAppRole as c, findOtherRoleMembers as d, findUngrantableTables as f, recordRequestRoles as g, readRecordedRequestRoles as h, assertAppRoleRestricted as i, ensureAppRoleGrants as l, proveRoleSwitch as m, appRoleSetupInstructions as n, authContextStatement as o, internalTablesGrantedToUserRole as p, applyAuthContext as r, detectConnectionPosture as s, REBASE_USER_ROLE$1 as t, findExposedInternalTables as u, rls_enforcement_exports as v, warnOnAnonymousGrants as x, roleHoldsTableGrants as y };
991
+
992
+ //# sourceMappingURL=rls-enforcement-BO618rnr.js.map