@rebasepro/server-postgres 0.29.2 → 0.30.0

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 (90) hide show
  1. package/dist/{BranchService-X9R505mP.js → BranchService-CrXvcES2.js} +3 -3
  2. package/dist/{BranchService-X9R505mP.js.map → BranchService-CrXvcES2.js.map} +1 -1
  3. package/dist/PostgresBootstrapper.d.ts +7 -0
  4. package/dist/{backup-cli-CwiJEp_J.js → backup-cli-CTKCOLpX.js} +3 -3
  5. package/dist/{backup-cli-CwiJEp_J.js.map → backup-cli-CTKCOLpX.js.map} +1 -1
  6. package/dist/{boot-ddl-CbZj9ovZ.js → boot-ddl-CqGIwSYx.js} +2 -2
  7. package/dist/{boot-ddl-CbZj9ovZ.js.map → boot-ddl-CqGIwSYx.js.map} +1 -1
  8. package/dist/{cli-console-DDkNetCz.js → cli-console-DBPw-oAz.js} +5 -5
  9. package/dist/{cli-console-DDkNetCz.js.map → cli-console-DBPw-oAz.js.map} +1 -1
  10. package/dist/{cli-errors-C73Qy7WJ.js → cli-errors-DYTxnLbW.js} +5 -5
  11. package/dist/{cli-errors-C73Qy7WJ.js.map → cli-errors-DYTxnLbW.js.map} +1 -1
  12. package/dist/cli.js +62 -42
  13. package/dist/cli.js.map +1 -1
  14. package/dist/{database-preflight-DIauc8i5.js → database-preflight-iBpT7-vv.js} +2 -2
  15. package/dist/{database-preflight-DIauc8i5.js.map → database-preflight-iBpT7-vv.js.map} +1 -1
  16. package/dist/{deferred-index-build-DDdnjaOW.js → deferred-index-build-BCU9RoHK.js} +6 -6
  17. package/dist/{deferred-index-build-DDdnjaOW.js.map → deferred-index-build-BCU9RoHK.js.map} +1 -1
  18. package/dist/{doctor-DwMXljiq.js → doctor-Kg1oUK0Q.js} +6 -6
  19. package/dist/{doctor-DwMXljiq.js.map → doctor-Kg1oUK0Q.js.map} +1 -1
  20. package/dist/{ensure-collection-policies-DJsOMpaI.js → ensure-collection-policies-Bo-_fDAy.js} +12 -12
  21. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +1 -0
  22. package/dist/{ensure-collection-tables-h1mUO7Uu.js → ensure-collection-tables-DCJINkT_.js} +9 -9
  23. package/dist/{ensure-collection-tables-h1mUO7Uu.js.map → ensure-collection-tables-DCJINkT_.js.map} +1 -1
  24. package/dist/{ensure-tables-CUqYgMvo.js → ensure-tables-BPGaGh0y.js} +4 -4
  25. package/dist/{ensure-tables-CUqYgMvo.js.map → ensure-tables-BPGaGh0y.js.map} +1 -1
  26. package/dist/{enum-labels-kept-z7ustOl_.js → enum-labels-kept-YAgOZS4I.js} +3 -3
  27. package/dist/{enum-labels-kept-z7ustOl_.js.map → enum-labels-kept-YAgOZS4I.js.map} +1 -1
  28. package/dist/{generate-drizzle-schema-BIUqhSzh.js → generate-drizzle-schema-DcrFr7YX.js} +2 -2
  29. package/dist/{generate-drizzle-schema-BIUqhSzh.js.map → generate-drizzle-schema-DcrFr7YX.js.map} +1 -1
  30. package/dist/{generate-drizzle-schema-logic-BBXjxm5z.js → generate-drizzle-schema-logic-LTLZvt6r.js} +2 -2
  31. package/dist/{generate-drizzle-schema-logic-BBXjxm5z.js.map → generate-drizzle-schema-logic-LTLZvt6r.js.map} +1 -1
  32. package/dist/{generate-files-BkiRFoV1.js → generate-files-CsaVzatS.js} +3 -3
  33. package/dist/{generate-files-BkiRFoV1.js.map → generate-files-CsaVzatS.js.map} +1 -1
  34. package/dist/{generate-postgres-ddl-logic-G9PvjHrr.js → generate-postgres-ddl-logic-Dg0bcENZ.js} +39 -6
  35. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +1 -0
  36. package/dist/{generated-schema-diff-D2soazQU.js → generated-schema-diff-By4dxyTH.js} +2 -2
  37. package/dist/{generated-schema-diff-D2soazQU.js.map → generated-schema-diff-By4dxyTH.js.map} +1 -1
  38. package/dist/index.es.js +12 -12
  39. package/dist/{migrate-baseline-CveNQli3.js → migrate-baseline-CmWXL7qx.js} +2 -2
  40. package/dist/{migrate-baseline-CveNQli3.js.map → migrate-baseline-CmWXL7qx.js.map} +1 -1
  41. package/dist/{migrate-policy-stamps-C4qbQ0jK.js → migrate-policy-stamps-BN_Qad6c.js} +6 -6
  42. package/dist/{migrate-policy-stamps-C4qbQ0jK.js.map → migrate-policy-stamps-BN_Qad6c.js.map} +1 -1
  43. package/dist/{open-rebase-Cvid3iwR.js → open-rebase-40paQfVW.js} +31 -24
  44. package/dist/{open-rebase-Cvid3iwR.js.map → open-rebase-40paQfVW.js.map} +1 -1
  45. package/dist/{pg-error-utils-80uTIHQs.js → pg-error-utils-DJHjCF7-.js} +2 -2
  46. package/dist/{pg-error-utils-80uTIHQs.js.map → pg-error-utils-DJHjCF7-.js.map} +1 -1
  47. package/dist/{plan-schema-CMhNYEYF.js → plan-schema-vJd3UEmT.js} +24 -9
  48. package/dist/plan-schema-vJd3UEmT.js.map +1 -0
  49. package/dist/{policy-drift-Bx6663KD.js → policy-drift-C-m0uWHH.js} +53 -8
  50. package/dist/policy-drift-C-m0uWHH.js.map +1 -0
  51. package/dist/{push-index-adoption-C-TpM445.js → push-index-adoption-Cp7oZxSl.js} +3 -3
  52. package/dist/{push-index-adoption-C-TpM445.js.map → push-index-adoption-Cp7oZxSl.js.map} +1 -1
  53. package/dist/{push-index-prebuild-xbpgZEJK.js → push-index-prebuild-DbwKGtQT.js} +4 -4
  54. package/dist/{push-index-prebuild-xbpgZEJK.js.map → push-index-prebuild-DbwKGtQT.js.map} +1 -1
  55. package/dist/{push-kept-defaults-D-JEv0Gn.js → push-kept-defaults-CLcgsEPt.js} +2 -2
  56. package/dist/{push-kept-defaults-D-JEv0Gn.js.map → push-kept-defaults-CLcgsEPt.js.map} +1 -1
  57. package/dist/{push-legacy-renames-7UKspspl.js → push-legacy-renames-BthD0E9W.js} +4 -4
  58. package/dist/{push-legacy-renames-7UKspspl.js.map → push-legacy-renames-BthD0E9W.js.map} +1 -1
  59. package/dist/{push-policy-plan-BOw5PtU8.js → push-policy-plan-BgcrroxQ.js} +3 -3
  60. package/dist/{push-policy-plan-BOw5PtU8.js.map → push-policy-plan-BgcrroxQ.js.map} +1 -1
  61. package/dist/{render-ddl-Di-fTGti.js → render-ddl-Ci3S_SoI.js} +23 -5
  62. package/dist/render-ddl-Ci3S_SoI.js.map +1 -0
  63. package/dist/{request-role-cli-Bxxskru9.js → request-role-cli-Dy1EgJU9.js} +8 -8
  64. package/dist/{request-role-cli-Bxxskru9.js.map → request-role-cli-Dy1EgJU9.js.map} +1 -1
  65. package/dist/{request-role-migration-BCW4v0rq.js → request-role-migration-GHTJnPMV.js} +2 -2
  66. package/dist/{request-role-migration-BCW4v0rq.js.map → request-role-migration-GHTJnPMV.js.map} +1 -1
  67. package/dist/{rls-bootstrap-sql-CxszeSc7.js → rls-bootstrap-sql-kPX4-MB1.js} +18 -3
  68. package/dist/rls-bootstrap-sql-kPX4-MB1.js.map +1 -0
  69. package/dist/{rls-enforcement-CyUCPDH8.js → rls-enforcement-Cc_UhOxb.js} +109 -6
  70. package/dist/rls-enforcement-Cc_UhOxb.js.map +1 -0
  71. package/dist/schema/doctor-cli.js +7 -7
  72. package/dist/schema/ensure-collection-policies.d.ts +8 -0
  73. package/dist/schema/generate-drizzle-schema.js +1 -1
  74. package/dist/schema/generate-postgres-ddl-logic.d.ts +9 -0
  75. package/dist/schema/generate-postgres-ddl.js +1 -1
  76. package/dist/schema/introspect-db.js +1 -1
  77. package/dist/schema/plan/types.d.ts +13 -0
  78. package/dist/schema/rls-bootstrap-sql.d.ts +6 -0
  79. package/dist/security/policy-drift.d.ts +13 -1
  80. package/dist/security/rls-enforcement.d.ts +31 -0
  81. package/dist/{websocket-BSYV_KSw.js → websocket-B7ex6AQM.js} +3 -3
  82. package/dist/{websocket-BSYV_KSw.js.map → websocket-B7ex6AQM.js.map} +1 -1
  83. package/package.json +7 -7
  84. package/dist/ensure-collection-policies-DJsOMpaI.js.map +0 -1
  85. package/dist/generate-postgres-ddl-logic-G9PvjHrr.js.map +0 -1
  86. package/dist/plan-schema-CMhNYEYF.js.map +0 -1
  87. package/dist/policy-drift-Bx6663KD.js.map +0 -1
  88. package/dist/render-ddl-Di-fTGti.js.map +0 -1
  89. package/dist/rls-bootstrap-sql-CxszeSc7.js.map +0 -1
  90. package/dist/rls-enforcement-CyUCPDH8.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"policy-drift-Bx6663KD.js","names":[],"sources":["../src/security/policy-drift.ts"],"sourcesContent":["/**\n * Compare the RLS policies a database actually has against the ones the\n * collections describe.\n *\n * Policies live in Postgres; the collection config is only their *source*.\n * Nothing reconciled the two, which is how the demo database served empty\n * collections indefinitely: its policies granted `TO authenticated` (a Supabase\n * role name) while requests run as `rebase_user`, so RLS filtered every row.\n * The config was later corrected and the database never noticed — an empty\n * table is indistinguishable from a table with no data.\n *\n * Expected policies are parsed from `generatePostgresPoliciesDdl`, the same\n * function `db push` uses to write `.rebase/sql/policies.sql`, so this compares\n * against exactly what would be applied rather than a reimplementation.\n */\nimport { RLS_UID_SQL, type CollectionConfig } from \"@rebasepro/types\";\nimport { toPostgresIdentifier } from \"@rebasepro/utils\";\n\nimport { generatePostgresPoliciesDdl, planCollectionPolicies } from \"../schema/generate-postgres-ddl-logic\";\n\nexport interface PolicyRef {\n schema: string;\n table: string;\n name: string;\n /** Roles in the TO clause. */\n roles: string[];\n /** SELECT / INSERT / UPDATE / DELETE / ALL. */\n command: string;\n /** Whether a USING clause is present at all (not what it says). */\n hasUsing: boolean;\n /** Whether a WITH CHECK clause is present at all (not what it says). */\n hasWithCheck: boolean;\n /**\n * PERMISSIVE or RESTRICTIVE — the `AS` clause.\n *\n * An exact catalogue value on both sides, so it belongs with roles and\n * command rather than with the expression text. It matters more than either:\n * permissive policies are ORed together and restrictive ones ANDed, so a rule\n * declared `mode: \"restrictive\"` whose live policy is PERMISSIVE has had its\n * gate turned from a requirement into an alternative — the maximally\n * permissive way for this to be wrong.\n *\n * The DDL regex captured this from the start and the destructuring threw it\n * away; `pg_policies.permissive` was never selected.\n */\n mode?: \"PERMISSIVE\" | \"RESTRICTIVE\";\n /**\n * The live clause text, when read from `pg_policies`. Present only for live\n * policies (the expected side is parsed from DDL and does not carry it).\n * Used solely for the insecure-tautology scan, not for divergence — Postgres\n * rewrites this text, so it is not safe to diff against expected.\n */\n qual?: string | null;\n withCheck?: string | null;\n}\n\nexport interface PolicyDrift {\n /** Described by the collections, absent from the database. */\n missing: PolicyRef[];\n /** In the database, described by no collection — stale pushes live here. */\n orphaned: PolicyRef[];\n /** Same policy name, different roles or command. */\n diverged: { expected: PolicyRef; actual: PolicyRef; differences: string[] }[];\n /**\n * A live policy whose expression is the known-permissive tautology\n * `rebase.uid() IS NOT NULL` — true for anonymous visitors too, because the\n * user path coerces a blank id to the `'anonymous'` sentinel. This is what\n * `policy.authenticated()` used to compile to, so a database pushed before\n * that fix carries it, and neither the name, roles, command nor clause\n * *presence* differs from the corrected policy — the only thing that changed\n * is the expression text, which this checker otherwise (correctly) ignores.\n * So it is the one drift that hides from every other check here.\n *\n * @see reason a sentence naming the clause and what to do.\n */\n insecure: { policy: PolicyRef; reason: string }[];\n /**\n * A table the collections describe whose RLS switch is off.\n *\n * `ALTER TABLE posts DISABLE ROW LEVEL SECURITY` leaves every row in\n * `pg_policies` untouched, so before this category every expected policy\n * still matched on name, roles, command and clause presence and the checker\n * reported clean — on a table Postgres was applying no filter to at all.\n * Requests run as `rebase_user`, which holds full DML, so the table is wide\n * open while `doctor` certifies it.\n *\n * `forced` reports `relforcerowsecurity`, which is what also subjects the\n * table's *owner* to its policies. Its absence is not drift on its own —\n * Rebase does not connect as the owner in the request path — so it is\n * reported for context rather than raised as a failure.\n */\n rlsDisabled: { schema: string; table: string; forced: boolean }[];\n}\n\nexport interface Queryable {\n query<R>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;\n}\n\n// The trailing group captures whichever clause follows the TO list, which is\n// what tells us the clause is present.\nconst CREATE_POLICY = /CREATE POLICY \"([^\"]+)\" ON \"([^\"]+)\"\\.\"([^\"]+)\"\\s+AS (\\w+)\\s+FOR (\\w+)\\s+TO ([^\\n]+?)(\\s+USING\\s*\\(|\\s+WITH CHECK\\s*\\(|;)/gi;\n\nconst WITH_CHECK_NEXT = /^\\s+WITH CHECK\\s*\\(/i;\n\n/**\n * Index just past the `)` closing a clause whose `(` ends at `open`.\n *\n * Needed because a policy expression nests parens and can contain a quoted\n * literal holding either character, so \"find the next `)`\" would stop early and\n * miss the `WITH CHECK` that follows.\n */\nfunction clauseEnd(ddl: string, open: number): number {\n let depth = 1;\n let inQuote = false;\n for (let i = open; i < ddl.length; i++) {\n const c = ddl[i];\n if (inQuote) {\n // '' is an escaped quote inside a string, not a close.\n if (c === \"'\") {\n if (ddl[i + 1] === \"'\") i++;\n else inQuote = false;\n }\n continue;\n }\n if (c === \"'\") inQuote = true;\n else if (c === \"(\") depth++;\n else if (c === \")\" && --depth === 0) return i + 1;\n }\n return ddl.length;\n}\n\n/**\n * `AS PERMISSIVE` / `AS RESTRICTIVE` from either side, or undefined.\n *\n * The DDL spells it as a bare word; `pg_policies.permissive` is the string\n * `\"PERMISSIVE\"`/`\"RESTRICTIVE\"` on modern Postgres but a boolean on some\n * drivers and older servers, so both are accepted. Anything unrecognised\n * becomes `undefined` and the comparison below skips it rather than inventing\n * drift from a shape we did not anticipate.\n */\nfunction normalizeMode(raw: unknown): \"PERMISSIVE\" | \"RESTRICTIVE\" | undefined {\n if (typeof raw === \"boolean\") return raw ? \"PERMISSIVE\" : \"RESTRICTIVE\";\n if (typeof raw !== \"string\") return undefined;\n const upper = raw.trim().toUpperCase();\n if (upper === \"PERMISSIVE\" || upper === \"TRUE\" || upper === \"T\") return \"PERMISSIVE\";\n if (upper === \"RESTRICTIVE\" || upper === \"FALSE\" || upper === \"F\") return \"RESTRICTIVE\";\n return undefined;\n}\n\n/**\n * Parse the generated DDL rather than rebuilding the shape by hand.\n *\n * Each name is the one Postgres stores — its first 63 bytes — because that is\n * the name every live policy is compared under. A rule's name can be longer,\n * and read as written its policy was both \"missing\" and, once cut to a name of\n * the generated shape, an \"orphan\" the push's reconcile dropped right after\n * `policies.sql` created it.\n */\nexport function parseExpectedPolicies(ddl: string): PolicyRef[] {\n const found: PolicyRef[] = [];\n for (const m of ddl.matchAll(CREATE_POLICY)) {\n const [, name, schema, table, modeRaw, command, rolesRaw, clause] = m;\n const roles = rolesRaw\n .split(\",\")\n .map((r) => r.trim().replace(/^\"|\"$/g, \"\"))\n .filter(Boolean);\n\n // The generator emits USING before WITH CHECK, so what follows the TO\n // list settles USING; WITH CHECK is then whatever follows that clause.\n const hasUsing = /USING/i.test(clause);\n const hasWithCheck = hasUsing\n ? WITH_CHECK_NEXT.test(ddl.slice(clauseEnd(ddl, m.index + m[0].length)))\n : /WITH CHECK/i.test(clause);\n\n found.push({\n schema, table, name: toPostgresIdentifier(name), roles,\n command: command.toUpperCase(),\n hasUsing, hasWithCheck,\n mode: normalizeMode(modeRaw)\n });\n }\n return found;\n}\n\nasync function readLivePolicies(client: Queryable, schemas: string[]): Promise<PolicyRef[]> {\n const { rows } = await client.query<{\n schemaname: string; tablename: string; policyname: string; roles: string[] | string; cmd: string;\n qual: string | null; with_check: string | null; permissive: string | boolean | null;\n }>(\n `SELECT schemaname, tablename, policyname, roles, cmd, qual, with_check, permissive\n FROM pg_policies\n WHERE schemaname = ANY($1)`,\n [schemas]\n );\n\n return rows.map((r) => ({\n schema: r.schemaname,\n table: r.tablename,\n name: r.policyname,\n // node-postgres yields text[] as an array; some drivers hand back \"{a,b}\".\n roles: Array.isArray(r.roles)\n ? r.roles\n : String(r.roles ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean),\n command: (r.cmd ?? \"ALL\").toUpperCase(),\n // Presence only. Postgres rewrites the text, but it does not invent or\n // drop a clause: NULL here means the policy genuinely has none.\n hasUsing: r.qual != null,\n hasWithCheck: r.with_check != null,\n mode: normalizeMode(r.permissive),\n qual: r.qual,\n withCheck: r.with_check\n }));\n}\n\n/**\n * Tables the collections describe whose RLS switch is off.\n *\n * Read from `pg_class` because `pg_policies` cannot answer it: disabling RLS\n * leaves the policy rows in place, so every other comparison in this file keeps\n * matching while Postgres applies none of them.\n *\n * Only tables that expect at least one policy are considered. A table with no\n * declared rules is not asserting anything about RLS, and reporting it would\n * make the check noisy on exactly the projects least able to judge the noise.\n */\nasync function readTablesWithRlsOff(\n client: Queryable,\n tables: { schema: string; table: string }[]\n): Promise<{ schema: string; table: string; forced: boolean }[]> {\n if (tables.length === 0) return [];\n const { rows } = await client.query<{\n schemaname: string; tablename: string; relrowsecurity: boolean; relforcerowsecurity: boolean;\n }>(\n `SELECT n.nspname AS schemaname,\n c.relname AS tablename,\n c.relrowsecurity,\n c.relforcerowsecurity\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind = 'r'\n AND (n.nspname || '.' || c.relname) = ANY($1)`,\n [tables.map((t) => `${t.schema}.${t.table}`)]\n );\n\n return rows\n .filter((r) => !r.relrowsecurity)\n .map((r) => ({\n schema: r.schemaname,\n table: r.tablename,\n forced: !!r.relforcerowsecurity\n }));\n}\n\n/**\n * The permissive tautology `rebase.uid() IS NOT NULL`, without the\n * `<> 'anonymous'` guard that makes it mean \"signed in\".\n *\n * Whitespace varies with Postgres's rewrite, so match on a collapsed form. The\n * guard clause ({@link EXCLUDES_ANONYMOUS}, in any spelling) is what\n * distinguishes the corrected policy from the stale one, so its presence\n * clears the text.\n *\n * Both schema spellings are matched. The helpers moved from `auth` to `rebase`\n * in 1.0, and this check reads policies *as the database stored them*: a\n * database pushed before the move still holds `auth.uid()` until it is\n * recompiled, while everything written since — including raw `securityRules`\n * SQL, which the compiler rewrites on the way in — stores `rebase.uid()`.\n * Matching only the pre-1.0 name made the check blind to every policy a current\n * release could write, which is precisely the set still worth scanning.\n */\nfunction isPermissiveAuthTautology(clause: string | null | undefined): boolean {\n if (!clause) return false;\n const flat = clause.toLowerCase().replace(/\\s+/g, \" \");\n // The call bare, or wrapped as an initPlan, which Postgres stores as\n // `( SELECT rebase.uid() AS uid)`.\n if (!/\\b(?:rebase|auth)\\.uid\\s*\\(\\s*\\)(?:\\s+as\\s+\\w+\\s*\\))?\\s*is not null/.test(flat)) return false;\n return !EXCLUDES_ANONYMOUS.some((guard) => guard.test(flat));\n}\n\n/**\n * The guard that makes the null test mean \"signed in\": the anonymous\n * sentinel excluded, in every spelling a policy reaches the catalogue in.\n *\n * `policy.authenticated()` compiles to `NOT IN ('anonymous', 'anon')`, which\n * Postgres stores as `<> ALL (ARRAY['anonymous'::text, 'anon'::text])`. Only\n * `<> 'anonymous'` was recognised, so `doctor` and every `db push` called each\n * `authenticated()` and `registered()` policy the insecure tautology. A list\n * that leaves out `'anonymous'` excludes nobody a signed-out request arrives\n * as, and does not clear it.\n */\nconst EXCLUDES_ANONYMOUS: RegExp[] = [\n /(?:<>|!=)\\s*'anonymous'/,\n /(?:<>|!=)\\s*all\\s*\\(\\s*array\\s*\\[[^\\]]*'anonymous'/,\n /\\bnot in\\s*\\([^)]*'anonymous'/\n];\n\nconst keyOf = (p: PolicyRef) => `${p.schema}.${p.table}.${p.name}`;\n\n/**\n * Where the server-or-admin policies are expected: `TO rebase_admin` (`true`),\n * `TO public` (`false`), or `\"detect\"` — read off the database as a boot on\n * this connection would decide it (`adminPoliciesLiveForCli`). A boot whose\n * admin switch is not live writes them `TO public`, and that is not drift.\n */\nexport type AdminPoliciesExpectation = boolean | \"detect\";\n\n/** {@link AdminPoliciesExpectation} as a yes or no. Left out, `TO rebase_admin`, as compiled. */\nexport async function resolveAdminPolicies(client: Queryable, expectation: AdminPoliciesExpectation | undefined): Promise<boolean> {\n if (expectation !== \"detect\") return expectation !== false;\n const { adminPoliciesLiveForCli } = await import(\"./rls-enforcement\");\n return adminPoliciesLiveForCli(async (text) => (await client.query<Record<string, unknown>>(text)).rows);\n}\n\n/**\n * The policies the collections declare, parsed from the DDL `db push` writes —\n * with the ones the compiler put `TO rebase_admin` read as `TO public` where\n * `adminRoleAvailable` is false, as the boot and the push then write them. A\n * rule that names `rebase_admin` itself keeps it.\n */\nexport function expectedPolicies(collections: CollectionConfig[], adminRoleAvailable: boolean): PolicyRef[] {\n const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(collections));\n if (adminRoleAvailable) return expected;\n const moved = new Set(planCollectionPolicies(collections).flatMap(plan =>\n plan.policies.filter(policy => policy.adminTarget).map(policy => `${plan.schema}.${plan.table}.${policy.name}`)));\n return expected.map(p => moved.has(keyOf(p)) ? { ...p, roles: [\"public\"] } : p);\n}\nconst sameRoles = (a: string[], b: string[]) =>\n a.length === b.length && [...a].sort().join(\",\") === [...b].sort().join(\",\");\n\n/**\n * Diff expected against live.\n *\n * Compares names, roles, command, and whether each clause exists — all exact\n * values. Policy expression *text* is deliberately not compared: Postgres\n * rewrites `qual`/`with_check` when storing them (parenthesising, casting,\n * schema-qualifying), so text comparison reports drift that does not exist, and\n * a check that cries wolf gets ignored.\n *\n * Presence is not text, though. A NULL `qual` is not a rewrite of an\n * expression, it is the absence of one, and absence has no false-positive risk:\n * either the generator emitted a clause or it did not. That distinction is worth\n * the extra comparison — a production database was found with a SELECT policy\n * whose `qual` was NULL, matching on every field this checked and denying 100%\n * of reads. The same blindness would hide a policy that fails open.\n */\nexport async function checkPolicyDrift(\n client: Queryable,\n collections: CollectionConfig[],\n options: { adminRoleAvailable?: AdminPoliciesExpectation } = {}\n): Promise<PolicyDrift> {\n const expected = expectedPolicies(collections, await resolveAdminPolicies(client, options.adminRoleAvailable));\n const schemas = [...new Set(expected.map((p) => p.schema))];\n // Nothing expected means nothing to reconcile against; scanning every\n // schema would report the whole database as orphaned.\n if (schemas.length === 0) return { missing: [], orphaned: [], diverged: [], insecure: [], rlsDisabled: [] };\n\n const live = await readLivePolicies(client, schemas);\n const liveByKey = new Map(live.map((p) => [keyOf(p), p]));\n const expectedByKey = new Map(expected.map((p) => [keyOf(p), p]));\n\n const drift: PolicyDrift = { missing: [], orphaned: [], diverged: [], insecure: [], rlsDisabled: [] };\n\n // Before comparing policy against policy: is the switch even on? A table\n // with RLS disabled matches every expected policy on every field compared\n // below, so this has to be asked separately or it cannot be asked at all.\n const expectedTables = [...new Map(\n expected.map((p) => [`${p.schema}.${p.table}`, { schema: p.schema, table: p.table }])\n ).values()];\n drift.rlsDisabled = await readTablesWithRlsOff(client, expectedTables);\n\n // Scan every live policy for the permissive tautology. This is deliberately\n // independent of the name-keyed diff below: a database pushed before the\n // `authenticated()` fix matches its expected policy on name, roles, command\n // and clause presence, so nothing else here would flag it.\n for (const p of live) {\n const clause = isPermissiveAuthTautology(p.qual)\n ? \"USING\"\n : isPermissiveAuthTautology(p.withCheck) ? \"WITH CHECK\" : null;\n if (clause) {\n drift.insecure.push({\n policy: p,\n reason: `${clause} is \\`${RLS_UID_SQL} IS NOT NULL\\`, which is true for anonymous ` +\n `visitors too — this grants access to signed-out requests. It predates the ` +\n `\\`policy.authenticated()\\` fix; re-run \\`rebase db push\\` to tighten it.`\n });\n }\n }\n\n for (const [key, want] of expectedByKey) {\n const got = liveByKey.get(key);\n if (!got) {\n drift.missing.push(want);\n continue;\n }\n const differences: string[] = [];\n if (!sameRoles(want.roles, got.roles)) {\n differences.push(`roles: expected [${want.roles.join(\", \")}], database has [${got.roles.join(\", \")}]`);\n }\n if (want.command !== got.command) {\n differences.push(`command: expected ${want.command}, database has ${got.command}`);\n }\n // Skipped when either side is unknown: an unrecognised catalogue shape\n // should not manufacture drift. See `normalizeMode`.\n if (want.mode && got.mode && want.mode !== got.mode) {\n differences.push(\n `mode: expected ${want.mode}, database has ${got.mode}` +\n (got.mode === \"PERMISSIVE\"\n ? \" — a RESTRICTIVE rule is ANDed with the others, a PERMISSIVE one is ORed, so this policy now widens access instead of narrowing it\"\n : \" — a PERMISSIVE rule is ORed with the others, a RESTRICTIVE one is ANDed, so this policy now narrows access instead of widening it\")\n );\n }\n for (const clause of [\"USING\", \"WITH CHECK\"] as const) {\n const key = clause === \"USING\" ? \"hasUsing\" : \"hasWithCheck\";\n if (want[key] === got[key]) continue;\n differences.push(want[key]\n ? `${clause}: expected an expression, database has none — this policy matches no rows`\n : `${clause}: expected none, database has an expression`);\n }\n if (differences.length > 0) drift.diverged.push({ expected: want, actual: got, differences });\n }\n\n for (const [key, got] of liveByKey) {\n if (!expectedByKey.has(key)) drift.orphaned.push(got);\n }\n\n return drift;\n}\n\n/**\n * Does this name look like one the generator produced for this table?\n *\n * Unnamed rules compile to `<table>_<op>_<sha1[0:7]>` (plus `_<idx>` when one\n * rule spans several operations), and the hash covers the rule's semantics — so\n * *editing* a rule renames its policy. The policy under the old name is left\n * behind by `db push`, which only DROPs the names it is about to CREATE, and\n * Postgres ORs PERMISSIVE policies together: a superseded `USING (true)` keeps\n * granting everything no matter how tight its replacement is.\n *\n * Matching the shape is what makes dropping them safe. A hand-written policy\n * would have to collide with a 7-hex digest to be mistaken for generated one;\n * a policy named anything else is left alone and merely reported, because a\n * custom name is indistinguishable from one someone wrote in SQL on purpose.\n */\nexport function isGeneratedPolicyName(name: string, table: string): boolean {\n return new RegExp(`^${table.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}_(select|insert|update|delete|all)_[0-9a-f]{7}(_\\\\d+)?$`)\n .test(name);\n}\n\nexport interface OrphanCleanup {\n /** Superseded generated policies that were dropped. */\n dropped: PolicyRef[];\n /** Orphans left in place because their names are not generator-shaped. */\n kept: PolicyRef[];\n}\n\n/**\n * Drop the policies an earlier push superseded but never removed.\n *\n * Only touches tables the collections describe — a table with no expected\n * policy is not ours to reconcile, and scanning by schema alone would sweep up\n * policies belonging to something else sharing the database.\n */\nexport async function dropOrphanedPolicies(\n client: Queryable,\n drift: PolicyDrift,\n collections: CollectionConfig[]\n): Promise<OrphanCleanup> {\n const { dropped, kept } = partitionOrphans(drift, collections);\n for (const p of dropped) {\n // Identifiers are quoted, and the name came from pg_policies rather than\n // from user input, so it is already a valid identifier.\n await client.query(`DROP POLICY IF EXISTS \"${p.name}\" ON \"${p.schema}\".\"${p.table}\"`);\n }\n return { dropped, kept };\n}\n\n/**\n * Which orphans {@link dropOrphanedPolicies} drops and which it keeps, decided\n * without dropping anything: what `db push --dry-run` lists.\n */\nexport function partitionOrphans(drift: PolicyDrift, collections: CollectionConfig[]): OrphanCleanup {\n const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(collections));\n const managed = new Set(expected.map((p) => `${p.schema}.${p.table}`));\n\n const cleanup: OrphanCleanup = { dropped: [], kept: [] };\n for (const p of drift.orphaned) {\n if (managed.has(`${p.schema}.${p.table}`) && isGeneratedPolicyName(p.name, p.table)) cleanup.dropped.push(p);\n else cleanup.kept.push(p);\n }\n return cleanup;\n}\n\nexport const hasDrift = (d: PolicyDrift): boolean =>\n d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0 || d.insecure.length > 0\n || d.rlsDisabled.length > 0;\n\n/** Human-readable report; empty string when the database matches the config. */\nexport function formatPolicyDrift(drift: PolicyDrift): string {\n if (!hasDrift(drift)) return \"\";\n const lines: string[] = [];\n\n // First, because it subsumes every other finding on the same table: if RLS\n // is off, the policies listed below are not being applied at all.\n if (drift.rlsDisabled.length > 0) {\n lines.push(\" RLS DISABLED — the table has policies, and Postgres is applying none of them:\");\n for (const t of drift.rlsDisabled) {\n lines.push(` • ${t.schema}.${t.table}${t.forced ? \"\" : \" (and FORCE is off)\"}`);\n }\n lines.push(\" Every row is readable and writable by any request that reaches the table.\");\n lines.push(` Fix: ALTER TABLE \"<schema>\".\"<table>\" ENABLE ROW LEVEL SECURITY; or re-run \\`rebase db push\\`.`);\n }\n if (drift.missing.length > 0) {\n lines.push(\" Missing — described by your collections, absent from the database:\");\n for (const p of drift.missing) lines.push(` • ${p.schema}.${p.table} → \"${p.name}\" (${p.command} TO ${p.roles.join(\", \")})`);\n lines.push(\" Run `rebase db push` to apply them.\");\n }\n if (drift.orphaned.length > 0) {\n // Two different things share this list, and they want opposite\n // advice. A name of the shape an unnamed rule compiles to is a rule\n // edited since: the next push drops it. Any other name was written by\n // hand or by another tool, and may be the table's whole access model —\n // \"left behind by an earlier push\" was false of it, and telling its\n // author to drop it would take that access away.\n const superseded = drift.orphaned.filter((p) => isGeneratedPolicyName(p.name, p.table));\n const unowned = drift.orphaned.filter((p) => !isGeneratedPolicyName(p.name, p.table));\n lines.push(\" Orphaned — in the database, described by no collection:\");\n for (const p of drift.orphaned) lines.push(` • ${p.schema}.${p.table} → \"${p.name}\" (${p.command} TO ${p.roles.join(\", \")})`);\n if (superseded.length > 0) {\n lines.push(` ${superseded.map((p) => `\"${p.name}\"`).join(\", \")}: left behind by an earlier push, when its rule changed. The next \\`rebase db push\\` drops it.`);\n }\n if (unowned.length > 0) {\n lines.push(` ${unowned.map((p) => `\"${p.name}\"`).join(\", \")}: written by hand or by another tool, and still in force.`);\n lines.push(\" To keep one, describe it in its collection's `securityRules` (Studio's RLS view imports it);\");\n lines.push(\" if it is stale, drop it by hand.\");\n }\n }\n if (drift.diverged.length > 0) {\n lines.push(\" Diverged — same policy, different definition:\");\n for (const d of drift.diverged) {\n lines.push(` • ${d.expected.schema}.${d.expected.table} → \"${d.expected.name}\"`);\n for (const diff of d.differences) lines.push(` ${diff}`);\n }\n }\n if (drift.insecure.length > 0) {\n lines.push(\" Insecure — a live policy grants access it should not:\");\n for (const i of drift.insecure) {\n lines.push(` • ${i.policy.schema}.${i.policy.table} → \"${i.policy.name}\"`);\n lines.push(` ${i.reason}`);\n }\n }\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoGA,IAAM,gBAAgB;AAEtB,IAAM,kBAAkB;;;;;;;;AASxB,SAAS,UAAU,KAAa,MAAsB;CAClD,IAAI,QAAQ;CACZ,IAAI,UAAU;CACd,KAAK,IAAI,IAAI,MAAM,IAAI,IAAI,QAAQ,KAAK;EACpC,MAAM,IAAI,IAAI;EACd,IAAI,SAAS;GAET,IAAI,MAAM,KACN,IAAI,IAAI,IAAI,OAAO,KAAK;QACn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AS,GACpB,MAAM,KAAK,OAAO,WAAW,KAAK,MAAM,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,+FAA+F;EAErK,IAAI,QAAQ,SAAS,GAAG;GACpB,MAAM,KAAK,OAAO,QAAQ,KAAK,MAAM,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,0DAA0D;GACzH,MAAM,KAAK,kGAAkG;GAC7G,MAAM,KAAK,sCAAsC;EACrD;CACJ;CACA,IAAI,MAAM,SAAS,SAAS,GAAG;EAC3B,MAAM,KAAK,iDAAiD;EAC5D,KAAK,MAAM,KAAK,MAAM,UAAU;GAC5B,MAAM,KAAK,SAAS,EAAE,SAAS,OAAO,GAAG,EAAE,SAAS,MAAM,MAAM,EAAE,SAAS,KAAK,EAAE;GAClF,KAAK,MAAM,QAAQ,EAAE,aAAa,MAAM,KAAK,WAAW,MAAM;EAClE;CACJ;CACA,IAAI,MAAM,SAAS,SAAS,GAAG;EAC3B,MAAM,KAAK,yDAAyD;EACpE,KAAK,MAAM,KAAK,MAAM,UAAU;GAC5B,MAAM,KAAK,SAAS,EAAE,OAAO,OAAO,GAAG,EAAE,OAAO,MAAM,MAAM,EAAE,OAAO,KAAK,EAAE;GAC5E,MAAM,KAAK,WAAW,EAAE,QAAQ;EACpC;CACJ;CACA,OAAO,MAAM,KAAK,IAAI;AAC1B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"render-ddl-Di-fTGti.js","names":[],"sources":["../src/schema/plan/render-ddl.ts"],"sourcesContent":["/**\n * The SQL files, rendered from a {@link SchemaPlan}.\n *\n * Four files, because Atlas owns exactly one of them:\n *\n * - `schema.sql` — the desired state Atlas diffs the database against.\n * - `policies.sql` — the RLS policies. Atlas has no model for a policy.\n * - `search.sql` — the generated `tsvector` column, its GIN index and the\n * IMMUTABLE helpers its expression calls. Atlas's free tier refuses to\n * *parse* a file containing a function, and it wipes the dev database it\n * diffs against, so a helper seeded there is gone by the time the plan runs.\n * - `vector.sql` — the `vector` columns and their ANN indexes. Atlas cannot\n * *execute* these: it materialises `schema.sql` in a dev database that is\n * created empty and emptied again on every run, so `VECTOR(384)` resolves\n * against a database that structurally cannot have pgvector.\n * - `triggers.sql` — `autoValue: \"on_update\"`, which is a function plus a\n * binding, so it is out for the same reason search is.\n *\n * Everything not in `schema.sql` is excluded from Atlas's view by pattern\n * (`…ExcludePatterns` below) and applied by Rebase — at push time by the CLI,\n * at boot by the schema ensure. Without the excludes a desired state that omits\n * an object reads to Atlas as an instruction to drop it.\n */\nimport { REBASE_ADMIN_ROLE } from \"@rebasepro/types\";\nimport { ADMIN_POLICY_ROLE_SQL } from \"../rls-bootstrap-sql\";\nimport {\n fuzzyColumnDefinition,\n searchColumnDefinition,\n searchColumnStamps,\n searchExtensionStatements,\n searchHelperFunctions,\n searchIndexNames,\n searchIndexStatements,\n searchStampGuards\n} from \"../search-column\";\nimport {\n VECTOR_EXTENSION_OPT_IN,\n vectorColumnDefinition,\n vectorDimensionGuard,\n vectorExtensionDeclared,\n vectorExtensionStatement,\n vectorIndexNames,\n vectorIndexStatements\n} from \"../vector-index\";\nimport { atlasExcludePattern } from \"../atlas-exclude\";\nimport { collectionIndexStatements } from \"../collection-index\";\nimport { quoteSqlLiteral } from \"./plan-schema\";\nimport { triggerStatements } from \"./updated-at-trigger\";\nimport { VIEW_ROWS_COMMENT_PREFIX, viewRowsName } from \"./view-names\";\nimport { REBASE_USER_ROLE } from \"@rebasepro/common\";\nimport type { ColumnPlan, PgType, PolicyPlan, SchemaPlan, TablePlan, ViewPlan } from \"./types\";\n\n/** What `schema.sql` may leave out, because another file owns it. */\nexport interface DdlRenderOptions {\n /** RLS policies. `false` puts them in `policies.sql` alone. */\n includePolicies?: boolean;\n /** The search column, its helpers and its index. See `search.sql`. */\n includeSearch?: boolean;\n /** The vector columns and their ANN indexes. See `vector.sql`. */\n includeVector?: boolean;\n}\n\n/**\n * A {@link PgType} as Postgres spells it.\n *\n * The one place. `getSqlColumnType` and `getDrizzleColumn` each carried their\n * own ladder and disagreed about `VARCHAR` widths, about `geopoint`, and about\n * whether an `increment` id honours `columnType`.\n */\nexport const renderPgType = (type: PgType): string => {\n switch (type.kind) {\n case \"text\": return \"TEXT\";\n case \"varchar\": return `VARCHAR(${type.length})`;\n case \"char\": return `CHAR(${type.length})`;\n case \"uuid\": return \"UUID\";\n case \"enum\": return `\"${type.schema}\".\"${type.name}\"`;\n case \"smallint\": return \"SMALLINT\";\n case \"integer\": return \"INTEGER\";\n case \"bigint\": return \"BIGINT\";\n case \"smallserial\": return \"SMALLSERIAL\";\n case \"serial\": return \"SERIAL\";\n case \"bigserial\": return \"BIGSERIAL\";\n case \"real\": return \"REAL\";\n case \"doublePrecision\": return \"DOUBLE PRECISION\";\n case \"numeric\":\n if (type.precision === undefined) return \"NUMERIC\";\n return type.scale === undefined\n ? `NUMERIC(${type.precision})`\n : `NUMERIC(${type.precision}, ${type.scale})`;\n case \"boolean\": return \"BOOLEAN\";\n case \"timestamptz\": return \"TIMESTAMP WITH TIME ZONE\";\n case \"date\": return \"DATE\";\n case \"time\": return \"TIME\";\n case \"json\": return \"JSON\";\n case \"jsonb\": return \"JSONB\";\n case \"vector\": return `VECTOR(${type.dimensions})`;\n case \"bytea\": return \"BYTEA\";\n case \"tsvector\": return \"tsvector\";\n case \"array\": return `${renderPgType(type.of)}[]`;\n }\n};\n\n/**\n * Everything after the column name, in one order for every SQL emitter.\n *\n * `CREATE TABLE` and `ADD COLUMN` used to assemble this separately, which is\n * how a required relation column came out `NOT NULL` after `db push` and\n * nullable after a boot-ensure. `identity` is part of the type rather than a\n * DEFAULT, which is why it is rendered here and not in the DEFAULT slot.\n */\nexport const renderColumnDefinition = (column: ColumnPlan): string => {\n // `auth-users-columns` is the single description of what an auth user\n // table's columns must be, and it hands over a rendered definition.\n if (column.sqlDefinition) return column.sqlDefinition;\n\n if (column.generated) {\n return `${renderPgType(column.type)} GENERATED ALWAYS AS (${column.generated.expression}) STORED`;\n }\n\n let definition = renderPgType(column.type);\n if (column.default?.kind === \"identity\") definition += \" GENERATED BY DEFAULT AS IDENTITY\";\n if (column.primaryKey) definition += \" PRIMARY KEY\";\n if (column.unique) definition += \" UNIQUE\";\n if (column.default && column.default.kind !== \"identity\") {\n definition += ` DEFAULT ${column.default.kind === \"sql\" ? column.default.expression : column.default.sql}`;\n }\n if (!column.nullable && !column.primaryKey) definition += \" NOT NULL\";\n return definition;\n};\n\n/**\n * `PRIMARY KEY (\"a\", \"b\")`, the clause a composite key takes inside a\n * `CREATE TABLE`. Shared by `schema.sql` and boot-ensure's `CREATE TABLE`, so\n * the two cannot list the columns differently.\n */\nexport const renderPrimaryKeyConstraint = (table: Pick<TablePlan, \"primaryKey\">): string =>\n `PRIMARY KEY (${table.primaryKey.map(c => `\"${c}\"`).join(\", \")})`;\n\n/** `\"col\" TYPE …`, as it appears inside a `CREATE TABLE`. */\nconst renderColumn = (column: ColumnPlan): string =>\n `\"${column.column}\" ${renderColumnDefinition(column)}`;\n\n// ── Policies ─────────────────────────────────────────────────────────────────\n\n/**\n * One policy as its `DROP` / `CREATE` pair — each a complete statement.\n *\n * This is the primitive the boot-time RLS applier runs one statement at a time\n * (the runtime's DB handle speaks the extended query protocol, which forbids\n * multiple commands in one execute), while `db push` writes the joined string.\n */\nexport const renderPolicyStatements = (\n table: Pick<TablePlan, \"schema\" | \"table\">,\n policy: PolicyPlan\n): string[] => {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n let create = `CREATE POLICY \"${policy.name}\" ON ${target} AS ${policy.mode.toUpperCase()} ` +\n `FOR ${policy.operation.toUpperCase()} TO ${policy.roles.map(r => `\"${r}\"`).join(\", \")}`;\n if (policy.using) create += ` USING (${policy.using})`;\n if (policy.withCheck) create += ` WITH CHECK (${policy.withCheck})`;\n // The one policy an older naming stored this rule's operations under —\n // see `PolicyPlan.supersedes`. In the same per-table transaction, so a\n // request sees the old policy or the new ones, never neither.\n const superseded = (policy.supersedes ?? []).map(name => `DROP POLICY IF EXISTS \"${name}\" ON ${target};`);\n return [...superseded, `DROP POLICY IF EXISTS \"${policy.name}\" ON ${target};`, `${create};`];\n};\n\n/**\n * A restrictive policy, under its own name, command and roles, that passes no\n * row: `USING (false)` / `WITH CHECK (false)` for the clauses its command takes.\n *\n * What the boot applier puts in place of a restrictive policy whose own\n * `CREATE` failed. A restrictive policy is a gate ANDed over every permissive\n * one, so its absence does not deny — it opens whatever the permissive policies\n * grant. Standing in for it with a gate nothing passes keeps the failure on\n * the denying side until the rule can be created.\n */\nexport const renderDenyingPolicyStatements = (\n table: Pick<TablePlan, \"schema\" | \"table\">,\n policy: PolicyPlan\n): string[] => {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n let create = `CREATE POLICY \"${policy.name}\" ON ${target} AS RESTRICTIVE ` +\n `FOR ${policy.operation.toUpperCase()} TO ${policy.roles.map(r => `\"${r}\"`).join(\", \")}`;\n if (policy.operation !== \"insert\") create += \" USING (false)\";\n if (policy.operation !== \"select\" && policy.operation !== \"delete\") create += \" WITH CHECK (false)\";\n return [`DROP POLICY IF EXISTS \"${policy.name}\" ON ${target};`, `${create};`];\n};\n\n/** `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` — every generated table is locked. */\nexport const renderEnableRls = (table: Pick<TablePlan, \"schema\" | \"table\">): string =>\n `ALTER TABLE \"${table.schema}\".\"${table.table}\" ENABLE ROW LEVEL SECURITY;`;\n\nconst statementsToDdl = (statements: string[]): string => statements.map(s => `${s}\\n`).join(\"\");\n\n// ── schema.sql ───────────────────────────────────────────────────────────────\n\nexport function renderPostgresDdl(plan: SchemaPlan, options: DdlRenderOptions = {}): string {\n const includePolicies = options.includePolicies !== false;\n const includeSearch = options.includeSearch !== false;\n const includeVector = options.includeVector !== false;\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\\n\";\n\n // 1. Custom schemas.\n //\n // `rebase` is unconditional and load-bearing. The RLS helper functions live\n // in it, so the migration preamble creates it — which puts it in Atlas's\n // replayed state, and anything in that state but absent from this desired\n // schema gets a `DROP SCHEMA … CASCADE` planned against it. That would take\n // the auth tables.\n plan.schemas.forEach(schema => { ddl += `CREATE SCHEMA IF NOT EXISTS \"${schema}\";\\n`; });\n if (plan.schemas.length > 0) ddl += \"\\n\";\n\n // 1b. Search support, for collections that opted in.\n //\n // Extensions and helper functions come before every CREATE TABLE because a\n // generated column's expression is resolved at creation time: a table whose\n // search column calls `rebase_search_text` cannot be created before that\n // function exists. Both are `IF NOT EXISTS` / `OR REPLACE`, so a file\n // replayed against a live database is a no-op here.\n const searchTables = plan.tables.filter(t => t.search);\n if (searchTables.length > 0) {\n if (!includeSearch) {\n ddl += \"-- Full-text search support lives in `search.sql`, applied separately.\\n\\n\";\n } else {\n const extensions = Array.from(new Set(searchTables.flatMap(t => searchExtensionStatements(t.search!))));\n const helpers = Array.from(new Set(searchTables.flatMap(t => searchHelperFunctions(t.search!))));\n ddl += \"-- Full-text search support (collections declaring a `search` block)\\n\";\n extensions.forEach(s => { ddl += `${s}\\n`; });\n if (extensions.length > 0) ddl += \"\\n\";\n helpers.forEach(s => { ddl += `${s}\\n\\n`; });\n }\n }\n\n // 1c. Vector support. Only ever a note, never a statement — unlike 1b.\n // `CREATE EXTENSION vector` is the one thing this file must never carry\n // whichever way the flag goes: Atlas rejects an extension in a desired\n // state as a paid feature.\n if (!includeVector && plan.tables.some(t => t.vectorColumns.length > 0)) {\n ddl += \"-- Vector columns and their ANN indexes live in `vector.sql`, applied separately.\\n\\n\";\n }\n\n // 1d. `autoValue: \"on_update\"`. A trigger is a function plus a binding, so\n // it is out of Atlas's sight for the reason search is — and out\n // unconditionally, because `schema.sql` has no flag that would make Atlas\n // able to read one.\n if (plan.tables.some(t => t.triggers.length > 0)) {\n ddl += \"-- `autoValue: \\\"on_update\\\"` triggers live in `triggers.sql`, applied separately.\\n\\n\";\n }\n\n // 2. Enum types.\n plan.enums.forEach(enumPlan => {\n ddl += `CREATE TYPE \"${enumPlan.schema}\".\"${enumPlan.name}\" AS ENUM (${enumPlan.labels.map(quoteSqlLiteral).join(\", \")});\\n`;\n });\n if (ddl.endsWith(\";\\n\")) ddl += \"\\n\";\n\n // 3. Tables, in the plan's order — each collection, then any junction its\n // relations imply.\n const fkStatements: string[] = [];\n // Indexes follow the tables for the same reason the FK constraints do: the\n // table has to exist first.\n const indexStatements: string[] = [];\n // Policies are emitted after every CREATE TABLE, like the FK constraints: a\n // policy may reference other tables (a junction's derived policies always\n // reference both endpoints; `policy.existsIn` references a join table), and\n // CREATE POLICY validates those relations at creation time.\n const policyStatements: string[] = [];\n\n for (const table of plan.tables) {\n const emitted = table.columns.filter(column => {\n // A vector column is not Atlas's — `vector.sql` adds it. Filtered\n // here rather than upstream so the column keeps its place in the\n // generator's order when it *is* included, which is what the\n // derived-names contract renders.\n if (!includeVector && column.type.kind === \"vector\") return false;\n if (!includeSearch && column.source.kind === \"search\") return false;\n // A declared property already emits this column (an explicit\n // `postId` beside the `belongsTo` that uses it); the relation\n // contributes only the constraint.\n if (column.columnOwnedByProperty) return false;\n return true;\n });\n\n ddl += `CREATE TABLE \"${table.schema}\".\"${table.table}\" (\\n`;\n const lines = emitted.map(column => ` ${renderColumn(column)}`);\n // A key over several columns — a junction's two endpoints, or a\n // collection with several `isId` properties — is one table constraint;\n // a single-column key is already inline on its column.\n if (table.primaryKey.length > 1) {\n lines.push(` ${renderPrimaryKeyConstraint(table)}`);\n }\n ddl += lines.join(\",\\n\");\n ddl += \"\\n);\\n\\n\";\n\n for (const column of table.columns) {\n if (column.foreignKey) fkStatements.push(`${column.foreignKey.sql};`);\n }\n\n if (includeSearch && table.search) {\n indexStatements.push(...searchIndexStatements(table.search));\n }\n // ANN indexes are emitted with the other indexes rather than inline,\n // because `CREATE INDEX` is a statement and a column definition is not\n // — and because a column too wide for pgvector to index still needs its\n // column. Absent alongside their column when vector is carved out.\n if (includeVector && table.vector) {\n indexStatements.push(...vectorIndexStatements(table.vector));\n for (const skip of table.vector.skipped) {\n indexStatements.push(`-- No ANN index on \"${skip.schema}\".\"${skip.table}\".\"${skip.column}\": ${skip.reason}`);\n }\n }\n // The collection's own `indexes:` block. Last of the three index\n // producers, and the only one the developer wrote deliberately rather\n // than getting as a side effect of another feature.\n indexStatements.push(...collectionIndexStatements(table.indexes));\n\n if (includePolicies) {\n // No FORCE: authenticated requests run as the non-owner\n // `rebase_user` role, which plain ENABLE already binds. The owner\n // (server context) must bypass — it is the trusted plane.\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n for (const policy of table.policies) {\n policyStatements.push(statementsToDdl(renderPolicyStatements(table, policy)));\n }\n }\n }\n\n // Indexes before foreign keys. Today every FK targets a primary key created\n // inline, so the order is safe by accident; the moment a declared\n // `unique: true` index can back an FK target, a constraint emitted first\n // would reference an index that does not exist yet.\n if (indexStatements.length > 0) {\n ddl += \"-- Indexes\\n\";\n ddl += indexStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (fkStatements.length > 0) {\n ddl += \"-- Foreign Key Constraints\\n\";\n ddl += fkStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (policyStatements.length > 0) {\n ddl += \"-- Row Level Security Policies\\n\";\n ddl += adminRolePreamble(plan);\n ddl += policyStatements.join(\"\");\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n// ── policies.sql ─────────────────────────────────────────────────────────────\n\n/**\n * The statement that creates `rebase_admin`, when a policy in the plan is\n * written `TO` it — so a file of policies is self-contained, as it is for the\n * RLS helpers: CREATE POLICY refuses a role that does not exist. Empty when no\n * policy names it (`rls.adminPolicies: \"public\"`).\n */\nexport function adminRolePreamble(plan: SchemaPlan): string {\n const named = plan.tables.some(table => table.policies.some(policy => policy.roles.includes(REBASE_ADMIN_ROLE)));\n return named ? `${ADMIN_POLICY_ROLE_SQL};\\n\\n` : \"\";\n}\n\nexport function renderPoliciesDdl(plan: SchemaPlan): string {\n let ddl = \"-- This file contains RLS policies generated by Rebase. Applied separately from migrations.\\n\\n\";\n ddl += adminRolePreamble(plan);\n\n // Collections first, then the junctions no collection declares — the order\n // the boot-time applier plans them in.\n for (const table of plan.tables.filter(t => t.kind === \"collection\")) {\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n if (table.policies.length === 0) continue;\n let announced: string | undefined;\n for (const policy of table.policies) {\n // Say which policies the author did not write. They are permissive,\n // so they OR with the declared rules and widen the final ACL beyond\n // what `securityRules` reads like — and re-appear after any manual\n // DROP, because a push asserts the declared state. Once per *rule*:\n // one rule with four operations is one thing the author did not\n // write, not four.\n if (policy.injected && policy.ruleKey !== announced) {\n ddl += \"-- Injected by Rebase (not from this collection's securityRules).\\n\";\n ddl += `-- Set \\`disableDefaultPolicies: true\\` on \"${table.slug}\" to drop these and own its RLS outright.\\n`;\n }\n announced = policy.ruleKey;\n ddl += statementsToDdl(renderPolicyStatements(table, policy));\n }\n ddl += \"\\n\";\n }\n\n for (const table of plan.tables.filter(t => t.kind === \"junction\")) {\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n if (table.policies.length === 0) continue;\n const declaringSlugs = (table.declaringSlugs ?? []).join('\", \"');\n ddl += `-- Derived by Rebase for the junction \"${table.table}\" (no collection declares it).\\n`;\n ddl += \"-- Reads require both endpoint rows to be visible; writes follow the update\\n\";\n ddl += `-- rules of \"${declaringSlugs}\". Set \\`disableDefaultPolicies: true\\` on the\\n`;\n ddl += \"-- declaring collection(s) to drop these and police the junction yourself.\\n\";\n for (const policy of table.policies) {\n ddl += statementsToDdl(renderPolicyStatements(table, policy));\n }\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n// ── search.sql ───────────────────────────────────────────────────────────────\n\nexport function renderSearchDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.search);\n if (tables.length === 0) return \"\";\n\n const extensions = Array.from(new Set(tables.flatMap(t => searchExtensionStatements(t.search!))));\n const helpers = Array.from(new Set(tables.flatMap(t => searchHelperFunctions(t.search!))));\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- Full-text search for the collections declaring a `search` block.\\n\";\n ddl += \"-- Applied by Rebase, not by Atlas — see generatePostgresSearchDdl.\\n\\n\";\n\n extensions.forEach(s => { ddl += `${s}\\n`; });\n if (extensions.length > 0) ddl += \"\\n\";\n helpers.forEach(s => { ddl += `${s}\\n\\n`; });\n\n for (const table of tables) {\n const spec = table.search!;\n const target = `\"${table.schema}\".\"${table.table}\"`;\n // ADD COLUMN IF NOT EXISTS rather than the inline definition the\n // CREATE TABLE would use: by the time this runs the table exists,\n // whether Atlas just created it or it has been live for a year. The\n // guard first, because `ADD COLUMN IF NOT EXISTS` is a no-op against an\n // existing column — without it the file would report success, leave the\n // old expression in place, and then stamp it as current.\n searchStampGuards(spec).forEach(s => { ddl += `${s}\\n`; });\n ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${searchColumnDefinition(spec)};\\n`;\n const fuzzy = fuzzyColumnDefinition(spec);\n if (fuzzy) ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${fuzzy};\\n`;\n searchColumnStamps(spec).forEach(s => { ddl += `${s.sql}\\n`; });\n searchIndexStatements(spec).forEach(s => { ddl += `${s}\\n`; });\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n/**\n * Glob patterns telling Atlas to leave an object alone.\n *\n * Fully qualified, `schema.table.object`, matching the include list. The\n * two-part form is what Atlas wants when the connection URL scopes it to one\n * schema and is *silently ignored* otherwise: it reads `posts.search_vector` as\n * a table named `search_vector` in a schema named `posts`, matches nothing, and\n * reports no error for the pattern that never fired. Each name is spelled by\n * `atlasExcludePattern`, so one holding a `.` or glob syntax still matches.\n */\nexport const searchExcludePatternsOf = (plan: SchemaPlan): string[] => {\n const patterns: string[] = [];\n for (const table of plan.tables) {\n if (!table.search) continue;\n for (const column of table.columns) {\n if (column.source.kind !== \"search\") continue;\n patterns.push(atlasExcludePattern(table.schema, table.table, column.column));\n }\n for (const index of searchIndexNames(table.search)) {\n patterns.push(atlasExcludePattern(table.schema, table.table, index));\n }\n }\n return patterns;\n};\n\n// ── vector.sql ───────────────────────────────────────────────────────────────\n\nexport function renderVectorDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.vectorColumns.length > 0);\n if (tables.length === 0) return \"\";\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- Vector columns and their ANN indexes, for the collections declaring a\\n\";\n ddl += \"-- `vector` property. Applied by Rebase, not by Atlas — see\\n\";\n ddl += \"-- generatePostgresVectorDdl.\\n\\n\";\n // The note is not decoration. Someone reading this file after a failed push\n // is looking for the reason the type does not exist, and \"no CREATE\n // EXTENSION here\" is invisible unless it is written down.\n ddl += vectorExtensionDeclared(plan.options.databaseExtensions)\n ? `${vectorExtensionStatement()}\\n\\n`\n : \"-- pgvector is not installed from here: no database declared it. To let Rebase\\n\" +\n `-- install it, add ${VECTOR_EXTENSION_OPT_IN} in config/resources.ts.\\n` +\n \"-- Otherwise install it once by hand; the column below needs the type either way.\\n\\n\";\n\n for (const table of tables) {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n for (const spec of table.vectorColumns) {\n // Guard before the ADD, so a changed `dimensions` is reported\n // rather than skipped over — see `vectorDimensionGuard`.\n ddl += `${vectorDimensionGuard(spec)}\\n`;\n ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${vectorColumnDefinition(spec)};\\n`;\n }\n if (table.vector) {\n vectorIndexStatements(table.vector).forEach(s => { ddl += `${s}\\n`; });\n for (const skip of table.vector.skipped) {\n ddl += `-- No ANN index on \"${skip.schema}\".\"${skip.table}\".\"${skip.column}\": ${skip.reason}\\n`;\n }\n }\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n/** @see searchExcludePatternsOf */\nexport const vectorExcludePatternsOf = (plan: SchemaPlan): string[] => {\n const patterns: string[] = [];\n for (const table of plan.tables) {\n const names = [\n ...table.vectorColumns.map(spec => spec.column),\n ...(table.vector ? vectorIndexNames(table.vector) : [])\n ];\n for (const name of names) patterns.push(atlasExcludePattern(table.schema, table.table, name));\n }\n return patterns;\n};\n\n// ── triggers.sql ─────────────────────────────────────────────────────────────\n\n/**\n * `autoValue: \"on_update\"`, as the file Rebase applies itself.\n *\n * Empty when nothing declares one — the caller writes no file then, and removes\n * a stale one.\n */\nexport function renderTriggersDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.triggers.length > 0);\n if (tables.length === 0) return \"\";\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- `updated_at` triggers, for the properties declaring `autoValue: \\\"on_update\\\"`,\\n\";\n ddl += \"-- and the triggers that keep a row in its tenant.\\n\";\n ddl += \"-- Applied by Rebase, not by Atlas — a trigger is a function plus a binding,\\n\";\n ddl += \"-- and Atlas's free tier refuses to parse a desired state containing one.\\n\\n\";\n\n for (const statement of plan.functions.filter(isTriggerFunction)) {\n ddl += `${statement}\\n\\n`;\n }\n for (const table of tables) {\n for (const trigger of table.triggers) {\n triggerStatements(trigger).forEach(s => { ddl += `${s}\\n`; });\n }\n ddl += \"\\n\";\n }\n return ddl;\n}\n\nconst isTriggerFunction = (statement: string): boolean => statement.includes(\"RETURNS trigger\");\n\n/** @see searchExcludePatternsOf */\nexport const triggerExcludePatternsOf = (plan: SchemaPlan): string[] =>\n plan.tables.flatMap(table => table.triggers.map(t => atlasExcludePattern(table.schema, table.table, t.name)));\n\nconst quoteIdentifier = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** The comment a view Rebase created carries: `rebase:view:<hash>`. */\nexport const viewComment = (view: ViewPlan): string => `rebase:view:${view.hash}`;\n\n/** A dollar-quote tag the text does not contain, so the text can be quoted whole. */\nfunction dollarTag(text: string): string {\n let tag = \"$rebase_view$\";\n for (let i = 1; text.includes(tag); i++) tag = `$rebase_view_${i}$`;\n return tag;\n}\n\n/**\n * The statements that create one view as planned, comment included, for\n * `EXECUTE`. A plain view runs as the caller (`security_invoker`), so the\n * policies of the tables it reads decide what each caller sees.\n *\n * A materialized view is two objects (see `view-names.ts`): its rows, stored\n * under {@link viewRowsName} with a unique index on the id columns (which\n * `REFRESH … CONCURRENTLY` needs), and the gate under the collection's name —\n * a `security_barrier` view that reads them with the owner's rights and serves\n * them to the collection's roles and to the server (no uid). It reads the\n * settings directly rather than through `rebase.roles()`, which a first boot\n * creates after the views. It carries each row's `xmin`, for `fingerprint()`;\n * the catalogue reader leaves that column out of the collection.\n */\nexport function viewCreateStatements(view: ViewPlan): string[] {\n const qualified = `${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`;\n if (!view.materialized) {\n return [\n `CREATE VIEW ${qualified} WITH (security_invoker = true) AS\\n${view.query}`,\n `COMMENT ON VIEW ${qualified} IS '${viewComment(view)}'`\n ];\n }\n const stored = `${quoteIdentifier(view.schema)}.${quoteIdentifier(viewRowsName(view.name))}`;\n const roles = view.roles.map(role => `'${role.replace(/'/g, \"''\")}'`).join(\", \");\n const statements = [`CREATE MATERIALIZED VIEW ${stored} AS\\n${view.query}\\nWITH DATA`];\n if (view.idColumns.length > 0) {\n statements.push(`CREATE UNIQUE INDEX ${quoteIdentifier(`${view.name}_rebase_id`)} ON ${stored} (${view.idColumns.map(quoteIdentifier).join(\", \")})`);\n }\n statements.push(...view.indexes);\n statements.push(\n `COMMENT ON MATERIALIZED VIEW ${stored} IS '${VIEW_ROWS_COMMENT_PREFIX}${view.hash}'`,\n `REVOKE ALL ON ${stored} FROM PUBLIC`,\n `CREATE VIEW ${qualified} WITH (security_barrier = true) AS\\n` +\n `SELECT rows.*, rows.xmin AS xmin FROM ${stored} rows\\n` +\n \"WHERE NULLIF(current_setting('app.uid', true), '') IS NULL\\n\" +\n ` OR string_to_array(COALESCE(current_setting('app.user_roles', true), ''), ',') && ARRAY[${roles || \"NULL\"}]::text[]`,\n `COMMENT ON VIEW ${qualified} IS '${viewComment(view)}'`\n );\n return statements;\n}\n\n/**\n * `views.sql`: the views of the collections that declare one, as the file\n * Rebase applies itself — Atlas manages no views on its free tier.\n *\n * Idempotent, in two passes. The first drops, last first, every view whose\n * comment no longer matches its plan and every view that reads one of those\n * (Postgres will not drop a view another still reads, and will not change a\n * view's columns in place); the second creates, in order, every view that is\n * not there. A view that is up to date is left alone, rows and all. A table or\n * a view Rebase did not create under the same name is refused, never dropped.\n *\n * Empty when no collection declares a view.\n */\nexport function renderViewsDdl(plan: SchemaPlan): string {\n if (plan.views.length === 0) return \"\";\n const literal = (text: string) => `'${text.replace(/'/g, \"''\")}'`;\n const regclass = (view: ViewPlan) => `to_regclass(${literal(`${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`)})`;\n const stale = (view: ViewPlan) =>\n `(${regclass(view)} IS NOT NULL AND obj_description(${regclass(view)}, 'pg_class') IS DISTINCT FROM ${literal(viewComment(view))})`;\n // Every planned view a view reads, directly or through another.\n const readsOf = (view: ViewPlan, seen = new Set<string>()): ViewPlan[] =>\n view.dependsOn.flatMap(name => {\n if (seen.has(name)) return [];\n seen.add(name);\n const target = plan.views.find(other => other.qualified === name);\n return target ? [target, ...readsOf(target, seen)] : [];\n });\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- The views of the collections that declare `view`. Applied by Rebase, not by Atlas.\\n\\n\";\n ddl += \"DO $rebase_views$\\nDECLARE\\n kind \\\"char\\\";\\n note text;\\nBEGIN\\n\";\n for (const view of [...plan.views].reverse()) {\n const qualified = `${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`;\n const reasons = [view, ...readsOf(view)].map(stale).join(\"\\n OR \");\n ddl += ` SELECT c.relkind, obj_description(c.oid, 'pg_class') INTO kind, note FROM pg_class c WHERE c.oid = ${regclass(view)};\\n`;\n ddl += \" IF kind IS NOT NULL AND (kind NOT IN ('v', 'm') OR note IS NULL OR note NOT LIKE 'rebase:view:%') THEN\\n\";\n ddl += ` RAISE EXCEPTION 'Rebase will not replace %: it is a table or a view Rebase did not create. Rename or drop it, or give the collection another table.', ${literal(view.qualified)};\\n`;\n ddl += \" END IF;\\n\";\n ddl += ` IF ${reasons} THEN\\n`;\n ddl += ` IF kind = 'm' THEN EXECUTE ${literal(`DROP MATERIALIZED VIEW ${qualified}`)}; ELSE EXECUTE ${literal(`DROP VIEW ${qualified}`)}; END IF;\\n`;\n ddl += \" END IF;\\n\";\n }\n for (const view of plan.views) {\n const rows = `${quoteIdentifier(view.schema)}.${quoteIdentifier(viewRowsName(view.name))}`;\n ddl += ` IF ${regclass(view)} IS NULL THEN\\n`;\n // A gate that is gone leaves its rows: they are this view's, recomputed below.\n if (view.materialized) {\n ddl += ` IF to_regclass(${literal(rows)}) IS NOT NULL THEN EXECUTE ${literal(`DROP MATERIALIZED VIEW ${rows}`)}; END IF;\\n`;\n }\n for (const statement of viewCreateStatements(view)) {\n const tag = dollarTag(statement);\n ddl += ` EXECUTE ${tag}${statement}${tag};\\n`;\n }\n if (view.materialized) {\n ddl += ` IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(REBASE_USER_ROLE)}) THEN EXECUTE ${literal(`REVOKE ALL ON ${rows} FROM ${REBASE_USER_ROLE}`)}; END IF;\\n`;\n }\n ddl += \" END IF;\\n\";\n }\n ddl += \"END\\n$rebase_views$;\\n\";\n return ddl;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,IAAa,gBAAgB,SAAyB;CAClD,QAAQ,KAAK,MAAb;EACI,KAAK,QAAQ,OAAO;EACpB,KAAK,WAAW,OAAO,WAAW,KAAK,OAAO;EAC9C,KAAK,QAAQ,OAAO,QAAQ,KAAK,OAAO;EACxC,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO,IAAI,KAAK,OAAO,KAAK,KAAK,KAAK;E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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"rls-bootstrap-sql-CxszeSc7.js","names":[],"sources":["../src/schema/rls-bootstrap-sql.ts"],"sourcesContent":["import { LEGACY_RLS_SCHEMA, REBASE_ADMIN_ROLE, REBASE_SCHEMA } from \"@rebasepro/types\";\nimport { sqlRows } from \"@rebasepro/common\";\n\n/**\n * Canonical SQL bootstrap for the RLS helper functions.\n *\n * Generated RLS policies reference `rebase.uid()` / `rebase.roles()` /\n * `rebase.jwt()`, so any SQL stream that can contain policies must be\n * self-contained: it has to (re)create these helpers first. This matters for\n * the migration directory in particular — Atlas replays migrations against a\n * clean dev database where no out-of-band bootstrap has ever run, so a\n * migration carrying policies without this preamble fails with\n * \"function rebase.uid() does not exist\".\n *\n * Idempotent (`IF NOT EXISTS` / `OR REPLACE`) so it can be prepended to every\n * policies block and re-applied freely. The runtime boot path\n * (`auth/ensure-tables.ts`) creates the same functions under an advisory lock\n * for HMR-safety; keep the definitions in sync.\n *\n * ## Creating the `rebase` schema here is now safe, and required\n *\n * It deliberately did not, once. These functions lived in a schema called\n * `auth`, and the note here read: creating `rebase` would leak it into Atlas's\n * replayed migration state, and — absent from the desired `schema.sql` — Atlas\n * would then plan `DROP SCHEMA \"rebase\" CASCADE`, taking the auth tables with\n * it. That reasoning still holds; what changed is the second half of it. The\n * DDL generator now emits `CREATE SCHEMA IF NOT EXISTS \"rebase\"`\n * unconditionally, so the schema is always in the desired state and the diff is\n * empty. (It used to appear only when some collection happened to declare\n * `schema: \"rebase\"` — true for the scaffold's users collection, and not a\n * property anything guaranteed.) `db push` additionally excludes the whole\n * schema from the declarative apply.\n *\n * See `@rebasepro/types`' `rls-functions` for why the functions moved out of\n * `auth` at all: the short version is that the name was Supabase's, and\n * `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` cannot be applied over\n * Supabase's `RETURNS uuid` — Postgres refuses, and the refusal used to be\n * swallowed.\n */\n/**\n * The bootstrap as individual statements.\n *\n * Kept as an array because the two consumers need different shapes and only one\n * of them can take a multi-command string: the migration preamble is written to\n * a file and replayed by Atlas, but the boot path runs through drizzle, whose\n * node-postgres handle speaks the extended query protocol and rejects more than\n * one command per call. Splitting a joined string back apart on `$$;` would be\n * a parser for a problem that does not need one.\n */\n/*\n * Every helper is `PARALLEL SAFE`: it reads a setting, which Postgres hands to\n * its parallel workers with the rest of the transaction's state. Left at the\n * default (`PARALLEL UNSAFE`), a policy calling one made every statement on\n * its table run without parallel workers — a large read as `rebase_user` took\n * twice what the same read took as the table's owner.\n */\nexport const RLS_BOOTSTRAP_STATEMENTS: readonly string[] = [\n `CREATE SCHEMA IF NOT EXISTS ${REBASE_SCHEMA}`,\n\n // Falls back to the pre-rename `app.user_id` so a database that has taken\n // the new schema but is still served by an older backend keeps resolving\n // the principal. Drop the COALESCE once no such deployment remains.\n `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.uid() RETURNS text AS $$\n SELECT COALESCE(\n NULLIF(current_setting('app.uid', true), ''),\n NULLIF(current_setting('app.user_id', true), '')\n );\n$$ LANGUAGE sql STABLE PARALLEL SAFE`,\n\n `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.jwt() RETURNS jsonb AS $$\n SELECT COALESCE(\n NULLIF(current_setting('app.jwt', true), ''),\n '{}'\n )::jsonb;\n$$ LANGUAGE sql STABLE PARALLEL SAFE`,\n\n `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.roles() RETURNS text AS $$\n SELECT COALESCE(NULLIF(current_setting('app.user_roles', true), ''), '');\n$$ LANGUAGE sql STABLE PARALLEL SAFE`,\n\n // Is the caller a GUEST — signed in through anonymous sign-in rather than\n // with an account?\n //\n // Anonymous sign-in mints a real user row and a real uid, so inside a policy\n // a guest was indistinguishable from a registered account: same `uid()`\n // shape, same default role. Every rule meaning \"a signed-in person\" was\n // therefore also a rule about anybody who had called\n // `POST /auth/anonymous`, which needs no email, no password and no consent\n // to anything. On a deployment with anonymous sign-in enabled, that is the\n // whole internet holding a session.\n //\n // The fact exists on the user row (`is_anonymous`) and simply never reached\n // the database's own identity. Now it does, and a policy can say\n // `NOT rebase.is_anonymous()`.\n //\n // Defaults to FALSE when the GUC is unset, which is the safe direction:\n // an older backend against a newer database leaves it unset, and reading\n // that as \"not a guest\" preserves exactly the behaviour that deployment\n // already had rather than locking its users out.\n `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.is_anonymous() RETURNS boolean AS $$\n SELECT COALESCE(NULLIF(current_setting('app.is_anonymous', true), ''), 'false')::boolean;\n$$ LANGUAGE sql STABLE PARALLEL SAFE`\n];\n\n/** Everything `CREATE OR REPLACE FUNCTION` sets on a function, as one comparable string. */\nconst describeFunction = (facts: {\n returns: string; language: string; volatility: string; strict: boolean; parallel: string;\n securityDefiner: boolean; leakproof: boolean; cost: number; hasConfig: boolean; body: string;\n}): string => JSON.stringify([\n facts.returns.toLowerCase(), facts.language.toLowerCase(), facts.volatility, facts.strict, facts.parallel,\n facts.securityDefiner, facts.leakproof, facts.cost, facts.hasConfig, facts.body\n]);\n\n/**\n * What each `CREATE OR REPLACE FUNCTION` in {@link RLS_BOOTSTRAP_STATEMENTS}\n * would leave in the catalogue, by `schema.name`. Parsed\n * from the statements themselves, so the two cannot drift; a statement this\n * does not recognise makes {@link rlsRuntimeIsCurrent} answer \"no\", and the\n * bootstrap runs as it always did.\n */\nconst expectedRlsFunctions = (): Map<string, string> | undefined => {\n const expected = new Map<string, string>();\n for (const statement of RLS_BOOTSTRAP_STATEMENTS) {\n if (/^CREATE SCHEMA IF NOT EXISTS /.test(statement)) continue;\n const match = /^CREATE OR REPLACE FUNCTION (\\w+)\\.(\\w+)\\(\\) RETURNS (\\w+) AS \\$\\$([\\s\\S]*)\\$\\$ LANGUAGE (\\w+) (IMMUTABLE|STABLE|VOLATILE)(?: PARALLEL (SAFE|RESTRICTED|UNSAFE))?$/\n .exec(statement);\n if (!match) return undefined;\n const [, schema, name, returns, body, language, volatility, parallel] = match;\n expected.set(`${schema}.${name}`, describeFunction({\n returns, language, volatility: volatility[0].toLowerCase(), strict: false, parallel: (parallel ?? \"UNSAFE\")[0].toLowerCase(),\n securityDefiner: false, leakproof: false, cost: 100, hasConfig: false, body\n }));\n }\n return expected;\n};\n\n/**\n * Whether the `rebase` schema and every RLS helper function are exactly what\n * {@link RLS_BOOTSTRAP_STATEMENTS} would make them — one catalogue read.\n *\n * The boot ran those statements unconditionally, on every boot and on every\n * source: four `CREATE OR REPLACE FUNCTION`s in a transaction under an\n * advisory lock. Replacing a function rewrites its `pg_proc` row even when\n * nothing changed, and every cached plan that inlined it — every plan of every\n * statement a policy applies to, on every connection — is invalidated by it.\n * A function that differs in anything `CREATE OR REPLACE` sets (body,\n * language, volatility, strictness, parallel safety, security, leakproofness,\n * cost, `SET` options), or is missing, answers `false`, and the statements run\n * as before.\n */\nexport async function rlsRuntimeIsCurrent(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<boolean> {\n const expected = expectedRlsFunctions();\n if (!expected) return false;\n const names = [...expected.keys()].map(key => key.split(\".\"));\n const rows = await run(\n `SELECT n.nspname AS schema, p.proname AS name, pg_get_function_identity_arguments(p.oid) AS args,\n format_type(p.prorettype, NULL) AS returns, l.lanname AS language,\n p.provolatile::text AS volatility, p.proisstrict AS strict, p.proparallel::text AS parallel,\n p.prosecdef AS security_definer, p.proleakproof AS leakproof, p.procost AS cost,\n p.proconfig IS NOT NULL AS has_config, p.prosrc AS body\n FROM pg_proc p\n JOIN pg_namespace n ON p.pronamespace = n.oid\n JOIN pg_language l ON p.prolang = l.oid\n WHERE (n.nspname, p.proname) IN (${names.map(([schema, name]) => `('${schema}', '${name}')`).join(\", \")})`\n );\n const live = new Map<string, string>();\n for (const row of rows) {\n // Only the no-argument overload is the one these statements replace.\n if (String(row.args ?? \"\") !== \"\") continue;\n live.set(`${row.schema}.${row.name}`, describeFunction({\n returns: String(row.returns),\n language: String(row.language),\n volatility: String(row.volatility),\n strict: row.strict === true,\n parallel: String(row.parallel),\n securityDefiner: row.security_definer === true,\n leakproof: row.leakproof === true,\n cost: Number(row.cost),\n hasConfig: row.has_config === true,\n body: String(row.body)\n }));\n }\n // The schema exists whenever a function in it does.\n for (const [key, definition] of expected) {\n if (live.get(key) !== definition) return false;\n }\n return true;\n}\n\n/** The same statements as one script, for migration files and raw clients. */\nexport const RLS_BOOTSTRAP_SQL =\n \"-- Rebase schema + RLS helper functions (required by the policies below)\\n\" +\n RLS_BOOTSTRAP_STATEMENTS.map(s => `${s};`).join(\"\\n\\n\") + \"\\n\";\n\n/** One of the helpers the pre-1.0 `auth` schema held. */\ninterface LegacyAuthHelper {\n name: string;\n returns: string;\n /** The GUCs its body read. Any one of them identifies it. */\n reads: readonly string[];\n}\n\n/**\n * The three functions every pre-1.0 release put in `auth`. (The auth tables\n * lived in `rebase`, or wherever the users collection was declared.)\n *\n * `uid()` is matched on either spelling of the principal because Rebase wrote\n * both. Until v0.10.0 its body was\n * `SELECT NULLIF(current_setting('app.user_id', true), '')`; v0.10.0 renamed\n * the GUC to `app.uid` and kept `app.user_id` as a fallback; v0.14.0 moved the\n * helpers to `rebase`. A database last booted before v0.10.0 therefore holds an\n * `auth.uid()` that reads `app.user_id` alone — as does anything that copied\n * that body, the Rebase control plane included — and matching `app.uid` only\n * left every one of them in place, with the schema around it.\n *\n * This is the one place either spelling is listed: the drop and the report of\n * what it left are both generated from it, so they cannot disagree about which\n * functions are Rebase's.\n */\nconst LEGACY_AUTH_HELPERS: readonly LegacyAuthHelper[] = [\n { name: \"uid\", returns: \"text\", reads: [\"app.uid\", \"app.user_id\"] },\n { name: \"jwt\", returns: \"jsonb\", reads: [\"app.jwt\"] },\n { name: \"roles\", returns: \"text\", reads: [\"app.user_roles\"] }\n];\n\n/**\n * `pg_proc p` has a Rebase helper's name, arity and result type: what\n * `CREATE OR REPLACE` would have left, whatever the body.\n *\n * Two things that share that shape are excluded outright: a body reading\n * `request.jwt` (Supabase's helpers and anything modelled on them) and a\n * function an extension installed (`pg_session_jwt` puts an `auth.jwt()\n * RETURNS jsonb` in the same schema).\n */\nconst isLegacyHelperShaped = (helper: LegacyAuthHelper): string => `(\n p.proname = '${helper.name}' AND p.pronargs = 0\n AND pg_get_function_result(p.oid) = '${helper.returns}'\n AND strpos(p.prosrc, 'request.jwt') = 0\n AND NOT EXISTS (\n SELECT 1 FROM pg_depend e\n WHERE e.classid = 'pg_proc'::regclass AND e.objid = p.oid AND e.deptype = 'e'\n ))`;\n\n/** `pg_proc p` is a helper Rebase wrote: its shape, and a body reading one of its GUCs. */\nconst isLegacyHelper = (helper: LegacyAuthHelper): string =>\n `${isLegacyHelperShaped(helper)}\n AND (${helper.reads.map(guc => `strpos(p.prosrc, '${guc}') > 0`).join(\" OR \")})`;\n\n/**\n * Removes the pre-1.0 `auth` schema, but only when Rebase is what put it there.\n *\n * ## Why this is safe against a Supabase database\n *\n * Two independent guards, and both have to pass:\n *\n * 1. **Each function is identified before it is dropped.** Ours returns `text`\n * and reads the `app.uid` or `app.user_id` GUC; Supabase's returns `uuid`\n * and reads `request.jwt.claims`. Nothing is dropped on a signature we did\n * not write, so a Supabase database — where our `CREATE OR REPLACE` could\n * never have succeeded in the first place, Postgres refusing to change a\n * return type — matches nothing and this is a no-op. See\n * {@link LEGACY_AUTH_HELPERS} for exactly what is matched.\n * 2. **`DROP SCHEMA … RESTRICT`**, never CASCADE. If anything else at all still\n * lives in `auth` (Supabase's `users` table, its other helpers), the drop\n * fails and the schema stays. CASCADE here would be unrecoverable.\n *\n * ## Why it cannot run too early\n *\n * Postgres records a dependency from every RLS policy to the functions its body\n * calls, so `DROP FUNCTION auth.uid()` fails for as long as a single policy\n * still references it. That is the interlock, and it is load-bearing: the drop\n * can only succeed once every policy has been recompiled to \\`rebase.uid()\\`.\n * Callers therefore run this *after* applying policies, and treat a failure as\n * \"not yet — try again next boot\" rather than as an error.\n */\nexport const DROP_LEGACY_AUTH_SCHEMA_SQL = `\nDO $rebase_drop_legacy$\nDECLARE\n dropped_any boolean := false;\nBEGIN\n -- Each function is matched on its own result type and body, so a schema\n -- that merely shares the name keeps everything it has.\n${LEGACY_AUTH_HELPERS.map(helper => ` IF EXISTS (\n SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = '${LEGACY_RLS_SCHEMA}' AND ${isLegacyHelper(helper)}\n ) THEN\n DROP FUNCTION ${LEGACY_RLS_SCHEMA}.${helper.name}();\n dropped_any := true;\n END IF;`).join(\"\\n\\n\")}\n\n -- RESTRICT: only an empty schema goes. Anything else in there — including a\n -- Supabase installation left untouched above — keeps it. Swallowed so the\n -- helpers dropped above stay dropped; dropLegacyAuthSchema looks afterwards\n -- and says what is left.\n IF dropped_any THEN\n BEGIN\n EXECUTE 'DROP SCHEMA ${LEGACY_RLS_SCHEMA} RESTRICT';\n EXCEPTION WHEN OTHERS THEN\n NULL;\n END;\n END IF;\nEND\n$rebase_drop_legacy$;\n`;\n\n/** One object in the `auth` schema that `DROP SCHEMA … RESTRICT` refuses on. */\nexport interface LegacyAuthSchemaObject {\n /**\n * As Postgres names it: `function auth.uid()`, `table auth.sessions`.\n * `null` on the one row an empty schema answers with.\n */\n object: string | null;\n /**\n * `ours` is a helper Rebase wrote, which the drop removes. `lookalike` has a\n * helper's name and result type but a body no release wrote, so the drop\n * leaves it alone. `null` for everything else.\n */\n helper: \"ours\" | \"lookalike\" | null;\n}\n\n/**\n * What the `auth` schema holds, one row per object keeping it alive.\n *\n * No rows: the schema does not exist. A single row with a `null` object: it\n * exists and is empty. Read from the namespace entries in `pg_depend`, which\n * are what `DROP SCHEMA … RESTRICT` itself consults — minus whatever goes with\n * its owner (a serial's sequence, an identity column's), which Postgres does not\n * name either.\n */\nexport const LEGACY_AUTH_SCHEMA_CONTENTS_SQL = `\n SELECT pg_describe_object(d.classid, d.objid, d.objsubid) AS object,\n CASE\n WHEN d.classid <> 'pg_proc'::regclass THEN NULL\n WHEN EXISTS (\n SELECT 1 FROM pg_proc p\n WHERE p.oid = d.objid\n AND (${LEGACY_AUTH_HELPERS.map(helper => `(${isLegacyHelper(helper)})`).join(\" OR \")})\n ) THEN 'ours'\n WHEN EXISTS (\n SELECT 1 FROM pg_proc p\n WHERE p.oid = d.objid\n AND (${LEGACY_AUTH_HELPERS.map(isLegacyHelperShaped).join(\" OR \")})\n ) THEN 'lookalike'\n END AS helper\n FROM pg_namespace n\n LEFT JOIN pg_depend d\n ON d.refclassid = 'pg_namespace'::regclass AND d.refobjid = n.oid AND d.deptype = 'n'\n AND NOT EXISTS (\n SELECT 1 FROM pg_depend o\n WHERE o.classid = d.classid AND o.objid = d.objid AND o.deptype IN ('a', 'i')\n )\n WHERE n.nspname = '${LEGACY_RLS_SCHEMA}'\n ORDER BY helper NULLS LAST, object\n`;\n\n/** Somebody's policy that still calls a pre-1.0 helper. */\nexport interface LegacyRlsDependent {\n schema: string;\n table: string;\n policy: string;\n}\n\n/**\n * Policies whose body still calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.\n *\n * Postgres will not drop a function a policy depends on, so this is exactly the\n * set standing between a database and losing the legacy schema. Rebase's own\n * policies leave the list on the next push or boot, when they are recompiled —\n * anything still here afterwards is hand-written, will never be recompiled by\n * anybody, and is the reason the drop keeps being skipped. Silence there would\n * leave an operator staring at a schema the release notes said would go.\n */\nexport const LEGACY_RLS_DEPENDENTS_SQL = `\n SELECT n.nspname AS schema, c.relname AS \"table\", p.polname AS policy\n FROM pg_policy p\n JOIN pg_class c ON c.oid = p.polrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE pg_get_expr(p.polqual, p.polrelid) ~* '\\\\m${LEGACY_RLS_SCHEMA}\\\\.(uid|jwt|roles)\\\\s*\\\\('\n OR pg_get_expr(p.polwithcheck, p.polrelid) ~* '\\\\m${LEGACY_RLS_SCHEMA}\\\\.(uid|jwt|roles)\\\\s*\\\\('\n ORDER BY 1, 2, 3\n`;\n\n/** Somebody's *function* that still calls a pre-1.0 helper from its own body. */\nexport interface LegacyRlsFunctionDependent {\n schema: string;\n function: string;\n}\n\n/**\n * Functions whose body calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.\n *\n * This is the half `DROP FUNCTION ... RESTRICT` cannot see, and the reason it\n * needs its own query. Postgres records a dependency for a *policy* that calls a\n * function, which is why the drop is safe against the policies above — but a\n * `LANGUAGE sql` function whose body is a **string literal** is not parsed when\n * it is created, so nothing is recorded and `RESTRICT` has nothing to refuse on.\n * The drop succeeds and the caller is left pointing at a function that no longer\n * exists, which fails at *query* time rather than at boot.\n *\n * A downstream project building on these helpers is not hypothetical: the Rebase\n * control plane defined `auth.is_org_member(uuid)` and `auth.is_org_admin(uuid)`\n * in this very schema, each calling `auth.uid()` in a string body, and eleven of\n * its row-level-security policies went through them. Every one of those would\n * have started failing the first time a recompile left no policy referencing\n * `auth.uid()` directly — the drop's own precondition. (Its migration 0065 has\n * since moved both to `public`, calling `rebase.uid()`.)\n *\n * Matching on the body text is the only option available, and it is deliberately\n * broad: a false positive costs a schema that stays one release longer and says\n * why, while a false negative costs somebody their policies.\n */\nexport const LEGACY_RLS_FUNCTION_DEPENDENTS_SQL = `\n SELECT n.nspname AS schema, p.proname AS function\n FROM pg_proc p\n JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND NOT (n.nspname = '${LEGACY_RLS_SCHEMA}' AND p.proname IN ('uid', 'jwt', 'roles'))\n AND p.prosrc ~* '\\\\m${LEGACY_RLS_SCHEMA}\\\\.(uid|jwt|roles)\\\\s*\\\\('\n ORDER BY 1, 2\n`;\n\n/**\n * Retire the pre-1.0 `auth` schema, reporting what is holding it back.\n *\n * The shared implementation behind the CLI's post-push step and the runtime's\n * post-policy step. Both used to just fire {@link DROP_LEGACY_AUTH_SCHEMA_SQL}\n * and swallow whatever came back, which is right for the ordinary case — a\n * table not recompiled *yet* — and wrong for the one that never resolves: a\n * hand-written policy nothing will ever rewrite. Then the schema stays forever\n * and nothing ever says why.\n *\n * The drop itself had the same blind spot. A helper it did not recognise as\n * Rebase's stayed, and so did anything else in the schema, behind a\n * `DROP SCHEMA … RESTRICT` whose failure is swallowed so the helpers it did\n * drop stay dropped. The control plane's `auth.uid()` was one such: it read\n * `app.user_id` alone, the drop looked for `app.uid`, and the schema stayed\n * with no word said. So the schema is read twice. Before, so that one with no\n * Rebase helper in it is left alone: one already gone, as on every boot after\n * the drop, or one that was never Rebase's, like Supabase's — whose own\n * policies the checks below would otherwise report as blockers. After, to name\n * whatever is still there.\n */\nexport async function dropLegacyAuthSchema(\n run: (sql: string) => Promise<Record<string, unknown>[]>,\n report: { info: (m: string) => void; warn: (m: string) => void }\n): Promise<void> {\n let before: LegacyAuthSchemaObject[];\n try {\n before = sqlRows<LegacyAuthSchemaObject>(await run(LEGACY_AUTH_SCHEMA_CONTENTS_SQL));\n } catch {\n return; // No catalogue access; nothing here is worth failing a boot for.\n }\n if (!before.some(o => o.helper !== null)) return;\n // Only a lookalike: nothing will be dropped, so whatever calls it is no\n // blocker, and saying so would ask somebody to rewrite their own policies.\n if (!before.some(o => o.helper === \"ours\")) {\n report.warn(describeLegacyAuthLeftovers(before, undefined));\n return;\n }\n\n let blockers: LegacyRlsDependent[];\n try {\n blockers = sqlRows<LegacyRlsDependent>(await run(LEGACY_RLS_DEPENDENTS_SQL));\n } catch {\n return; // No catalogue access; nothing here is worth failing a boot for.\n }\n\n if (blockers.length > 0) {\n report.warn(\n `The pre-1.0 \\`${LEGACY_RLS_SCHEMA}\\` schema cannot be removed yet: ${blockers.length} ` +\n `${blockers.length === 1 ? \"policy still calls\" : \"policies still call\"} ` +\n `\\`${LEGACY_RLS_SCHEMA}.uid()\\` and friends, and Postgres will not drop a function a policy ` +\n `depends on. Rebase's own policies are ` +\n `rewritten automatically — anything listed here is hand-written SQL that has to be updated to ` +\n `\\`${REBASE_SCHEMA}.uid()\\` by hand, after which the schema goes on its own:\\n` +\n blockers.map(b => ` • ${b.schema}.${b.table} → \"${b.policy}\"`).join(\"\\n\")\n );\n return;\n }\n\n // The half Postgres will not refuse on. See LEGACY_RLS_FUNCTION_DEPENDENTS_SQL:\n // a string-literal SQL body records no dependency, so `DROP FUNCTION` drops\n // out from under a caller that is still using it and nothing complains until\n // a query runs.\n let borrowers: LegacyRlsFunctionDependent[];\n try {\n borrowers = sqlRows<LegacyRlsFunctionDependent>(await run(LEGACY_RLS_FUNCTION_DEPENDENTS_SQL));\n } catch {\n return;\n }\n\n if (borrowers.length > 0) {\n report.warn(\n `The pre-1.0 \\`${LEGACY_RLS_SCHEMA}\\` schema cannot be removed yet: ${borrowers.length} ` +\n `${borrowers.length === 1 ? \"function calls\" : \"functions call\"} ` +\n `\\`${LEGACY_RLS_SCHEMA}.uid()\\` and friends from its own body. Postgres records no dependency ` +\n `for that — a SQL body written as a string literal is never parsed — so dropping the helpers ` +\n `would leave these pointing at nothing, and they would fail when a query reached them rather ` +\n `than now. Repoint them at \\`${REBASE_SCHEMA}.uid()\\`, after which the schema goes on its own:\\n` +\n borrowers.map(b => ` • ${b.schema}.${b.function}()`).join(\"\\n\")\n );\n return;\n }\n\n // A failure is not fatal — the schema is inert now that no policy calls it —\n // but it is reported below with whatever it left, not on its own.\n let failure: string | undefined;\n try {\n await run(DROP_LEGACY_AUTH_SCHEMA_SQL);\n } catch (err) {\n // Postgres names the dependent object in DETAIL, not in the message.\n const detail = err instanceof Error && \"detail\" in err && typeof err.detail === \"string\" ? err.detail : \"\";\n failure = (err instanceof Error ? err.message : String(err)) +\n (detail ? ` (${detail.replace(/\\n/g, \"; \")})` : \"\");\n }\n\n let left: LegacyAuthSchemaObject[];\n try {\n left = sqlRows<LegacyAuthSchemaObject>(await run(LEGACY_AUTH_SCHEMA_CONTENTS_SQL));\n } catch {\n if (failure) report.info(`Left the \\`${LEGACY_RLS_SCHEMA}\\` schema in place: ${failure}`);\n return;\n }\n if (left.length === 0) return; // Gone.\n\n report.warn(describeLegacyAuthLeftovers(left, failure));\n}\n\n/** At most this many objects are named; a schema this full is plainly in use. */\nconst MAX_LEFTOVERS_NAMED = 20;\n\n/**\n * The warning for an `auth` schema the drop left standing.\n *\n * Said once for objects that are not Rebase's: on the next boot the schema holds\n * no helper, so {@link dropLegacyAuthSchema} leaves it alone — it is somebody\n * else's schema by then. A helper that is still there, Rebase's or a lookalike,\n * keeps it said on every boot until it goes.\n */\nfunction describeLegacyAuthLeftovers(left: LegacyAuthSchemaObject[], failure: string | undefined): string {\n const schema = LEGACY_RLS_SCHEMA;\n const objects = left.filter(o => o.object !== null);\n\n if (objects.length === 0) {\n return `The pre-1.0 \\`${schema}\\` schema is empty, but this connection could not drop it — most likely ` +\n `because it does not own the schema. Run \\`DROP SCHEMA ${schema};\\` as its owner.`;\n }\n\n const why = failure\n ? `dropping Rebase's old helpers from it failed: ${failure}.`\n : `\\`DROP SCHEMA … RESTRICT\\` refuses a schema that is not empty, and Rebase drops only the helpers it ` +\n `can tell are its own.`;\n\n const lines = objects.slice(0, MAX_LEFTOVERS_NAMED).map(o =>\n o.helper === \"ours\"\n ? ` • ${o.object} — Rebase's old helper, which could not be dropped`\n : o.helper === \"lookalike\"\n ? ` • ${o.object} — named and typed like Rebase's old helper, but no release wrote this body, ` +\n `so it was left alone; drop it by hand if nothing of yours calls it`\n : ` • ${o.object}`\n );\n if (objects.length > MAX_LEFTOVERS_NAMED) lines.push(` • …and ${objects.length - MAX_LEFTOVERS_NAMED} more`);\n\n return `The pre-1.0 \\`${schema}\\` schema is still here: ${why} Still in it:\\n` +\n lines.join(\"\\n\") + \"\\n\" +\n `Anything of yours can stay where it is — Rebase no longer uses this schema — or move out with ` +\n `\\`ALTER … SET SCHEMA\\`. Once the schema is empty, \\`DROP SCHEMA ${schema};\\` removes it.`;\n}\n\n/**\n * `rebase.is_request_role(role)` — is `role` one of the roles this database's\n * requests run as? The predicate `rls.policyTarget: \"requestRole\"` ANDs into\n * every permissive policy (`RLS_IS_REQUEST_ROLE_SQL`), called with\n * `current_user`.\n *\n * SECURITY DEFINER because the recorded roles live in `rebase.schema_meta`,\n * which the request roles cannot read. That is also why the caller's role is\n * an argument: inside the function `current_user` is its owner. The body is\n * dynamic SQL so the function can be created before the table exists — in\n * Atlas's replay of the migrations, for one. With nothing recorded the answer\n * is `rebase_user`, as everywhere else. Each recorded role's admin counterpart\n * (`<role>_admin`, what an admin request switches to) answers `true` as well.\n *\n * Created only for a project that asks for `policyTarget: \"requestRole\"`, so\n * every other project's migrations and boot are exactly what they were.\n */\nexport const REQUEST_ROLE_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.is_request_role(role_name text) RETURNS boolean AS $$\nDECLARE\n request_roles text[];\nBEGIN\n IF to_regclass('\"${REBASE_SCHEMA}\".\"schema_meta\"') IS NOT NULL THEN\n EXECUTE 'SELECT string_to_array(value, '','') FROM \"${REBASE_SCHEMA}\".\"schema_meta\" WHERE key = ''request_roles'''\n INTO request_roles;\n END IF;\n request_roles := COALESCE(request_roles, ARRAY['rebase_user']);\n -- An admin request runs as the request role's admin counterpart\n -- (adminRequestRoleFor), which is a request role here too.\n RETURN role_name = ANY(request_roles) OR role_name = ANY(ARRAY(SELECT r || '_admin' FROM unnest(request_roles) AS r));\nEND\n$$ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog`;\n\n/**\n * Create {@link REQUEST_ROLE_FUNCTION_SQL} when it is missing or its body\n * differs — replacing an unchanged function would still invalidate every\n * cached plan of every policy that calls it.\n */\nexport async function ensureRequestRoleFunction(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<void> {\n const body = /AS \\$\\$([\\s\\S]*)\\$\\$ LANGUAGE/.exec(REQUEST_ROLE_FUNCTION_SQL)?.[1];\n const [live] = await run(\n `SELECT p.prosrc AS body FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = '${REBASE_SCHEMA}' AND p.proname = 'is_request_role'`\n );\n if (live && String(live.body) === body) return;\n // `IF NOT EXISTS` still asks for CREATE on the database before it looks.\n const [schema] = await run(`SELECT to_regnamespace('${REBASE_SCHEMA}') IS NOT NULL AS present`);\n if (schema?.present !== true) await run(`CREATE SCHEMA IF NOT EXISTS ${REBASE_SCHEMA}`);\n await run(REQUEST_ROLE_FUNCTION_SQL);\n}\n\n/**\n * The statement that creates {@link REBASE_ADMIN_ROLE} when it is missing — a\n * role with no privilege that cannot log in, whose only job is to be what the\n * server-or-admin policies are written `TO`. Guarded in the statement, and a\n * concurrent creator's win taken as success, because a role belongs to the\n * cluster and two databases' boots can race for it.\n */\nexport const ADMIN_POLICY_ROLE_SQL = `DO $rebase_admin_role$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') THEN\n CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\nEXCEPTION\n WHEN duplicate_object OR unique_violation THEN NULL;\n WHEN insufficient_privilege THEN\n RAISE EXCEPTION 'Rebase writes its server-or-admin policies TO ${REBASE_ADMIN_ROLE}, which does not exist, and % may not create it.', current_user\n USING HINT = 'Run CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN; as an administrator, or declare database({ rls: { adminPolicies: \"public\" } }) (REBASE_RLS_ADMIN_POLICIES=public) to write them TO public.';\nEND\n$rebase_admin_role$`;\n\n/** Create {@link REBASE_ADMIN_ROLE} unless it exists — one read when it does. */\nexport async function ensureAdminPolicyRole(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<void> {\n const [row] = await run(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') AS present`);\n if (row?.present !== true) await run(ADMIN_POLICY_ROLE_SQL);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,2BAA8C;CACvD,+BAA+B;CAK/B,8BAA8B,cAAc;;;;;;CAO5C,8BAA8B,cAAc;;;;;;CAO5C,8BAA8B,cA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S,oBAAoB,MAAM;CAE5G,OAAO,iBAAiB,OAAO,2BAA2B,IAAI,mBAC1D,MAAM,KAAK,IAAI,IAAI;gKAEgD,OAAO;AAClF;;;;;;;;;;;;;;;;;;AAmBA,IAAa,4BAA4B,8BAA8B,cAAc;;;;uBAI9D,cAAc;8DACyB,cAAc;;;;;;;;;;;;;;AAe5E,eAAsB,0BAA0B,KAAyE;CACrH,MAAM,OAAO,gCAAgC,KAAK,yBAAyB,CAAC,GAAG;CAC/E,MAAM,CAAC,QAAQ,MAAM,IACjB;8BACsB,cAAc,oCACxC;CACA,IAAI,QAAQ,OAAO,KAAK,IAAI,MAAM,MAAM;CAExC,MAAM,CAAC,UAAU,MAAM,IAAI,2BAA2B,cAAc,0BAA0B;CAC9F,IAAI,QAAQ,YAAY,MAAM,MAAM,IAAI,+BAA+B,eAAe;CACtF,MAAM,IAAI,yBAAyB;AACvC;;;;;;;;AASA,IAAa,wBAAwB;;6DAEwB,kBAAkB;sBACzD,kBAAkB;;;;;yEAKiC,kBAAkB;4CAC/C,kBAAkB;;;;AAK9D,eAAsB,sBAAsB,KAAyE;CACjH,MAAM,CAAC,OAAO,MAAM,IAAI,0DAA0D,kBAAkB,cAAc;CAClH,IAAI,KAAK,YAAY,MAAM,MAAM,IAAI,qBAAqB;AAC9D"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"rls-enforcement-CyUCPDH8.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 LOAD_REQUEST_ROLES_PLPGSQL,\n REBASE_INTERNAL_TABLES,\n AUTH_USERS_TABLE,\n REBASE_USER_ROLE,\n revokeInternalTableAccess,\n revokeInternalTableSql,\n securityRuleToConditions\n} from \"@rebasepro/common\";\nimport { holdsAdminRole, REBASE_ADMIN_ROLE, REBASE_SCHEMA, usesLegacyRlsFunctions } from \"@rebasepro/types\";\nimport { logger } from \"@rebasepro/server\";\nimport { extractCauseMessage } from \"../utils/error-cause\";\nimport { cliRlsSettings, type GrantsMode, type ProvisionRoleMode, type RequestIdentity, type RlsSettings } from \"./rls-settings\";\nimport { VIEW_ROWS_COMMENT_PREFIX } from \"../schema/plan/view-names\";\nimport { ADMIN_POLICY_ROLE_SQL } from \"../schema/rls-bootstrap-sql\";\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/** 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/** A `text[]` column as read back — an array, or `{a,b}` from a driver that hands arrays back as text. */\nconst textArrayValue = (value: unknown): string[] => Array.isArray(value)\n ? value.map(String)\n : String(value ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean);\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 request roles hold on one table back — what a\n * table gets when RLS cannot be switched on for it, so it is unreachable\n * rather than unprotected. Quoted exactly: a mixed-case adopted table\n * (`\"User\"`) folded to lower case names a table that does not exist.\n *\n * Every request role, as this database recorded them (`rls.requestRole`), and\n * each only if it exists: one statement, for the boot's policies step and its\n * final posture check alike, without either being handed the roles.\n */\nexport const revokeUserRoleSql = (schema: string, table: string): string => `\n DO $rebase_withhold$\n DECLARE\n request_roles text[];\n request_role text;\n BEGIN\n ${LOAD_REQUEST_ROLES_PLPGSQL}\n FOREACH request_role IN ARRAY request_roles LOOP\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = request_role) THEN\n EXECUTE format('REVOKE ALL PRIVILEGES ON %I.%I FROM %I', ${sqlLiteral(schema)}, ${sqlLiteral(table)}, request_role);\n END IF;\n END LOOP;\n END\n $rebase_withhold$\n`.trim();\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 * The Postgres major from which a role membership carries a separate SET\n * option, as `server_version_num` spells it.\n *\n * From 16, `pg_has_role(…, 'MEMBER')` no longer answers \"may this connection\n * `SET ROLE` to it\": a membership can be held with `SET FALSE`. That is exactly\n * what a non-superuser with CREATEROLE gets for a role it creates — Postgres\n * records the creator as a member `WITH ADMIN TRUE, SET FALSE, INHERIT FALSE`\n * (unless `createrole_self_grant` says otherwise). RDS's master user, Cloud\n * SQL's `postgres`, Neon's owner and most managed \"admin\" users are that kind\n * of role. Asking MEMBER said yes, the grant was skipped, boot logged RLS as\n * active, and every signed-in request then failed with 42501 \"permission\n * denied to set role\". A plain `GRANT` on top changes nothing — Postgres reports\n * the membership as already granted — so the grant has to name the option.\n */\nconst SET_OPTION_SINCE = 160000;\n\n/**\n * Raised when `rebase_user` cannot be provisioned, adopted or switched to —\n * with the SQL that fixes it in {@link instructions}.\n *\n * Its own class so a caller that prints the instructions itself (the CLI) can\n * tell they are already in the message.\n */\nexport class AppRoleSetupError extends Error {\n readonly instructions: string;\n\n constructor(problem: string, instructions: string) {\n super(`${problem}\\n\\n${instructions}`);\n this.name = \"AppRoleSetupError\";\n this.instructions = instructions;\n }\n}\n\n/**\n * What a failed statement said, without the statement.\n *\n * A Drizzle runner throws `Failed query: <sql>\\nparams: <values>` and keeps\n * Postgres's own sentence in `.cause`. The logger redacts from that marker to\n * the next stack frame — the params have no terminator — so any text appended\n * after a Drizzle message is redacted with it. That is how the setup SQL below\n * used to vanish from a production log. Postgres's messages carry no statement\n * and no row values, and they are the part that says what is wrong.\n */\nfunction failureReason(err: unknown): string {\n return extractCauseMessage(err) ?? (err instanceof Error ? err.message : String(err));\n}\n\n/**\n * The statement that lets `connectionRole` switch to the user role, as one\n * statement that works on any Postgres the driver supports.\n *\n * Version-adaptive rather than two alternatives for the reader to choose\n * between: `WITH SET TRUE` is a syntax error before 16, and a plain `GRANT`\n * from 16 on is a no-op on a membership that exists without SET.\n * `INHERIT FALSE` keeps the connection from picking up the user role's\n * privileges as its own; the switch is all it needs.\n */\nfunction membershipGrantSql(connectionRole: string, role: string = REBASE_USER_ROLE): string {\n const member = sqlLiteral(connectionRole);\n const target = sqlLiteral(role);\n return (\n `DO $rebase_grant$\\n` +\n `BEGIN\\n` +\n ` IF current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} THEN\\n` +\n ` EXECUTE format('GRANT %I TO %I WITH SET TRUE, INHERIT FALSE', ${target}, ${member});\\n` +\n ` ELSE\\n` +\n ` EXECUTE format('GRANT %I TO %I', ${target}, ${member});\\n` +\n ` END IF;\\n` +\n `END\\n` +\n `$rebase_grant$;`\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 * or holds it without the right to switch to it.\n *\n * Every statement is safe to re-run and the same text works on Postgres 15 and\n * 16+, so it can be pasted whole whatever state the database is in.\n * `connectionRole` is the role the server connects as; without one, a\n * placeholder Postgres will refuse until it is replaced.\n */\nexport function appRoleSetupInstructions(\n connectionRole: string | undefined,\n schemas: string[],\n role: string = REBASE_USER_ROLE,\n mode: GrantsMode = \"schema\"\n): string {\n const member = connectionRole ?? \"<your database user>\";\n // The schema-wide grants are what the default mode makes; the other modes\n // grant table by table (`managed`) or not at all (`none`), and the\n // connection makes those itself once it may switch.\n const grants = mode !== \"schema\" ? \"\" : schemas.map((s) =>\n `GRANT USAGE ON SCHEMA ${quoteIdent(s)} TO ${role};\\n` +\n `GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${quoteIdent(s)} TO ${role};\\n` +\n `GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${quoteIdent(s)} TO ${role};`\n ).join(\"\\n\");\n return (\n `Rebase enforces row-level security by running authenticated requests as ` +\n `the restricted role \"${role}\", but the connection role ` +\n `\"${member}\" bypasses RLS and cannot set that role up itself.\\n` +\n `Run the following as a database administrator (a superuser, or the role that created ` +\n `\"${role}\"), then restart:\\n\\n` +\n `DO $rebase_role$\\n` +\n `BEGIN\\n` +\n ` IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${sqlLiteral(role)}) THEN\\n` +\n ` CREATE ROLE ${role} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\\n` +\n ` END IF;\\n` +\n `END\\n` +\n `$rebase_role$;\\n` +\n `${membershipGrantSql(member, role)}\\n` +\n grants\n );\n}\n\n/**\n * Refuse a `rebase_user` that would not restrict anything.\n *\n * The role is cluster-wide and found by name, so the one a boot adopts may\n * have been made by anybody — an earlier tool, a hand-written script, another\n * application on the same cluster. Every authenticated request runs as it, so\n * an attribute or a membership that lifts RLS lifts it from all of them, and\n * nothing would say so: requests succeed, with every row.\n *\n * - LOGIN: anyone holding its password connects as the request role directly.\n * - SUPERUSER, BYPASSRLS: RLS does not apply to it at all.\n * - A membership in a role that owns tables here, or is itself a login,\n * superuser or BYPASSRLS role: a member inheriting an owner is the owner for\n * every policy check, and one that may `SET ROLE` to a privileged role is a\n * statement away from it. (`GRANT app TO rebase_user` for `GRANT rebase_user\n * TO app` is the easy way to get here.)\n *\n * A plain NOLOGIN group role is left alone: `validatePolicyPgRoles` sends a\n * project with `pgRoles` to exactly that grant.\n */\nexport async function assertAppRoleRestricted(run: RawSqlRunner, role: string = REBASE_USER_ROLE): Promise<void> {\n const rows = await run(`\n SELECT r.rolcanlogin AS can_login,\n r.rolsuper AS superuser,\n r.rolbypassrls AS bypassrls,\n ARRAY(\n SELECT g.rolname::text FROM pg_roles g\n WHERE g.oid <> r.oid\n AND pg_has_role(r.oid, g.oid, 'MEMBER')\n AND (g.rolsuper OR g.rolbypassrls OR g.rolcanlogin\n OR EXISTS (SELECT 1 FROM pg_class c\n WHERE c.relowner = g.oid AND c.relkind IN ('r', 'p', 'v', 'm', 'f')))\n ORDER BY 1\n ) AS privileged_memberships\n FROM pg_roles r\n WHERE r.rolname = ${sqlLiteral(role)}\n `);\n const row = rows[0];\n if (!row) return;\n const memberships = textArrayValue(row.privileged_memberships);\n const problems: string[] = [];\n const fixes: string[] = [];\n const attributes: string[] = [];\n if (row.can_login === true) { problems.push(\"it can log in (LOGIN)\"); attributes.push(\"NOLOGIN\"); }\n if (row.superuser === true) { problems.push(\"it is a superuser, so RLS does not apply to it\"); attributes.push(\"NOSUPERUSER\"); }\n if (row.bypassrls === true) { problems.push(\"it has BYPASSRLS, so RLS does not apply to it\"); attributes.push(\"NOBYPASSRLS\"); }\n if (attributes.length > 0) fixes.push(`ALTER ROLE ${role} ${attributes.join(\" \")};`);\n if (memberships.length > 0) {\n problems.push(\n `it is a member of ${memberships.map((m) => `\"${m}\"`).join(\", \")} — a role that owns tables or ` +\n \"logs in, or is a superuser or BYPASSRLS — so requests can act as that role\"\n );\n for (const m of memberships) fixes.push(`REVOKE ${quoteIdent(m)} FROM ${role};`);\n }\n if (problems.length === 0) return;\n throw new AppRoleSetupError(\n `Refusing to use the existing \"${role}\" role: every authenticated request runs as it, ` +\n `and ${problems.join(\"; \")}. Row-level security would not restrict those requests.`,\n `Run the following as a database administrator, then restart. If another application on this ` +\n `cluster relies on \"${role}\" being this way, the two cannot share it.\\n\\n` +\n fixes.join(\"\\n\")\n );\n}\n\n/**\n * Prove the connection can switch to the user role, the way every request\n * will, and leave nothing behind.\n *\n * Catalogue answers are only a model of what Postgres will allow. This is the\n * switch itself — `set_config('role', …, true)` is what `applyAuthContext`\n * sends — followed, in the same statement, by switching back to the role the\n * session had, so nothing outlives the probe even when the runner is inside a\n * transaction of its own. A refusal escapes as Postgres's own 42501.\n *\n * Each step is its own subquery level, so the order is the plan's, not the\n * order of a target list: the innermost reads the role the session has, the\n * middle switches, the outer switches back. `OFFSET 0` keeps the levels from\n * being flattened, and a volatile column is never pruned as unused.\n *\n * A `SELECT`, not a `DO` block with a rolled-back subtransaction: the\n * provisioning recorder and the provisioning-off guard both read a leading\n * `DO` as a schema change, and this changes nothing.\n */\nconst roleSwitchProbe = (role: string): string => `\n SELECT set_config('role', switched.previous, true) AS restored\n FROM (\n SELECT session.previous, set_config('role', ${sqlLiteral(role)}, true) AS probe\n FROM (SELECT current_setting('role') AS previous OFFSET 0) session\n OFFSET 0\n ) switched\n`;\n\n/**\n * Run {@link roleSwitchProbe}, and on a refusal throw an\n * {@link AppRoleSetupError} carrying the SQL that grants the switch.\n *\n * For a boot that adopts the role without provisioning it as much as for one\n * that just did: either way the next thing that happens is a request running\n * as it.\n */\nexport async function proveRoleSwitch(\n run: RawSqlRunner,\n schemas: string[],\n connectionRole?: string,\n role: string = REBASE_USER_ROLE\n): Promise<void> {\n try {\n await run(roleSwitchProbe(role));\n } catch (err) {\n const member = connectionRole ?? String((await run(\"SELECT current_user AS role\").catch(() => []))[0]?.role ?? \"\");\n throw new AppRoleSetupError(\n `The connection role \"${member}\" cannot switch to \"${role}\", so every ` +\n `authenticated request would fail: ${failureReason(err)}`,\n appRoleSetupInstructions(member || undefined, Array.from(new Set(schemas.filter(Boolean))), role)\n );\n }\n}\n\n/** The `rebase.schema_meta` key that records which roles requests run as. */\nexport const REQUEST_ROLES_KEY = \"request_roles\";\n\n/**\n * The request roles this database recorded on an earlier provisioning boot, or\n * `undefined` when none has — every database provisioned before the setting\n * existed, which ran as `rebase_user`.\n *\n * Recorded in the database rather than only configured because a role belongs\n * to the cluster and holds grants here: a later boot configured with another\n * name would provision a second role and leave the first one holding every\n * grant. Reading the record is how that boot notices.\n */\nexport async function readRecordedRequestRoles(run: RawSqlRunner): Promise<string[] | undefined> {\n const [present] = await run(`SELECT to_regclass('\"${REBASE_SCHEMA}\".\"schema_meta\"') IS NOT NULL AS present`);\n if (present?.present !== true) return undefined;\n const [row] = await run(`SELECT value FROM \"${REBASE_SCHEMA}\".\"schema_meta\" WHERE key = ${sqlLiteral(REQUEST_ROLES_KEY)}`);\n const value = row?.value === undefined ? \"\" : String(row.value).trim();\n return value === \"\" ? undefined : value.split(\",\").map((r) => r.trim()).filter(Boolean);\n}\n\n/**\n * Record `roles` as this database's request roles, creating `rebase.schema_meta`\n * if nothing has yet. The table is one of Rebase's internal tables, so it is\n * taken back from the request roles here, as its every creator does.\n */\nexport async function recordRequestRoles(run: RawSqlRunner, roles: readonly string[]): Promise<void> {\n // Checked first: `CREATE SCHEMA IF NOT EXISTS` asks for CREATE on the\n // database before it looks, and a connection without it would fail here\n // on a schema that is already there.\n const [schema] = await run(`SELECT to_regnamespace('${REBASE_SCHEMA}') IS NOT NULL AS present`);\n if (schema?.present !== true) await run(`CREATE SCHEMA IF NOT EXISTS \"${REBASE_SCHEMA}\"`);\n await run(`\n CREATE TABLE IF NOT EXISTS \"${REBASE_SCHEMA}\".\"schema_meta\" (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL,\n updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL\n )\n `);\n await run(`\n INSERT INTO \"${REBASE_SCHEMA}\".\"schema_meta\" (key, value)\n VALUES (${sqlLiteral(REQUEST_ROLES_KEY)}, ${sqlLiteral(roles.join(\",\"))})\n ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()\n WHERE \"schema_meta\".value IS DISTINCT FROM EXCLUDED.value\n `);\n await run(revokeInternalTableSql(REBASE_SCHEMA, \"schema_meta\"));\n}\n\n/**\n * Refuse a boot configured with request roles other than the ones this\n * database recorded. The same set in any order is the same.\n *\n * Nothing recorded means `rebase_user`, as every database from before the\n * setting ran — but only where `rebase_user` actually holds grants here. A\n * database it has never been granted on (a fresh one) has nothing to strand,\n * and a new role is simply recorded.\n */\nexport function assertRecordedRequestRoles(\n configured: readonly string[],\n recorded: readonly string[] | undefined,\n defaultRoleHoldsGrants: boolean\n): void {\n if (!recorded && !defaultRoleHoldsGrants) return;\n const effective = recorded ?? [REBASE_USER_ROLE];\n const same = configured.length === effective.length && configured.every((r) => effective.includes(r));\n if (same) return;\n throw new AppRoleSetupError(\n `This database's requests run as ${effective.map((r) => `\"${r}\"`).join(\", \")}` +\n `${recorded ? \"\" : \" (the default, which holds grants here)\"}, but this server is configured ` +\n `for ${configured.map((r) => `\"${r}\"`).join(\", \")} (rls.requestRole / REBASE_RLS_REQUEST_ROLE). ` +\n \"Booting would provision new roles and leave the old ones holding every grant.\",\n \"Move this database to the new role(s) — it re-creates each grant in this database only and records them:\\n\\n\" +\n ` rebase db request-role migrate --to ${configured.join(\",\")}\\n\\n` +\n `Or set the setting back to ${effective.join(\",\")}.`\n );\n}\n\n/** Whether `role` holds any table privilege in `schemas` — something a new role would strand. */\nexport async function roleHoldsTableGrants(run: RawSqlRunner, schemas: readonly string[], role: string = REBASE_USER_ROLE): Promise<boolean> {\n const [row] = await run(`\n SELECT to_regrole(${sqlLiteral(role)}) IS NOT NULL AND EXISTS (\n SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY(${textArray(schemas)}) AND c.relkind IN ('r', 'v', 'm', 'f', 'p')\n AND EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = to_regrole(${sqlLiteral(role)}))\n ) AS holds\n `);\n return row?.holds === true;\n}\n\n/**\n * Login roles other than this connection that can switch into `role`, and so\n * can pass this database's policies as whichever user they like: the settings the\n * policies read can be set by any session.\n *\n * Roles belong to the cluster, so this is how two projects on one cluster\n * sharing `rebase_user` shows up from inside either database. Superusers are\n * left out — they can become any role, and nothing here changes that.\n */\nexport async function findOtherRoleMembers(run: RawSqlRunner, role: string): Promise<string[]> {\n const rows = await run(`\n SELECT r.rolname AS name\n FROM pg_roles r\n WHERE r.rolcanlogin AND NOT r.rolsuper AND r.rolname <> current_user\n AND to_regrole(${sqlLiteral(role)}) IS NOT NULL\n AND pg_has_role(r.oid, to_regrole(${sqlLiteral(role)}),\n CASE WHEN current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} THEN 'SET' ELSE 'MEMBER' END)\n ORDER BY 1\n `);\n return rows.map((row) => String(row.name));\n}\n\n/** How {@link ensureAppRole} provisions: which role, and what it may create and grant. */\nexport interface EnsureAppRoleOptions {\n /** The request role. Default `rebase_user`. */\n role?: string;\n /** `\"never\"`: check the role and the membership, create neither. */\n provisionRole?: ProvisionRoleMode;\n /** What the grant tier grants — see {@link ensureAppRoleGrants}. */\n grants?: GrantsMode;\n /** The tables Rebase serves, for `grants: \"managed\"`. */\n managedTables?: readonly ManagedTable[];\n /** Roles granted to the request role `WITH INHERIT TRUE` (PostgreSQL 16+). */\n inheritRoles?: readonly string[];\n}\n\n/** A table Rebase serves, by schema and name. */\nexport interface ManagedTable {\n schema: string;\n table: string;\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 {@link AppRoleSetupError}, with precise setup instructions, when the\n * role is missing and the connection cannot create it, when an existing role\n * would not restrict anything, and when the connection cannot switch to it.\n * Boot fails then, rather than serving an API whose every signed-in request is\n * refused — or, worse, allowed.\n */\nexport async function ensureAppRole(run: RawSqlRunner, schemas: string[], options: EnsureAppRoleOptions = {}): Promise<void> {\n const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));\n const role = options.role ?? REBASE_USER_ROLE;\n const provision = options.provisionRole !== \"never\";\n\n const [who] = await run(`\n SELECT current_user AS role,\n (SELECT rolsuper FROM pg_roles WHERE rolname = current_user) AS superuser,\n current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS set_option,\n EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${sqlLiteral(role)}) AS role_exists\n `);\n const connectionRole = String(who?.role ?? \"\");\n const superuser = who?.superuser === true;\n const setOption = who?.set_option === true;\n const instructions = () => appRoleSetupInstructions(connectionRole || undefined, uniqueSchemas, role, options.grants);\n\n // Tier 1 — role existence, and a role found rather than made is checked\n // before anything is granted to it or runs as it.\n if (who?.role_exists !== true && !provision) {\n throw new AppRoleSetupError(\n `The request role \"${role}\" does not exist, and rls.provisionRole is \"never\", so Rebase does not create it.`,\n instructions()\n );\n }\n if (who?.role_exists !== true) {\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 = '${role}') THEN\n CREATE ROLE ${role} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\n END\n $rebase_role$\n `);\n } catch (err) {\n throw new AppRoleSetupError(`Failed to create the \"${role}\" role: ${failureReason(err)}`, instructions());\n }\n } else {\n await assertAppRoleRestricted(run, role);\n }\n\n // Tier 2 — membership with the right to SET ROLE to it. A superuser needs\n // none. From 16 that right is its own option, and MEMBER alone is not it.\n if (!superuser) {\n const [membership] = await run(\n `SELECT pg_has_role(current_user, ${sqlLiteral(role)}, '${setOption ? \"SET\" : \"MEMBER\"}') AS can_set`\n );\n if (membership?.can_set !== true && !provision) {\n throw new AppRoleSetupError(\n `The connection role \"${connectionRole}\" may not switch to \"${role}\", and rls.provisionRole is ` +\n `\"never\", so Rebase does not grant itself that.`,\n instructions()\n );\n }\n if (membership?.can_set !== true) {\n try {\n await run(setOption\n ? `GRANT ${role} TO CURRENT_USER WITH SET TRUE, INHERIT FALSE`\n : `GRANT ${role} TO CURRENT_USER`);\n } catch (err) {\n throw new AppRoleSetupError(\n `The connection role \"${connectionRole}\" may not switch to \"${role}\" ` +\n `${setOption ? \"(no membership WITH SET TRUE)\" : \"(not a member)\"} and cannot grant that ` +\n `to itself: ${failureReason(err)}`,\n instructions()\n );\n }\n }\n }\n\n // Tier 2b — the switch itself. Without this the boot logged enforcement as\n // active on a connection Postgres would refuse on the first request.\n await proveRoleSwitch(run, uniqueSchemas, connectionRole || undefined, role);\n\n // Tier 2c — roles whose `TO` policies should apply to requests.\n if (options.inheritRoles?.length) await ensureInheritedRoles(run, role, options.inheritRoles);\n\n // Tier 3 — grants.\n await ensureAppRoleGrants(run, uniqueSchemas, { role, mode: options.grants, managedTables: options.managedTables });\n\n logger.debug(`🔐 [rls] User role \"${role}\" provisioned (schemas: ${uniqueSchemas.join(\", \")})`);\n}\n\n/**\n * SQL: whether `c` (in namespace `n`) is a table the request roles are kept\n * off when RLS is off on it — see `withheldTablesIn`.\n */\nconst isWithheldTable = (c: string, n: string): string =>\n `(${c}.relname = ANY(${textArray(REBASE_INTERNAL_TABLES)}) OR (${n}.nspname = ${sqlLiteral(AUTH_USERS_TABLE.schema)} AND ${c}.relname = ${sqlLiteral(AUTH_USERS_TABLE.table)}))`;\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[], role: string = REBASE_USER_ROLE): 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 ${isWithheldTable(\"c\", \"n\")}\n AND c.relkind IN ('r', 'p')\n AND NOT c.relrowsecurity\n AND (has_table_privilege(${sqlLiteral(role)}, c.oid, 'SELECT, INSERT, UPDATE, DELETE')\n OR has_any_column_privilege(${sqlLiteral(role)}, c.oid, 'SELECT, INSERT, UPDATE'))\n ORDER BY 1\n `);\n return rows.map(row => String(row.name));\n}\n\n/** The connection role's oid, for a catalogue read. */\nconst CURRENT_ROLE_OID = \"(SELECT oid FROM pg_roles WHERE rolname = current_user)\";\n\n/**\n * SQL: may this connection grant every one of `privileges` on an object?\n *\n * Its owner, a role that inherits the owner, or a superuser — `pg_has_role`\n * answers yes for all three — or a role holding each privilege `WITH GRANT\n * OPTION`. Every one, because a grant short of one only warns and leaves the\n * object reading as missing, which is the boot-after-boot re-grant this exists\n * to stop.\n */\nfunction mayGrant(kind: \"schema\" | \"table\" | \"sequence\", oid: string, owner: string, privileges: readonly string[]): string {\n const withGrantOption = privileges\n .map((p) => `has_${kind}_privilege(current_user, ${oid}, ${sqlLiteral(`${p} WITH GRANT OPTION`)})`)\n .join(\" AND \");\n return `(pg_has_role(current_user, ${owner}, 'USAGE') OR (${withGrantOption}))`;\n}\n\n/**\n * Tables collections are served from that the user role holds no privilege on\n * and this connection cannot grant it, because another role owns them.\n *\n * The grant tier passes these over — it could only fail on them — so on a\n * database another application shares, a collection over that application's\n * table boots and then refuses every request with \"permission denied\". This\n * names them, with the owner who can run the grant. Refusing rather than\n * widening, so the boot warns instead of stopping: the rest of the project\n * works, and an introspected project serves every table in the schema,\n * whoever owns it.\n */\nexport async function findUngrantableTables(\n run: RawSqlRunner,\n tables: readonly ManagedTable[],\n role: string = REBASE_USER_ROLE\n): Promise<{ name: string; owner: string; grant: string }[]> {\n if (tables.length === 0) return [];\n const rows = await run(`\n SELECT n.nspname AS schema, c.relname AS table, pg_get_userbyid(c.relowner) AS owner\n FROM unnest(${textArray(tables.map((t) => t.schema))}, ${textArray(tables.map((t) => t.table))}) AS w(s, t)\n JOIN pg_namespace n ON n.nspname = w.s\n JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = w.t\n WHERE NOT ${mayGrant(\"table\", \"c.oid\", \"c.relowner\", USER_TABLE_PRIVILEGES.split(\", \"))}\n AND NOT has_table_privilege(to_regrole(${sqlLiteral(role)}), c.oid, 'SELECT, INSERT, UPDATE, DELETE')\n ORDER BY 1, 2\n `);\n return rows.map((row) => {\n const name = `${quoteIdent(String(row.schema))}.${quoteIdent(String(row.table))}`;\n return { name, owner: String(row.owner), grant: `GRANT ${USER_TABLE_PRIVILEGES} ON ${name} TO ${role};` };\n });\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 — or nothing this connection could grant. */\n usage: boolean;\n /**\n * Relations (`GRANT … ON ALL TABLES` reaches the same kinds) still missing\n * one of the four DML privileges from their owner, among those this\n * connection may grant on. Rebase's own RLS-off tables are left out: they\n * are never to have them.\n *\n * Only the grantable ones, because the rest can never be completed from\n * here. A shared `public` holding another application's table used to make\n * this \"missing\" forever: every boot re-ran a schema-wide grant that\n * Postgres refused for that table, with an error that aborted boot or a\n * warning that came back on the next one.\n */\n tables: string[];\n /** Sequences still missing `USAGE, SELECT` from their owner, among those this connection may grant on. */\n sequences: string[];\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 * The stored rows of materialized-view collections (`view-names.ts`) the\n * user role holds a privilege on. Only the owner may read them; the\n * schema-wide grant hands them out like any relation, so they are taken\n * back after it.\n */\n viewRowsGranted: 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, or this connection itself, which\n * is what a GRANT on its grant option 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(\n run: RawSqlRunner,\n schemas: string[],\n role: string = REBASE_USER_ROLE,\n managedTables?: readonly ManagedTable[]\n): Promise<Map<string, SchemaGrants>> {\n // `grants: \"managed\"`: only the tables Rebase serves, and the sequences\n // those tables own (serial and identity columns).\n const managed = managedTables\n ? `(SELECT * FROM unnest(${textArray(managedTables.map((t) => t.schema))}, ${textArray(managedTables.map((t) => t.table))}))`\n : undefined;\n const onlyManagedTables = managed ? `AND (n.nspname, c.relname::text) IN ${managed}` : \"\";\n const onlyManagedSequences = managed\n ? `AND EXISTS (SELECT 1 FROM pg_depend d JOIN pg_class t ON t.oid = d.refobjid\n WHERE d.objid = c.oid AND d.deptype IN ('a', 'i')\n AND (n.nspname, t.relname::text) IN ${managed})`\n : \"\";\n const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(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 IN (${grantor}, ${CURRENT_ROLE_OID})` : \"\"} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(\", \")}))`;\n const DML = [\"SELECT\", \"INSERT\", \"UPDATE\", \"DELETE\"];\n const SEQ = [\"USAGE\", \"SELECT\"];\n const viewRows = (alias: string): string =>\n `(${alias}.relkind = 'm' AND COALESCE(obj_description(${alias}.oid, 'pg_class'), '') LIKE '${VIEW_ROWS_COMMENT_PREFIX}%')`;\n const rows = await run(`\n SELECT n.nspname AS schema,\n -- Settled as well when this connection cannot grant it: a schema\n -- another role owns (a shared database's \\`public\\`) only warned,\n -- and was re-granted on every boot. PUBLIC's own USAGE covers it there.\n (${held(\"n.nspacl\", [\"USAGE\"], \"n.nspowner\")} = 1\n OR NOT ${mayGrant(\"schema\", \"n.oid\", \"n.nspowner\", [\"USAGE\"])}) AS usage,\n ARRAY(\n SELECT c.relname::text FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')\n AND NOT (${isWithheldTable(\"c\", \"n\")} AND NOT c.relrowsecurity)\n AND ${mayGrant(\"table\", \"c.oid\", \"c.relowner\", DML)}\n ${onlyManagedTables}\n AND NOT ${viewRows(\"c\")}\n AND ${held(\"c.relacl\", DML, \"c.relowner\")} < ${DML.length}\n ORDER BY 1\n ) AS tables,\n ARRAY(\n SELECT c.relname::text FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relkind = 'S'\n AND ${mayGrant(\"sequence\", \"c.oid\", \"c.relowner\", SEQ)}\n ${onlyManagedSequences}\n AND ${held(\"c.relacl\", SEQ, \"c.relowner\")} < ${SEQ.length}\n ORDER BY 1\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 ${isWithheldTable(\"c\", \"n\")} 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 ARRAY(\n SELECT c.relname::text FROM pg_class c\n WHERE c.relnamespace = n.oid AND ${viewRows(\"c\")}\n AND EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target})\n ORDER BY 1\n ) AS view_rows_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 const viewRowsGranted = row.view_rows_granted;\n grants.set(String(row.schema), {\n usage: row.usage === true,\n tables: textArrayValue(row.tables),\n sequences: textArrayValue(row.sequences),\n defaultTables: row.default_tables === true,\n defaultSequences: row.default_sequences === true,\n internalGranted: textArrayValue(internalGranted),\n viewRowsGranted: textArrayValue(viewRowsGranted)\n });\n }\n return grants;\n}\n\n/** What {@link ensureAppRoleGrants} grants, and to whom. */\nexport interface AppRoleGrantOptions {\n /** The request role. Default `rebase_user`. */\n role?: string;\n /**\n * `\"schema\"` (default): every table and sequence in the schemas that this\n * connection may grant on, and default privileges for later ones.\n * `\"managed\"`: only {@link managedTables} and the sequences they own, no\n * default privileges. `\"none\"`: nothing, not even the revoke sweep.\n */\n mode?: GrantsMode;\n managedTables?: readonly ManagedTable[];\n}\n\n/**\n * Grant each of `inheritRoles` to the request role `WITH INHERIT TRUE`, so a\n * policy written `TO` one of them — Supabase's `authenticated`, say — applies\n * to requests.\n *\n * PostgreSQL 16 and newer only. From 16 inheritance is an option of each\n * grant, so the request role takes on these roles' privileges and stays\n * NOINHERIT towards every other membership. Before 16 the only lever is the\n * role's own INHERIT attribute, which would hand it every role it belongs to;\n * that is refused rather than done.\n */\nexport async function ensureInheritedRoles(run: RawSqlRunner, role: string, inheritRoles: readonly string[]): Promise<void> {\n const [server] = await run(`SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant`);\n if (server?.per_grant !== true) {\n throw new AppRoleSetupError(\n `rls.inheritRoles (${inheritRoles.join(\", \")}) needs PostgreSQL 16 or newer: before 16 the request role ` +\n `\"${role}\" can only inherit by inheriting from every role it belongs to.`,\n \"Upgrade to PostgreSQL 16+, or drop rls.inheritRoles and express those policies as the collection's securityRules.\"\n );\n }\n const rows = await run(`\n SELECT w.name, r.oid IS NOT NULL AS present,\n COALESCE(pg_has_role(to_regrole(${sqlLiteral(role)}), r.oid, 'USAGE'), false) AS inherits\n FROM unnest(${textArray(inheritRoles)}) AS w(name)\n LEFT JOIN pg_roles r ON r.rolname = w.name\n `);\n const missing = rows.filter((row) => row.present !== true).map((row) => String(row.name));\n if (missing.length > 0) {\n throw new AppRoleSetupError(\n `rls.inheritRoles names ${missing.map((m) => `\"${m}\"`).join(\", \")}, which ${missing.length === 1 ? \"does\" : \"do\"} not exist in this cluster.`,\n \"Create the role(s), or remove them from rls.inheritRoles.\"\n );\n }\n for (const row of rows) {\n if (row.inherits === true) continue;\n const name = String(row.name);\n const grant = `GRANT ${quoteIdent(name)} TO ${quoteIdent(role)} WITH INHERIT TRUE, SET FALSE`;\n try {\n await run(grant);\n } catch (err) {\n throw new AppRoleSetupError(\n `Could not grant \"${name}\" to the request role \"${role}\" for rls.inheritRoles: ${failureReason(err)}`,\n `Run as a database administrator, then restart:\\n\\n${grant};`\n );\n }\n }\n}\n\n/**\n * Provision the role admin requests run as for one request role:\n * `<role>_admin`, inheriting `role` — its grants, and every policy written\n * for it — and {@link REBASE_ADMIN_ROLE}, with the connection able to switch\n * to it. The role itself goes through {@link ensureAppRole} (created NOLOGIN\n * NOSUPERUSER NOBYPASSRLS, checked as restricted when found, the switch\n * proved), with no grants of its own: everything it can reach, it reaches as\n * `role` does.\n *\n * Inheriting is per grant from PostgreSQL 16 (`WITH INHERIT TRUE`); before\n * that it is the role's own `INHERIT` attribute, harmless here because this\n * role belongs to exactly the two roles granted below.\n */\nexport async function ensureAdminRequestRole(\n run: RawSqlRunner,\n schemas: string[],\n options: { role: string; adminRole: string; provisionRole?: ProvisionRoleMode }\n): Promise<void> {\n const { role, adminRole } = options;\n const provision = options.provisionRole !== \"never\";\n const [present] = await run(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') AS present`);\n if (present?.present !== true) {\n if (!provision) {\n throw new AppRoleSetupError(\n `The role \"${REBASE_ADMIN_ROLE}\" does not exist, and rls.provisionRole is \"never\", so Rebase does not create it.`,\n `Run as a database administrator, then restart:\\n\\nCREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;`\n );\n }\n await run(ADMIN_POLICY_ROLE_SQL);\n }\n\n await ensureAppRole(run, schemas, { role: adminRole, provisionRole: options.provisionRole, grants: \"none\" });\n\n const [state] = await run(`\n SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,\n r.rolinherit AS inherits_all,\n pg_has_role(r.oid, to_regrole(${sqlLiteral(role)}), 'USAGE') AS has_request_role,\n pg_has_role(r.oid, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE') AS has_admin_role\n FROM pg_roles r WHERE r.rolname = ${sqlLiteral(adminRole)}\n `);\n const perGrant = state?.per_grant === true;\n const missing = [\n ...(state?.has_request_role === true ? [] : [role]),\n ...(state?.has_admin_role === true ? [] : [REBASE_ADMIN_ROLE])\n ];\n if (missing.length === 0) return;\n const statements = [\n ...(!perGrant && state?.inherits_all !== true ? [`ALTER ROLE ${adminRole} INHERIT`] : []),\n ...missing.map((granted) => perGrant\n ? `GRANT ${quoteIdent(granted)} TO ${adminRole} WITH INHERIT TRUE, SET FALSE`\n : `GRANT ${quoteIdent(granted)} TO ${adminRole}`)\n ];\n const instructions = `Run as a database administrator, then restart:\\n\\n${statements.map((st) => `${st};`).join(\"\\n\")}`;\n if (!provision) {\n throw new AppRoleSetupError(\n `The admin request role \"${adminRole}\" does not inherit ${missing.map((m) => `\"${m}\"`).join(\" and \")}, and ` +\n \"rls.provisionRole is \\\"never\\\", so Rebase does not grant it.\",\n instructions\n );\n }\n try {\n for (const statement of statements) await run(statement);\n } catch (err) {\n throw new AppRoleSetupError(\n `Could not let the admin request role \"${adminRole}\" inherit ${missing.map((m) => `\"${m}\"`).join(\" and \")}: ${failureReason(err)}`,\n instructions\n );\n }\n}\n\n/**\n * Let the connection role itself pass the server-or-admin policies, by\n * inheriting {@link REBASE_ADMIN_ROLE} — which is what `TO public` gave it.\n *\n * It matters where the connection is subject to RLS: always, when it owns\n * none of the tables (requests then run as the connection itself, so the\n * server context and admins depend on it), and on any table it does not own\n * otherwise. Best effort: a connection that cannot be granted the role is\n * told what to run, and its server-context and admin reads of those tables are\n * refused — closed, never wider — until someone does.\n */\nexport async function ensureConnectionInheritsAdminRole(run: RawSqlRunner, options: { provision: boolean }): Promise<void> {\n const [state] = await run(`\n SELECT current_user AS role,\n (SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user) AS exempt,\n current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,\n to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present,\n COALESCE(pg_has_role(current_user, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false) AS inherits\n `);\n if (state?.exempt === true || state?.inherits === true) return;\n const connection = String(state?.role ?? \"\");\n const grant = state?.per_grant === true\n ? `GRANT ${REBASE_ADMIN_ROLE} TO ${quoteIdent(connection)} WITH INHERIT TRUE, SET FALSE`\n : `GRANT ${REBASE_ADMIN_ROLE} TO ${quoteIdent(connection)}`;\n // Only once the role exists can a policy be written TO it; until then the\n // policies step keeps them TO public, and there is nothing to refuse.\n const warn = (why: string, roleExists: boolean) => (roleExists ? (m: string) => logger.warn(m) : (m: string) => logger.debug(m))(\n `⚠️ RLS enforcement: the connection role \"${connection}\" does not inherit \"${REBASE_ADMIN_ROLE}\" (${why}), ` +\n \"so on any table it does not own, its server-context and admin requests do not pass the server-or-admin \" +\n `policies and are refused. Run as an administrator: ${roleExists ? \"\" : `CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN; `}${grant}; ` +\n \"— or declare rls.adminPolicies \\\"public\\\".\"\n );\n if (!options.provision) {\n warn(\"this driver was opened without provisioning\", state?.present === true);\n return;\n }\n let roleExists = state?.present === true;\n try {\n if (!roleExists) await run(ADMIN_POLICY_ROLE_SQL);\n roleExists = true;\n await run(grant);\n } catch (err) {\n warn(failureReason(err), roleExists);\n }\n}\n\n/**\n * The request identity a boot hands the driver and the realtime refetch, with\n * the admin switch on when every admin request role is ready: provisioned\n * here, or — on a boot that provisions nothing — found existing, inheriting\n * what it should and switchable. Otherwise admin requests run as the request\n * role, as before, and the boot says why: under `adminPolicies: \"adminRole\"`,\n * policies already written `TO rebase_admin` then refuse them.\n */\nexport async function settleAdminRequestRoles(\n run: RawSqlRunner,\n schemas: string[],\n settings: RlsSettings,\n options: { provision: boolean }\n): Promise<RequestIdentity> {\n if (settings.adminRoles.size === 0) return settings.request;\n const failures: string[] = [];\n for (const [role, adminRole] of settings.adminRoles) {\n try {\n // A boot that provisions nothing only checks: \"never\" creates and\n // grants nothing, and refuses what is not already there.\n await ensureAdminRequestRole(run, schemas, {\n role, adminRole, provisionRole: options.provision ? settings.provisionRole : \"never\"\n });\n } catch (err) {\n failures.push(`\"${adminRole}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n if (failures.length > 0) {\n // The policies step then writes the server-or-admin policies TO public\n // (`settleAdminSwitch`), which the request role passes: as before, and\n // nothing refused. Louder when `rebase_admin` exists, since that is a\n // setup someone started and this server cannot finish.\n const [marker] = await run(`SELECT to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present`);\n (marker?.present === true ? (m: string) => logger.warn(m) : (m: string) => logger.info(m))(\n `${marker?.present === true ? \"⚠️\" : \"🔐\"} RLS enforcement: admin requests keep running as the request role, because ${failures.join(\"; \")}. ` +\n `The server-or-admin policies are written TO public by this server until that is fixed, so signed-in ` +\n `users' owner-scoped reads cannot use the owner index. Create ${REBASE_ADMIN_ROLE} and the admin request role ` +\n \"as above to change that, or declare adminPolicies \\\"public\\\" to say this on purpose.\"\n );\n return settings.request;\n }\n const adminRoles = settings.adminRoles;\n return { ...settings.request, adminRoleFor: (role) => adminRoles.get(role) };\n}\n\n/**\n * Whether policies written `TO rebase_admin` reach every caller they are for on\n * this connection, read from the catalogue without changing anything: the role\n * exists, the connection passes it (exempt from RLS, or inheriting it — the\n * server context on tables it does not own), and each of `adminRoles` exists,\n * inherits its request role and `rebase_admin`, and the connection can switch\n * into it. The state {@link settleAdminRequestRoles} and\n * {@link ensureConnectionInheritsAdminRole} leave when both succeed.\n *\n * With `existingOnly`, an admin role that does not exist is passed over, but at\n * least one must be ready: for a role list read back from the database, which\n * does not say which role is an anonymous one with no admin counterpart.\n *\n * Anything it cannot read answers `false`, and `false` means `TO public`: the\n * shape every caller passes, as before the admin role existed.\n */\nexport async function adminSwitchLive(\n run: RawSqlRunner,\n adminRoles: ReadonlyMap<string, string>,\n options: { existingOnly?: boolean } = {}\n): Promise<boolean> {\n if (adminRoles.size === 0) return false;\n const [connection] = await run(`\n SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,\n to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present,\n COALESCE((SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user), false)\n OR COALESCE(pg_has_role(current_user, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false) AS passes\n `);\n if (connection?.present !== true || connection?.passes !== true) return false;\n // Switching is the SET option from 16 on; before it, any membership.\n const privilege = connection.per_grant === true ? \"SET\" : \"MEMBER\";\n let ready = 0;\n for (const [role, adminRole] of adminRoles) {\n const [state] = await run(`\n SELECT to_regrole(${sqlLiteral(adminRole)}) IS NOT NULL AS present,\n COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole(${sqlLiteral(role)}), 'USAGE'), false)\n AND COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false)\n AND COALESCE(pg_has_role(current_user, to_regrole(${sqlLiteral(adminRole)}), '${privilege}'), false) AS ready\n `);\n if (options.existingOnly && state?.present !== true) continue;\n if (state?.ready !== true) return false;\n ready++;\n }\n return ready > 0;\n}\n\n/**\n * The admin switch for a boot whose requests switch roles: settle the admin\n * request roles and the connection's `rebase_admin`, then say whether the\n * switch is live — which is what decides where the policies step writes the\n * server-or-admin policies. `TO rebase_admin` only when it is: written there\n * while admin requests still run as the request role, they refuse every admin\n * caller, `dataAsAdmin` included, as an empty table. Otherwise `TO public`, the\n * documented fallback, which the request role passes.\n */\nexport async function settleAdminSwitch(\n run: RawSqlRunner,\n schemas: string[],\n settings: RlsSettings,\n options: { provision: boolean }\n): Promise<{ request: RequestIdentity; adminPoliciesLive: boolean }> {\n const request = await settleAdminRequestRoles(run, schemas, settings, options);\n if (settings.adminPolicies !== \"adminRole\") return { request, adminPoliciesLive: false };\n await ensureConnectionInheritsAdminRole(run, options);\n const adminPoliciesLive = request.adminRoleFor !== undefined && await adminSwitchLive(run, settings.adminRoles);\n return { request, adminPoliciesLive };\n}\n\n/**\n * Where `db push` and `rebase doctor` expect the server-or-admin policies, for\n * the request roles this database records (or the configured ones): `TO\n * rebase_admin` only when {@link adminSwitchLive} says a server on this\n * connection would have the switch live, `TO public` otherwise — the same\n * answer a boot reaches, without provisioning anything. Settings that do not\n * resolve answer `false`.\n */\nexport async function adminPoliciesLiveForCli(run: RawSqlRunner): Promise<boolean> {\n try {\n const settings = cliRlsSettings(await readRecordedRequestRoles(run));\n if (settings.adminPolicies !== \"adminRole\") return false;\n return await adminSwitchLive(run, settings.adminRoles, { existingOnly: true });\n } catch {\n return false;\n }\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.\n *\n * Tables and sequences are granted by name, the ones that are missing it and\n * that this connection may grant on — not `ON ALL … IN SCHEMA`, which also\n * tries every relation another role owns. On a schema shared with another\n * application that statement fails for a table this connection holds no\n * privilege on, or only warns for one it holds without grant option, and either\n * way the schema never reads as granted. The ACLs this leaves are the ones the\n * schema-wide statement left on everything it could reach.\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[], options: AppRoleGrantOptions = {}): Promise<void> {\n const role = options.role ?? REBASE_USER_ROLE;\n const mode = options.mode ?? \"schema\";\n // `none`: grants are the operator's, and so are revokes — nothing here.\n if (mode === \"none\") return;\n const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));\n const grants = await readSchemaGrants(run, uniqueSchemas, role, mode === \"managed\" ? options.managedTables ?? [] : undefined);\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 ${role}`);\n const named = (relations: string[]) => relations.map((r) => `${s}.${quoteIdent(r)}`).join(\", \");\n if (state.tables.length > 0) {\n await run(`GRANT ${USER_TABLE_PRIVILEGES} ON TABLE ${named(state.tables)} TO ${role}`);\n }\n if (state.sequences.length > 0) {\n await run(`GRANT USAGE, SELECT ON SEQUENCE ${named(state.sequences)} TO ${role}`);\n }\n // The stored rows of a materialized-view collection are the owner's\n // alone (`view-names.ts`). The grants above name them out; a default\n // privilege, or the schema-wide grant an older release ran, did not.\n for (const rows of state.viewRowsGranted) await run(`REVOKE ALL ON ${s}.${quoteIdent(rows)} FROM ${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. Not in\n // `managed`: a default privilege cannot tell Rebase's next table from\n // anybody else's.\n if (!state.defaultTables && mode === \"schema\") {\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${role}`);\n }\n if (!state.defaultSequences && mode === \"schema\") {\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${role}`);\n }\n\n // The grants above deliberately cover the whole schema — 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. The grant above leaves them out;\n // taking back what someone else gave them covers every table that\n // already exists, and each creator revokes on the table it just made,\n // for the boot that creates them for the first time.\n if (state.internalGranted.length === 0) continue;\n await revokeInternalTableAccess(async (text) => { await run(text); }, schema, {\n tables: state.internalGranted,\n onError: (table, error) => logger.warn(\n `🔐 [rls] Could not revoke \"${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, role: string = REBASE_USER_ROLE): Promise<string[]> {\n return (await readSchemaGrants(run, [schema], role)).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 | RequestIdentity): Promise<void> {\n const settings = authContextSettings(auth, userRole);\n await tx.execute(drizzleSql`SELECT ${drizzleSql.join(\n settings.map(([name, value]) => drizzleSql`${drizzleSql.raw(`set_config(${settingNameLiteral(name)}, `)}${value}, true)`),\n drizzleSql`, `\n )}`);\n}\n\n/**\n * {@link applyAuthContext} as one statement and its values, for a transaction\n * that sends it in the same batch as its first query\n * (`pipelined-transaction.ts`). `before` are settings of the transaction's own\n * — what a pooled connection could not carry at connect — set ahead of the\n * caller's, in the same statement.\n */\nexport function authContextStatement(\n auth: AuthContext,\n userRole?: string | RequestIdentity,\n before: readonly (readonly [string, string])[] = []\n): { text: string; values: string[] } {\n const settings = [...before, ...authContextSettings(auth, userRole)];\n return {\n text: `SELECT ${settings.map(([name], i) => `set_config(${settingNameLiteral(name)}, $${i + 1}, true)`).join(\", \")}`,\n values: settings.map(([, value]) => value)\n };\n}\n\n/**\n * A setting's name as a SQL literal. Names are this module's constants (and\n * the pooled settings' two), never a caller's value, which is a bound\n * parameter; written into the text so a statement log reads as the settings\n * it sets.\n */\nfunction settingNameLiteral(name: string): string {\n return `'${name.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * The transaction-local settings that make a transaction the caller's, in the\n * order they are set: the `app.*` GUCs, then the role.\n *\n * `userRole` is the role to switch to — or, for a project whose requests do not\n * all run as one role or carry their identity in more than `app.*`, the\n * resolved `rls` settings ({@link RequestIdentity}), which choose the role for\n * this caller and add their own settings ahead of the switch.\n */\nfunction authContextSettings(auth: AuthContext, userRole?: string | RequestIdentity): [string, string][] {\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 const settings: [string, string][] = [\n [\"app.uid\", uid],\n [\"app.user_id\", uid],\n [\"app.user_roles\", normalizedRoles.join(\",\")],\n [\"app.is_anonymous\", isAnonymous],\n [\"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 })]\n ];\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 const role = typeof userRole === \"object\" ? userRole.roleFor(auth) : userRole;\n // Another convention's identity settings (`rls.identity`), after Rebase's\n // own and before the switch, so the switch stays last.\n if (typeof userRole === \"object\" && role) {\n for (const [name, value] of userRole.settingsFor(auth, role)) settings.push([name, value]);\n }\n // A caller the `admin` arm of a policy would pass runs as the role that\n // inherits `rebase_admin`, the only role the server-or-admin policies apply\n // to (`adminPolicies: \"adminRole\"`). Decided from the same comma-joined\n // `app.user_roles` those policies split, so the two cannot disagree about\n // who is an admin. Everyone else stays on `role`, whose plans no longer\n // carry those policies at all.\n const admin = role && typeof userRole === \"object\" && holdsAdminRole(normalizedRoles.map(String))\n ? userRole.adminRoleFor?.(role)\n : undefined;\n if (role) settings.push([\"role\", admin ?? role]);\n return settings;\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 whose privileges `rebase_user` has. Anything else is a\n * configuration error worth failing the boot for.\n *\n * Privileges, not membership: Postgres applies a policy `TO r` to a role that\n * has `r`'s privileges, which a member only gets by inheriting them, and\n * `rebase_user` is `NOINHERIT`. This used to ask `pg_has_role(…, 'MEMBER')`, so\n * `GRANT authenticated TO rebase_user` — the grant its own hint suggested —\n * passed here and still read every collection as empty.\n */\nexport async function validatePolicyPgRoles(\n run: RawSqlRunner,\n collections: { slug?: string; securityRules?: readonly { name?: string; pgRoles?: readonly string[] }[] }[],\n /** The role(s) requests actually run as: `rebase_user` (or the `rls.requestRole`\n * roles) when the connection is privileged enough to switch, otherwise the\n * connection role itself. With several, a role is usable when any reaches it. */\n requestRoles: string | readonly string[] = REBASE_USER_ROLE\n): Promise<void> {\n const candidates = typeof requestRoles === \"string\" ? [requestRoles] : [...requestRoles];\n const requestRole = candidates[0] ?? REBASE_USER_ROLE;\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\" || candidates.includes(role)) 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(bool_or(pg_has_role(to_regrole(req.name), r.oid, 'USAGE')), false) AS reachable,\n COALESCE(bool_or(pg_has_role(to_regrole(req.name), r.oid, 'MEMBER')), false) AS member\n FROM pg_roles r CROSS JOIN unnest(${textArray(candidates)}) AS req(name)\n WHERE r.rolname IN (${names})\n GROUP BY r.rolname\n `);\n const [server] = await run(`\n SELECT current_setting('server_version_num')::int >= 160000 AS per_grant_inherit,\n (SELECT rolinherit FROM pg_roles WHERE oid = to_regrole('${escapedRequestRole}')) AS inherits\n `);\n // From 16 inheritance is an option of each grant, so one membership can pass\n // its privileges on while the role stays NOINHERIT for every other. Before\n // 16 it is the role's attribute: a NOINHERIT role inherits from nothing.\n const grantThatWorks = (role: string): string | undefined =>\n server?.per_grant_inherit === true\n ? `GRANT ${role} TO ${requestRole} WITH INHERIT TRUE`\n : server?.inherits === true ? `GRANT ${role} TO ${requestRole}` : undefined;\n\n const found = new Map(rows.map((row) => [String(row.role), row]));\n const problems: string[] = [];\n\n for (const [role, slugs] of wanted) {\n const row = found.get(role);\n if (row?.reachable === true) continue;\n\n const why = !row\n ? \"no such role exists in this database\"\n : row.member === true\n ? `\"${requestRole}\" is a member of it but does not inherit its privileges, so its policies do not apply`\n : `\"${requestRole}\" is not a member of it`;\n const platform = FOREIGN_CONVENTION_ROLES[role];\n const grant = grantThatWorks(role);\n const hint = platform && !row\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 : grant\n ? `Either grant it (${grant}) or drop \\`pgRoles\\` so the policy targets \\`public\\`.`\n : `\"${requestRole}\" is NOINHERIT, and before PostgreSQL 16 a NOINHERIT role takes on no other role's policies. 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6IA,IAAM,cAAc,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;;AAG5E,IAAM,cAAc,UAA0B,IAAI,MAAM,QAAQ,MAAM,IAAI,EAAE;AAC5E,IAAM,aAAa,WACf,OAAO,WAAW,IAAI,oBAAoB,SAAS,OAAO,IAAI,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE;;AAEzF,IAAM,kBAAkB,UAA6B,MAAM,QAAQ,KAAK,IAClE,MAAM,IAAI,MAAM,IAChB,OAAO,SAAS,EAAE,CAAC,CAAC,QAAQ,YAAY,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;;AAG3E,IAAM,wBAAwB;;;;;;;;;;;AAY9B,IAAa,qBAAqB,QAAgB,UAA0B;;;;;;UAMlE,2BAA2B;;;2EAGsC,WAAW,MAAM,EAAE,IAAI,WAAW,KAAK,EAAE;;;;;EAKlH,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BP,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;;;;;;;;;;;;;;u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