@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
@@ -1,502 +0,0 @@
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 { logger } from "@rebasepro/server";
5
- import { sql } from "drizzle-orm";
6
- import { ANONYMOUS_USER_ID, REBASE_SCHEMA, usesLegacyRlsFunctions } from "@rebasepro/types";
7
- import { REBASE_INTERNAL_TABLES, REBASE_USER_ROLE as REBASE_USER_ROLE$1, findAnonymousGrants, revokeInternalTableAccess, securityRuleToConditions } from "@rebasepro/common";
8
- //#region src/security/rls-enforcement.ts
9
- var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
10
- REBASE_USER_ROLE: () => REBASE_USER_ROLE$1,
11
- appRoleSetupInstructions: () => appRoleSetupInstructions,
12
- applyAuthContext: () => applyAuthContext,
13
- detectConnectionPosture: () => detectConnectionPosture,
14
- ensureAppRole: () => ensureAppRole,
15
- ensureAppRoleGrants: () => ensureAppRoleGrants,
16
- findExposedInternalTables: () => findExposedInternalTables,
17
- internalTablesGrantedToUserRole: () => internalTablesGrantedToUserRole,
18
- revokeUserRoleSql: () => revokeUserRoleSql,
19
- validatePolicyPgRoles: () => validatePolicyPgRoles,
20
- warnOnAnonymousGrants: () => warnOnAnonymousGrants,
21
- warnOnLegacyRlsFunctions: () => warnOnLegacyRlsFunctions,
22
- warnOnRoleSchemaCollision: () => warnOnRoleSchemaCollision
23
- });
24
- var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
25
- /** DML the user role holds on managed tables (RLS still filters per row). */
26
- var USER_TABLE_PRIVILEGES = "SELECT, INSERT, UPDATE, DELETE";
27
- /**
28
- * Take every privilege the user role holds on one table back — what a table
29
- * gets when RLS cannot be switched on for it, so it is unreachable rather than
30
- * unprotected. Quoted exactly: a mixed-case adopted table (`"User"`) folded to
31
- * lower case names a table that does not exist.
32
- */
33
- var revokeUserRoleSql = (schema, table) => `REVOKE ALL PRIVILEGES ON ${quoteIdent(schema)}.${quoteIdent(table)} FROM ${quoteIdent(REBASE_USER_ROLE$1)}`;
34
- /**
35
- * Warn when the connection role shares its name with an existing schema.
36
- *
37
- * Postgres resolves unqualified names through `search_path`, which defaults to
38
- * `"$user", public` — and `$user` is the connection ROLE. When a schema of that
39
- * name exists it sits ahead of `public`, so every unqualified statement
40
- * silently operates on it instead:
41
- *
42
- * CREATE TABLE posts (...); -- you meant public.posts; you got <role>.posts
43
- *
44
- * Nothing errors. You get a second table of the same name in the wrong schema,
45
- * and reads that pin `public` cannot see it — which reads as "missing table" and
46
- * sends people to re-run a push that creates a *third* copy. The bootstrapper
47
- * has a whole branch dedicated to recognising the symptom after the fact.
48
- *
49
- * Rebase shipped straight into this: it creates a schema named `rebase` while
50
- * every template named the database role `rebase` too. The scaffold uses
51
- * `rebase_app` now, and every pool Rebase opens pins `search_path=public`
52
- * (`pinSearchPath`), which covers the paths the framework controls. This covers
53
- * the ones it does not — `psql`, `pg_dump`, drizzle-kit, a colleague's script,
54
- * a hand-written migration — because the hazard is a property of the two NAMES,
55
- * not of any one connection.
56
- *
57
- * A warning rather than a boot failure: the database works, the framework's own
58
- * traffic is pinned, and refusing to start over a naming choice a user may have
59
- * inherited would be worse than the risk.
60
- */
61
- async function warnOnRoleSchemaCollision(run) {
62
- try {
63
- const rows = await run(`
64
- SELECT current_user AS role,
65
- EXISTS (
66
- SELECT 1 FROM pg_namespace n WHERE n.nspname = current_user
67
- ) AS collides
68
- `);
69
- if (rows[0]?.collides !== true) return;
70
- const role = String(rows[0]?.role ?? "the connection role");
71
- 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".`);
72
- } catch {}
73
- }
74
- /**
75
- * Would RLS actually constrain this connection?
76
- *
77
- * Four ways the answer is no, and only two of them are obvious. Superuser and
78
- * BYPASSRLS announce themselves in `pg_roles`. The other two are about
79
- * ownership, and both used to read as "no bypass here":
80
- *
81
- * - **Ownership through membership.** The old query compared
82
- * `pg_tables.tableowner` to `current_user` as a string. Postgres does not: a
83
- * role that INHERITs the owner passes every ownership test the planner makes,
84
- * including the one that decides whether a policy applies. So a perfectly
85
- * ordinary "app role that is a member of the owner role" setup reported
86
- * unprivileged and bypassed every policy — permanently, since no restart
87
- * changes a string comparison's answer.
88
- *
89
- * - **Ownership that has not happened yet.** The posture is decided once, at
90
- * boot, and on a fresh database there is nothing in the catalogue to find. The
91
- * same process then creates every table and owns all of them. The first boot
92
- * of a new deployment therefore served every request unconstrained, the log
93
- * said RLS was fine, and the SECOND boot silently fixed it — which is the
94
- * worst possible shape for a security check, because the state that reproduces
95
- * it is gone by the time anyone looks. Asking "may this role create tables
96
- * where the server provisions?" answers about the process's whole life rather
97
- * than about one instant of it.
98
- *
99
- * `schemas` narrows the CREATE question to where the server actually writes.
100
- * Omitted, it asks about every schema the role can see, which is the safe
101
- * direction: over-reporting costs a role switch that was not strictly needed,
102
- * under-reporting costs the entire authorization model.
103
- */
104
- async function detectConnectionPosture(run, schemas) {
105
- const row = (await run(`
106
- SELECT current_user AS role,
107
- r.rolsuper AS superuser,
108
- r.rolbypassrls AS bypassrls,
109
- EXISTS (
110
- SELECT 1 FROM pg_tables t
111
- WHERE pg_has_role(current_user, t.tableowner, 'USAGE')
112
- AND t.schemaname NOT IN ('pg_catalog', 'information_schema')
113
- ) AS owns_tables,
114
- EXISTS (
115
- SELECT 1 FROM pg_namespace n
116
- WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
117
- AND n.nspname NOT LIKE 'pg\\_toast%'
118
- AND n.nspname NOT LIKE 'pg\\_temp%'
119
- ${schemas?.length ? `AND n.nspname IN (${Array.from(new Set(schemas)).map((s) => `'${s.replace(/'/g, "''")}'`).join(", ")})` : ""}
120
- AND has_schema_privilege(current_user, n.oid, 'CREATE')
121
- ) AS can_create
122
- FROM pg_roles r
123
- WHERE r.rolname = current_user
124
- `))[0] ?? {};
125
- const superuser = row.superuser === true;
126
- const bypassRLS = row.bypassrls === true;
127
- const ownsTables = row.owns_tables === true;
128
- const canCreateTables = row.can_create === true;
129
- return {
130
- role: String(row.role ?? "unknown"),
131
- superuser,
132
- bypassRLS,
133
- ownsTables,
134
- canCreateTables,
135
- privileged: superuser || bypassRLS || ownsTables || canCreateTables
136
- };
137
- }
138
- /**
139
- * Human-actionable instructions for when the connection cannot provision the
140
- * user role itself (no CREATEROLE and role not pre-created by the platform).
141
- */
142
- function appRoleSetupInstructions(connectionRole, schemas) {
143
- const grants = schemas.map((s) => `GRANT USAGE ON SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE$1};\nGRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE$1};\nGRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE$1};`).join("\n");
144
- return `Rebase enforces row-level security by running authenticated requests as the restricted role "${REBASE_USER_ROLE$1}", but the connection role "${connectionRole}" bypasses RLS and cannot create that role itself.\nRun the following as a database administrator, then restart:\n\nCREATE ROLE ${REBASE_USER_ROLE$1} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\nGRANT ${REBASE_USER_ROLE$1} TO ${quoteIdent(connectionRole)};\n` + grants;
145
- }
146
- /**
147
- * Idempotently provision the `rebase_user` role, membership for the current
148
- * connection role, and DML grants (+ default privileges for future tables)
149
- * on every existing schema in `schemas`.
150
- *
151
- * Split into privilege tiers so it works both when the connection is a
152
- * superuser (creates everything) and when the platform pre-created the role
153
- * and membership (e.g. CNPG `postInitApplicationSQL`) and the connection is
154
- * merely the table owner — owners can always run the grant tier themselves.
155
- *
156
- * RLS still filters every row: these grants only make the tables *reachable*
157
- * by the role; the policies decide which rows/commands actually pass.
158
- *
159
- * Throws with precise setup instructions when the role is missing and the
160
- * connection cannot create it.
161
- */
162
- async function ensureAppRole(run, schemas) {
163
- const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));
164
- if ((await run(`SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE$1}'`)).length === 0) try {
165
- await run(`
166
- DO $rebase_role$
167
- BEGIN
168
- IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE$1}') THEN
169
- CREATE ROLE ${REBASE_USER_ROLE$1} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;
170
- END IF;
171
- END
172
- $rebase_role$
173
- `);
174
- } catch (err) {
175
- throw new Error(`Failed to create the "${REBASE_USER_ROLE$1}" role: ${err instanceof Error ? err.message : String(err)}\n\n` + appRoleSetupInstructions("current connection role", uniqueSchemas));
176
- }
177
- const memberRows = await run(`
178
- SELECT (pg_has_role(current_user, '${REBASE_USER_ROLE$1}', 'MEMBER')
179
- OR (SELECT rolsuper FROM pg_roles WHERE rolname = current_user)) AS can_set,
180
- current_user AS role
181
- `);
182
- if (memberRows[0]?.can_set !== true) try {
183
- await run(`GRANT ${REBASE_USER_ROLE$1} TO CURRENT_USER`);
184
- } catch (err) {
185
- throw new Error(`The connection role is not a member of "${REBASE_USER_ROLE$1}" and cannot grant itself membership: ${err instanceof Error ? err.message : String(err)}\n\n` + appRoleSetupInstructions(String(memberRows[0]?.role ?? "current connection role"), uniqueSchemas));
186
- }
187
- await ensureAppRoleGrants(run, uniqueSchemas);
188
- logger.debug(`🔐 [rls] User role "${REBASE_USER_ROLE$1}" provisioned (schemas: ${uniqueSchemas.join(", ")})`);
189
- }
190
- /** A string literal for a catalogue read. Names come from config and constants, never from a request. */
191
- var sqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
192
- var textArray = (values) => values.length === 0 ? "ARRAY[]::text[]" : `ARRAY[${values.map(sqlLiteral).join(", ")}]::text[]`;
193
- /**
194
- * The framework's internal tables in `schemas` that the request role can
195
- * reach — `schema.table`, sorted — when nothing is left to take it back off.
196
- *
197
- * Every provisioning boot repairs this: each store revokes on its own table
198
- * and {@link ensureAppRole}'s sweep revokes on the rest, because the grant
199
- * tier hands the request role DML on whole schemas. A backend that changes
200
- * nothing in its database runs neither, so a database whose `rebase_user` can
201
- * read `refresh_tokens` or `api_keys` would stay that way for as long as it
202
- * served. This is the question the sweep would have answered, asked instead.
203
- *
204
- * "Can reach" is what the role can actually do — through a grant to it, to a
205
- * role it inherits, or to PUBLIC, on the table or on any of its columns —
206
- * because that, not how the ACL is spelled, is what a request running as it
207
- * gets. A table with RLS on is somebody's collection by that same rule as the
208
- * sweep's, and is left out.
209
- */
210
- async function findExposedInternalTables(run, schemas) {
211
- return (await run(`
212
- SELECT n.nspname || '.' || c.relname AS name
213
- FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
214
- WHERE n.nspname = ANY(${textArray(Array.from(new Set(schemas)))})
215
- AND c.relname = ANY(${textArray(REBASE_INTERNAL_TABLES)})
216
- AND c.relkind IN ('r', 'p')
217
- AND NOT c.relrowsecurity
218
- AND (has_table_privilege(${sqlLiteral(REBASE_USER_ROLE$1)}, c.oid, 'SELECT, INSERT, UPDATE, DELETE')
219
- OR has_any_column_privilege(${sqlLiteral(REBASE_USER_ROLE$1)}, c.oid, 'SELECT, INSERT, UPDATE'))
220
- ORDER BY 1
221
- `)).map((row) => String(row.name));
222
- }
223
- /**
224
- * The grant tier's state for every existing schema in `schemas`, in one read.
225
- *
226
- * A grant counts as present only as the statement this tier runs would record
227
- * it — grantor the object's owner, which is what a GRANT by the owner, a member
228
- * of the owning role or a superuser records — so skipping it leaves the ACL
229
- * exactly as running it would. Anything else reads as missing, and the
230
- * statement runs as it always did.
231
- */
232
- async function readSchemaGrants(run, schemas) {
233
- const internal = textArray(REBASE_INTERNAL_TABLES);
234
- const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(REBASE_USER_ROLE$1)})`;
235
- /** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */
236
- const held = (acl, privileges, grantor) => `(SELECT count(DISTINCT a.privilege_type) FROM aclexplode(${acl}) a WHERE a.grantee = ${target}${grantor ? ` AND a.grantor = ${grantor}` : ""} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(", ")}))`;
237
- const DML = [
238
- "SELECT",
239
- "INSERT",
240
- "UPDATE",
241
- "DELETE"
242
- ];
243
- const SEQ = ["USAGE", "SELECT"];
244
- const rows = await run(`
245
- SELECT n.nspname AS schema,
246
- ${held("n.nspacl", ["USAGE"], "n.nspowner")} = 1 AS usage,
247
- NOT EXISTS (
248
- SELECT 1 FROM pg_class c
249
- WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')
250
- AND NOT (c.relname = ANY(${internal}) AND NOT c.relrowsecurity)
251
- AND ${held("c.relacl", DML, "c.relowner")} < ${DML.length}
252
- ) AS tables,
253
- NOT EXISTS (
254
- SELECT 1 FROM pg_class c
255
- WHERE c.relnamespace = n.oid AND c.relkind = 'S'
256
- AND ${held("c.relacl", SEQ, "c.relowner")} < ${SEQ.length}
257
- ) AS sequences,
258
- EXISTS (
259
- SELECT 1 FROM pg_default_acl d
260
- WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
261
- AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'r'
262
- AND ${held("d.defaclacl", DML)} = ${DML.length}
263
- ) AS default_tables,
264
- EXISTS (
265
- SELECT 1 FROM pg_default_acl d
266
- WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
267
- AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'S'
268
- AND ${held("d.defaclacl", SEQ)} = ${SEQ.length}
269
- ) AS default_sequences,
270
- ARRAY(
271
- SELECT c.relname::text FROM pg_class c
272
- WHERE c.relnamespace = n.oid AND c.relname = ANY(${internal}) AND NOT c.relrowsecurity
273
- AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))
274
- ORDER BY 1
275
- ) AS internal_granted
276
- FROM pg_namespace n
277
- WHERE n.nspname = ANY(${textArray(schemas)})
278
- `);
279
- const grants = /* @__PURE__ */ new Map();
280
- for (const row of rows) {
281
- const internalGranted = row.internal_granted;
282
- grants.set(String(row.schema), {
283
- usage: row.usage === true,
284
- tables: row.tables === true,
285
- sequences: row.sequences === true,
286
- defaultTables: row.default_tables === true,
287
- defaultSequences: row.default_sequences === true,
288
- internalGranted: Array.isArray(internalGranted) ? internalGranted.map(String) : String(internalGranted ?? "").replace(/^\{|\}$/g, "").split(",").filter(Boolean)
289
- });
290
- }
291
- return grants;
292
- }
293
- /**
294
- * The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing
295
- * schema in `schemas`, DML on its tables and `USAGE, SELECT` on its
296
- * sequences, the default privileges that cover what this role creates later,
297
- * and Rebase's own tables taken back — for a role and membership already
298
- * provisioned.
299
- *
300
- * Every statement is issued only when the catalogue says it would change
301
- * something. They used to run unconditionally, twice per boot (at connect, and
302
- * again in the final posture check): a `GRANT … ON ALL TABLES` rewrites every
303
- * table's `pg_class` row whether or not the ACL changes, which invalidates
304
- * every table's cached plans on every connection, and the internal-table sweep
305
- * ran 23 `REVOKE`s per schema. A boot against a database whose grants already
306
- * hold now reads one catalogue query and writes nothing; one that is missing
307
- * any of them runs exactly the statements it always ran.
308
- *
309
- * Table owners (the expected non-superuser posture) can always grant on their
310
- * own objects, so this needs no extra privilege.
311
- */
312
- async function ensureAppRoleGrants(run, schemas) {
313
- const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));
314
- const grants = await readSchemaGrants(run, uniqueSchemas);
315
- for (const schema of uniqueSchemas) {
316
- const state = grants.get(schema);
317
- if (!state) continue;
318
- const s = quoteIdent(schema);
319
- if (!state.usage) await run(`GRANT USAGE ON SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
320
- if (!state.tables) await run(`GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
321
- if (!state.sequences) await run(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
322
- if (!state.defaultTables) await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${REBASE_USER_ROLE$1}`);
323
- if (!state.defaultSequences) await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${REBASE_USER_ROLE$1}`);
324
- const tables = state.tables ? state.internalGranted : void 0;
325
- if (tables && tables.length === 0) continue;
326
- await revokeInternalTableAccess(async (text) => {
327
- await run(text);
328
- }, schema, {
329
- tables,
330
- onError: (table, error) => logger.warn(`🔐 [rls] Could not revoke "${REBASE_USER_ROLE$1}" access to "${schema}"."${table}" — it stays reachable by authenticated requests: ` + (error instanceof Error ? error.message : String(error)))
331
- });
332
- }
333
- }
334
- /**
335
- * Rebase's own RLS-off tables in `schema` that a `revokeInternalTableAccess`
336
- * sweep would change — the user role holds a privilege on them, or their ACL
337
- * has never been written. One read; the sweep it narrows is one `DO` per
338
- * table name.
339
- */
340
- async function internalTablesGrantedToUserRole(run, schema) {
341
- return (await readSchemaGrants(run, [schema])).get(schema)?.internalGranted ?? [];
342
- }
343
- /**
344
- * Apply the authenticated context to a transaction: the `app.*` GUCs that RLS
345
- * policies read via `rebase.uid()` / `rebase.roles()` / `rebase.jwt()`, and — when
346
- * `userRole` is set — the `LOCAL` role switch, in the same statement, so RLS
347
- * binds every statement in this transaction (reads *and* writes).
348
- *
349
- * GUCs are set with `is_local = true` and the role switch is `LOCAL`: both
350
- * reset at commit/rollback, so pooled connections are never polluted.
351
- *
352
- * Fails closed by construction: if the role switch errors, the transaction
353
- * aborts instead of proceeding privileged.
354
- *
355
- * SECURITY: this function is only ever called on the **user** path (the server
356
- * context uses the base/owner driver and never calls it). The default policies
357
- * treat `rebase.uid() IS NULL` as the trusted server context, and `rebase.uid()`
358
- * is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would
359
- * be read as NULL and silently escalate a user request to server privileges.
360
- * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
361
- * rather than trusting every caller (e.g. realtime subscription auth) to do it.
362
- * That sentinel is exported from `@rebasepro/types` because it leaks into rule
363
- * semantics: it is why `rebase.uid() IS NOT NULL` is true for anonymous requests.
364
- */
365
- async function applyAuthContext(tx, auth, userRole) {
366
- const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
367
- const normalizedRoles = auth.roles.map((r) => typeof r === "string" ? r : r?.id ?? String(r));
368
- const isAnonymous = auth.isAnonymous === true ? "true" : "false";
369
- await tx.execute(sql`
370
- SELECT
371
- set_config('app.uid', ${uid}, true),
372
- set_config('app.user_id', ${uid}, true),
373
- set_config('app.user_roles', ${normalizedRoles.join(",")}, true),
374
- set_config('app.is_anonymous', ${isAnonymous}, true),
375
- set_config('app.jwt', ${JSON.stringify({
376
- ...auth.claims ?? {},
377
- sub: uid,
378
- roles: auth.roles,
379
- is_anonymous: auth.isAnonymous === true
380
- })}, true)${userRole ? sql`,
381
- set_config('role', ${userRole}, true)` : sql``}
382
- `);
383
- }
384
- /** Role names from other BaaS platforms that people reach for out of habit. */
385
- var FOREIGN_CONVENTION_ROLES = {
386
- authenticated: "Supabase",
387
- anon: "Supabase",
388
- service_role: "Supabase"
389
- };
390
- /**
391
- * Warn about rules that read as "signed-in users only" but admit anonymous
392
- * callers — `rebase.uid() IS NOT NULL`, or a comparison against another
393
- * platform's magic user id such as `'anon'`.
394
- *
395
- * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling
396
- * of the same habit. A foreign `pgRoles` value makes a policy unreachable and
397
- * the table reads empty — loud, and that guard throws. These do the opposite:
398
- * the rule compiles to a grant, and nothing looks wrong until the data is
399
- * already public.
400
- *
401
- * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are
402
- * serving traffic today: refusing to boot would take an app offline to report a
403
- * problem it already has, and on the read path it would take it offline
404
- * *because* its data was exposed. Rewriting the author's SQL is not an option
405
- * either — this is the escape hatch whose whole promise is that it means what it
406
- * says. So: say so, loudly, and leave the rule alone.
407
- */
408
- function warnOnAnonymousGrants(collections) {
409
- const byRisk = /* @__PURE__ */ new Map();
410
- for (const collection of collections) for (const rule of collection.securityRules ?? []) {
411
- const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
412
- const risks = [usingExpr, withCheckExpr].filter((e) => e !== null).flatMap(findAnonymousGrants);
413
- for (const risk of risks) {
414
- const key = `${risk.pattern}:${risk.detail}`;
415
- const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
416
- const entry = byRisk.get(key) ?? {
417
- risk,
418
- sites: []
419
- };
420
- if (!entry.sites.includes(site)) entry.sites.push(site);
421
- byRisk.set(key, entry);
422
- }
423
- }
424
- if (byRisk.size === 0) return;
425
- const problems = [...byRisk.values()].map(({ risk, sites }) => ` • ${risk.explanation}\n ${sites.length} rule(s): ${sites.join(", ")}`);
426
- 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");
427
- }
428
- /**
429
- * Name the collections whose raw policy SQL still calls the pre-1.0 helpers.
430
- *
431
- * The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the
432
- * database, so nothing is broken and no policy is wrong — which is exactly why
433
- * this has to be said out loud. A silent rewrite that works forever is not a
434
- * migration, it is a second supported spelling nobody wrote down, and the next
435
- * person to read those rules will copy the old one.
436
- *
437
- * Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,
438
- * `policy.rolesOverlap(...)`) compile from the model and were never affected.
439
- */
440
- function warnOnLegacyRlsFunctions(collections) {
441
- const sites = [];
442
- for (const collection of collections) for (const rule of collection.securityRules ?? []) {
443
- const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
444
- if (![usingExpr, withCheckExpr].filter((e) => e !== null).some(containsLegacyRlsCall)) continue;
445
- const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
446
- if (!sites.includes(site)) sites.push(site);
447
- }
448
- if (sites.length === 0) return;
449
- 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");
450
- }
451
- /** Whether any `raw` expression in the tree calls a pre-1.0 helper. */
452
- function containsLegacyRlsCall(expr) {
453
- switch (expr.kind) {
454
- case "raw": return usesLegacyRlsFunctions(expr.sql);
455
- case "and":
456
- case "or": return expr.operands.some(containsLegacyRlsCall);
457
- case "not": return containsLegacyRlsCall(expr.operand);
458
- case "existsIn": return containsLegacyRlsCall(expr.where);
459
- default: return false;
460
- }
461
- }
462
- /**
463
- * Reject `pgRoles` that this server can never satisfy.
464
- *
465
- * `pgRoles` sets the `TO` clause of a generated policy, so a policy naming a
466
- * role the request never runs as simply never applies — and RLS then filters
467
- * every row. The table reads as empty, which is indistinguishable from having
468
- * no data, so the mistake survives review and ships.
469
- *
470
- * Requests run as `rebase_user`, so a policy is only reachable if it targets
471
- * `public` or a role `rebase_user` holds. Anything else is a configuration
472
- * error worth failing the boot for.
473
- */
474
- async function validatePolicyPgRoles(run, collections, requestRole = REBASE_USER_ROLE$1) {
475
- const wanted = /* @__PURE__ */ new Map();
476
- for (const collection of collections) for (const rule of collection.securityRules ?? []) for (const role of rule.pgRoles ?? []) {
477
- if (role === "public") continue;
478
- wanted.set(role, [...wanted.get(role) ?? [], collection.slug ?? "(unnamed)"]);
479
- }
480
- if (wanted.size === 0) return;
481
- const names = [...wanted.keys()].map((r) => `'${r.replace(/'/g, "''")}'`).join(",");
482
- const rows = await run(`
483
- SELECT r.rolname AS role,
484
- COALESCE(pg_has_role(to_regrole('${requestRole.replace(/'/g, "''")}'), r.oid, 'MEMBER'), false) AS reachable
485
- FROM pg_roles r
486
- WHERE r.rolname IN (${names})
487
- `);
488
- const reachable = new Map(rows.map((row) => [String(row.role), row.reachable === true]));
489
- const problems = [];
490
- for (const [role, slugs] of wanted) {
491
- if (reachable.get(role) === true) continue;
492
- const why = reachable.has(role) ? `"${requestRole}" is not a member of it` : "no such role exists in this database";
493
- const platform = FOREIGN_CONVENTION_ROLES[role];
494
- const hint = platform ? `"${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().` : `Either grant it (GRANT ${role} TO ${requestRole}) or drop \`pgRoles\` so the policy targets \`public\`.`;
495
- problems.push(` • pgRoles: ["${role}"] on ${slugs.join(", ")} — ${why}.\n ${hint}`);
496
- }
497
- 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");
498
- }
499
- //#endregion
500
- export { ensureAppRoleGrants as a, revokeUserRoleSql as c, warnOnAnonymousGrants as d, warnOnLegacyRlsFunctions as f, ensureAppRole as i, rls_enforcement_exports as l, applyAuthContext as n, findExposedInternalTables as o, warnOnRoleSchemaCollision as p, detectConnectionPosture as r, internalTablesGrantedToUserRole as s, REBASE_USER_ROLE$1 as t, validatePolicyPgRoles as u };
501
-
502
- //# sourceMappingURL=rls-enforcement-BOHuHVlc.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rls-enforcement-BOHuHVlc.js","names":[],"sources":["../src/security/rls-enforcement.ts"],"sourcesContent":["import { sql as drizzleSql, SQL } from \"drizzle-orm\";\nimport { ANONYMOUS_USER_ID, PolicyExpression, SecurityRule } from \"@rebasepro/types\";\nimport {\n AnonymousGrantRisk,\n findAnonymousGrants,\n REBASE_INTERNAL_TABLES,\n REBASE_USER_ROLE,\n revokeInternalTableAccess,\n securityRuleToConditions\n} from \"@rebasepro/common\";\nimport { REBASE_SCHEMA, usesLegacyRlsFunctions } from \"@rebasepro/types\";\nimport { logger } from \"@rebasepro/server\";\n\n/**\n * Unified RLS enforcement — the \"user context vs server context\" model.\n *\n * Every operation runs in one of two contexts:\n *\n * - **User context** — a request authenticated (or anonymous) via\n * `driver.withAuth(user)`. Runs as the restricted `rebase_user` role: a\n * non-owner, NOSUPERUSER, NOBYPASSRLS role, so Postgres RLS binds *every*\n * statement (SELECT, INSERT, UPDATE, DELETE). The collection's\n * `securityRules` are the whole authorization model; app-layer callbacks\n * are validation/side-effects, not a security boundary.\n *\n * - **Server context** — the base (owner) connection: auth flows, migrations,\n * and raw `rebase.sql`. As table owner it bypasses RLS. This is the trusted\n * plane, equivalent to Supabase's `service_role`.\n *\n * `rebase.dataAsAdmin` is **not** in it, despite the name. `init.ts` scopes\n * that driver with `withAuth(SERVICE_IDENTITY)`, so it arrives as user\n * context above — `rebase_user`, `app.uid = 'service'`, policies evaluated —\n * and clears the default policies through their admin arm rather than the\n * `rebase.uid() IS NULL` one.\n *\n * This module provides the three pieces:\n *\n * 1. {@link detectConnectionPosture} — is the connection subject to RLS at\n * all? (superuser / BYPASSRLS / table owner ⇒ no)\n * 2. {@link ensureAppRole} — idempotently provision `rebase_user` with\n * SELECT/INSERT/UPDATE/DELETE grants (+ default privileges so future\n * tables stay covered).\n * 3. {@link applyAuthContext} — per-transaction: set the `app.*` GUCs the\n * policies read (`rebase.uid()` etc.) and the transaction-local role\n * `rebase_user` so RLS binds, in one statement. Transaction-scoped, so it\n * composes with poolers.\n *\n * Provisioning runs from the framework's own bootstrap/migrate (which already\n * self-creates the `auth` schema and functions) — enforcement is default-on,\n * not an operator opt-in.\n */\n\n/**\n * The restricted role every authenticated (user-context) request runs as.\n *\n * Re-exported, not re-declared: the same name is needed by\n * `@rebasepro/common`'s internal-table revokes, and two spellings of a role name\n * fail as a silent no-op rather than an error.\n */\nexport { REBASE_USER_ROLE };\n\n/** Minimal SQL runner so callers can adapt drizzle or pg.Client. */\nexport type RawSqlRunner = (sqlText: string) => Promise<Record<string, unknown>[]>;\n\n/** Minimal transaction surface needed by {@link applyAuthContext}. */\nexport interface SqlTx {\n execute(query: SQL): Promise<unknown>;\n}\n\nexport interface ConnectionPosture {\n /** The connection's `current_user`. */\n role: string;\n superuser: boolean;\n bypassRLS: boolean;\n /**\n * Owns at least one user table — owners bypass non-FORCE RLS.\n *\n * \"Owns\" in Postgres's sense, not by name: a role that INHERITs the owner is\n * the owner for every ownership test the planner makes, including the one\n * that decides whether a policy applies at all.\n */\n ownsTables: boolean;\n /**\n * May create tables somewhere the server writes — and would then own them.\n *\n * The reason this is part of the posture rather than a separate question:\n * the posture is decided ONCE, at boot, and on a fresh database the\n * catalogue has nothing to report yet. The process that asks then goes on to\n * create every table in the schema and owns all of them for the rest of its\n * life. Asking only what is already there answers about the wrong instant.\n */\n canCreateTables: boolean;\n /** True when RLS would NOT constrain this connection. */\n privileged: boolean;\n}\n\nexport interface AuthContext {\n uid: string;\n /** Raw roles as carried on the user (strings or `{ id }` objects). */\n roles: unknown[];\n /**\n * Whether this session came from anonymous sign-in rather than an account.\n *\n * Anonymous sign-in mints a real user row and a real uid, so a guest was\n * indistinguishable from a registered account inside a policy: same\n * `rebase.uid()`, same default role. Every rule meaning \"a signed-in\n * person\" was therefore also a rule about anybody who had called\n * `POST /auth/anonymous`, which asks for no email, no password and no\n * agreement to anything.\n *\n * Optional, and absent reads as `false`: a caller that predates this — a\n * realtime subscription, a custom validator — keeps the behaviour it had\n * rather than having every one of its users reclassified as guests.\n */\n isAnonymous?: boolean;\n /**\n * The **custom** claims on the caller's token, as `rebase.jwt()` reports\n * them.\n *\n * This is how a policy reaches a fact about the session that is neither the\n * uid nor the roles — which, before this, it could not: `app.jwt` was built\n * from three fields the driver already had, so `rebase.jwt()`, documented\n * as \"full JWT claims as JSONB\", returned a three-key object that never had\n * a claim in it.\n *\n * Multi-tenancy's `claim` form is the first caller — `policy.authClaim(…)`\n * compiles to `rebase.jwt() ->> '<name>'`. Identity claims are stripped out\n * before they reach here (`AccessTokenPayload.claims`) and the identity\n * fields are written *over* them below, so nothing a hook put on a token\n * can assert a uid, roles or guest status.\n */\n claims?: Record<string, unknown>;\n}\n\nconst quoteIdent = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** DML the user role holds on managed tables (RLS still filters per row). */\nconst USER_TABLE_PRIVILEGES = \"SELECT, INSERT, UPDATE, DELETE\";\n\n/**\n * Take every privilege the user role holds on one table back — what a table\n * gets when RLS cannot be switched on for it, so it is unreachable rather than\n * unprotected. Quoted exactly: a mixed-case adopted table (`\"User\"`) folded to\n * lower case names a table that does not exist.\n */\nexport const revokeUserRoleSql = (schema: string, table: string): string =>\n `REVOKE ALL PRIVILEGES ON ${quoteIdent(schema)}.${quoteIdent(table)} FROM ${quoteIdent(REBASE_USER_ROLE)}`;\n\n/**\n * Warn when the connection role shares its name with an existing schema.\n *\n * Postgres resolves unqualified names through `search_path`, which defaults to\n * `\"$user\", public` — and `$user` is the connection ROLE. When a schema of that\n * name exists it sits ahead of `public`, so every unqualified statement\n * silently operates on it instead:\n *\n * CREATE TABLE posts (...); -- you meant public.posts; you got <role>.posts\n *\n * Nothing errors. You get a second table of the same name in the wrong schema,\n * and reads that pin `public` cannot see it — which reads as \"missing table\" and\n * sends people to re-run a push that creates a *third* copy. The bootstrapper\n * has a whole branch dedicated to recognising the symptom after the fact.\n *\n * Rebase shipped straight into this: it creates a schema named `rebase` while\n * every template named the database role `rebase` too. The scaffold uses\n * `rebase_app` now, and every pool Rebase opens pins `search_path=public`\n * (`pinSearchPath`), which covers the paths the framework controls. This covers\n * the ones it does not — `psql`, `pg_dump`, drizzle-kit, a colleague's script,\n * a hand-written migration — because the hazard is a property of the two NAMES,\n * not of any one connection.\n *\n * A warning rather than a boot failure: the database works, the framework's own\n * traffic is pinned, and refusing to start over a naming choice a user may have\n * inherited would be worse than the risk.\n */\nexport async function warnOnRoleSchemaCollision(run: RawSqlRunner): Promise<void> {\n try {\n const rows = await run(`\n SELECT current_user AS role,\n EXISTS (\n SELECT 1 FROM pg_namespace n WHERE n.nspname = current_user\n ) AS collides\n `);\n if (rows[0]?.collides !== true) return;\n const role = String(rows[0]?.role ?? \"the connection role\");\n logger.warn(\n `⚠️ The database role \"${role}\" has the same name as a schema. Postgres resolves unqualified ` +\n `names through \\`search_path\\`, which defaults to \\`\"$user\", public\\` — so \"${role}\" is searched ` +\n `BEFORE public, and any unqualified \\`CREATE TABLE\\`/\\`SELECT\\` from a tool that does not pin the ` +\n `path (psql, pg_dump, drizzle-kit, a hand-written migration) silently lands in \"${role}\" instead. ` +\n `Rebase's own connections pin \\`search_path=public\\`, so the server is unaffected. To remove the ` +\n `hazard entirely, connect as a role whose name is not also a schema — the scaffold uses ` +\n `\"rebase_app\".`\n );\n } catch {\n // A diagnostic must never be the reason a boot fails.\n }\n}\n\n/**\n * Would RLS actually constrain this connection?\n *\n * Four ways the answer is no, and only two of them are obvious. Superuser and\n * BYPASSRLS announce themselves in `pg_roles`. The other two are about\n * ownership, and both used to read as \"no bypass here\":\n *\n * - **Ownership through membership.** The old query compared\n * `pg_tables.tableowner` to `current_user` as a string. Postgres does not: a\n * role that INHERITs the owner passes every ownership test the planner makes,\n * including the one that decides whether a policy applies. So a perfectly\n * ordinary \"app role that is a member of the owner role\" setup reported\n * unprivileged and bypassed every policy — permanently, since no restart\n * changes a string comparison's answer.\n *\n * - **Ownership that has not happened yet.** The posture is decided once, at\n * boot, and on a fresh database there is nothing in the catalogue to find. The\n * same process then creates every table and owns all of them. The first boot\n * of a new deployment therefore served every request unconstrained, the log\n * said RLS was fine, and the SECOND boot silently fixed it — which is the\n * worst possible shape for a security check, because the state that reproduces\n * it is gone by the time anyone looks. Asking \"may this role create tables\n * where the server provisions?\" answers about the process's whole life rather\n * than about one instant of it.\n *\n * `schemas` narrows the CREATE question to where the server actually writes.\n * Omitted, it asks about every schema the role can see, which is the safe\n * direction: over-reporting costs a role switch that was not strictly needed,\n * under-reporting costs the entire authorization model.\n */\nexport async function detectConnectionPosture(\n run: RawSqlRunner,\n schemas?: string[]\n): Promise<ConnectionPosture> {\n // Identifiers, and they reach SQL as literals in a catalogue comparison —\n // but they arrive from collection configs, so they are quoted as string\n // literals rather than interpolated as names, and a quote inside one is\n // escaped rather than trusted.\n const schemaFilter = schemas?.length\n ? `AND n.nspname IN (${Array.from(new Set(schemas))\n .map((s) => `'${s.replace(/'/g, \"''\")}'`)\n .join(\", \")})`\n : \"\";\n\n const rows = await run(`\n SELECT current_user AS role,\n r.rolsuper AS superuser,\n r.rolbypassrls AS bypassrls,\n EXISTS (\n SELECT 1 FROM pg_tables t\n WHERE pg_has_role(current_user, t.tableowner, 'USAGE')\n AND t.schemaname NOT IN ('pg_catalog', 'information_schema')\n ) AS owns_tables,\n EXISTS (\n SELECT 1 FROM pg_namespace n\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND n.nspname NOT LIKE 'pg\\\\_toast%'\n AND n.nspname NOT LIKE 'pg\\\\_temp%'\n ${schemaFilter}\n AND has_schema_privilege(current_user, n.oid, 'CREATE')\n ) AS can_create\n FROM pg_roles r\n WHERE r.rolname = current_user\n `);\n const row = rows[0] ?? {};\n const superuser = row.superuser === true;\n const bypassRLS = row.bypassrls === true;\n const ownsTables = row.owns_tables === true;\n const canCreateTables = row.can_create === true;\n return {\n role: String(row.role ?? \"unknown\"),\n superuser,\n bypassRLS,\n ownsTables,\n canCreateTables,\n privileged: superuser || bypassRLS || ownsTables || canCreateTables\n };\n}\n\n/**\n * Human-actionable instructions for when the connection cannot provision the\n * user role itself (no CREATEROLE and role not pre-created by the platform).\n */\nexport function appRoleSetupInstructions(connectionRole: string, schemas: string[]): string {\n const grants = schemas.map((s) =>\n `GRANT USAGE ON SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};\\n` +\n `GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};\\n` +\n `GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};`\n ).join(\"\\n\");\n return (\n `Rebase enforces row-level security by running authenticated requests as ` +\n `the restricted role \"${REBASE_USER_ROLE}\", but the connection role ` +\n `\"${connectionRole}\" bypasses RLS and cannot create that role itself.\\n` +\n `Run the following as a database administrator, then restart:\\n\\n` +\n `CREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\\n` +\n `GRANT ${REBASE_USER_ROLE} TO ${quoteIdent(connectionRole)};\\n` +\n grants\n );\n}\n\n/**\n * Idempotently provision the `rebase_user` role, membership for the current\n * connection role, and DML grants (+ default privileges for future tables)\n * on every existing schema in `schemas`.\n *\n * Split into privilege tiers so it works both when the connection is a\n * superuser (creates everything) and when the platform pre-created the role\n * and membership (e.g. CNPG `postInitApplicationSQL`) and the connection is\n * merely the table owner — owners can always run the grant tier themselves.\n *\n * RLS still filters every row: these grants only make the tables *reachable*\n * by the role; the policies decide which rows/commands actually pass.\n *\n * Throws with precise setup instructions when the role is missing and the\n * connection cannot create it.\n */\nexport async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promise<void> {\n const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));\n\n // Tier 1 — role existence.\n const roleRows = await run(`SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}'`);\n if (roleRows.length === 0) {\n try {\n // Guarded in the statement as well as by the probe above. A role\n // belongs to the cluster, not the database, so a recorded\n // provisioning run (REBASE_PROVISION_SQL_OUT) replayed into another\n // database on a cluster that already has the role must find this a\n // no-op rather than its first error.\n await run(`\n DO $rebase_role$\n BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}') THEN\n CREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\n END\n $rebase_role$\n `);\n } catch (err) {\n throw new Error(\n `Failed to create the \"${REBASE_USER_ROLE}\" role: ${err instanceof Error ? err.message : String(err)}\\n\\n` +\n appRoleSetupInstructions(\"current connection role\", uniqueSchemas)\n );\n }\n }\n\n // Tier 2 — membership, so a non-superuser connection may SET ROLE to it.\n const memberRows = await run(`\n SELECT (pg_has_role(current_user, '${REBASE_USER_ROLE}', 'MEMBER')\n OR (SELECT rolsuper FROM pg_roles WHERE rolname = current_user)) AS can_set,\n current_user AS role\n `);\n if (memberRows[0]?.can_set !== true) {\n try {\n await run(`GRANT ${REBASE_USER_ROLE} TO CURRENT_USER`);\n } catch (err) {\n throw new Error(\n `The connection role is not a member of \"${REBASE_USER_ROLE}\" and cannot grant itself membership: ` +\n `${err instanceof Error ? err.message : String(err)}\\n\\n` +\n appRoleSetupInstructions(String(memberRows[0]?.role ?? \"current connection role\"), uniqueSchemas)\n );\n }\n }\n\n // Tier 3 — grants.\n await ensureAppRoleGrants(run, uniqueSchemas);\n\n logger.debug(`🔐 [rls] User role \"${REBASE_USER_ROLE}\" provisioned (schemas: ${uniqueSchemas.join(\", \")})`);\n}\n\n/** A string literal for a catalogue read. Names come from config and constants, never from a request. */\nconst sqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\nconst textArray = (values: readonly string[]): string =>\n values.length === 0 ? \"ARRAY[]::text[]\" : `ARRAY[${values.map(sqlLiteral).join(\", \")}]::text[]`;\n\n/**\n * The framework's internal tables in `schemas` that the request role can\n * reach — `schema.table`, sorted — when nothing is left to take it back off.\n *\n * Every provisioning boot repairs this: each store revokes on its own table\n * and {@link ensureAppRole}'s sweep revokes on the rest, because the grant\n * tier hands the request role DML on whole schemas. A backend that changes\n * nothing in its database runs neither, so a database whose `rebase_user` can\n * read `refresh_tokens` or `api_keys` would stay that way for as long as it\n * served. This is the question the sweep would have answered, asked instead.\n *\n * \"Can reach\" is what the role can actually do — through a grant to it, to a\n * role it inherits, or to PUBLIC, on the table or on any of its columns —\n * because that, not how the ACL is spelled, is what a request running as it\n * gets. A table with RLS on is somebody's collection by that same rule as the\n * sweep's, and is left out.\n */\nexport async function findExposedInternalTables(run: RawSqlRunner, schemas: string[]): Promise<string[]> {\n const rows = await run(`\n SELECT n.nspname || '.' || c.relname AS name\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY(${textArray(Array.from(new Set(schemas)))})\n AND c.relname = ANY(${textArray(REBASE_INTERNAL_TABLES)})\n AND c.relkind IN ('r', 'p')\n AND NOT c.relrowsecurity\n AND (has_table_privilege(${sqlLiteral(REBASE_USER_ROLE)}, c.oid, 'SELECT, INSERT, UPDATE, DELETE')\n OR has_any_column_privilege(${sqlLiteral(REBASE_USER_ROLE)}, c.oid, 'SELECT, INSERT, UPDATE'))\n ORDER BY 1\n `);\n return rows.map(row => String(row.name));\n}\n\n/** What the grant tier would find already in place in one schema. */\ninterface SchemaGrants {\n /** `USAGE` on the schema, granted by its owner. */\n usage: boolean;\n /**\n * Every relation `GRANT … ON ALL TABLES` reaches already has all four DML\n * privileges from its owner — Rebase's own RLS-off tables aside, which the\n * sweep takes back right after and so never keep them.\n */\n tables: boolean;\n /** Every sequence already has `USAGE, SELECT` from its owner. */\n sequences: boolean;\n /** This role's default privileges in the schema already grant the table DML. */\n defaultTables: boolean;\n /** …and the sequence `USAGE, SELECT`. */\n defaultSequences: boolean;\n /**\n * Rebase's own RLS-off tables a `REVOKE` would still change: the user role\n * holds a privilege on them, or the table has never had an ACL written —\n * `NULL`, which a `REVOKE` (like the grant-and-revoke it replaces) turns\n * into the owner's explicit default. Same access either way; the same\n * catalogue only this way.\n */\n internalGranted: string[];\n}\n\n/**\n * The grant tier's state for every existing schema in `schemas`, in one read.\n *\n * A grant counts as present only as the statement this tier runs would record\n * it — grantor the object's owner, which is what a GRANT by the owner, a member\n * of the owning role or a superuser records — so skipping it leaves the ACL\n * exactly as running it would. Anything else reads as missing, and the\n * statement runs as it always did.\n */\nasync function readSchemaGrants(run: RawSqlRunner, schemas: string[]): Promise<Map<string, SchemaGrants>> {\n const internal = textArray(REBASE_INTERNAL_TABLES);\n const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(REBASE_USER_ROLE)})`;\n /** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */\n const held = (acl: string, privileges: string[], grantor?: string): string =>\n `(SELECT count(DISTINCT a.privilege_type) FROM aclexplode(${acl}) a WHERE a.grantee = ${target}` +\n `${grantor ? ` AND a.grantor = ${grantor}` : \"\"} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(\", \")}))`;\n const DML = [\"SELECT\", \"INSERT\", \"UPDATE\", \"DELETE\"];\n const SEQ = [\"USAGE\", \"SELECT\"];\n const rows = await run(`\n SELECT n.nspname AS schema,\n ${held(\"n.nspacl\", [\"USAGE\"], \"n.nspowner\")} = 1 AS usage,\n NOT EXISTS (\n SELECT 1 FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')\n AND NOT (c.relname = ANY(${internal}) AND NOT c.relrowsecurity)\n AND ${held(\"c.relacl\", DML, \"c.relowner\")} < ${DML.length}\n ) AS tables,\n NOT EXISTS (\n SELECT 1 FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relkind = 'S'\n AND ${held(\"c.relacl\", SEQ, \"c.relowner\")} < ${SEQ.length}\n ) AS sequences,\n EXISTS (\n SELECT 1 FROM pg_default_acl d\n WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'r'\n AND ${held(\"d.defaclacl\", DML)} = ${DML.length}\n ) AS default_tables,\n EXISTS (\n SELECT 1 FROM pg_default_acl d\n WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'S'\n AND ${held(\"d.defaclacl\", SEQ)} = ${SEQ.length}\n ) AS default_sequences,\n ARRAY(\n SELECT c.relname::text FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relname = ANY(${internal}) AND NOT c.relrowsecurity\n AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))\n ORDER BY 1\n ) AS internal_granted\n FROM pg_namespace n\n WHERE n.nspname = ANY(${textArray(schemas)})\n `);\n const grants = new Map<string, SchemaGrants>();\n for (const row of rows) {\n const internalGranted = row.internal_granted;\n grants.set(String(row.schema), {\n usage: row.usage === true,\n tables: row.tables === true,\n sequences: row.sequences === true,\n defaultTables: row.default_tables === true,\n defaultSequences: row.default_sequences === true,\n internalGranted: Array.isArray(internalGranted)\n ? internalGranted.map(String)\n // A driver that hands arrays back as text: `{a,b}`.\n : String(internalGranted ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean)\n });\n }\n return grants;\n}\n\n/**\n * The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing\n * schema in `schemas`, DML on its tables and `USAGE, SELECT` on its\n * sequences, the default privileges that cover what this role creates later,\n * and Rebase's own tables taken back — for a role and membership already\n * provisioned.\n *\n * Every statement is issued only when the catalogue says it would change\n * something. They used to run unconditionally, twice per boot (at connect, and\n * again in the final posture check): a `GRANT … ON ALL TABLES` rewrites every\n * table's `pg_class` row whether or not the ACL changes, which invalidates\n * every table's cached plans on every connection, and the internal-table sweep\n * ran 23 `REVOKE`s per schema. A boot against a database whose grants already\n * hold now reads one catalogue query and writes nothing; one that is missing\n * any of them runs exactly the statements it always ran.\n *\n * Table owners (the expected non-superuser posture) can always grant on their\n * own objects, so this needs no extra privilege.\n */\nexport async function ensureAppRoleGrants(run: RawSqlRunner, schemas: string[]): Promise<void> {\n const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));\n const grants = await readSchemaGrants(run, uniqueSchemas);\n for (const schema of uniqueSchemas) {\n const state = grants.get(schema);\n // Not there (yet): a later call, once provisioning has created it, grants it.\n if (!state) continue;\n const s = quoteIdent(schema);\n if (!state.usage) await run(`GRANT USAGE ON SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n if (!state.tables) await run(`GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n if (!state.sequences) await run(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n // Cover objects created later by the CURRENT role (the role that runs\n // migrations), so a migrate can never strand the user role.\n if (!state.defaultTables) {\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${REBASE_USER_ROLE}`);\n }\n if (!state.defaultSequences) {\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${REBASE_USER_ROLE}`);\n }\n\n // The grants above are deliberately schema-wide — a project's own\n // collections may live in `rebase`, and future tables must be reachable\n // or a migration strands the role. Rebase's OWN tables are the exception:\n // refresh tokens, MFA secrets, API keys and the rest carry no RLS and no\n // row an end user should ever address. Taking the privilege back here\n // covers every table that already exists; each creator revokes on the\n // table it just made, for the boot that creates them for the first time.\n //\n // All of them right after the schema-wide grant, which has just handed\n // them out; otherwise only the ones the catalogue says still hold one.\n const tables = state.tables ? state.internalGranted : undefined;\n if (tables && tables.length === 0) continue;\n await revokeInternalTableAccess(async (text) => { await run(text); }, schema, {\n tables,\n onError: (table, error) => logger.warn(\n `🔐 [rls] Could not revoke \"${REBASE_USER_ROLE}\" access to \"${schema}\".\"${table}\" — ` +\n \"it stays reachable by authenticated requests: \" +\n (error instanceof Error ? error.message : String(error))\n )\n });\n }\n}\n\n/**\n * Rebase's own RLS-off tables in `schema` that a `revokeInternalTableAccess`\n * sweep would change — the user role holds a privilege on them, or their ACL\n * has never been written. One read; the sweep it narrows is one `DO` per\n * table name.\n */\nexport async function internalTablesGrantedToUserRole(run: RawSqlRunner, schema: string): Promise<string[]> {\n return (await readSchemaGrants(run, [schema])).get(schema)?.internalGranted ?? [];\n}\n\n/**\n * Apply the authenticated context to a transaction: the `app.*` GUCs that RLS\n * policies read via `rebase.uid()` / `rebase.roles()` / `rebase.jwt()`, and — when\n * `userRole` is set — the `LOCAL` role switch, in the same statement, so RLS\n * binds every statement in this transaction (reads *and* writes).\n *\n * GUCs are set with `is_local = true` and the role switch is `LOCAL`: both\n * reset at commit/rollback, so pooled connections are never polluted.\n *\n * Fails closed by construction: if the role switch errors, the transaction\n * aborts instead of proceeding privileged.\n *\n * SECURITY: this function is only ever called on the **user** path (the server\n * context uses the base/owner driver and never calls it). The default policies\n * treat `rebase.uid() IS NULL` as the trusted server context, and `rebase.uid()`\n * is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would\n * be read as NULL and silently escalate a user request to server privileges.\n * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,\n * rather than trusting every caller (e.g. realtime subscription auth) to do it.\n * That sentinel is exported from `@rebasepro/types` because it leaks into rule\n * semantics: it is why `rebase.uid() IS NOT NULL` is true for anonymous requests.\n */\nexport async function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void> {\n const uid = typeof auth.uid === \"string\" && auth.uid.trim() !== \"\" ? auth.uid : ANONYMOUS_USER_ID;\n const normalizedRoles = auth.roles.map((r: unknown) =>\n typeof r === \"string\" ? r : (r as Record<string, unknown>)?.id ?? String(r)\n );\n // `app.user_id` is the pre-rename spelling, still written because policies\n // are data: a database provisioned before the rename holds rules compiled\n // to `current_setting('app.user_id')`, and those predicates would evaluate\n // to NULL — failing open or locking out — if we stopped setting it. Drop\n // the alias only once no live database carries a legacy policy.\n // A guest is a signed-in caller with no account behind them, and until this\n // the database could not tell the difference — see `rebase.is_anonymous()`.\n // Written as a string because that is what `set_config` takes.\n const isAnonymous = auth.isAnonymous === true ? \"true\" : \"false\";\n\n await tx.execute(drizzleSql`\n SELECT\n set_config('app.uid', ${uid}, true),\n set_config('app.user_id', ${uid}, true),\n set_config('app.user_roles', ${normalizedRoles.join(\",\")}, true),\n set_config('app.is_anonymous', ${isAnonymous}, true),\n set_config('app.jwt', ${JSON.stringify({\n // The caller's custom claims, FIRST, so the identity keys below\n // overwrite them rather than the other way round. Same ordering, and\n // the same reason, as `generateAccessToken`: a claims hook is a place\n // to add facts about a session, not the place its subject is decided.\n // `verifyAccessToken` already strips the identity claims out of this\n // object; the ordering is the second lock on the same door.\n ...(auth.claims ?? {}),\n sub: uid,\n roles: auth.roles,\n // In the claims too, so a policy reading `rebase.jwt()` — which is\n // how a rule reaches anything that is not uid or roles — sees the\n // same fact as `rebase.is_anonymous()`. Two sources that could\n // disagree would be worse than one.\n is_anonymous: auth.isAnonymous === true\n })}, true)${userRole\n // The role switch, in the same statement rather than a `SET LOCAL ROLE`\n // round trip of its own on every transaction. Postgres implements\n // `SET ROLE` as the `role` setting: `set_config('role', name, true)`\n // runs the same membership check, fails with the same SQLSTATE and\n // message (42501 \"permission denied to set role\", 22023 for an unknown\n // role — `isRoleSwitchingPermissionError` still reads it), takes the\n // name verbatim as the quoted identifier did, and resets at COMMIT and\n // ROLLBACK like `LOCAL`. Last in the list, after the GUCs; a refusal\n // fails the whole statement, so the transaction aborts rather than\n // running on as the connection owner. auth-context-one-statement.test.ts.\n ? drizzleSql`,\n set_config('role', ${userRole}, true)`\n : drizzleSql``}\n `);\n}\n\n/** Role names from other BaaS platforms that people reach for out of habit. */\nconst FOREIGN_CONVENTION_ROLES: Record<string, string> = {\n authenticated: \"Supabase\",\n anon: \"Supabase\",\n service_role: \"Supabase\"\n};\n\n/**\n * Warn about rules that read as \"signed-in users only\" but admit anonymous\n * callers — `rebase.uid() IS NOT NULL`, or a comparison against another\n * platform's magic user id such as `'anon'`.\n *\n * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling\n * of the same habit. A foreign `pgRoles` value makes a policy unreachable and\n * the table reads empty — loud, and that guard throws. These do the opposite:\n * the rule compiles to a grant, and nothing looks wrong until the data is\n * already public.\n *\n * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are\n * serving traffic today: refusing to boot would take an app offline to report a\n * problem it already has, and on the read path it would take it offline\n * *because* its data was exposed. Rewriting the author's SQL is not an option\n * either — this is the escape hatch whose whole promise is that it means what it\n * says. So: say so, loudly, and leave the rule alone.\n */\nexport function warnOnAnonymousGrants(\n collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]\n): void {\n // Grouped by the mistake, not by the rule: one habit typically repeats\n // across every collection an author wrote, and a per-rule list would repeat\n // the same paragraph dozens of times and get skimmed.\n const byRisk = new Map<string, { risk: AnonymousGrantRisk; sites: string[] }>();\n\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n const risks = [usingExpr, withCheckExpr]\n .filter((e): e is PolicyExpression => e !== null)\n .flatMap(findAnonymousGrants);\n\n for (const risk of risks) {\n const key = `${risk.pattern}:${risk.detail}`;\n const site = `${collection.slug ?? \"(unnamed)\"} → \"${rule.name ?? \"(unnamed rule)\"}\"`;\n const entry = byRisk.get(key) ?? { risk, sites: [] };\n if (!entry.sites.includes(site)) entry.sites.push(site);\n byRisk.set(key, entry);\n }\n }\n }\n\n if (byRisk.size === 0) return;\n\n const problems = [...byRisk.values()].map(({ risk, sites }) =>\n ` • ${risk.explanation}\\n ${sites.length} rule(s): ${sites.join(\", \")}`\n );\n\n logger.warn(\n `Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a ` +\n `client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are ` +\n `true for everyone:\\n\\n` +\n problems.join(\"\\n\\n\") + \"\\n\"\n );\n}\n\n/**\n * Name the collections whose raw policy SQL still calls the pre-1.0 helpers.\n *\n * The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the\n * database, so nothing is broken and no policy is wrong — which is exactly why\n * this has to be said out loud. A silent rewrite that works forever is not a\n * migration, it is a second supported spelling nobody wrote down, and the next\n * person to read those rules will copy the old one.\n *\n * Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,\n * `policy.rolesOverlap(...)`) compile from the model and were never affected.\n */\nexport function warnOnLegacyRlsFunctions(\n collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]\n): void {\n const sites: string[] = [];\n\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n const carriesLegacy = [usingExpr, withCheckExpr]\n .filter((e): e is PolicyExpression => e !== null)\n .some(containsLegacyRlsCall);\n if (!carriesLegacy) continue;\n\n const site = `${collection.slug ?? \"(unnamed)\"} → \"${rule.name ?? \"(unnamed rule)\"}\"`;\n if (!sites.includes(site)) sites.push(site);\n }\n }\n\n if (sites.length === 0) return;\n\n logger.warn(\n `These security rules call the pre-1.0 RLS helpers (\\`auth.uid()\\`, \\`auth.roles()\\`, \\`auth.jwt()\\`). ` +\n `They still work — the compiler rewrites them — but the functions now live in the \\`rebase\\` schema, ` +\n `and the \\`auth\\` one is Supabase's. Update the raw SQL in these rules to \\`${REBASE_SCHEMA}.uid()\\` ` +\n `and friends, or switch them to the structured helpers (\\`policy.authUid()\\`, \\`policy.rolesOverlap()\\`), ` +\n `which never had to be spelled by hand:\\n\\n` +\n sites.map(s => ` • ${s}`).join(\"\\n\") + \"\\n\"\n );\n}\n\n/** Whether any `raw` expression in the tree calls a pre-1.0 helper. */\nfunction containsLegacyRlsCall(expr: PolicyExpression): boolean {\n switch (expr.kind) {\n case \"raw\":\n return usesLegacyRlsFunctions(expr.sql);\n case \"and\":\n case \"or\":\n return expr.operands.some(containsLegacyRlsCall);\n case \"not\":\n return containsLegacyRlsCall(expr.operand);\n case \"existsIn\":\n return containsLegacyRlsCall(expr.where);\n default:\n return false;\n }\n}\n\n/**\n * Reject `pgRoles` that this server can never satisfy.\n *\n * `pgRoles` sets the `TO` clause of a generated policy, so a policy naming a\n * role the request never runs as simply never applies — and RLS then filters\n * every row. The table reads as empty, which is indistinguishable from having\n * no data, so the mistake survives review and ships.\n *\n * Requests run as `rebase_user`, so a policy is only reachable if it targets\n * `public` or a role `rebase_user` holds. Anything else is a configuration\n * error worth failing the boot for.\n */\nexport async function validatePolicyPgRoles(\n run: RawSqlRunner,\n collections: { slug?: string; securityRules?: readonly { name?: string; pgRoles?: readonly string[] }[] }[],\n /** The role requests actually run as: `rebase_user` when the connection is\n * privileged enough to switch, otherwise the connection role itself. */\n requestRole: string = REBASE_USER_ROLE\n): Promise<void> {\n const wanted = new Map<string, string[]>();\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n for (const role of rule.pgRoles ?? []) {\n if (role === \"public\") continue;\n wanted.set(role, [...(wanted.get(role) ?? []), collection.slug ?? \"(unnamed)\"]);\n }\n }\n }\n if (wanted.size === 0) return;\n\n const names = [...wanted.keys()].map((r) => `'${r.replace(/'/g, \"''\")}'`).join(\",\");\n const escapedRequestRole = requestRole.replace(/'/g, \"''\");\n const rows = await run(`\n SELECT r.rolname AS role,\n COALESCE(pg_has_role(to_regrole('${escapedRequestRole}'), r.oid, 'MEMBER'), false) AS reachable\n FROM pg_roles r\n WHERE r.rolname IN (${names})\n `);\n\n const reachable = new Map(rows.map((row) => [String(row.role), row.reachable === true]));\n const problems: string[] = [];\n\n for (const [role, slugs] of wanted) {\n if (reachable.get(role) === true) continue;\n\n const why = reachable.has(role)\n ? `\"${requestRole}\" is not a member of it`\n : \"no such role exists in this database\";\n const platform = FOREIGN_CONVENTION_ROLES[role];\n const hint = platform\n ? `\"${role}\" is a ${platform} convention, not a PostgreSQL role. Application roles belong in \\`roles: [\"${role === \"service_role\" ? \"admin\" : role}\"]\\`, which is checked inside the policy via rebase.roles().`\n : `Either grant it (GRANT ${role} TO ${requestRole}) or drop \\`pgRoles\\` so the policy targets \\`public\\`.`;\n\n problems.push(\n ` • pgRoles: [\"${role}\"] on ${slugs.join(\", \")} — ${why}.\\n ${hint}`\n );\n }\n\n if (problems.length > 0) {\n throw new Error(\n `Security rules target PostgreSQL roles this server cannot use. Requests run as ` +\n `\"${requestRole}\", so these policies would never apply and every row would be ` +\n `filtered out — the collections would look empty rather than error.\\n\\n` +\n problems.join(\"\\n\\n\") + \"\\n\"\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsIA,IAAM,cAAc,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;;AAG5E,IAAM,wBAAwB;;;;;;;AAQ9B,IAAa,qBAAqB,QAAgB,UAC9C,4BAA4B,WAAW,MAAM,EAAE,GAAG,WAAW,KAAK,EAAE,QAAQ,WAAW,kBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6B3G,eAAsB,0BAA0B,KAAkC;CAC9E,IAAI;EACA,MAAM,OAAO,MAAM,IAAI;;;;;SAKtB;EACD,IAAI,KAAK,EAAE,EAAE,aAAa,MAAM;EAChC,MAAM,OAAO,OAAO,KAAK,EAAE,EAAE,QAAQ,qBAAqB;EAC1D,OAAO,KACH,0BAA0B,KAAK,4IAC+C,KAAK,gMAED,KAAK,gNAI3F;CACJ,QAAQ,CAER;AACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,wBAClB,KACA,SAC0B;CA+B1B,MAAM,OAAM,MApBO,IAAI;;;;;;;;;;;;;;uBANF,SAAS,SACxB,qBAAqB,MAAM,KAAK,IAAI,IAAI,OAAO,CAAC,CAAC,CAC9C,KAAK,MAAM,IAAI,EAAE,QAAQ,MAAM,IAAI,EAAE,EAAE,CAAC,CACxC,KAAK,IAAI,EAAE,KACd,GAgB0B;;;;;KAK/B,EAAA,CACgB,MAAM,CAAC;CACxB,MAAM,YAAY,IAAI,cAAc;CACpC,MAAM,YAAY,IAAI,c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