@rebasepro/server-postgres 0.29.1 → 0.29.2
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-BIIBF5ZL.js → BranchService-X9R505mP.js} +3 -3
- package/dist/{BranchService-BIIBF5ZL.js.map → BranchService-X9R505mP.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +64 -4
- package/dist/PostgresBootstrapper.d.ts +20 -0
- package/dist/auth/ensure-tables.d.ts +2 -2
- package/dist/auth/schema-version.d.ts +5 -5
- package/dist/auth/services.d.ts +9 -9
- package/dist/{backup-cli-QcOpmRpQ.js → backup-cli-CwiJEp_J.js} +3 -3
- package/dist/{backup-cli-QcOpmRpQ.js.map → backup-cli-CwiJEp_J.js.map} +1 -1
- package/dist/{boot-ddl-BSNpEUOS.js → boot-ddl-CbZj9ovZ.js} +2 -2
- package/dist/{boot-ddl-BSNpEUOS.js.map → boot-ddl-CbZj9ovZ.js.map} +1 -1
- package/dist/{cli-console-DTsm96lW.js → cli-console-DDkNetCz.js} +6 -6
- package/dist/{cli-console-DTsm96lW.js.map → cli-console-DDkNetCz.js.map} +1 -1
- package/dist/{cli-errors-DwqFRIWz.js → cli-errors-C73Qy7WJ.js} +5 -5
- package/dist/{cli-errors-DwqFRIWz.js.map → cli-errors-C73Qy7WJ.js.map} +1 -1
- package/dist/cli.js +165 -49
- package/dist/cli.js.map +1 -1
- package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
- package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
- package/dist/data-transformer.d.ts +2 -2
- package/dist/database-health.d.ts +2 -1
- package/dist/{database-preflight-D5JtPt8i.js → database-preflight-DIauc8i5.js} +36 -3
- package/dist/database-preflight-DIauc8i5.js.map +1 -0
- package/dist/{databasePoolManager-7hXVurmG.js → databasePoolManager-DIjzlTK4.js} +2 -2
- package/dist/{databasePoolManager-7hXVurmG.js.map → databasePoolManager-DIjzlTK4.js.map} +1 -1
- package/dist/{deferred-index-build-B8feKnUj.js → deferred-index-build-DDdnjaOW.js} +18 -6
- package/dist/deferred-index-build-DDdnjaOW.js.map +1 -0
- package/dist/{doctor-BaR11xUe.js → doctor-DwMXljiq.js} +11 -11
- package/dist/doctor-DwMXljiq.js.map +1 -0
- package/dist/{ensure-collection-policies-85HiG-k1.js → ensure-collection-policies-DJsOMpaI.js} +23 -13
- package/dist/ensure-collection-policies-DJsOMpaI.js.map +1 -0
- package/dist/{ensure-collection-tables-DR_WcxLA.js → ensure-collection-tables-h1mUO7Uu.js} +11 -8
- package/dist/ensure-collection-tables-h1mUO7Uu.js.map +1 -0
- package/dist/{ensure-tables-Dh5UP_Zs.js → ensure-tables-CUqYgMvo.js} +4 -4
- package/dist/ensure-tables-CUqYgMvo.js.map +1 -0
- package/dist/{enum-labels-kept-DSU8lAnd.js → enum-labels-kept-z7ustOl_.js} +3 -3
- package/dist/{enum-labels-kept-DSU8lAnd.js.map → enum-labels-kept-z7ustOl_.js.map} +1 -1
- package/dist/{generate-drizzle-schema-5spbTyQ6.js → generate-drizzle-schema-BIUqhSzh.js} +2 -2
- package/dist/{generate-drizzle-schema-5spbTyQ6.js.map → generate-drizzle-schema-BIUqhSzh.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js → generate-drizzle-schema-logic-BBXjxm5z.js} +3 -3
- package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js.map → generate-drizzle-schema-logic-BBXjxm5z.js.map} +1 -1
- package/dist/{generate-files-Bl3_D_oP.js → generate-files-BkiRFoV1.js} +3 -3
- package/dist/{generate-files-Bl3_D_oP.js.map → generate-files-BkiRFoV1.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-BC3JA93M.js → generate-postgres-ddl-logic-G9PvjHrr.js} +10 -5
- package/dist/{generate-postgres-ddl-logic-BC3JA93M.js.map → generate-postgres-ddl-logic-G9PvjHrr.js.map} +1 -1
- package/dist/{generated-schema-diff-Jm93vyJB.js → generated-schema-diff-D2soazQU.js} +8 -5
- package/dist/generated-schema-diff-D2soazQU.js.map +1 -0
- package/dist/history/HistoryService.d.ts +2 -3
- package/dist/history/ensure-history-table.d.ts +8 -3
- package/dist/index.es.js +15 -15
- package/dist/interfaces.d.ts +24 -2
- package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
- package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
- package/dist/{migrate-baseline-BfHmq3vN.js → migrate-baseline-CveNQli3.js} +163 -502
- package/dist/migrate-baseline-CveNQli3.js.map +1 -0
- package/dist/{migrate-policy-stamps-B4k1ggma.js → migrate-policy-stamps-C4qbQ0jK.js} +42 -13
- package/dist/migrate-policy-stamps-C4qbQ0jK.js.map +1 -0
- package/dist/{open-rebase-CiO_sjMT.js → open-rebase-Cvid3iwR.js} +1395 -656
- package/dist/open-rebase-Cvid3iwR.js.map +1 -0
- package/dist/open-rebase.d.ts +1 -1
- package/dist/{pg-error-utils-D1Nc0UML.js → pg-error-utils-80uTIHQs.js} +2 -2
- package/dist/{pg-error-utils-D1Nc0UML.js.map → pg-error-utils-80uTIHQs.js.map} +1 -1
- package/dist/pipelined-transaction.d.ts +24 -37
- package/dist/{plan-schema-BYxOzflz.js → plan-schema-CMhNYEYF.js} +21 -6
- package/dist/plan-schema-CMhNYEYF.js.map +1 -0
- package/dist/{policy-drift-DKuTJHfc.js → policy-drift-Bx6663KD.js} +29 -6
- package/dist/policy-drift-Bx6663KD.js.map +1 -0
- package/dist/push-index-adoption-C-TpM445.js +22 -0
- package/dist/push-index-adoption-C-TpM445.js.map +1 -0
- package/dist/{push-index-prebuild-bqXimSZz.js → push-index-prebuild-xbpgZEJK.js} +4 -4
- package/dist/{push-index-prebuild-bqXimSZz.js.map → push-index-prebuild-xbpgZEJK.js.map} +1 -1
- package/dist/{push-kept-defaults-CN9R8cHf.js → push-kept-defaults-D-JEv0Gn.js} +2 -2
- package/dist/{push-kept-defaults-CN9R8cHf.js.map → push-kept-defaults-D-JEv0Gn.js.map} +1 -1
- package/dist/{push-legacy-renames-CU_UYPbz.js → push-legacy-renames-7UKspspl.js} +4 -4
- package/dist/{push-legacy-renames-CU_UYPbz.js.map → push-legacy-renames-7UKspspl.js.map} +1 -1
- package/dist/{push-policy-plan-JcyK94bc.js → push-policy-plan-BOw5PtU8.js} +14 -8
- package/dist/push-policy-plan-BOw5PtU8.js.map +1 -0
- package/dist/read-routing.d.ts +10 -30
- package/dist/{render-ddl-DCdVP-pQ.js → render-ddl-Di-fTGti.js} +15 -2
- package/dist/render-ddl-Di-fTGti.js.map +1 -0
- package/dist/{request-role-cli-DSdRtvgH.js → request-role-cli-Bxxskru9.js} +10 -10
- package/dist/{request-role-cli-DSdRtvgH.js.map → request-role-cli-Bxxskru9.js.map} +1 -1
- package/dist/{request-role-migration-D9BZ5Uba.js → request-role-migration-BCW4v0rq.js} +2 -2
- package/dist/{request-role-migration-D9BZ5Uba.js.map → request-role-migration-BCW4v0rq.js.map} +1 -1
- package/dist/rls-bootstrap-sql-CxszeSc7.js +534 -0
- package/dist/rls-bootstrap-sql-CxszeSc7.js.map +1 -0
- package/dist/{rls-enforcement-BO618rnr.js → rls-enforcement-CyUCPDH8.js} +213 -10
- package/dist/rls-enforcement-CyUCPDH8.js.map +1 -0
- package/dist/{rls-settings-De5NoHHy.js → rls-settings-BCGMIig3.js} +23 -3
- package/dist/rls-settings-BCGMIig3.js.map +1 -0
- package/dist/schema/doctor-cli.js +9 -9
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/drizzle-ddl.d.ts +2 -2
- package/dist/schema/ensure-collection-policies.d.ts +15 -3
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -1
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/index-adoption.d.ts +99 -0
- package/dist/schema/introspect-db-logic.d.ts +2 -1
- package/dist/schema/introspect-db.js +3 -3
- package/dist/schema/migrate-policy-stamps.d.ts +19 -1
- package/dist/schema/plan/diff-plan.d.ts +8 -1
- package/dist/schema/plan/render-ddl.d.ts +7 -0
- package/dist/schema/plan/types.d.ts +2 -0
- package/dist/schema/push-index-adoption.d.ts +10 -0
- package/dist/schema/push-policy-plan.d.ts +5 -1
- package/dist/schema/rls-bootstrap-sql.d.ts +13 -2
- package/dist/schema/search-column.d.ts +2 -2
- package/dist/search-column-BM-GV6vH.js.map +1 -1
- package/dist/security/policy-drift.d.ts +19 -1
- package/dist/security/rls-enforcement.d.ts +87 -1
- package/dist/security/rls-settings.d.ts +33 -0
- package/dist/services/FetchService.d.ts +33 -8
- package/dist/services/PersistService.d.ts +75 -4
- package/dist/services/RelationService.d.ts +1 -1
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
- package/dist/services/channel-bus/index.d.ts +2 -2
- package/dist/services/channel-history.d.ts +2 -2
- package/dist/services/channel-presence.d.ts +3 -3
- package/dist/services/dataService.d.ts +6 -2
- package/dist/services/realtimeService.d.ts +18 -5
- package/dist/services/socket-liveness.d.ts +6 -1
- package/dist/types.d.ts +1 -1
- package/dist/utils/drizzle-conditions.d.ts +12 -0
- package/dist/utils/positional-params.d.ts +40 -0
- package/dist/{websocket-B33YjKhs.js → websocket-BSYV_KSw.js} +3 -3
- package/dist/websocket-BSYV_KSw.js.map +1 -0
- package/dist/websocket.d.ts +14 -3
- package/package.json +7 -7
- package/dist/database-preflight-D5JtPt8i.js.map +0 -1
- package/dist/deferred-index-build-B8feKnUj.js.map +0 -1
- package/dist/doctor-BaR11xUe.js.map +0 -1
- package/dist/ensure-collection-policies-85HiG-k1.js.map +0 -1
- package/dist/ensure-collection-tables-DR_WcxLA.js.map +0 -1
- package/dist/ensure-tables-Dh5UP_Zs.js.map +0 -1
- package/dist/generated-schema-diff-Jm93vyJB.js.map +0 -1
- package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
- package/dist/migrate-baseline-BfHmq3vN.js.map +0 -1
- package/dist/migrate-policy-stamps-B4k1ggma.js.map +0 -1
- package/dist/open-rebase-CiO_sjMT.js.map +0 -1
- package/dist/plan-schema-BYxOzflz.js.map +0 -1
- package/dist/policy-drift-DKuTJHfc.js.map +0 -1
- package/dist/push-policy-plan-JcyK94bc.js.map +0 -1
- package/dist/render-ddl-DCdVP-pQ.js.map +0 -1
- package/dist/rls-enforcement-BO618rnr.js.map +0 -1
- package/dist/rls-settings-De5NoHHy.js.map +0 -1
- package/dist/websocket-B33YjKhs.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rls-bootstrap-sql-CxszeSc7.js","names":[],"sources":["../src/schema/rls-bootstrap-sql.ts"],"sourcesContent":["import { LEGACY_RLS_SCHEMA, REBASE_ADMIN_ROLE, REBASE_SCHEMA } from \"@rebasepro/types\";\nimport { sqlRows } from \"@rebasepro/common\";\n\n/**\n * Canonical SQL bootstrap for the RLS helper functions.\n *\n * Generated RLS policies reference `rebase.uid()` / `rebase.roles()` /\n * `rebase.jwt()`, so any SQL stream that can contain policies must be\n * self-contained: it has to (re)create these helpers first. This matters for\n * the migration directory in particular — Atlas replays migrations against a\n * clean dev database where no out-of-band bootstrap has ever run, so a\n * migration carrying policies without this preamble fails with\n * \"function rebase.uid() does not exist\".\n *\n * Idempotent (`IF NOT EXISTS` / `OR REPLACE`) so it can be prepended to every\n * policies block and re-applied freely. The runtime boot path\n * (`auth/ensure-tables.ts`) creates the same functions under an advisory lock\n * for HMR-safety; keep the definitions in sync.\n *\n * ## Creating the `rebase` schema here is now safe, and required\n *\n * It deliberately did not, once. These functions lived in a schema called\n * `auth`, and the note here read: creating `rebase` would leak it into Atlas's\n * replayed migration state, and — absent from the desired `schema.sql` — Atlas\n * would then plan `DROP SCHEMA \"rebase\" CASCADE`, taking the auth tables with\n * it. That reasoning still holds; what changed is the second half of it. The\n * DDL generator now emits `CREATE SCHEMA IF NOT EXISTS \"rebase\"`\n * unconditionally, so the schema is always in the desired state and the diff is\n * empty. (It used to appear only when some collection happened to declare\n * `schema: \"rebase\"` — true for the scaffold's users collection, and not a\n * property anything guaranteed.) `db push` additionally excludes the whole\n * schema from the declarative apply.\n *\n * See `@rebasepro/types`' `rls-functions` for why the functions moved out of\n * `auth` at all: the short version is that the name was Supabase's, and\n * `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` cannot be applied over\n * Supabase's `RETURNS uuid` — Postgres refuses, and the refusal used to be\n * swallowed.\n */\n/**\n * The bootstrap as individual statements.\n *\n * Kept as an array because the two consumers need different shapes and only one\n * of them can take a multi-command string: the migration preamble is written to\n * a file and replayed by Atlas, but the boot path runs through drizzle, whose\n * node-postgres handle speaks the extended query protocol and rejects more than\n * one command per call. Splitting a joined string back apart on `$$;` would be\n * a parser for a problem that does not need one.\n */\n/*\n * Every helper is `PARALLEL SAFE`: it reads a setting, which Postgres hands to\n * its parallel workers with the rest of the transaction's state. Left at the\n * default (`PARALLEL UNSAFE`), a policy calling one made every statement on\n * its table run without parallel workers — a large read as `rebase_user` took\n * twice what the same read took as the table's owner.\n */\nexport const RLS_BOOTSTRAP_STATEMENTS: readonly string[] = [\n `CREATE SCHEMA IF NOT EXISTS ${REBASE_SCHEMA}`,\n\n // Falls back to the pre-rename `app.user_id` so a database that has taken\n // the new schema but is still served by an older backend keeps resolving\n // the principal. Drop the COALESCE once no such deployment remains.\n `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.uid() RETURNS text AS $$\n SELECT COALESCE(\n NULLIF(current_setting('app.uid', true), ''),\n NULLIF(current_setting('app.user_id', true), '')\n );\n$$ LANGUAGE sql STABLE PARALLEL SAFE`,\n\n `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.jwt() RETURNS jsonb AS $$\n SELECT COALESCE(\n NULLIF(current_setting('app.jwt', true), ''),\n '{}'\n )::jsonb;\n$$ LANGUAGE sql STABLE PARALLEL SAFE`,\n\n `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.roles() RETURNS text AS $$\n SELECT COALESCE(NULLIF(current_setting('app.user_roles', true), ''), '');\n$$ LANGUAGE sql STABLE PARALLEL SAFE`,\n\n // Is the caller a GUEST — signed in through anonymous sign-in rather than\n // with an account?\n //\n // Anonymous sign-in mints a real user row and a real uid, so inside a policy\n // a guest was indistinguishable from a registered account: same `uid()`\n // shape, same default role. Every rule meaning \"a signed-in person\" was\n // therefore also a rule about anybody who had called\n // `POST /auth/anonymous`, which needs no email, no password and no consent\n // to anything. On a deployment with anonymous sign-in enabled, that is the\n // whole internet holding a session.\n //\n // The fact exists on the user row (`is_anonymous`) and simply never reached\n // the database's own identity. Now it does, and a policy can say\n // `NOT rebase.is_anonymous()`.\n //\n // Defaults to FALSE when the GUC is unset, which is the safe direction:\n // an older backend against a newer database leaves it unset, and reading\n // that as \"not a guest\" preserves exactly the behaviour that deployment\n // already had rather than locking its users out.\n `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.is_anonymous() RETURNS boolean AS $$\n SELECT COALESCE(NULLIF(current_setting('app.is_anonymous', true), ''), 'false')::boolean;\n$$ LANGUAGE sql STABLE PARALLEL SAFE`\n];\n\n/** Everything `CREATE OR REPLACE FUNCTION` sets on a function, as one comparable string. */\nconst describeFunction = (facts: {\n returns: string; language: string; volatility: string; strict: boolean; parallel: string;\n securityDefiner: boolean; leakproof: boolean; cost: number; hasConfig: boolean; body: string;\n}): string => JSON.stringify([\n facts.returns.toLowerCase(), facts.language.toLowerCase(), facts.volatility, facts.strict, facts.parallel,\n facts.securityDefiner, facts.leakproof, facts.cost, facts.hasConfig, facts.body\n]);\n\n/**\n * What each `CREATE OR REPLACE FUNCTION` in {@link RLS_BOOTSTRAP_STATEMENTS}\n * would leave in the catalogue, by `schema.name`. Parsed\n * from the statements themselves, so the two cannot drift; a statement this\n * does not recognise makes {@link rlsRuntimeIsCurrent} answer \"no\", and the\n * bootstrap runs as it always did.\n */\nconst expectedRlsFunctions = (): Map<string, string> | undefined => {\n const expected = new Map<string, string>();\n for (const statement of RLS_BOOTSTRAP_STATEMENTS) {\n if (/^CREATE SCHEMA IF NOT EXISTS /.test(statement)) continue;\n const match = /^CREATE OR REPLACE FUNCTION (\\w+)\\.(\\w+)\\(\\) RETURNS (\\w+) AS \\$\\$([\\s\\S]*)\\$\\$ LANGUAGE (\\w+) (IMMUTABLE|STABLE|VOLATILE)(?: PARALLEL (SAFE|RESTRICTED|UNSAFE))?$/\n .exec(statement);\n if (!match) return undefined;\n const [, schema, name, returns, body, language, volatility, parallel] = match;\n expected.set(`${schema}.${name}`, describeFunction({\n returns, language, volatility: volatility[0].toLowerCase(), strict: false, parallel: (parallel ?? \"UNSAFE\")[0].toLowerCase(),\n securityDefiner: false, leakproof: false, cost: 100, hasConfig: false, body\n }));\n }\n return expected;\n};\n\n/**\n * Whether the `rebase` schema and every RLS helper function are exactly what\n * {@link RLS_BOOTSTRAP_STATEMENTS} would make them — one catalogue read.\n *\n * The boot ran those statements unconditionally, on every boot and on every\n * source: four `CREATE OR REPLACE FUNCTION`s in a transaction under an\n * advisory lock. Replacing a function rewrites its `pg_proc` row even when\n * nothing changed, and every cached plan that inlined it — every plan of every\n * statement a policy applies to, on every connection — is invalidated by it.\n * A function that differs in anything `CREATE OR REPLACE` sets (body,\n * language, volatility, strictness, parallel safety, security, leakproofness,\n * cost, `SET` options), or is missing, answers `false`, and the statements run\n * as before.\n */\nexport async function rlsRuntimeIsCurrent(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<boolean> {\n const expected = expectedRlsFunctions();\n if (!expected) return false;\n const names = [...expected.keys()].map(key => key.split(\".\"));\n const rows = await run(\n `SELECT n.nspname AS schema, p.proname AS name, pg_get_function_identity_arguments(p.oid) AS args,\n format_type(p.prorettype, NULL) AS returns, l.lanname AS language,\n p.provolatile::text AS volatility, p.proisstrict AS strict, p.proparallel::text AS parallel,\n p.prosecdef AS security_definer, p.proleakproof AS leakproof, p.procost AS cost,\n p.proconfig IS NOT NULL AS has_config, p.prosrc AS body\n FROM pg_proc p\n JOIN pg_namespace n ON p.pronamespace = n.oid\n JOIN pg_language l ON p.prolang = l.oid\n WHERE (n.nspname, p.proname) IN (${names.map(([schema, name]) => `('${schema}', '${name}')`).join(\", \")})`\n );\n const live = new Map<string, string>();\n for (const row of rows) {\n // Only the no-argument overload is the one these statements replace.\n if (String(row.args ?? \"\") !== \"\") continue;\n live.set(`${row.schema}.${row.name}`, describeFunction({\n returns: String(row.returns),\n language: String(row.language),\n volatility: String(row.volatility),\n strict: row.strict === true,\n parallel: String(row.parallel),\n securityDefiner: row.security_definer === true,\n leakproof: row.leakproof === true,\n cost: Number(row.cost),\n hasConfig: row.has_config === true,\n body: String(row.body)\n }));\n }\n // The schema exists whenever a function in it does.\n for (const [key, definition] of expected) {\n if (live.get(key) !== definition) return false;\n }\n return true;\n}\n\n/** The same statements as one script, for migration files and raw clients. */\nexport const RLS_BOOTSTRAP_SQL =\n \"-- Rebase schema + RLS helper functions (required by the policies below)\\n\" +\n RLS_BOOTSTRAP_STATEMENTS.map(s => `${s};`).join(\"\\n\\n\") + \"\\n\";\n\n/** One of the helpers the pre-1.0 `auth` schema held. */\ninterface LegacyAuthHelper {\n name: string;\n returns: string;\n /** The GUCs its body read. Any one of them identifies it. */\n reads: readonly string[];\n}\n\n/**\n * The three functions every pre-1.0 release put in `auth`. (The auth tables\n * lived in `rebase`, or wherever the users collection was declared.)\n *\n * `uid()` is matched on either spelling of the principal because Rebase wrote\n * both. Until v0.10.0 its body was\n * `SELECT NULLIF(current_setting('app.user_id', true), '')`; v0.10.0 renamed\n * the GUC to `app.uid` and kept `app.user_id` as a fallback; v0.14.0 moved the\n * helpers to `rebase`. A database last booted before v0.10.0 therefore holds an\n * `auth.uid()` that reads `app.user_id` alone — as does anything that copied\n * that body, the Rebase control plane included — and matching `app.uid` only\n * left every one of them in place, with the schema around it.\n *\n * This is the one place either spelling is listed: the drop and the report of\n * what it left are both generated from it, so they cannot disagree about which\n * functions are Rebase's.\n */\nconst LEGACY_AUTH_HELPERS: readonly LegacyAuthHelper[] = [\n { name: \"uid\", returns: \"text\", reads: [\"app.uid\", \"app.user_id\"] },\n { name: \"jwt\", returns: \"jsonb\", reads: [\"app.jwt\"] },\n { name: \"roles\", returns: \"text\", reads: [\"app.user_roles\"] }\n];\n\n/**\n * `pg_proc p` has a Rebase helper's name, arity and result type: what\n * `CREATE OR REPLACE` would have left, whatever the body.\n *\n * Two things that share that shape are excluded outright: a body reading\n * `request.jwt` (Supabase's helpers and anything modelled on them) and a\n * function an extension installed (`pg_session_jwt` puts an `auth.jwt()\n * RETURNS jsonb` in the same schema).\n */\nconst isLegacyHelperShaped = (helper: LegacyAuthHelper): string => `(\n p.proname = '${helper.name}' AND p.pronargs = 0\n AND pg_get_function_result(p.oid) = '${helper.returns}'\n AND strpos(p.prosrc, 'request.jwt') = 0\n AND NOT EXISTS (\n SELECT 1 FROM pg_depend e\n WHERE e.classid = 'pg_proc'::regclass AND e.objid = p.oid AND e.deptype = 'e'\n ))`;\n\n/** `pg_proc p` is a helper Rebase wrote: its shape, and a body reading one of its GUCs. */\nconst isLegacyHelper = (helper: LegacyAuthHelper): string =>\n `${isLegacyHelperShaped(helper)}\n AND (${helper.reads.map(guc => `strpos(p.prosrc, '${guc}') > 0`).join(\" OR \")})`;\n\n/**\n * Removes the pre-1.0 `auth` schema, but only when Rebase is what put it there.\n *\n * ## Why this is safe against a Supabase database\n *\n * Two independent guards, and both have to pass:\n *\n * 1. **Each function is identified before it is dropped.** Ours returns `text`\n * and reads the `app.uid` or `app.user_id` GUC; Supabase's returns `uuid`\n * and reads `request.jwt.claims`. Nothing is dropped on a signature we did\n * not write, so a Supabase database — where our `CREATE OR REPLACE` could\n * never have succeeded in the first place, Postgres refusing to change a\n * return type — matches nothing and this is a no-op. See\n * {@link LEGACY_AUTH_HELPERS} for exactly what is matched.\n * 2. **`DROP SCHEMA … RESTRICT`**, never CASCADE. If anything else at all still\n * lives in `auth` (Supabase's `users` table, its other helpers), the drop\n * fails and the schema stays. CASCADE here would be unrecoverable.\n *\n * ## Why it cannot run too early\n *\n * Postgres records a dependency from every RLS policy to the functions its body\n * calls, so `DROP FUNCTION auth.uid()` fails for as long as a single policy\n * still references it. That is the interlock, and it is load-bearing: the drop\n * can only succeed once every policy has been recompiled to \\`rebase.uid()\\`.\n * Callers therefore run this *after* applying policies, and treat a failure as\n * \"not yet — try again next boot\" rather than as an error.\n */\nexport const DROP_LEGACY_AUTH_SCHEMA_SQL = `\nDO $rebase_drop_legacy$\nDECLARE\n dropped_any boolean := false;\nBEGIN\n -- Each function is matched on its own result type and body, so a schema\n -- that merely shares the name keeps everything it has.\n${LEGACY_AUTH_HELPERS.map(helper => ` IF EXISTS (\n SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = '${LEGACY_RLS_SCHEMA}' AND ${isLegacyHelper(helper)}\n ) THEN\n DROP FUNCTION ${LEGACY_RLS_SCHEMA}.${helper.name}();\n dropped_any := true;\n END IF;`).join(\"\\n\\n\")}\n\n -- RESTRICT: only an empty schema goes. Anything else in there — including a\n -- Supabase installation left untouched above — keeps it. Swallowed so the\n -- helpers dropped above stay dropped; dropLegacyAuthSchema looks afterwards\n -- and says what is left.\n IF dropped_any THEN\n BEGIN\n EXECUTE 'DROP SCHEMA ${LEGACY_RLS_SCHEMA} RESTRICT';\n EXCEPTION WHEN OTHERS THEN\n NULL;\n END;\n END IF;\nEND\n$rebase_drop_legacy$;\n`;\n\n/** One object in the `auth` schema that `DROP SCHEMA … RESTRICT` refuses on. */\nexport interface LegacyAuthSchemaObject {\n /**\n * As Postgres names it: `function auth.uid()`, `table auth.sessions`.\n * `null` on the one row an empty schema answers with.\n */\n object: string | null;\n /**\n * `ours` is a helper Rebase wrote, which the drop removes. `lookalike` has a\n * helper's name and result type but a body no release wrote, so the drop\n * leaves it alone. `null` for everything else.\n */\n helper: \"ours\" | \"lookalike\" | null;\n}\n\n/**\n * What the `auth` schema holds, one row per object keeping it alive.\n *\n * No rows: the schema does not exist. A single row with a `null` object: it\n * exists and is empty. Read from the namespace entries in `pg_depend`, which\n * are what `DROP SCHEMA … RESTRICT` itself consults — minus whatever goes with\n * its owner (a serial's sequence, an identity column's), which Postgres does not\n * name either.\n */\nexport const LEGACY_AUTH_SCHEMA_CONTENTS_SQL = `\n SELECT pg_describe_object(d.classid, d.objid, d.objsubid) AS object,\n CASE\n WHEN d.classid <> 'pg_proc'::regclass THEN NULL\n WHEN EXISTS (\n SELECT 1 FROM pg_proc p\n WHERE p.oid = d.objid\n AND (${LEGACY_AUTH_HELPERS.map(helper => `(${isLegacyHelper(helper)})`).join(\" OR \")})\n ) THEN 'ours'\n WHEN EXISTS (\n SELECT 1 FROM pg_proc p\n WHERE p.oid = d.objid\n AND (${LEGACY_AUTH_HELPERS.map(isLegacyHelperShaped).join(\" OR \")})\n ) THEN 'lookalike'\n END AS helper\n FROM pg_namespace n\n LEFT JOIN pg_depend d\n ON d.refclassid = 'pg_namespace'::regclass AND d.refobjid = n.oid AND d.deptype = 'n'\n AND NOT EXISTS (\n SELECT 1 FROM pg_depend o\n WHERE o.classid = d.classid AND o.objid = d.objid AND o.deptype IN ('a', 'i')\n )\n WHERE n.nspname = '${LEGACY_RLS_SCHEMA}'\n ORDER BY helper NULLS LAST, object\n`;\n\n/** Somebody's policy that still calls a pre-1.0 helper. */\nexport interface LegacyRlsDependent {\n schema: string;\n table: string;\n policy: string;\n}\n\n/**\n * Policies whose body still calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.\n *\n * Postgres will not drop a function a policy depends on, so this is exactly the\n * set standing between a database and losing the legacy schema. Rebase's own\n * policies leave the list on the next push or boot, when they are recompiled —\n * anything still here afterwards is hand-written, will never be recompiled by\n * anybody, and is the reason the drop keeps being skipped. Silence there would\n * leave an operator staring at a schema the release notes said would go.\n */\nexport const LEGACY_RLS_DEPENDENTS_SQL = `\n SELECT n.nspname AS schema, c.relname AS \"table\", p.polname AS policy\n FROM pg_policy p\n JOIN pg_class c ON c.oid = p.polrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE pg_get_expr(p.polqual, p.polrelid) ~* '\\\\m${LEGACY_RLS_SCHEMA}\\\\.(uid|jwt|roles)\\\\s*\\\\('\n OR pg_get_expr(p.polwithcheck, p.polrelid) ~* '\\\\m${LEGACY_RLS_SCHEMA}\\\\.(uid|jwt|roles)\\\\s*\\\\('\n ORDER BY 1, 2, 3\n`;\n\n/** Somebody's *function* that still calls a pre-1.0 helper from its own body. */\nexport interface LegacyRlsFunctionDependent {\n schema: string;\n function: string;\n}\n\n/**\n * Functions whose body calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.\n *\n * This is the half `DROP FUNCTION ... RESTRICT` cannot see, and the reason it\n * needs its own query. Postgres records a dependency for a *policy* that calls a\n * function, which is why the drop is safe against the policies above — but a\n * `LANGUAGE sql` function whose body is a **string literal** is not parsed when\n * it is created, so nothing is recorded and `RESTRICT` has nothing to refuse on.\n * The drop succeeds and the caller is left pointing at a function that no longer\n * exists, which fails at *query* time rather than at boot.\n *\n * A downstream project building on these helpers is not hypothetical: the Rebase\n * control plane defined `auth.is_org_member(uuid)` and `auth.is_org_admin(uuid)`\n * in this very schema, each calling `auth.uid()` in a string body, and eleven of\n * its row-level-security policies went through them. Every one of those would\n * have started failing the first time a recompile left no policy referencing\n * `auth.uid()` directly — the drop's own precondition. (Its migration 0065 has\n * since moved both to `public`, calling `rebase.uid()`.)\n *\n * Matching on the body text is the only option available, and it is deliberately\n * broad: a false positive costs a schema that stays one release longer and says\n * why, while a false negative costs somebody their policies.\n */\nexport const LEGACY_RLS_FUNCTION_DEPENDENTS_SQL = `\n SELECT n.nspname AS schema, p.proname AS function\n FROM pg_proc p\n JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND NOT (n.nspname = '${LEGACY_RLS_SCHEMA}' AND p.proname IN ('uid', 'jwt', 'roles'))\n AND p.prosrc ~* '\\\\m${LEGACY_RLS_SCHEMA}\\\\.(uid|jwt|roles)\\\\s*\\\\('\n ORDER BY 1, 2\n`;\n\n/**\n * Retire the pre-1.0 `auth` schema, reporting what is holding it back.\n *\n * The shared implementation behind the CLI's post-push step and the runtime's\n * post-policy step. Both used to just fire {@link DROP_LEGACY_AUTH_SCHEMA_SQL}\n * and swallow whatever came back, which is right for the ordinary case — a\n * table not recompiled *yet* — and wrong for the one that never resolves: a\n * hand-written policy nothing will ever rewrite. Then the schema stays forever\n * and nothing ever says why.\n *\n * The drop itself had the same blind spot. A helper it did not recognise as\n * Rebase's stayed, and so did anything else in the schema, behind a\n * `DROP SCHEMA … RESTRICT` whose failure is swallowed so the helpers it did\n * drop stay dropped. The control plane's `auth.uid()` was one such: it read\n * `app.user_id` alone, the drop looked for `app.uid`, and the schema stayed\n * with no word said. So the schema is read twice. Before, so that one with no\n * Rebase helper in it is left alone: one already gone, as on every boot after\n * the drop, or one that was never Rebase's, like Supabase's — whose own\n * policies the checks below would otherwise report as blockers. After, to name\n * whatever is still there.\n */\nexport async function dropLegacyAuthSchema(\n run: (sql: string) => Promise<Record<string, unknown>[]>,\n report: { info: (m: string) => void; warn: (m: string) => void }\n): Promise<void> {\n let before: LegacyAuthSchemaObject[];\n try {\n before = sqlRows<LegacyAuthSchemaObject>(await run(LEGACY_AUTH_SCHEMA_CONTENTS_SQL));\n } catch {\n return; // No catalogue access; nothing here is worth failing a boot for.\n }\n if (!before.some(o => o.helper !== null)) return;\n // Only a lookalike: nothing will be dropped, so whatever calls it is no\n // blocker, and saying so would ask somebody to rewrite their own policies.\n if (!before.some(o => o.helper === \"ours\")) {\n report.warn(describeLegacyAuthLeftovers(before, undefined));\n return;\n }\n\n let blockers: LegacyRlsDependent[];\n try {\n blockers = sqlRows<LegacyRlsDependent>(await run(LEGACY_RLS_DEPENDENTS_SQL));\n } catch {\n return; // No catalogue access; nothing here is worth failing a boot for.\n }\n\n if (blockers.length > 0) {\n report.warn(\n `The pre-1.0 \\`${LEGACY_RLS_SCHEMA}\\` schema cannot be removed yet: ${blockers.length} ` +\n `${blockers.length === 1 ? \"policy still calls\" : \"policies still call\"} ` +\n `\\`${LEGACY_RLS_SCHEMA}.uid()\\` and friends, and Postgres will not drop a function a policy ` +\n `depends on. Rebase's own policies are ` +\n `rewritten automatically — anything listed here is hand-written SQL that has to be updated to ` +\n `\\`${REBASE_SCHEMA}.uid()\\` by hand, after which the schema goes on its own:\\n` +\n blockers.map(b => ` • ${b.schema}.${b.table} → \"${b.policy}\"`).join(\"\\n\")\n );\n return;\n }\n\n // The half Postgres will not refuse on. See LEGACY_RLS_FUNCTION_DEPENDENTS_SQL:\n // a string-literal SQL body records no dependency, so `DROP FUNCTION` drops\n // out from under a caller that is still using it and nothing complains until\n // a query runs.\n let borrowers: LegacyRlsFunctionDependent[];\n try {\n borrowers = sqlRows<LegacyRlsFunctionDependent>(await run(LEGACY_RLS_FUNCTION_DEPENDENTS_SQL));\n } catch {\n return;\n }\n\n if (borrowers.length > 0) {\n report.warn(\n `The pre-1.0 \\`${LEGACY_RLS_SCHEMA}\\` schema cannot be removed yet: ${borrowers.length} ` +\n `${borrowers.length === 1 ? \"function calls\" : \"functions call\"} ` +\n `\\`${LEGACY_RLS_SCHEMA}.uid()\\` and friends from its own body. Postgres records no dependency ` +\n `for that — a SQL body written as a string literal is never parsed — so dropping the helpers ` +\n `would leave these pointing at nothing, and they would fail when a query reached them rather ` +\n `than now. Repoint them at \\`${REBASE_SCHEMA}.uid()\\`, after which the schema goes on its own:\\n` +\n borrowers.map(b => ` • ${b.schema}.${b.function}()`).join(\"\\n\")\n );\n return;\n }\n\n // A failure is not fatal — the schema is inert now that no policy calls it —\n // but it is reported below with whatever it left, not on its own.\n let failure: string | undefined;\n try {\n await run(DROP_LEGACY_AUTH_SCHEMA_SQL);\n } catch (err) {\n // Postgres names the dependent object in DETAIL, not in the message.\n const detail = err instanceof Error && \"detail\" in err && typeof err.detail === \"string\" ? err.detail : \"\";\n failure = (err instanceof Error ? err.message : String(err)) +\n (detail ? ` (${detail.replace(/\\n/g, \"; \")})` : \"\");\n }\n\n let left: LegacyAuthSchemaObject[];\n try {\n left = sqlRows<LegacyAuthSchemaObject>(await run(LEGACY_AUTH_SCHEMA_CONTENTS_SQL));\n } catch {\n if (failure) report.info(`Left the \\`${LEGACY_RLS_SCHEMA}\\` schema in place: ${failure}`);\n return;\n }\n if (left.length === 0) return; // Gone.\n\n report.warn(describeLegacyAuthLeftovers(left, failure));\n}\n\n/** At most this many objects are named; a schema this full is plainly in use. */\nconst MAX_LEFTOVERS_NAMED = 20;\n\n/**\n * The warning for an `auth` schema the drop left standing.\n *\n * Said once for objects that are not Rebase's: on the next boot the schema holds\n * no helper, so {@link dropLegacyAuthSchema} leaves it alone — it is somebody\n * else's schema by then. A helper that is still there, Rebase's or a lookalike,\n * keeps it said on every boot until it goes.\n */\nfunction describeLegacyAuthLeftovers(left: LegacyAuthSchemaObject[], failure: string | undefined): string {\n const schema = LEGACY_RLS_SCHEMA;\n const objects = left.filter(o => o.object !== null);\n\n if (objects.length === 0) {\n return `The pre-1.0 \\`${schema}\\` schema is empty, but this connection could not drop it — most likely ` +\n `because it does not own the schema. Run \\`DROP SCHEMA ${schema};\\` as its owner.`;\n }\n\n const why = failure\n ? `dropping Rebase's old helpers from it failed: ${failure}.`\n : `\\`DROP SCHEMA … RESTRICT\\` refuses a schema that is not empty, and Rebase drops only the helpers it ` +\n `can tell are its own.`;\n\n const lines = objects.slice(0, MAX_LEFTOVERS_NAMED).map(o =>\n o.helper === \"ours\"\n ? ` • ${o.object} — Rebase's old helper, which could not be dropped`\n : o.helper === \"lookalike\"\n ? ` • ${o.object} — named and typed like Rebase's old helper, but no release wrote this body, ` +\n `so it was left alone; drop it by hand if nothing of yours calls it`\n : ` • ${o.object}`\n );\n if (objects.length > MAX_LEFTOVERS_NAMED) lines.push(` • …and ${objects.length - MAX_LEFTOVERS_NAMED} more`);\n\n return `The pre-1.0 \\`${schema}\\` schema is still here: ${why} Still in it:\\n` +\n lines.join(\"\\n\") + \"\\n\" +\n `Anything of yours can stay where it is — Rebase no longer uses this schema — or move out with ` +\n `\\`ALTER … SET SCHEMA\\`. Once the schema is empty, \\`DROP SCHEMA ${schema};\\` removes it.`;\n}\n\n/**\n * `rebase.is_request_role(role)` — is `role` one of the roles this database's\n * requests run as? The predicate `rls.policyTarget: \"requestRole\"` ANDs into\n * every permissive policy (`RLS_IS_REQUEST_ROLE_SQL`), called with\n * `current_user`.\n *\n * SECURITY DEFINER because the recorded roles live in `rebase.schema_meta`,\n * which the request roles cannot read. That is also why the caller's role is\n * an argument: inside the function `current_user` is its owner. The body is\n * dynamic SQL so the function can be created before the table exists — in\n * Atlas's replay of the migrations, for one. With nothing recorded the answer\n * is `rebase_user`, as everywhere else. Each recorded role's admin counterpart\n * (`<role>_admin`, what an admin request switches to) answers `true` as well.\n *\n * Created only for a project that asks for `policyTarget: \"requestRole\"`, so\n * every other project's migrations and boot are exactly what they were.\n */\nexport const REQUEST_ROLE_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.is_request_role(role_name text) RETURNS boolean AS $$\nDECLARE\n request_roles text[];\nBEGIN\n IF to_regclass('\"${REBASE_SCHEMA}\".\"schema_meta\"') IS NOT NULL THEN\n EXECUTE 'SELECT string_to_array(value, '','') FROM \"${REBASE_SCHEMA}\".\"schema_meta\" WHERE key = ''request_roles'''\n INTO request_roles;\n END IF;\n request_roles := COALESCE(request_roles, ARRAY['rebase_user']);\n -- An admin request runs as the request role's admin counterpart\n -- (adminRequestRoleFor), which is a request role here too.\n RETURN role_name = ANY(request_roles) OR role_name = ANY(ARRAY(SELECT r || '_admin' FROM unnest(request_roles) AS r));\nEND\n$$ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog`;\n\n/**\n * Create {@link REQUEST_ROLE_FUNCTION_SQL} when it is missing or its body\n * differs — replacing an unchanged function would still invalidate every\n * cached plan of every policy that calls it.\n */\nexport async function ensureRequestRoleFunction(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<void> {\n const body = /AS \\$\\$([\\s\\S]*)\\$\\$ LANGUAGE/.exec(REQUEST_ROLE_FUNCTION_SQL)?.[1];\n const [live] = await run(\n `SELECT p.prosrc AS body FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = '${REBASE_SCHEMA}' AND p.proname = 'is_request_role'`\n );\n if (live && String(live.body) === body) return;\n // `IF NOT EXISTS` still asks for CREATE on the database before it looks.\n const [schema] = await run(`SELECT to_regnamespace('${REBASE_SCHEMA}') IS NOT NULL AS present`);\n if (schema?.present !== true) await run(`CREATE SCHEMA IF NOT EXISTS ${REBASE_SCHEMA}`);\n await run(REQUEST_ROLE_FUNCTION_SQL);\n}\n\n/**\n * The statement that creates {@link REBASE_ADMIN_ROLE} when it is missing — a\n * role with no privilege that cannot log in, whose only job is to be what the\n * server-or-admin policies are written `TO`. Guarded in the statement, and a\n * concurrent creator's win taken as success, because a role belongs to the\n * cluster and two databases' boots can race for it.\n */\nexport const ADMIN_POLICY_ROLE_SQL = `DO $rebase_admin_role$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') THEN\n CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\nEXCEPTION\n WHEN duplicate_object OR unique_violation THEN NULL;\n WHEN insufficient_privilege THEN\n RAISE EXCEPTION 'Rebase writes its server-or-admin policies TO ${REBASE_ADMIN_ROLE}, which does not exist, and % may not create it.', current_user\n USING HINT = 'Run CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN; as an administrator, or declare database({ rls: { adminPolicies: \"public\" } }) (REBASE_RLS_ADMIN_POLICIES=public) to write them TO public.';\nEND\n$rebase_admin_role$`;\n\n/** Create {@link REBASE_ADMIN_ROLE} unless it exists — one read when it does. */\nexport async function ensureAdminPolicyRole(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<void> {\n const [row] = await run(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') AS present`);\n if (row?.present !== true) await run(ADMIN_POLICY_ROLE_SQL);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,2BAA8C;CACvD,+BAA+B;CAK/B,8BAA8B,cAAc;;;;;;CAO5C,8BAA8B,cAAc;;;;;;CAO5C,8BAA8B,cAAc;;;CAuB5C,8BAA8B,cAAc;;;AAGhD;;AAGA,IAAM,oBAAoB,UAGZ,KAAK,UAAU;CACzB,MAAM,QAAQ,YAAY;CAAG,MAAM,SAAS,YAAY;CAAG,MAAM;CAAY,MAAM;CAAQ,MAAM;CACjG,MAAM;CAAiB,MAAM;CAAW,MAAM;CAAM,MAAM;CAAW,MAAM;AAC/E,CAAC;;;;;;;;AASD,IAAM,6BAA8D;CAChE,MAAM,2BAAW,IAAI,IAAoB;CACzC,KAAK,MAAM,aAAa,0BAA0B;EAC9C,IAAI,gCAAgC,KAAK,SAAS,GAAG;EACrD,MAAM,QAAQ,qKACT,KAAK,SAAS;EACnB,IAAI,CAAC,OAAO,OAAO,KAAA;EACnB,MAAM,GAAG,QAAQ,MAAM,SAAS,MAAM,UAAU,YAAY,YAAY;EACxE,SAAS,IAAI,GAAG,OAAO,GAAG,QAAQ,iBAAiB;GAC/C;GAAS;GAAU,YAAY,WAAW,EAAE,CAAC,YAAY;GAAG,QAAQ;GAAO,WAAW,YAAY,SAAA,CAAU,EAAE,CAAC,YAAY;GAC3H,iBAAiB;GAAO,WAAW;GAAO,MAAM;GAAK,WAAW;GAAO;EAC3E,CAAC,CAAC;CACN;CACA,OAAO;AACX;;;;;;;;;;;;;;;AAgBA,eAAsB,oBAAoB,KAA4E;CAClH,MAAM,WAAW,qBAAqB;CACtC,IAAI,CAAC,UAAU,OAAO;CAEtB,MAAM,OAA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|
3
3
|
import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
|
|
4
4
|
import { n as VIEW_ROWS_COMMENT_PREFIX } from "./view-names-Dscp6--B.js";
|
|
5
|
-
import { ot as extractCauseMessage } from "./cli-errors-
|
|
5
|
+
import { ot as extractCauseMessage } from "./cli-errors-C73Qy7WJ.js";
|
|
6
|
+
import { t as cliRlsSettings } from "./rls-settings-BCGMIig3.js";
|
|
7
|
+
import { t as ADMIN_POLICY_ROLE_SQL } from "./rls-bootstrap-sql-CxszeSc7.js";
|
|
6
8
|
import { logger } from "@rebasepro/server";
|
|
7
9
|
import { sql } from "drizzle-orm";
|
|
8
|
-
import { ANONYMOUS_USER_ID, REBASE_SCHEMA, usesLegacyRlsFunctions } from "@rebasepro/types";
|
|
9
|
-
import { LOAD_REQUEST_ROLES_PLPGSQL, REBASE_INTERNAL_TABLES, REBASE_USER_ROLE as REBASE_USER_ROLE$1, findAnonymousGrants, revokeInternalTableAccess, revokeInternalTableSql, securityRuleToConditions } from "@rebasepro/common";
|
|
10
|
+
import { ANONYMOUS_USER_ID, REBASE_ADMIN_ROLE, REBASE_SCHEMA, holdsAdminRole, usesLegacyRlsFunctions } from "@rebasepro/types";
|
|
11
|
+
import { AUTH_USERS_TABLE, LOAD_REQUEST_ROLES_PLPGSQL, REBASE_INTERNAL_TABLES, REBASE_USER_ROLE as REBASE_USER_ROLE$1, findAnonymousGrants, revokeInternalTableAccess, revokeInternalTableSql, securityRuleToConditions } from "@rebasepro/common";
|
|
10
12
|
//#region src/security/rls-enforcement.ts
|
|
11
13
|
var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
|
|
12
14
|
AppRoleSetupError: () => AppRoleSetupError,
|
|
13
15
|
REBASE_USER_ROLE: () => REBASE_USER_ROLE$1,
|
|
14
16
|
REQUEST_ROLES_KEY: () => REQUEST_ROLES_KEY,
|
|
17
|
+
adminPoliciesLiveForCli: () => adminPoliciesLiveForCli,
|
|
18
|
+
adminSwitchLive: () => adminSwitchLive,
|
|
15
19
|
appRoleSetupInstructions: () => appRoleSetupInstructions,
|
|
16
20
|
applyAuthContext: () => applyAuthContext,
|
|
17
21
|
assertAppRoleRestricted: () => assertAppRoleRestricted,
|
|
18
22
|
assertRecordedRequestRoles: () => assertRecordedRequestRoles,
|
|
19
23
|
authContextStatement: () => authContextStatement,
|
|
20
24
|
detectConnectionPosture: () => detectConnectionPosture,
|
|
25
|
+
ensureAdminRequestRole: () => ensureAdminRequestRole,
|
|
21
26
|
ensureAppRole: () => ensureAppRole,
|
|
22
27
|
ensureAppRoleGrants: () => ensureAppRoleGrants,
|
|
28
|
+
ensureConnectionInheritsAdminRole: () => ensureConnectionInheritsAdminRole,
|
|
23
29
|
ensureInheritedRoles: () => ensureInheritedRoles,
|
|
24
30
|
findExposedInternalTables: () => findExposedInternalTables,
|
|
25
31
|
findOtherRoleMembers: () => findOtherRoleMembers,
|
|
@@ -30,6 +36,8 @@ var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
|
|
|
30
36
|
recordRequestRoles: () => recordRequestRoles,
|
|
31
37
|
revokeUserRoleSql: () => revokeUserRoleSql,
|
|
32
38
|
roleHoldsTableGrants: () => roleHoldsTableGrants,
|
|
39
|
+
settleAdminRequestRoles: () => settleAdminRequestRoles,
|
|
40
|
+
settleAdminSwitch: () => settleAdminSwitch,
|
|
33
41
|
validatePolicyPgRoles: () => validatePolicyPgRoles,
|
|
34
42
|
warnOnAnonymousGrants: () => warnOnAnonymousGrants,
|
|
35
43
|
warnOnLegacyRlsFunctions: () => warnOnLegacyRlsFunctions,
|
|
@@ -510,6 +518,11 @@ async function ensureAppRole(run, schemas, options = {}) {
|
|
|
510
518
|
logger.debug(`🔐 [rls] User role "${role}" provisioned (schemas: ${uniqueSchemas.join(", ")})`);
|
|
511
519
|
}
|
|
512
520
|
/**
|
|
521
|
+
* SQL: whether `c` (in namespace `n`) is a table the request roles are kept
|
|
522
|
+
* off when RLS is off on it — see `withheldTablesIn`.
|
|
523
|
+
*/
|
|
524
|
+
var isWithheldTable = (c, n) => `(${c}.relname = ANY(${textArray(REBASE_INTERNAL_TABLES)}) OR (${n}.nspname = ${sqlLiteral(AUTH_USERS_TABLE.schema)} AND ${c}.relname = ${sqlLiteral(AUTH_USERS_TABLE.table)}))`;
|
|
525
|
+
/**
|
|
513
526
|
* The framework's internal tables in `schemas` that the request role can
|
|
514
527
|
* reach — `schema.table`, sorted — when nothing is left to take it back off.
|
|
515
528
|
*
|
|
@@ -531,7 +544,7 @@ async function findExposedInternalTables(run, schemas, role = REBASE_USER_ROLE$1
|
|
|
531
544
|
SELECT n.nspname || '.' || c.relname AS name
|
|
532
545
|
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
533
546
|
WHERE n.nspname = ANY(${textArray(Array.from(new Set(schemas)))})
|
|
534
|
-
AND
|
|
547
|
+
AND ${isWithheldTable("c", "n")}
|
|
535
548
|
AND c.relkind IN ('r', 'p')
|
|
536
549
|
AND NOT c.relrowsecurity
|
|
537
550
|
AND (has_table_privilege(${sqlLiteral(role)}, c.oid, 'SELECT, INSERT, UPDATE, DELETE')
|
|
@@ -600,7 +613,6 @@ async function readSchemaGrants(run, schemas, role = REBASE_USER_ROLE$1, managed
|
|
|
600
613
|
const onlyManagedSequences = managed ? `AND EXISTS (SELECT 1 FROM pg_depend d JOIN pg_class t ON t.oid = d.refobjid
|
|
601
614
|
WHERE d.objid = c.oid AND d.deptype IN ('a', 'i')
|
|
602
615
|
AND (n.nspname, t.relname::text) IN ${managed})` : "";
|
|
603
|
-
const internal = textArray(REBASE_INTERNAL_TABLES);
|
|
604
616
|
const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(role)})`;
|
|
605
617
|
/** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */
|
|
606
618
|
const held = (acl, privileges, grantor) => `(SELECT count(DISTINCT a.privilege_type) FROM aclexplode(${acl}) a WHERE a.grantee = ${target}${grantor ? ` AND a.grantor IN (${grantor}, ${CURRENT_ROLE_OID})` : ""} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(", ")}))`;
|
|
@@ -622,7 +634,7 @@ async function readSchemaGrants(run, schemas, role = REBASE_USER_ROLE$1, managed
|
|
|
622
634
|
ARRAY(
|
|
623
635
|
SELECT c.relname::text FROM pg_class c
|
|
624
636
|
WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')
|
|
625
|
-
AND NOT (c
|
|
637
|
+
AND NOT (${isWithheldTable("c", "n")} AND NOT c.relrowsecurity)
|
|
626
638
|
AND ${mayGrant("table", "c.oid", "c.relowner", DML)}
|
|
627
639
|
${onlyManagedTables}
|
|
628
640
|
AND NOT ${viewRows("c")}
|
|
@@ -651,7 +663,7 @@ async function readSchemaGrants(run, schemas, role = REBASE_USER_ROLE$1, managed
|
|
|
651
663
|
) AS default_sequences,
|
|
652
664
|
ARRAY(
|
|
653
665
|
SELECT c.relname::text FROM pg_class c
|
|
654
|
-
WHERE c.relnamespace = n.oid AND c
|
|
666
|
+
WHERE c.relnamespace = n.oid AND ${isWithheldTable("c", "n")} AND NOT c.relrowsecurity
|
|
655
667
|
AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))
|
|
656
668
|
ORDER BY 1
|
|
657
669
|
) AS internal_granted,
|
|
@@ -714,6 +726,196 @@ async function ensureInheritedRoles(run, role, inheritRoles) {
|
|
|
714
726
|
}
|
|
715
727
|
}
|
|
716
728
|
/**
|
|
729
|
+
* Provision the role admin requests run as for one request role:
|
|
730
|
+
* `<role>_admin`, inheriting `role` — its grants, and every policy written
|
|
731
|
+
* for it — and {@link REBASE_ADMIN_ROLE}, with the connection able to switch
|
|
732
|
+
* to it. The role itself goes through {@link ensureAppRole} (created NOLOGIN
|
|
733
|
+
* NOSUPERUSER NOBYPASSRLS, checked as restricted when found, the switch
|
|
734
|
+
* proved), with no grants of its own: everything it can reach, it reaches as
|
|
735
|
+
* `role` does.
|
|
736
|
+
*
|
|
737
|
+
* Inheriting is per grant from PostgreSQL 16 (`WITH INHERIT TRUE`); before
|
|
738
|
+
* that it is the role's own `INHERIT` attribute, harmless here because this
|
|
739
|
+
* role belongs to exactly the two roles granted below.
|
|
740
|
+
*/
|
|
741
|
+
async function ensureAdminRequestRole(run, schemas, options) {
|
|
742
|
+
const { role, adminRole } = options;
|
|
743
|
+
const provision = options.provisionRole !== "never";
|
|
744
|
+
const [present] = await run(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') AS present`);
|
|
745
|
+
if (present?.present !== true) {
|
|
746
|
+
if (!provision) throw new AppRoleSetupError(`The role "${REBASE_ADMIN_ROLE}" does not exist, and rls.provisionRole is "never", so Rebase does not create it.`, `Run as a database administrator, then restart:\n\nCREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;`);
|
|
747
|
+
await run(ADMIN_POLICY_ROLE_SQL);
|
|
748
|
+
}
|
|
749
|
+
await ensureAppRole(run, schemas, {
|
|
750
|
+
role: adminRole,
|
|
751
|
+
provisionRole: options.provisionRole,
|
|
752
|
+
grants: "none"
|
|
753
|
+
});
|
|
754
|
+
const [state] = await run(`
|
|
755
|
+
SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,
|
|
756
|
+
r.rolinherit AS inherits_all,
|
|
757
|
+
pg_has_role(r.oid, to_regrole(${sqlLiteral(role)}), 'USAGE') AS has_request_role,
|
|
758
|
+
pg_has_role(r.oid, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE') AS has_admin_role
|
|
759
|
+
FROM pg_roles r WHERE r.rolname = ${sqlLiteral(adminRole)}
|
|
760
|
+
`);
|
|
761
|
+
const perGrant = state?.per_grant === true;
|
|
762
|
+
const missing = [...state?.has_request_role === true ? [] : [role], ...state?.has_admin_role === true ? [] : [REBASE_ADMIN_ROLE]];
|
|
763
|
+
if (missing.length === 0) return;
|
|
764
|
+
const statements = [...!perGrant && state?.inherits_all !== true ? [`ALTER ROLE ${adminRole} INHERIT`] : [], ...missing.map((granted) => perGrant ? `GRANT ${quoteIdent(granted)} TO ${adminRole} WITH INHERIT TRUE, SET FALSE` : `GRANT ${quoteIdent(granted)} TO ${adminRole}`)];
|
|
765
|
+
const instructions = `Run as a database administrator, then restart:\n\n${statements.map((st) => `${st};`).join("\n")}`;
|
|
766
|
+
if (!provision) throw new AppRoleSetupError(`The admin request role "${adminRole}" does not inherit ${missing.map((m) => `"${m}"`).join(" and ")}, and rls.provisionRole is "never", so Rebase does not grant it.`, instructions);
|
|
767
|
+
try {
|
|
768
|
+
for (const statement of statements) await run(statement);
|
|
769
|
+
} catch (err) {
|
|
770
|
+
throw new AppRoleSetupError(`Could not let the admin request role "${adminRole}" inherit ${missing.map((m) => `"${m}"`).join(" and ")}: ${failureReason(err)}`, instructions);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Let the connection role itself pass the server-or-admin policies, by
|
|
775
|
+
* inheriting {@link REBASE_ADMIN_ROLE} — which is what `TO public` gave it.
|
|
776
|
+
*
|
|
777
|
+
* It matters where the connection is subject to RLS: always, when it owns
|
|
778
|
+
* none of the tables (requests then run as the connection itself, so the
|
|
779
|
+
* server context and admins depend on it), and on any table it does not own
|
|
780
|
+
* otherwise. Best effort: a connection that cannot be granted the role is
|
|
781
|
+
* told what to run, and its server-context and admin reads of those tables are
|
|
782
|
+
* refused — closed, never wider — until someone does.
|
|
783
|
+
*/
|
|
784
|
+
async function ensureConnectionInheritsAdminRole(run, options) {
|
|
785
|
+
const [state] = await run(`
|
|
786
|
+
SELECT current_user AS role,
|
|
787
|
+
(SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user) AS exempt,
|
|
788
|
+
current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,
|
|
789
|
+
to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present,
|
|
790
|
+
COALESCE(pg_has_role(current_user, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false) AS inherits
|
|
791
|
+
`);
|
|
792
|
+
if (state?.exempt === true || state?.inherits === true) return;
|
|
793
|
+
const connection = String(state?.role ?? "");
|
|
794
|
+
const grant = state?.per_grant === true ? `GRANT ${REBASE_ADMIN_ROLE} TO ${quoteIdent(connection)} WITH INHERIT TRUE, SET FALSE` : `GRANT ${REBASE_ADMIN_ROLE} TO ${quoteIdent(connection)}`;
|
|
795
|
+
const warn = (why, roleExists) => (roleExists ? (m) => logger.warn(m) : (m) => logger.debug(m))(`⚠️ RLS enforcement: the connection role "${connection}" does not inherit "${REBASE_ADMIN_ROLE}" (${why}), so on any table it does not own, its server-context and admin requests do not pass the server-or-admin policies and are refused. Run as an administrator: ${roleExists ? "" : `CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN; `}${grant}; — or declare rls.adminPolicies "public".`);
|
|
796
|
+
if (!options.provision) {
|
|
797
|
+
warn("this driver was opened without provisioning", state?.present === true);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
let roleExists = state?.present === true;
|
|
801
|
+
try {
|
|
802
|
+
if (!roleExists) await run(ADMIN_POLICY_ROLE_SQL);
|
|
803
|
+
roleExists = true;
|
|
804
|
+
await run(grant);
|
|
805
|
+
} catch (err) {
|
|
806
|
+
warn(failureReason(err), roleExists);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* The request identity a boot hands the driver and the realtime refetch, with
|
|
811
|
+
* the admin switch on when every admin request role is ready: provisioned
|
|
812
|
+
* here, or — on a boot that provisions nothing — found existing, inheriting
|
|
813
|
+
* what it should and switchable. Otherwise admin requests run as the request
|
|
814
|
+
* role, as before, and the boot says why: under `adminPolicies: "adminRole"`,
|
|
815
|
+
* policies already written `TO rebase_admin` then refuse them.
|
|
816
|
+
*/
|
|
817
|
+
async function settleAdminRequestRoles(run, schemas, settings, options) {
|
|
818
|
+
if (settings.adminRoles.size === 0) return settings.request;
|
|
819
|
+
const failures = [];
|
|
820
|
+
for (const [role, adminRole] of settings.adminRoles) try {
|
|
821
|
+
await ensureAdminRequestRole(run, schemas, {
|
|
822
|
+
role,
|
|
823
|
+
adminRole,
|
|
824
|
+
provisionRole: options.provision ? settings.provisionRole : "never"
|
|
825
|
+
});
|
|
826
|
+
} catch (err) {
|
|
827
|
+
failures.push(`"${adminRole}": ${err instanceof Error ? err.message : String(err)}`);
|
|
828
|
+
}
|
|
829
|
+
if (failures.length > 0) {
|
|
830
|
+
const [marker] = await run(`SELECT to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present`);
|
|
831
|
+
(marker?.present === true ? (m) => logger.warn(m) : (m) => logger.info(m))(`${marker?.present === true ? "⚠️" : "🔐"} RLS enforcement: admin requests keep running as the request role, because ${failures.join("; ")}. The server-or-admin policies are written TO public by this server until that is fixed, so signed-in users' owner-scoped reads cannot use the owner index. Create ${REBASE_ADMIN_ROLE} and the admin request role as above to change that, or declare adminPolicies "public" to say this on purpose.`);
|
|
832
|
+
return settings.request;
|
|
833
|
+
}
|
|
834
|
+
const adminRoles = settings.adminRoles;
|
|
835
|
+
return {
|
|
836
|
+
...settings.request,
|
|
837
|
+
adminRoleFor: (role) => adminRoles.get(role)
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Whether policies written `TO rebase_admin` reach every caller they are for on
|
|
842
|
+
* this connection, read from the catalogue without changing anything: the role
|
|
843
|
+
* exists, the connection passes it (exempt from RLS, or inheriting it — the
|
|
844
|
+
* server context on tables it does not own), and each of `adminRoles` exists,
|
|
845
|
+
* inherits its request role and `rebase_admin`, and the connection can switch
|
|
846
|
+
* into it. The state {@link settleAdminRequestRoles} and
|
|
847
|
+
* {@link ensureConnectionInheritsAdminRole} leave when both succeed.
|
|
848
|
+
*
|
|
849
|
+
* With `existingOnly`, an admin role that does not exist is passed over, but at
|
|
850
|
+
* least one must be ready: for a role list read back from the database, which
|
|
851
|
+
* does not say which role is an anonymous one with no admin counterpart.
|
|
852
|
+
*
|
|
853
|
+
* Anything it cannot read answers `false`, and `false` means `TO public`: the
|
|
854
|
+
* shape every caller passes, as before the admin role existed.
|
|
855
|
+
*/
|
|
856
|
+
async function adminSwitchLive(run, adminRoles, options = {}) {
|
|
857
|
+
if (adminRoles.size === 0) return false;
|
|
858
|
+
const [connection] = await run(`
|
|
859
|
+
SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,
|
|
860
|
+
to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present,
|
|
861
|
+
COALESCE((SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user), false)
|
|
862
|
+
OR COALESCE(pg_has_role(current_user, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false) AS passes
|
|
863
|
+
`);
|
|
864
|
+
if (connection?.present !== true || connection?.passes !== true) return false;
|
|
865
|
+
const privilege = connection.per_grant === true ? "SET" : "MEMBER";
|
|
866
|
+
let ready = 0;
|
|
867
|
+
for (const [role, adminRole] of adminRoles) {
|
|
868
|
+
const [state] = await run(`
|
|
869
|
+
SELECT to_regrole(${sqlLiteral(adminRole)}) IS NOT NULL AS present,
|
|
870
|
+
COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole(${sqlLiteral(role)}), 'USAGE'), false)
|
|
871
|
+
AND COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false)
|
|
872
|
+
AND COALESCE(pg_has_role(current_user, to_regrole(${sqlLiteral(adminRole)}), '${privilege}'), false) AS ready
|
|
873
|
+
`);
|
|
874
|
+
if (options.existingOnly && state?.present !== true) continue;
|
|
875
|
+
if (state?.ready !== true) return false;
|
|
876
|
+
ready++;
|
|
877
|
+
}
|
|
878
|
+
return ready > 0;
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* The admin switch for a boot whose requests switch roles: settle the admin
|
|
882
|
+
* request roles and the connection's `rebase_admin`, then say whether the
|
|
883
|
+
* switch is live — which is what decides where the policies step writes the
|
|
884
|
+
* server-or-admin policies. `TO rebase_admin` only when it is: written there
|
|
885
|
+
* while admin requests still run as the request role, they refuse every admin
|
|
886
|
+
* caller, `dataAsAdmin` included, as an empty table. Otherwise `TO public`, the
|
|
887
|
+
* documented fallback, which the request role passes.
|
|
888
|
+
*/
|
|
889
|
+
async function settleAdminSwitch(run, schemas, settings, options) {
|
|
890
|
+
const request = await settleAdminRequestRoles(run, schemas, settings, options);
|
|
891
|
+
if (settings.adminPolicies !== "adminRole") return {
|
|
892
|
+
request,
|
|
893
|
+
adminPoliciesLive: false
|
|
894
|
+
};
|
|
895
|
+
await ensureConnectionInheritsAdminRole(run, options);
|
|
896
|
+
return {
|
|
897
|
+
request,
|
|
898
|
+
adminPoliciesLive: request.adminRoleFor !== void 0 && await adminSwitchLive(run, settings.adminRoles)
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Where `db push` and `rebase doctor` expect the server-or-admin policies, for
|
|
903
|
+
* the request roles this database records (or the configured ones): `TO
|
|
904
|
+
* rebase_admin` only when {@link adminSwitchLive} says a server on this
|
|
905
|
+
* connection would have the switch live, `TO public` otherwise — the same
|
|
906
|
+
* answer a boot reaches, without provisioning anything. Settings that do not
|
|
907
|
+
* resolve answer `false`.
|
|
908
|
+
*/
|
|
909
|
+
async function adminPoliciesLiveForCli(run) {
|
|
910
|
+
try {
|
|
911
|
+
const settings = cliRlsSettings(await readRecordedRequestRoles(run));
|
|
912
|
+
if (settings.adminPolicies !== "adminRole") return false;
|
|
913
|
+
return await adminSwitchLive(run, settings.adminRoles, { existingOnly: true });
|
|
914
|
+
} catch {
|
|
915
|
+
return false;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
717
919
|
* The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing
|
|
718
920
|
* schema in `schemas`, DML on its tables and `USAGE, SELECT` on its
|
|
719
921
|
* sequences, the default privileges that cover what this role creates later,
|
|
@@ -850,7 +1052,8 @@ function authContextSettings(auth, userRole) {
|
|
|
850
1052
|
];
|
|
851
1053
|
const role = typeof userRole === "object" ? userRole.roleFor(auth) : userRole;
|
|
852
1054
|
if (typeof userRole === "object" && role) for (const [name, value] of userRole.settingsFor(auth, role)) settings.push([name, value]);
|
|
853
|
-
|
|
1055
|
+
const admin = role && typeof userRole === "object" && holdsAdminRole(normalizedRoles.map(String)) ? userRole.adminRoleFor?.(role) : void 0;
|
|
1056
|
+
if (role) settings.push(["role", admin ?? role]);
|
|
854
1057
|
return settings;
|
|
855
1058
|
}
|
|
856
1059
|
/** Role names from other BaaS platforms that people reach for out of habit. */
|
|
@@ -987,6 +1190,6 @@ async function validatePolicyPgRoles(run, collections, requestRoles = REBASE_USE
|
|
|
987
1190
|
if (problems.length > 0) throw new Error(`Security rules target PostgreSQL roles this server cannot use. Requests run as "${requestRole}", so these policies would never apply and every row would be filtered out — the collections would look empty rather than error.\n\n` + problems.join("\n\n") + "\n");
|
|
988
1191
|
}
|
|
989
1192
|
//#endregion
|
|
990
|
-
export {
|
|
1193
|
+
export { warnOnAnonymousGrants as C, validatePolicyPgRoles as S, warnOnRoleSchemaCollision as T, recordRequestRoles as _, assertRecordedRequestRoles as a, roleHoldsTableGrants as b, ensureAppRole as c, findExposedInternalTables as d, findOtherRoleMembers as f, readRecordedRequestRoles as g, proveRoleSwitch as h, assertAppRoleRestricted as i, ensureAppRoleGrants as l, internalTablesGrantedToUserRole as m, appRoleSetupInstructions as n, authContextStatement as o, findUngrantableTables as p, applyAuthContext as r, detectConnectionPosture as s, REBASE_USER_ROLE$1 as t, ensureConnectionInheritsAdminRole as u, revokeUserRoleSql as v, warnOnLegacyRlsFunctions as w, settleAdminSwitch as x, rls_enforcement_exports as y };
|
|
991
1194
|
|
|
992
|
-
//# sourceMappingURL=rls-enforcement-
|
|
1195
|
+
//# sourceMappingURL=rls-enforcement-CyUCPDH8.js.map
|