@rebasepro/server-postgres 0.33.2 → 0.34.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BranchService-Bdin0Wxh.js → BranchService-BLcVK_Rd.js} +3 -3
- package/dist/{BranchService-Bdin0Wxh.js.map → BranchService-BLcVK_Rd.js.map} +1 -1
- package/dist/{backup-cli-BEAMPWMs.js → backup-cli-CVLOCTo_.js} +3 -3
- package/dist/{backup-cli-BEAMPWMs.js.map → backup-cli-CVLOCTo_.js.map} +1 -1
- package/dist/{boot-ddl-Bu6gAY-2.js → boot-ddl-C7hAFEvY.js} +2 -2
- package/dist/{boot-ddl-Bu6gAY-2.js.map → boot-ddl-C7hAFEvY.js.map} +1 -1
- package/dist/{cli-console-BU_Rf22O.js → cli-console-E5TM3GaL.js} +4 -4
- package/dist/{cli-console-BU_Rf22O.js.map → cli-console-E5TM3GaL.js.map} +1 -1
- package/dist/{cli-schema-dir-CjDH_31U.js → cli-schema-dir-CdEqBcph.js} +29 -10
- package/dist/cli-schema-dir-CdEqBcph.js.map +1 -0
- package/dist/cli.js +29 -27
- package/dist/cli.js.map +1 -1
- package/dist/{database-preflight-DKzsGnc4.js → database-preflight-NmFI_rFN.js} +2 -2
- package/dist/{database-preflight-DKzsGnc4.js.map → database-preflight-NmFI_rFN.js.map} +1 -1
- package/dist/{deferred-index-build-88bWtYgx.js → deferred-index-build-Bz37bvxW.js} +4 -4
- package/dist/{deferred-index-build-88bWtYgx.js.map → deferred-index-build-Bz37bvxW.js.map} +1 -1
- package/dist/{ensure-policies-nIITKxud.js → ensure-policies-C1UCom37.js} +6 -6
- package/dist/{ensure-policies-nIITKxud.js.map → ensure-policies-C1UCom37.js.map} +1 -1
- package/dist/{ensure-tables-hQ5oAK_j.js → ensure-tables-BVUNi6uG.js} +3 -3
- package/dist/{ensure-tables-hQ5oAK_j.js.map → ensure-tables-BVUNi6uG.js.map} +1 -1
- package/dist/{ensure-tables-Lm-77eM5.js → ensure-tables-DjuNRClr.js} +7 -7
- package/dist/{ensure-tables-Lm-77eM5.js.map → ensure-tables-DjuNRClr.js.map} +1 -1
- package/dist/{enum-labels-kept-mesgEJWH.js → enum-labels-kept-DrCueSHr.js} +2 -2
- package/dist/{enum-labels-kept-mesgEJWH.js.map → enum-labels-kept-DrCueSHr.js.map} +1 -1
- package/dist/{generated-schema-diff-DoT2dYDe.js → generated-schema-diff-DDktAATD.js} +2 -2
- package/dist/{generated-schema-diff-DoT2dYDe.js.map → generated-schema-diff-DDktAATD.js.map} +1 -1
- package/dist/index.es.js +11 -11
- package/dist/{introspect-db-queries-BgiRQqtR.js → introspect-db-queries-D7u9EOfV.js} +66 -4
- package/dist/introspect-db-queries-D7u9EOfV.js.map +1 -0
- package/dist/{introspect-tables-Cw_A-kk4.js → introspect-tables-2yJ3p98l.js} +267 -30
- package/dist/introspect-tables-2yJ3p98l.js.map +1 -0
- package/dist/{migrate-baseline-Bzj5gSCM.js → migrate-baseline-CnIbBRgh.js} +4 -3
- package/dist/{migrate-baseline-Bzj5gSCM.js.map → migrate-baseline-CnIbBRgh.js.map} +1 -1
- package/dist/{migrate-policy-stamps-C2WaOEsB.js → migrate-policy-stamps-D7BaYeKO.js} +4 -4
- package/dist/{migrate-policy-stamps-C2WaOEsB.js.map → migrate-policy-stamps-D7BaYeKO.js.map} +1 -1
- package/dist/{open-rebase-x3yAPy5g.js → open-rebase-DykxNl1j.js} +72 -20
- package/dist/open-rebase-DykxNl1j.js.map +1 -0
- package/dist/{pg-error-utils-CWopxboq.js → pg-error-utils-DXyqf9yP.js} +2 -2
- package/dist/{pg-error-utils-CWopxboq.js.map → pg-error-utils-DXyqf9yP.js.map} +1 -1
- package/dist/{policy-drift-rVLKS2AG.js → policy-drift-B2Czzs2Z.js} +3 -3
- package/dist/{policy-drift-rVLKS2AG.js.map → policy-drift-B2Czzs2Z.js.map} +1 -1
- package/dist/{push-index-adoption-EcamXfW2.js → push-index-adoption-DTLPk_5i.js} +2 -2
- package/dist/{push-index-adoption-EcamXfW2.js.map → push-index-adoption-DTLPk_5i.js.map} +1 -1
- package/dist/{push-index-prebuild-BPIns6wA.js → push-index-prebuild-WP5272gZ.js} +3 -3
- package/dist/{push-index-prebuild-BPIns6wA.js.map → push-index-prebuild-WP5272gZ.js.map} +1 -1
- package/dist/{push-legacy-renames-lmYkb41I.js → push-legacy-renames-CvWSBxRu.js} +3 -3
- package/dist/{push-legacy-renames-lmYkb41I.js.map → push-legacy-renames-CvWSBxRu.js.map} +1 -1
- package/dist/{push-policy-plan-Dqu4FKWh.js → push-policy-plan-D8HvHgPs.js} +3 -3
- package/dist/{push-policy-plan-Dqu4FKWh.js.map → push-policy-plan-D8HvHgPs.js.map} +1 -1
- package/dist/{request-role-cli-Ay0v9oYZ.js → request-role-cli-Y5Uqalop.js} +8 -8
- package/dist/{request-role-cli-Ay0v9oYZ.js.map → request-role-cli-Y5Uqalop.js.map} +1 -1
- package/dist/{request-role-migration-DTE3Owsh.js → request-role-migration-Cc0gJSso.js} +2 -2
- package/dist/{request-role-migration-DTE3Owsh.js.map → request-role-migration-Cc0gJSso.js.map} +1 -1
- package/dist/{rls-enforcement-Ck-d8zdJ.js → rls-enforcement-NZKe3Jr-.js} +2 -2
- package/dist/{rls-enforcement-Ck-d8zdJ.js.map → rls-enforcement-NZKe3Jr-.js.map} +1 -1
- package/dist/schema/destructive-sql.d.ts +9 -1
- package/dist/schema/doctor-cli.js +6 -6
- package/dist/schema/introspect-db-logic.d.ts +51 -0
- package/dist/schema/introspect-db-project.d.ts +6 -0
- package/dist/schema/introspect-db-queries.d.ts +21 -2
- package/dist/schema/introspect-db.js +53 -4
- package/dist/schema/introspect-db.js.map +1 -1
- package/dist/schema/introspect-foreign.d.ts +47 -0
- package/dist/schema/introspect-tables.d.ts +17 -0
- package/dist/schema/undeclarable-constraints.d.ts +16 -3
- package/dist/utils/result-rows.d.ts +20 -0
- package/dist/{websocket-DAVDn7Ki.js → websocket-CvmbzBeS.js} +3 -3
- package/dist/{websocket-DAVDn7Ki.js.map → websocket-CvmbzBeS.js.map} +1 -1
- package/package.json +7 -7
- package/dist/cli-schema-dir-CjDH_31U.js.map +0 -1
- package/dist/introspect-db-queries-BgiRQqtR.js.map +0 -1
- package/dist/introspect-tables-Cw_A-kk4.js.map +0 -1
- package/dist/open-rebase-x3yAPy5g.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rls-enforcement-Ck-d8zdJ.js","names":[],"sources":["../src/security/rls-enforcement.ts"],"sourcesContent":["import { sql as drizzleSql, SQL } from \"drizzle-orm\";\nimport { ANONYMOUS_USER_ID, PolicyExpression, type TableDescriptor } 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_REQUEST_ROLE, 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, ADMIN_REQUEST_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 table's `rls` rules\n * are the whole authorization model; app-layer hooks are\n * 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 table definitions, 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 declared table 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 * Served tables 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 declared table 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 views (`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 table's `rls` rules (backend/schema).\"\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; adminRequestPoliciesLive: boolean }> {\n const request = await settleAdminRequestRoles(run, schemas, settings, options);\n if (settings.adminPolicies !== \"adminRole\") return { request, adminPoliciesLive: false, adminRequestPoliciesLive: false };\n await ensureConnectionInheritsAdminRole(run, options);\n const adminPoliciesLive = request.adminRoleFor !== undefined && await adminSwitchLive(run, settings.adminRoles);\n const adminRequestPoliciesLive = adminPoliciesLive\n && await settleAdminRequestGroup(run, [...settings.adminRoles.values()], options).catch((err: unknown) => {\n logger.warn(`⚠️ RLS enforcement: admin reads keep their policy barrier (${failureReason(err)}).`);\n return false;\n });\n return { request, adminPoliciesLive, adminRequestPoliciesLive };\n}\n\n/**\n * Make {@link REBASE_ADMIN_REQUEST_ROLE} the admin request roles' alone, and\n * say whether it is — which decides whether the admin-only policies get their\n * `USING (true)` companions, and with them an admin request's index plans.\n *\n * The companions admit every member of that role to every row the admin\n * policies grant, so membership is the whole boundary, and it is checked, not\n * assumed. From PostgreSQL 16 each admin request role is granted it `WITH\n * INHERIT TRUE, SET FALSE`; the connection holds those roles `WITH INHERIT\n * FALSE` and so not this one. Before 16 inheritance is a property of the role,\n * the connection would inherit it through them, and nothing is granted. Then\n * the catalogue is asked who holds its privileges: anyone but the admin\n * request roles — the connection by `createrole_self_grant`, a request role, a\n * grant by hand — and the answer is `false`, the companions are not planned,\n * and the policies step drops any it finds. A role that bypasses RLS anyway\n * (a superuser, BYPASSRLS) gains nothing from them and does not count.\n *\n * A boot that provisions nothing creates and grants nothing, and only reads.\n */\nexport async function settleAdminRequestGroup(\n run: RawSqlRunner,\n adminRoles: readonly string[],\n options: { provision: boolean }\n): Promise<boolean> {\n if (adminRoles.length === 0) return false;\n const group = REBASE_ADMIN_REQUEST_ROLE;\n const [state] = await run(`\n SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,\n to_regrole('${group}') IS NOT NULL AS present\n `);\n if (state?.per_grant !== true) return false;\n if (state.present !== true) {\n if (!options.provision) return false;\n try {\n await run(ADMIN_REQUEST_ROLE_SQL);\n } catch (err) {\n logger.info(`🔐 RLS enforcement: \"${group}\" could not be created (${failureReason(err)}); admin reads keep their policy barrier.`);\n return false;\n }\n }\n if (options.provision) {\n for (const adminRole of adminRoles) {\n const [held] = await run(`SELECT pg_has_role(${sqlLiteral(adminRole)}, '${group}', 'USAGE') AS inherits`);\n if (held?.inherits !== true) await run(`GRANT ${group} TO ${quoteIdent(adminRole)} WITH INHERIT TRUE, SET FALSE`);\n }\n }\n const { others, adminsHold } = await adminRequestGroupHolders(run, adminRoles);\n if (others.length > 0) {\n logger.warn(\n `⚠️ RLS enforcement: ${others.map(r => `\"${r}\"`).join(\", \")} ${others.length === 1 ? \"holds\" : \"hold\"} the privileges of \"${group}\", ` +\n \"which only the admin request roles may: its policies admit every row the admin policies grant. They are not written, \" +\n `so admin reads keep their policy barrier. Revoke it (REVOKE ${group} FROM …, or REVOKE INHERIT OPTION FOR ${group} FROM …).`\n );\n return false;\n }\n return adminsHold;\n}\n\n/**\n * Who holds the privileges of {@link REBASE_ADMIN_REQUEST_ROLE}: `others`, the\n * roles that may not (anything subject to RLS but the admin request roles),\n * and whether every admin request role does. Read-only — the check\n * {@link settleAdminRequestGroup} makes after granting, and the one `db push`\n * and `rebase doctor` make before trusting a companion they find.\n */\nasync function adminRequestGroupHolders(\n run: RawSqlRunner,\n adminRoles: readonly string[]\n): Promise<{ others: string[]; adminsHold: boolean }> {\n const group = REBASE_ADMIN_REQUEST_ROLE;\n const [present] = await run(`SELECT to_regrole('${group}') IS NOT NULL AS present`);\n if (present?.present !== true) return { others: [], adminsHold: false };\n const [check] = await run(`\n SELECT ARRAY(\n SELECT r.rolname::text FROM pg_roles r\n WHERE pg_has_role(r.oid, '${group}'::regrole, 'USAGE')\n AND r.rolname <> '${group}'\n AND NOT r.rolsuper AND NOT r.rolbypassrls\n AND r.rolname <> ALL(${textArray(adminRoles)})\n ORDER BY 1\n ) AS others,\n (SELECT bool_and(pg_has_role(r.oid, '${group}'::regrole, 'USAGE')) FROM pg_roles r\n WHERE r.rolname = ANY(${textArray(adminRoles)})) AS admins\n `);\n return { others: textArrayValue(check?.others), adminsHold: check?.admins === true };\n}\n\n/**\n * Whether a companion found in the database may stay: the admin switch would\n * be live for this database's request roles, and nothing but their admin\n * roles holds {@link REBASE_ADMIN_REQUEST_ROLE}. `db push` and `rebase doctor`\n * ask this before taking a live companion for Rebase's own — otherwise it is\n * an orphan, and push drops it. Anything it cannot read answers `false`.\n */\nexport async function adminRequestCompanionsSafeForCli(run: RawSqlRunner): Promise<boolean> {\n try {\n const settings = cliRlsSettings(await readRecordedRequestRoles(run));\n if (settings.adminPolicies !== \"adminRole\" || settings.adminRoles.size === 0) return false;\n const { others } = await adminRequestGroupHolders(run, [...settings.adminRoles.values()]);\n return others.length === 0;\n } catch {\n return false;\n }\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 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 // tables 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 * What the rule checks read of a table: its slug, to name it, and its\n * row-level security, whose `rules` are what the policies are compiled from.\n * A {@link TableDescriptor} is one.\n */\nexport type TableRules = Pick<TableDescriptor, \"slug\" | \"rls\">;\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(tables: readonly TableRules[]): void {\n // Grouped by the mistake, not by the rule: one habit typically repeats\n // across every table 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 table of tables) {\n for (const rule of table.rls.rules) {\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 = `${table.slug} → \"${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 tables 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(tables: readonly TableRules[]): void {\n const sites: string[] = [];\n\n for (const table of tables) {\n for (const rule of table.rls.rules) {\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 = `${table.slug} → \"${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 table as empty.\n */\nexport async function validatePolicyPgRoles(\n run: RawSqlRunner,\n tables: readonly TableRules[],\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 table of tables) {\n for (const rule of table.rls.rules) {\n for (const role of rule.pgRoles ?? []) {\n if (role === \"public\" || candidates.includes(role)) continue;\n wanted.set(role, [...(wanted.get(role) ?? []), table.slug]);\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 `RLS 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 tables would look empty rather than error.\\n\\n` +\n problems.join(\"\\n\\n\") + \"\\n\"\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AChC,QAAQ,aAAa,OAAO,SAAS,KAAK,MAAM,gBAAgB,KAAA;CAE1E,MAAM,QAAQ,IAAI,IAAI,KAAK,KAAK,QAAQ,CAAC,OAAO,IAAI,IAAI,GAAG,GAAG,CAAC,CAAC;CAChE,MAAM,WAAqB,CAAC;CAE5B,KAAK,MAAM,CAAC,MAAM,UAAU,QAAQ;EAChC,MAAM,MAAM,MAAM,IAAI,IAAI;EAC1B,IAAI,KAAK,cAAc,MAAM;EAE7B,MAAM,MAAM,CAAC,MACP,yCACA,IAAI,WAAW,OACX,IAAI,YAAY,yFAChB,IAAI,YAAY;EAC1B,MAAM,WAAW,yBAAyB;EAC1C,MAAM,QAAQ,eAAe,IAAI;EACjC,MAAM,OAAO,YAAY,CAAC,MACpB,IAAI,KAAK,SAAS,SAAS,6EAA6E,SAAS,iBAAiB,UAAU,KAAK,gEACjJ,QACI,oBAAoB,MAAM,2DAC1B,IAAI,YAAY;EAE1B,SAAS,KACL,kBAAkB,KAAK,QAAQ,MAAM,KAAK,IAAI,EAAE,KAAK,IAAI,SAAS,MACtE;CACJ;CAEA,IAAI,SAAS,SAAS,GAClB,MAAM,IAAI,MACN,8EACI,YAAY,mIAEhB,SAAS,KAAK,MAAM,IAAI,IAC5B;AAER"}
|
|
1
|
+
{"version":3,"file":"rls-enforcement-NZKe3Jr-.js","names":[],"sources":["../src/security/rls-enforcement.ts"],"sourcesContent":["import { sql as drizzleSql, SQL } from \"drizzle-orm\";\nimport { ANONYMOUS_USER_ID, PolicyExpression, type TableDescriptor } 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_REQUEST_ROLE, 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, ADMIN_REQUEST_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 table's `rls` rules\n * are the whole authorization model; app-layer hooks are\n * 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 table definitions, 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 declared table 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 * Served tables 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 declared table 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 views (`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 table's `rls` rules (backend/schema).\"\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; adminRequestPoliciesLive: boolean }> {\n const request = await settleAdminRequestRoles(run, schemas, settings, options);\n if (settings.adminPolicies !== \"adminRole\") return { request, adminPoliciesLive: false, adminRequestPoliciesLive: false };\n await ensureConnectionInheritsAdminRole(run, options);\n const adminPoliciesLive = request.adminRoleFor !== undefined && await adminSwitchLive(run, settings.adminRoles);\n const adminRequestPoliciesLive = adminPoliciesLive\n && await settleAdminRequestGroup(run, [...settings.adminRoles.values()], options).catch((err: unknown) => {\n logger.warn(`⚠️ RLS enforcement: admin reads keep their policy barrier (${failureReason(err)}).`);\n return false;\n });\n return { request, adminPoliciesLive, adminRequestPoliciesLive };\n}\n\n/**\n * Make {@link REBASE_ADMIN_REQUEST_ROLE} the admin request roles' alone, and\n * say whether it is — which decides whether the admin-only policies get their\n * `USING (true)` companions, and with them an admin request's index plans.\n *\n * The companions admit every member of that role to every row the admin\n * policies grant, so membership is the whole boundary, and it is checked, not\n * assumed. From PostgreSQL 16 each admin request role is granted it `WITH\n * INHERIT TRUE, SET FALSE`; the connection holds those roles `WITH INHERIT\n * FALSE` and so not this one. Before 16 inheritance is a property of the role,\n * the connection would inherit it through them, and nothing is granted. Then\n * the catalogue is asked who holds its privileges: anyone but the admin\n * request roles — the connection by `createrole_self_grant`, a request role, a\n * grant by hand — and the answer is `false`, the companions are not planned,\n * and the policies step drops any it finds. A role that bypasses RLS anyway\n * (a superuser, BYPASSRLS) gains nothing from them and does not count.\n *\n * A boot that provisions nothing creates and grants nothing, and only reads.\n */\nexport async function settleAdminRequestGroup(\n run: RawSqlRunner,\n adminRoles: readonly string[],\n options: { provision: boolean }\n): Promise<boolean> {\n if (adminRoles.length === 0) return false;\n const group = REBASE_ADMIN_REQUEST_ROLE;\n const [state] = await run(`\n SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,\n to_regrole('${group}') IS NOT NULL AS present\n `);\n if (state?.per_grant !== true) return false;\n if (state.present !== true) {\n if (!options.provision) return false;\n try {\n await run(ADMIN_REQUEST_ROLE_SQL);\n } catch (err) {\n logger.info(`🔐 RLS enforcement: \"${group}\" could not be created (${failureReason(err)}); admin reads keep their policy barrier.`);\n return false;\n }\n }\n if (options.provision) {\n for (const adminRole of adminRoles) {\n const [held] = await run(`SELECT pg_has_role(${sqlLiteral(adminRole)}, '${group}', 'USAGE') AS inherits`);\n if (held?.inherits !== true) await run(`GRANT ${group} TO ${quoteIdent(adminRole)} WITH INHERIT TRUE, SET FALSE`);\n }\n }\n const { others, adminsHold } = await adminRequestGroupHolders(run, adminRoles);\n if (others.length > 0) {\n logger.warn(\n `⚠️ RLS enforcement: ${others.map(r => `\"${r}\"`).join(\", \")} ${others.length === 1 ? \"holds\" : \"hold\"} the privileges of \"${group}\", ` +\n \"which only the admin request roles may: its policies admit every row the admin policies grant. They are not written, \" +\n `so admin reads keep their policy barrier. Revoke it (REVOKE ${group} FROM …, or REVOKE INHERIT OPTION FOR ${group} FROM …).`\n );\n return false;\n }\n return adminsHold;\n}\n\n/**\n * Who holds the privileges of {@link REBASE_ADMIN_REQUEST_ROLE}: `others`, the\n * roles that may not (anything subject to RLS but the admin request roles),\n * and whether every admin request role does. Read-only — the check\n * {@link settleAdminRequestGroup} makes after granting, and the one `db push`\n * and `rebase doctor` make before trusting a companion they find.\n */\nasync function adminRequestGroupHolders(\n run: RawSqlRunner,\n adminRoles: readonly string[]\n): Promise<{ others: string[]; adminsHold: boolean }> {\n const group = REBASE_ADMIN_REQUEST_ROLE;\n const [present] = await run(`SELECT to_regrole('${group}') IS NOT NULL AS present`);\n if (present?.present !== true) return { others: [], adminsHold: false };\n const [check] = await run(`\n SELECT ARRAY(\n SELECT r.rolname::text FROM pg_roles r\n WHERE pg_has_role(r.oid, '${group}'::regrole, 'USAGE')\n AND r.rolname <> '${group}'\n AND NOT r.rolsuper AND NOT r.rolbypassrls\n AND r.rolname <> ALL(${textArray(adminRoles)})\n ORDER BY 1\n ) AS others,\n (SELECT bool_and(pg_has_role(r.oid, '${group}'::regrole, 'USAGE')) FROM pg_roles r\n WHERE r.rolname = ANY(${textArray(adminRoles)})) AS admins\n `);\n return { others: textArrayValue(check?.others), adminsHold: check?.admins === true };\n}\n\n/**\n * Whether a companion found in the database may stay: the admin switch would\n * be live for this database's request roles, and nothing but their admin\n * roles holds {@link REBASE_ADMIN_REQUEST_ROLE}. `db push` and `rebase doctor`\n * ask this before taking a live companion for Rebase's own — otherwise it is\n * an orphan, and push drops it. Anything it cannot read answers `false`.\n */\nexport async function adminRequestCompanionsSafeForCli(run: RawSqlRunner): Promise<boolean> {\n try {\n const settings = cliRlsSettings(await readRecordedRequestRoles(run));\n if (settings.adminPolicies !== \"adminRole\" || settings.adminRoles.size === 0) return false;\n const { others } = await adminRequestGroupHolders(run, [...settings.adminRoles.values()]);\n return others.length === 0;\n } catch {\n return false;\n }\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 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 // tables 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 * What the rule checks read of a table: its slug, to name it, and its\n * row-level security, whose `rules` are what the policies are compiled from.\n * A {@link TableDescriptor} is one.\n */\nexport type TableRules = Pick<TableDescriptor, \"slug\" | \"rls\">;\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(tables: readonly TableRules[]): void {\n // Grouped by the mistake, not by the rule: one habit typically repeats\n // across every table 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 table of tables) {\n for (const rule of table.rls.rules) {\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 = `${table.slug} → \"${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 tables 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(tables: readonly TableRules[]): void {\n const sites: string[] = [];\n\n for (const table of tables) {\n for (const rule of table.rls.rules) {\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 = `${table.slug} → \"${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 table as empty.\n */\nexport async function validatePolicyPgRoles(\n run: RawSqlRunner,\n tables: readonly TableRules[],\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 table of tables) {\n for (const rule of table.rls.rules) {\n for (const role of rule.pgRoles ?? []) {\n if (role === \"public\" || candidates.includes(role)) continue;\n wanted.set(role, [...(wanted.get(role) ?? []), table.slug]);\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 `RLS 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 tables 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,IA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