@rebasepro/server-postgres 0.32.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BranchService-C8LtpMho.js → BranchService-Bdin0Wxh.js} +3 -3
- package/dist/{BranchService-C8LtpMho.js.map → BranchService-Bdin0Wxh.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +3 -0
- package/dist/{backup-cli-DtV6n3oB.js → backup-cli-BEAMPWMs.js} +3 -3
- package/dist/{backup-cli-DtV6n3oB.js.map → backup-cli-BEAMPWMs.js.map} +1 -1
- package/dist/{boot-ddl-CSYhSSZD.js → boot-ddl-Bu6gAY-2.js} +2 -2
- package/dist/{boot-ddl-CSYhSSZD.js.map → boot-ddl-Bu6gAY-2.js.map} +1 -1
- package/dist/{cli-console-Cu1DzqvR.js → cli-console-DjFiYlSe.js} +4 -4
- package/dist/{cli-console-Cu1DzqvR.js.map → cli-console-DjFiYlSe.js.map} +1 -1
- package/dist/cli-errors.d.ts +12 -0
- package/dist/cli-helpers.d.ts +20 -0
- package/dist/{cli-schema-dir-DuZIsF2e.js → cli-schema-dir-CjDH_31U.js} +111 -5
- package/dist/cli-schema-dir-CjDH_31U.js.map +1 -0
- package/dist/cli.js +28 -23
- package/dist/cli.js.map +1 -1
- package/dist/{database-preflight-CyTCWlfc.js → database-preflight-DKzsGnc4.js} +2 -2
- package/dist/{database-preflight-CyTCWlfc.js.map → database-preflight-DKzsGnc4.js.map} +1 -1
- package/dist/{deferred-index-build-ueYVUBZc.js → deferred-index-build-88bWtYgx.js} +4 -4
- package/dist/{deferred-index-build-ueYVUBZc.js.map → deferred-index-build-88bWtYgx.js.map} +1 -1
- package/dist/{ensure-policies-13mHWjBs.js → ensure-policies-nIITKxud.js} +6 -6
- package/dist/{ensure-policies-13mHWjBs.js.map → ensure-policies-nIITKxud.js.map} +1 -1
- package/dist/{ensure-tables-B3Kh2RwT.js → ensure-tables-Lm-77eM5.js} +6 -6
- package/dist/{ensure-tables-B3Kh2RwT.js.map → ensure-tables-Lm-77eM5.js.map} +1 -1
- package/dist/{ensure-tables-DM1U9AZK.js → ensure-tables-hQ5oAK_j.js} +3 -3
- package/dist/{ensure-tables-DM1U9AZK.js.map → ensure-tables-hQ5oAK_j.js.map} +1 -1
- package/dist/{enum-labels-kept-CJDVtX14.js → enum-labels-kept-mesgEJWH.js} +2 -2
- package/dist/{enum-labels-kept-CJDVtX14.js.map → enum-labels-kept-mesgEJWH.js.map} +1 -1
- package/dist/index.es.js +11 -11
- package/dist/{migrate-baseline-DnMlSDup.js → migrate-baseline-Bzj5gSCM.js} +2 -2
- package/dist/{migrate-baseline-DnMlSDup.js.map → migrate-baseline-Bzj5gSCM.js.map} +1 -1
- package/dist/{migrate-policy-stamps-BpHyEFkk.js → migrate-policy-stamps-C2WaOEsB.js} +4 -4
- package/dist/{migrate-policy-stamps-BpHyEFkk.js.map → migrate-policy-stamps-C2WaOEsB.js.map} +1 -1
- package/dist/{open-rebase-B2mAA7UE.js → open-rebase-OB4hhQuk.js} +391 -33
- package/dist/open-rebase-OB4hhQuk.js.map +1 -0
- package/dist/{pg-error-utils-CpUiBkp-.js → pg-error-utils-CWopxboq.js} +2 -2
- package/dist/{pg-error-utils-CpUiBkp-.js.map → pg-error-utils-CWopxboq.js.map} +1 -1
- package/dist/{policy-drift-C9xRcbsU.js → policy-drift-rVLKS2AG.js} +3 -3
- package/dist/{policy-drift-C9xRcbsU.js.map → policy-drift-rVLKS2AG.js.map} +1 -1
- package/dist/{push-index-adoption-D-ph6kBc.js → push-index-adoption-EcamXfW2.js} +2 -2
- package/dist/{push-index-adoption-D-ph6kBc.js.map → push-index-adoption-EcamXfW2.js.map} +1 -1
- package/dist/{push-index-prebuild-DUKtH87s.js → push-index-prebuild-BPIns6wA.js} +3 -3
- package/dist/{push-index-prebuild-DUKtH87s.js.map → push-index-prebuild-BPIns6wA.js.map} +1 -1
- package/dist/{push-legacy-renames-wLSsAg80.js → push-legacy-renames-lmYkb41I.js} +3 -3
- package/dist/{push-legacy-renames-wLSsAg80.js.map → push-legacy-renames-lmYkb41I.js.map} +1 -1
- package/dist/{push-policy-plan-I9RNoP_-.js → push-policy-plan-Dqu4FKWh.js} +3 -3
- package/dist/{push-policy-plan-I9RNoP_-.js.map → push-policy-plan-Dqu4FKWh.js.map} +1 -1
- package/dist/{request-role-cli-D9yWoeSl.js → request-role-cli-Ay0v9oYZ.js} +8 -8
- package/dist/{request-role-cli-D9yWoeSl.js.map → request-role-cli-Ay0v9oYZ.js.map} +1 -1
- package/dist/{request-role-migration-DQLiYJ4c.js → request-role-migration-DTE3Owsh.js} +2 -2
- package/dist/{request-role-migration-DQLiYJ4c.js.map → request-role-migration-DTE3Owsh.js.map} +1 -1
- package/dist/{rls-enforcement-Cwh5SJRx.js → rls-enforcement-Ck-d8zdJ.js} +2 -2
- package/dist/{rls-enforcement-Cwh5SJRx.js.map → rls-enforcement-Ck-d8zdJ.js.map} +1 -1
- package/dist/schema/doctor-cli.js +5 -5
- package/dist/schema/introspect-db.js +1 -1
- package/dist/services/cdc/CdcListener.d.ts +12 -0
- package/dist/services/cdc/pgoutput.d.ts +6 -0
- package/dist/services/realtime-prefilter.d.ts +90 -0
- package/dist/services/realtimeService.d.ts +39 -1
- package/dist/utils/connection-string.d.ts +9 -1
- package/dist/{websocket-CSVNOYHC.js → websocket-kZixcOXt.js} +3 -3
- package/dist/{websocket-CSVNOYHC.js.map → websocket-kZixcOXt.js.map} +1 -1
- package/package.json +7 -7
- package/dist/cli-schema-dir-DuZIsF2e.js.map +0 -1
- package/dist/open-rebase-B2mAA7UE.js.map +0 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { i as __exportAll, t as promptConfirm } from "./cli-prompt-DXG0yk-h.js";
|
|
4
|
-
import {
|
|
4
|
+
import { ct as redactConnectionPasswords } from "./cli-schema-dir-CjDH_31U.js";
|
|
5
5
|
import { n as resolveRlsSettings } from "./rls-settings-CmGK2U0a.js";
|
|
6
6
|
import { a as outWarn, i as outError, r as out, t as chalk } from "./source-VxbrQojV.js";
|
|
7
|
-
import { _ as closestWord, v as parseCommandFlags } from "./migrate-baseline-
|
|
7
|
+
import { _ as closestWord, v as parseCommandFlags } from "./migrate-baseline-Bzj5gSCM.js";
|
|
8
8
|
import { REBASE_USER_ROLE } from "@rebasepro/common";
|
|
9
9
|
//#region src/request-role-cli.ts
|
|
10
10
|
var request_role_cli_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -163,8 +163,8 @@ function databaseUrlOrExit() {
|
|
|
163
163
|
async function provisionCommand(rawArgs) {
|
|
164
164
|
parseProvisionLine(rawArgs);
|
|
165
165
|
const databaseUrl = databaseUrlOrExit();
|
|
166
|
-
const { withAppClient } = await import("./cli-schema-dir-
|
|
167
|
-
const { appRoleSetupInstructions, readRecordedRequestRoles } = await import("./rls-enforcement-
|
|
166
|
+
const { withAppClient } = await import("./cli-schema-dir-CjDH_31U.js").then((n) => n.S);
|
|
167
|
+
const { appRoleSetupInstructions, readRecordedRequestRoles } = await import("./rls-enforcement-Ck-d8zdJ.js").then((n) => n.y);
|
|
168
168
|
const { cliRlsSettings } = await import("./rls-settings-CmGK2U0a.js").then((n) => n.a);
|
|
169
169
|
out(await withAppClient(databaseUrl, async (client) => {
|
|
170
170
|
const run = async (text) => (await client.query(text)).rows;
|
|
@@ -195,9 +195,9 @@ async function confirmMigration(yes) {
|
|
|
195
195
|
async function requestRoleCommand(rawArgs) {
|
|
196
196
|
const line = parseRequestRoleLine(rawArgs);
|
|
197
197
|
const databaseUrl = databaseUrlOrExit();
|
|
198
|
-
const { withAppClient } = await import("./cli-schema-dir-
|
|
199
|
-
const { AppRoleSetupError, readRecordedRequestRoles } = await import("./rls-enforcement-
|
|
200
|
-
const { migrateRequestRoles, planRequestRoleMigration } = await import("./request-role-migration-
|
|
198
|
+
const { withAppClient } = await import("./cli-schema-dir-CjDH_31U.js").then((n) => n.S);
|
|
199
|
+
const { AppRoleSetupError, readRecordedRequestRoles } = await import("./rls-enforcement-Ck-d8zdJ.js").then((n) => n.y);
|
|
200
|
+
const { migrateRequestRoles, planRequestRoleMigration } = await import("./request-role-migration-DTE3Owsh.js");
|
|
201
201
|
out("");
|
|
202
202
|
out(chalk.bold(" rebase db request-role migrate"));
|
|
203
203
|
out("");
|
|
@@ -257,4 +257,4 @@ function requestRoleReminder(to) {
|
|
|
257
257
|
//#endregion
|
|
258
258
|
export { parseRequestRoleLine as n, request_role_cli_exports as r, parseProvisionLine as t };
|
|
259
259
|
|
|
260
|
-
//# sourceMappingURL=request-role-cli-
|
|
260
|
+
//# sourceMappingURL=request-role-cli-Ay0v9oYZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-role-cli-D9yWoeSl.js","names":[],"sources":["../src/request-role-cli.ts"],"sourcesContent":["/**\n * `rebase db request-role migrate` and `rebase db provision --print`: the\n * commands that move a database to another request role, and show the SQL\n * that sets one up, for a database Rebase does not own outright.\n *\n * The line parsers and the renderers are pure and load nothing heavy, because\n * `db-command-line.ts` judges every `rebase db …` line with them before the\n * CLI starts a database. The commands themselves import the security modules\n * and the connection only when they run.\n */\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\nimport { REBASE_USER_ROLE } from \"@rebasepro/common\";\n\nimport { closestWord, parseCommandFlags } from \"./cli-flags\";\nimport { out, outError, outWarn } from \"./cli-output\";\nimport { promptConfirm } from \"./cli-prompt\";\nimport { redactConnectionPasswords } from \"./utils/connection-string\";\nimport { resolveRlsSettings, type RlsSettings } from \"./security/rls-settings\";\nimport type { RequestRoleMigrationPlan } from \"./security/request-role-migration\";\nimport type { RawSqlRunner } from \"./security/rls-enforcement\";\n\n/**\n * The schemas both commands provision in: the ones `db push` and `db migrate`\n * provision the request role in after a schema change.\n */\nexport const REQUEST_ROLE_SCHEMAS = [\"public\", \"rebase\"] as const;\n\n/** The actions `rebase db request-role` answers. */\nexport const REQUEST_ROLE_ACTIONS = [\"migrate\"] as const;\n\n/** The flags of `rebase db request-role migrate`. Named `…FLAGS` so the docs verifier reads them. */\nexport const REQUEST_ROLE_FLAGS = {\n \"--to\": String,\n \"--dry-run\": Boolean,\n \"--yes\": Boolean,\n \"-y\": \"--yes\"\n} satisfies arg.Spec;\n\n/** The flags of `rebase db provision`. */\nexport const PROVISION_FLAGS = {\n \"--print\": Boolean\n} satisfies arg.Spec;\n\nexport interface RequestRoleLine {\n action: typeof REQUEST_ROLE_ACTIONS[number];\n /** The role(s) to move to, in the order given, without duplicates. */\n to: string[];\n dryRun: boolean;\n yes: boolean;\n}\n\n/**\n * `\"app_prod_user, app_prod_anon\"` → `[\"app_prod_user\", \"app_prod_anon\"]`.\n * Each name is checked by the same rule the `rls.requestRole` setting uses, so\n * a name the server would refuse at boot is refused here, before anything runs.\n */\nexport function parseRoleList(value: string, flag: string): string[] {\n const roles = Array.from(new Set(value.split(\",\").map((r) => r.trim()).filter(Boolean)));\n if (roles.length === 0) throw new Error(`${flag} needs at least one role name, e.g. ${flag} app_prod_user.`);\n for (const role of roles) {\n try {\n resolveRlsSettings({ requestRole: role });\n } catch (err) {\n throw new Error(`${flag} ${role}: ${err instanceof Error ? err.message.replace(/^[^:]*:\\s*/, \"\") : String(err)}`);\n }\n }\n return roles;\n}\n\n/**\n * Parse a `rebase db request-role <action> …` line — `[\"db\", \"request-role\",\n * \"migrate\", …]`. Throws, with nothing run, on a missing or unknown action, an\n * undeclared flag, a stray word or a missing or unusable `--to`.\n */\nexport function parseRequestRoleLine(rawArgs: readonly string[]): RequestRoleLine {\n const action = rawArgs[2];\n if (action === undefined || action.startsWith(\"-\")) {\n throw new Error(\n \"`rebase db request-role` needs an action: `rebase db request-role migrate --to <role[,role]>`. Nothing was run.\"\n );\n }\n if (!REQUEST_ROLE_ACTIONS.some((known) => known === action)) {\n const near = closestWord(action, REQUEST_ROLE_ACTIONS);\n throw new Error(\n `\\`rebase db request-role\\` has no action \"${redactConnectionPasswords(action)}\"` +\n (near ? ` — did you mean ${near}?` : `. It takes: ${REQUEST_ROLE_ACTIONS.join(\", \")}.`) +\n \" Nothing was run.\"\n );\n }\n const args = parseCommandFlags(REQUEST_ROLE_FLAGS, [...rawArgs.slice(3)], \"db request-role migrate\");\n if (args._.length > 0) {\n throw new Error(\n `\\`rebase db request-role migrate\\` takes no argument \"${redactConnectionPasswords(args._[0])}\". ` +\n \"Name the new role(s) with --to. Nothing was run.\"\n );\n }\n const to = args[\"--to\"];\n if (to === undefined) {\n throw new Error(\n \"`rebase db request-role migrate` needs --to <role[,role]>: the role(s) requests should run as from now on. Nothing was run.\"\n );\n }\n return {\n action: \"migrate\",\n to: parseRoleList(to, \"--to\"),\n dryRun: args[\"--dry-run\"] === true,\n yes: args[\"--yes\"] === true\n };\n}\n\n/**\n * Parse a `rebase db provision …` line. `--print` is required: the command\n * shows the SQL and runs none of it — a server boot, `db push` and\n * `db migrate` are what provision.\n */\nexport function parseProvisionLine(rawArgs: readonly string[]): { print: true } {\n const args = parseCommandFlags(PROVISION_FLAGS, [...rawArgs.slice(2)], \"db provision\");\n if (args._.length > 0) {\n throw new Error(\n `\\`rebase db provision\\` takes no argument \"${redactConnectionPasswords(args._[0])}\". Nothing was run.`\n );\n }\n if (args[\"--print\"] !== true) {\n throw new Error(\n \"`rebase db provision` prints the SQL and runs none of it: pass --print. A server boot, \" +\n \"`rebase db push` and `rebase db migrate` provision the request role themselves. Nothing was run.\"\n );\n }\n return { print: true };\n}\n\n/**\n * Which roles a migration moves from and to. From is what this database\n * recorded, or `rebase_user` — every database provisioned before the setting\n * existed ran as it. `null` when the two are the same set, in any order:\n * there is nothing to move.\n */\nexport function resolveMigrationRoles(\n recorded: readonly string[] | undefined,\n to: readonly string[]\n): { from: string[]; to: string[] } | null {\n const from = recorded && recorded.length > 0 ? [...recorded] : [REBASE_USER_ROLE];\n const same = from.length === to.length && from.every((role) => to.includes(role));\n return same ? null : { from, to: [...to] };\n}\n\nconst quoted = (roles: readonly string[]): string => roles.map((r) => `\"${r}\"`).join(\", \");\n\n/** What `db request-role migrate` says before it runs, or instead of running with `--dry-run`. */\nexport function renderMigrationPlan(\n plan: RequestRoleMigrationPlan,\n roles: { from: readonly string[]; to: readonly string[] },\n dryRun: boolean\n): string[] {\n const lines: string[] = [];\n lines.push(` Requests in this database run as ${quoted(roles.from)}. This moves them to ${quoted(roles.to)}.`);\n lines.push(chalk.gray(\" Grants are re-issued in this database only; the old role is left as it is, because another database may use it.\"));\n lines.push(\"\");\n lines.push(dryRun ? \" Would run, in one transaction:\" : \" Will run, in one transaction:\");\n lines.push(chalk.gray(` -- create ${quoted(roles.to)} if missing (NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT), and let this connection switch to it`));\n if (plan.statements.length === 0) {\n lines.push(chalk.gray(` -- ${quoted(roles.from)} holds no grants here: nothing to copy`));\n }\n for (const statement of plan.statements) lines.push(` ${statement};`);\n lines.push(chalk.gray(` -- record ${quoted(roles.to)} in rebase.schema_meta (request_roles)`));\n if (dryRun) {\n lines.push(\"\");\n lines.push(...renderRevokeOld(plan, roles.from));\n }\n return lines;\n}\n\n/** The statements that take the old role's grants back here, for the operator to run once satisfied. */\nexport function renderRevokeOld(plan: RequestRoleMigrationPlan, from: readonly string[]): string[] {\n if (plan.revokeOld.length === 0) {\n return [chalk.gray(` ${quoted(from)} holds no grants in this database, so there is nothing to take back.`)];\n }\n return [\n ` Run these once you no longer need ${quoted(from)} in this database:`,\n ...plan.revokeOld.map((statement) => ` ${statement};`)\n ];\n}\n\n/**\n * The prose `appRoleSetupInstructions` opens with, as SQL comments, and the SQL\n * after it as it is — so the output of `db provision --print` can be piped\n * into `psql` whole.\n */\nexport function asSqlScript(instructions: string): string {\n const split = instructions.indexOf(\"\\n\\n\");\n if (split === -1) return instructions;\n const prose = instructions.slice(0, split).split(\"\\n\").map((line) => `-- ${line}`.trimEnd());\n return [...prose, instructions.slice(split + 2)].join(\"\\n\");\n}\n\n/**\n * The whole `db provision --print` script: for each request role, the SQL that\n * creates it and lets the connection switch to it, plus the grants the\n * `grants` mode makes schema-wide. Runs nothing.\n */\nexport function renderProvisionScript(\n connectionRole: string,\n settings: Pick<RlsSettings, \"roles\" | \"grants\" | \"provisionRole\">,\n sqlFor: (role: string) => string\n): string {\n const parts: string[] = [\n \"-- Request role setup for this database, as a database administrator would run it.\",\n `-- Connection role: \"${connectionRole}\". Request role(s): ${quoted(settings.roles)}. grants: ${settings.grants}. provisionRole: ${settings.provisionRole}.`,\n \"-- Printed by `rebase db provision --print`; nothing was run. Every statement is safe to re-run.\"\n ];\n if (settings.grants === \"managed\") {\n parts.push(\"-- grants: managed — no schema-wide grants here; once the connection can switch, a boot grants each table Rebase serves.\");\n } else if (settings.grants === \"none\") {\n parts.push(\"-- grants: none — Rebase grants nothing; grant the request role the tables it should reach yourself.\");\n }\n for (const role of settings.roles) {\n parts.push(\"\", `-- ── \"${role}\" ──`, asSqlScript(sqlFor(role)));\n }\n return parts.join(\"\\n\");\n}\n\nfunction databaseUrlOrExit(): string {\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n if (!databaseUrl) {\n outError(chalk.red(\"✗ DATABASE_URL is not set. Make sure your .env file is configured.\"));\n process.exit(1);\n }\n return databaseUrl;\n}\n\n/** `rebase db provision --print`. */\nexport async function provisionCommand(rawArgs: string[]): Promise<void> {\n parseProvisionLine(rawArgs);\n const databaseUrl = databaseUrlOrExit();\n const { withAppClient } = await import(\"./cli-helpers\");\n const { appRoleSetupInstructions, readRecordedRequestRoles } = await import(\"./security/rls-enforcement\");\n const { cliRlsSettings } = await import(\"./security/rls-settings\");\n\n const script = await withAppClient(databaseUrl, async (client) => {\n const run: RawSqlRunner = async (text) => (await client.query(text)).rows as Record<string, unknown>[];\n const [who] = await run(\"SELECT current_user AS role\");\n const connectionRole = String(who?.role ?? \"\");\n const settings = cliRlsSettings(await readRecordedRequestRoles(run));\n // Only the schemas that exist: a GRANT on a missing schema fails the\n // script, and a boot grants on `rebase` itself when it creates it.\n const present = await run(\n `SELECT nspname FROM pg_namespace WHERE nspname IN (${REQUEST_ROLE_SCHEMAS.map((s) => `'${s}'`).join(\", \")})`\n );\n const schemas = REQUEST_ROLE_SCHEMAS.filter((schema) => present.some((row) => row.nspname === schema));\n return renderProvisionScript(\n connectionRole,\n settings,\n (role) => appRoleSetupInstructions(connectionRole, schemas, role, settings.grants)\n );\n });\n out(script);\n}\n\n/**\n * The confirmation `db request-role migrate` asks for. `--yes` skips it; with\n * no terminal nobody can answer, so it refuses and names `--yes`.\n */\nasync function confirmMigration(yes: boolean): Promise<boolean> {\n if (yes) return true;\n if (!process.stdin.isTTY) {\n outError(chalk.red(\" ✗ Nothing was changed: there is no terminal to confirm on.\"));\n outError(chalk.gray(\" Re-run with --yes, or with --dry-run to see the plan.\"));\n return false;\n }\n const confirmed = await promptConfirm(chalk.yellow(\" Type 'yes' to move this database to the new request role(s): \"));\n if (!confirmed) out(chalk.gray(\" Aborted. No changes were made.\"));\n return confirmed;\n}\n\n/** `rebase db request-role migrate --to <role[,role]> [--dry-run] [--yes]`. */\nexport async function requestRoleCommand(rawArgs: string[]): Promise<void> {\n const line = parseRequestRoleLine(rawArgs);\n const databaseUrl = databaseUrlOrExit();\n const { withAppClient } = await import(\"./cli-helpers\");\n const { AppRoleSetupError, readRecordedRequestRoles } = await import(\"./security/rls-enforcement\");\n const { migrateRequestRoles, planRequestRoleMigration } = await import(\"./security/request-role-migration\");\n\n out(\"\");\n out(chalk.bold(\" rebase db request-role migrate\"));\n out(\"\");\n\n await withAppClient(databaseUrl, async (client) => {\n const run: RawSqlRunner = async (text) => (await client.query(text)).rows as Record<string, unknown>[];\n const roles = resolveMigrationRoles(await readRecordedRequestRoles(run), line.to);\n if (!roles) {\n out(chalk.green(` ✓ Requests in this database already run as ${quoted(line.to)}. Nothing to do.`));\n return;\n }\n\n const plan = await planRequestRoleMigration(run, roles.from, roles.to);\n for (const text of renderMigrationPlan(plan, roles, line.dryRun)) out(text);\n out(\"\");\n if (line.dryRun) {\n out(chalk.gray(\" Dry run: nothing was changed.\"));\n return;\n }\n if (!(await confirmMigration(line.yes))) {\n process.exitCode = 1;\n return;\n }\n\n let applied: RequestRoleMigrationPlan;\n await client.query(\"BEGIN\");\n try {\n applied = await migrateRequestRoles(run, { from: roles.from, to: roles.to, schemas: REQUEST_ROLE_SCHEMAS });\n await client.query(\"COMMIT\");\n } catch (err) {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n if (err instanceof AppRoleSetupError) {\n outError(chalk.red(` ✗ Nothing was changed: ${err.message.slice(0, -err.instructions.length).trimEnd()}`));\n outError(chalk.gray(err.instructions));\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n out(chalk.green(` ✓ Requests in this database now run as ${quoted(roles.to)} (${applied.statements.length} grant(s) re-issued).`));\n out(\"\");\n for (const text of renderRevokeOld(applied, roles.from)) out(text);\n out(\"\");\n outWarn(chalk.yellow(` ${requestRoleReminder(roles.to)}`));\n out(\"\");\n });\n}\n\n/**\n * What to change on the servers once the database has moved: a boot configured\n * for other roles than the recorded ones refuses to start. One role fits the\n * environment variable; several need the setting in code.\n */\nexport function requestRoleReminder(to: readonly string[]): string {\n const setting = to.length === 1\n ? `REBASE_RLS_REQUEST_ROLE=${to[0]} (or rls.requestRole: \"${to[0]}\" in the driver config)`\n : `rls.requestRole in the driver config (a { anonymous, signedIn } map, or a function with rls.requestRoles: [${to.map((r) => `\"${r}\"`).join(\", \")}])`;\n return `Set ${setting} on every server that uses this database: a boot configured for other roles refuses to start.`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,IAAa,uBAAuB,CAAC,UAAU,QAAQ;;AAGvD,IAAa,uBAAuB,CAAC,SAAS;;AAG9C,IAAa,qBAAqB;CAC9B,QAAQ;CACR,aAAa;CACb,SAAS;CACT,MAAM;AACV;;AAGA,IAAa,kBAAkB,EAC3B,WAAW,QACf;;;;;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YAAY,KAAA,CAAS;GACpD,IAAI,eAAe,mBAAmB;IAClC,SAAS,MAAM,IAAI,4BAA4B,IAAI,QAAQ,MAAM,GAAG,CAAC,IAAI,aAAa,MAAM,CAAC,CAAC,QAAQ,GAAG,CAAC;IAC1G,SAAS,MAAM,KAAK,IAAI,YAAY,CAAC;IACrC,QAAQ,WAAW;IACnB;GACJ;GACA,MAAM;EACV;EAEA,IAAI,MAAM,MAAM,4CAA4C,OAAO,MAAM,EAAE,EAAE,IAAI,QAAQ,WAAW,OAAO,sBAAsB,CAAC;EAClI,IAAI,EAAE;EACN,KAAK,MAAM,QAAQ,gBAAgB,SAAS,MAAM,IAAI,GAAG,IAAI,IAAI;EACjE,IAAI,EAAE;EACN,QAAQ,MAAM,OAAO,KAAK,oBAAoB,MAAM,EAAE,GAAG,CAAC;EAC1D,IAAI,EAAE;CACV,CAAC;AACL;;;;;;AAOA,SAAgB,oBAAoB,IAA+B;CAI/D,OAAO,OAHS,GAAG,WAAW,IACxB,2BAA2B,GAAG,GAAG,yBAAyB,GAAG,GAAG,2BAChE,8GAA8G,GAAG,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,IACjI;AAC1B"}
|
|
1
|
+
{"version":3,"file":"request-role-cli-Ay0v9oYZ.js","names":[],"sources":["../src/request-role-cli.ts"],"sourcesContent":["/**\n * `rebase db request-role migrate` and `rebase db provision --print`: the\n * commands that move a database to another request role, and show the SQL\n * that sets one up, for a database Rebase does not own outright.\n *\n * The line parsers and the renderers are pure and load nothing heavy, because\n * `db-command-line.ts` judges every `rebase db …` line with them before the\n * CLI starts a database. The commands themselves import the security modules\n * and the connection only when they run.\n */\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\nimport { REBASE_USER_ROLE } from \"@rebasepro/common\";\n\nimport { closestWord, parseCommandFlags } from \"./cli-flags\";\nimport { out, outError, outWarn } from \"./cli-output\";\nimport { promptConfirm } from \"./cli-prompt\";\nimport { redactConnectionPasswords } from \"./utils/connection-string\";\nimport { resolveRlsSettings, type RlsSettings } from \"./security/rls-settings\";\nimport type { RequestRoleMigrationPlan } from \"./security/request-role-migration\";\nimport type { RawSqlRunner } from \"./security/rls-enforcement\";\n\n/**\n * The schemas both commands provision in: the ones `db push` and `db migrate`\n * provision the request role in after a schema change.\n */\nexport const REQUEST_ROLE_SCHEMAS = [\"public\", \"rebase\"] as const;\n\n/** The actions `rebase db request-role` answers. */\nexport const REQUEST_ROLE_ACTIONS = [\"migrate\"] as const;\n\n/** The flags of `rebase db request-role migrate`. Named `…FLAGS` so the docs verifier reads them. */\nexport const REQUEST_ROLE_FLAGS = {\n \"--to\": String,\n \"--dry-run\": Boolean,\n \"--yes\": Boolean,\n \"-y\": \"--yes\"\n} satisfies arg.Spec;\n\n/** The flags of `rebase db provision`. */\nexport const PROVISION_FLAGS = {\n \"--print\": Boolean\n} satisfies arg.Spec;\n\nexport interface RequestRoleLine {\n action: typeof REQUEST_ROLE_ACTIONS[number];\n /** The role(s) to move to, in the order given, without duplicates. */\n to: string[];\n dryRun: boolean;\n yes: boolean;\n}\n\n/**\n * `\"app_prod_user, app_prod_anon\"` → `[\"app_prod_user\", \"app_prod_anon\"]`.\n * Each name is checked by the same rule the `rls.requestRole` setting uses, so\n * a name the server would refuse at boot is refused here, before anything runs.\n */\nexport function parseRoleList(value: string, flag: string): string[] {\n const roles = Array.from(new Set(value.split(\",\").map((r) => r.trim()).filter(Boolean)));\n if (roles.length === 0) throw new Error(`${flag} needs at least one role name, e.g. ${flag} app_prod_user.`);\n for (const role of roles) {\n try {\n resolveRlsSettings({ requestRole: role });\n } catch (err) {\n throw new Error(`${flag} ${role}: ${err instanceof Error ? err.message.replace(/^[^:]*:\\s*/, \"\") : String(err)}`);\n }\n }\n return roles;\n}\n\n/**\n * Parse a `rebase db request-role <action> …` line — `[\"db\", \"request-role\",\n * \"migrate\", …]`. Throws, with nothing run, on a missing or unknown action, an\n * undeclared flag, a stray word or a missing or unusable `--to`.\n */\nexport function parseRequestRoleLine(rawArgs: readonly string[]): RequestRoleLine {\n const action = rawArgs[2];\n if (action === undefined || action.startsWith(\"-\")) {\n throw new Error(\n \"`rebase db request-role` needs an action: `rebase db request-role migrate --to <role[,role]>`. Nothing was run.\"\n );\n }\n if (!REQUEST_ROLE_ACTIONS.some((known) => known === action)) {\n const near = closestWord(action, REQUEST_ROLE_ACTIONS);\n throw new Error(\n `\\`rebase db request-role\\` has no action \"${redactConnectionPasswords(action)}\"` +\n (near ? ` — did you mean ${near}?` : `. It takes: ${REQUEST_ROLE_ACTIONS.join(\", \")}.`) +\n \" Nothing was run.\"\n );\n }\n const args = parseCommandFlags(REQUEST_ROLE_FLAGS, [...rawArgs.slice(3)], \"db request-role migrate\");\n if (args._.length > 0) {\n throw new Error(\n `\\`rebase db request-role migrate\\` takes no argument \"${redactConnectionPasswords(args._[0])}\". ` +\n \"Name the new role(s) with --to. Nothing was run.\"\n );\n }\n const to = args[\"--to\"];\n if (to === undefined) {\n throw new Error(\n \"`rebase db request-role migrate` needs --to <role[,role]>: the role(s) requests should run as from now on. Nothing was run.\"\n );\n }\n return {\n action: \"migrate\",\n to: parseRoleList(to, \"--to\"),\n dryRun: args[\"--dry-run\"] === true,\n yes: args[\"--yes\"] === true\n };\n}\n\n/**\n * Parse a `rebase db provision …` line. `--print` is required: the command\n * shows the SQL and runs none of it — a server boot, `db push` and\n * `db migrate` are what provision.\n */\nexport function parseProvisionLine(rawArgs: readonly string[]): { print: true } {\n const args = parseCommandFlags(PROVISION_FLAGS, [...rawArgs.slice(2)], \"db provision\");\n if (args._.length > 0) {\n throw new Error(\n `\\`rebase db provision\\` takes no argument \"${redactConnectionPasswords(args._[0])}\". Nothing was run.`\n );\n }\n if (args[\"--print\"] !== true) {\n throw new Error(\n \"`rebase db provision` prints the SQL and runs none of it: pass --print. A server boot, \" +\n \"`rebase db push` and `rebase db migrate` provision the request role themselves. Nothing was run.\"\n );\n }\n return { print: true };\n}\n\n/**\n * Which roles a migration moves from and to. From is what this database\n * recorded, or `rebase_user` — every database provisioned before the setting\n * existed ran as it. `null` when the two are the same set, in any order:\n * there is nothing to move.\n */\nexport function resolveMigrationRoles(\n recorded: readonly string[] | undefined,\n to: readonly string[]\n): { from: string[]; to: string[] } | null {\n const from = recorded && recorded.length > 0 ? [...recorded] : [REBASE_USER_ROLE];\n const same = from.length === to.length && from.every((role) => to.includes(role));\n return same ? null : { from, to: [...to] };\n}\n\nconst quoted = (roles: readonly string[]): string => roles.map((r) => `\"${r}\"`).join(\", \");\n\n/** What `db request-role migrate` says before it runs, or instead of running with `--dry-run`. */\nexport function renderMigrationPlan(\n plan: RequestRoleMigrationPlan,\n roles: { from: readonly string[]; to: readonly string[] },\n dryRun: boolean\n): string[] {\n const lines: string[] = [];\n lines.push(` Requests in this database run as ${quoted(roles.from)}. This moves them to ${quoted(roles.to)}.`);\n lines.push(chalk.gray(\" Grants are re-issued in this database only; the old role is left as it is, because another database may use it.\"));\n lines.push(\"\");\n lines.push(dryRun ? \" Would run, in one transaction:\" : \" Will run, in one transaction:\");\n lines.push(chalk.gray(` -- create ${quoted(roles.to)} if missing (NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT), and let this connection switch to it`));\n if (plan.statements.length === 0) {\n lines.push(chalk.gray(` -- ${quoted(roles.from)} holds no grants here: nothing to copy`));\n }\n for (const statement of plan.statements) lines.push(` ${statement};`);\n lines.push(chalk.gray(` -- record ${quoted(roles.to)} in rebase.schema_meta (request_roles)`));\n if (dryRun) {\n lines.push(\"\");\n lines.push(...renderRevokeOld(plan, roles.from));\n }\n return lines;\n}\n\n/** The statements that take the old role's grants back here, for the operator to run once satisfied. */\nexport function renderRevokeOld(plan: RequestRoleMigrationPlan, from: readonly string[]): string[] {\n if (plan.revokeOld.length === 0) {\n return [chalk.gray(` ${quoted(from)} holds no grants in this database, so there is nothing to take back.`)];\n }\n return [\n ` Run these once you no longer need ${quoted(from)} in this database:`,\n ...plan.revokeOld.map((statement) => ` ${statement};`)\n ];\n}\n\n/**\n * The prose `appRoleSetupInstructions` opens with, as SQL comments, and the SQL\n * after it as it is — so the output of `db provision --print` can be piped\n * into `psql` whole.\n */\nexport function asSqlScript(instructions: string): string {\n const split = instructions.indexOf(\"\\n\\n\");\n if (split === -1) return instructions;\n const prose = instructions.slice(0, split).split(\"\\n\").map((line) => `-- ${line}`.trimEnd());\n return [...prose, instructions.slice(split + 2)].join(\"\\n\");\n}\n\n/**\n * The whole `db provision --print` script: for each request role, the SQL that\n * creates it and lets the connection switch to it, plus the grants the\n * `grants` mode makes schema-wide. Runs nothing.\n */\nexport function renderProvisionScript(\n connectionRole: string,\n settings: Pick<RlsSettings, \"roles\" | \"grants\" | \"provisionRole\">,\n sqlFor: (role: string) => string\n): string {\n const parts: string[] = [\n \"-- Request role setup for this database, as a database administrator would run it.\",\n `-- Connection role: \"${connectionRole}\". Request role(s): ${quoted(settings.roles)}. grants: ${settings.grants}. provisionRole: ${settings.provisionRole}.`,\n \"-- Printed by `rebase db provision --print`; nothing was run. Every statement is safe to re-run.\"\n ];\n if (settings.grants === \"managed\") {\n parts.push(\"-- grants: managed — no schema-wide grants here; once the connection can switch, a boot grants each table Rebase serves.\");\n } else if (settings.grants === \"none\") {\n parts.push(\"-- grants: none — Rebase grants nothing; grant the request role the tables it should reach yourself.\");\n }\n for (const role of settings.roles) {\n parts.push(\"\", `-- ── \"${role}\" ──`, asSqlScript(sqlFor(role)));\n }\n return parts.join(\"\\n\");\n}\n\nfunction databaseUrlOrExit(): string {\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n if (!databaseUrl) {\n outError(chalk.red(\"✗ DATABASE_URL is not set. Make sure your .env file is configured.\"));\n process.exit(1);\n }\n return databaseUrl;\n}\n\n/** `rebase db provision --print`. */\nexport async function provisionCommand(rawArgs: string[]): Promise<void> {\n parseProvisionLine(rawArgs);\n const databaseUrl = databaseUrlOrExit();\n const { withAppClient } = await import(\"./cli-helpers\");\n const { appRoleSetupInstructions, readRecordedRequestRoles } = await import(\"./security/rls-enforcement\");\n const { cliRlsSettings } = await import(\"./security/rls-settings\");\n\n const script = await withAppClient(databaseUrl, async (client) => {\n const run: RawSqlRunner = async (text) => (await client.query(text)).rows as Record<string, unknown>[];\n const [who] = await run(\"SELECT current_user AS role\");\n const connectionRole = String(who?.role ?? \"\");\n const settings = cliRlsSettings(await readRecordedRequestRoles(run));\n // Only the schemas that exist: a GRANT on a missing schema fails the\n // script, and a boot grants on `rebase` itself when it creates it.\n const present = await run(\n `SELECT nspname FROM pg_namespace WHERE nspname IN (${REQUEST_ROLE_SCHEMAS.map((s) => `'${s}'`).join(\", \")})`\n );\n const schemas = REQUEST_ROLE_SCHEMAS.filter((schema) => present.some((row) => row.nspname === schema));\n return renderProvisionScript(\n connectionRole,\n settings,\n (role) => appRoleSetupInstructions(connectionRole, schemas, role, settings.grants)\n );\n });\n out(script);\n}\n\n/**\n * The confirmation `db request-role migrate` asks for. `--yes` skips it; with\n * no terminal nobody can answer, so it refuses and names `--yes`.\n */\nasync function confirmMigration(yes: boolean): Promise<boolean> {\n if (yes) return true;\n if (!process.stdin.isTTY) {\n outError(chalk.red(\" ✗ Nothing was changed: there is no terminal to confirm on.\"));\n outError(chalk.gray(\" Re-run with --yes, or with --dry-run to see the plan.\"));\n return false;\n }\n const confirmed = await promptConfirm(chalk.yellow(\" Type 'yes' to move this database to the new request role(s): \"));\n if (!confirmed) out(chalk.gray(\" Aborted. No changes were made.\"));\n return confirmed;\n}\n\n/** `rebase db request-role migrate --to <role[,role]> [--dry-run] [--yes]`. */\nexport async function requestRoleCommand(rawArgs: string[]): Promise<void> {\n const line = parseRequestRoleLine(rawArgs);\n const databaseUrl = databaseUrlOrExit();\n const { withAppClient } = await import(\"./cli-helpers\");\n const { AppRoleSetupError, readRecordedRequestRoles } = await import(\"./security/rls-enforcement\");\n const { migrateRequestRoles, planRequestRoleMigration } = await import(\"./security/request-role-migration\");\n\n out(\"\");\n out(chalk.bold(\" rebase db request-role migrate\"));\n out(\"\");\n\n await withAppClient(databaseUrl, async (client) => {\n const run: RawSqlRunner = async (text) => (await client.query(text)).rows as Record<string, unknown>[];\n const roles = resolveMigrationRoles(await readRecordedRequestRoles(run), line.to);\n if (!roles) {\n out(chalk.green(` ✓ Requests in this database already run as ${quoted(line.to)}. Nothing to do.`));\n return;\n }\n\n const plan = await planRequestRoleMigration(run, roles.from, roles.to);\n for (const text of renderMigrationPlan(plan, roles, line.dryRun)) out(text);\n out(\"\");\n if (line.dryRun) {\n out(chalk.gray(\" Dry run: nothing was changed.\"));\n return;\n }\n if (!(await confirmMigration(line.yes))) {\n process.exitCode = 1;\n return;\n }\n\n let applied: RequestRoleMigrationPlan;\n await client.query(\"BEGIN\");\n try {\n applied = await migrateRequestRoles(run, { from: roles.from, to: roles.to, schemas: REQUEST_ROLE_SCHEMAS });\n await client.query(\"COMMIT\");\n } catch (err) {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n if (err instanceof AppRoleSetupError) {\n outError(chalk.red(` ✗ Nothing was changed: ${err.message.slice(0, -err.instructions.length).trimEnd()}`));\n outError(chalk.gray(err.instructions));\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n out(chalk.green(` ✓ Requests in this database now run as ${quoted(roles.to)} (${applied.statements.length} grant(s) re-issued).`));\n out(\"\");\n for (const text of renderRevokeOld(applied, roles.from)) out(text);\n out(\"\");\n outWarn(chalk.yellow(` ${requestRoleReminder(roles.to)}`));\n out(\"\");\n });\n}\n\n/**\n * What to change on the servers once the database has moved: a boot configured\n * for other roles than the recorded ones refuses to start. One role fits the\n * environment variable; several need the setting in code.\n */\nexport function requestRoleReminder(to: readonly string[]): string {\n const setting = to.length === 1\n ? `REBASE_RLS_REQUEST_ROLE=${to[0]} (or rls.requestRole: \"${to[0]}\" in the driver config)`\n : `rls.requestRole in the driver config (a { anonymous, signedIn } map, or a function with rls.requestRoles: [${to.map((r) => `\"${r}\"`).join(\", \")}])`;\n return `Set ${setting} on every server that uses this database: a boot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Q,WAAW;GACnB;EACJ;EAEA,IAAI;EACJ,MAAM,OAAO,MAAM,OAAO;EAC1B,IAAI;GACA,UAAU,MAAM,oBAAoB,KAAK;IAAE,MAAM,MAAM;IAAM,IAAI,MAAM;IAAI,SAAS;GAAqB,CAAC;GAC1G,MAAM,OAAO,MAAM,QAAQ;EAC/B,SAAS,KAAK;GACV,MAAM,OAAO,MAAM,UAAU,CAAC,CAAC,YAAY,KAAA,CAAS;GACpD,IAAI,eAAe,mBAAmB;IAClC,SAAS,MAAM,IAAI,4BAA4B,IAAI,QAAQ,MAAM,GAAG,CAAC,IAAI,aAAa,MAAM,CAAC,CAAC,QAAQ,GAAG,CAAC;IAC1G,SAAS,MAAM,KAAK,IAAI,YAAY,CAAC;IACrC,QAAQ,WAAW;IACnB;GACJ;GACA,MAAM;EACV;EAEA,IAAI,MAAM,MAAM,4CAA4C,OAAO,MAAM,EAAE,EAAE,IAAI,QAAQ,WAAW,OAAO,sBAAsB,CAAC;EAClI,IAAI,EAAE;EACN,KAAK,MAAM,QAAQ,gBAAgB,SAAS,MAAM,IAAI,GAAG,IAAI,IAAI;EACjE,IAAI,EAAE;EACN,QAAQ,MAAM,OAAO,KAAK,oBAAoB,MAAM,EAAE,GAAG,CAAC;EAC1D,IAAI,EAAE;CACV,CAAC;AACL;;;;;;AAOA,SAAgB,oBAAoB,IAA+B;CAI/D,OAAO,OAHS,GAAG,WAAW,IACxB,2BAA2B,GAAG,GAAG,yBAAyB,GAAG,GAAG,2BAChE,8GAA8G,GAAG,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,IACjI;AAC1B"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
|
-
import { _ as recordRequestRoles, c as ensureAppRole } from "./rls-enforcement-
|
|
3
|
+
import { _ as recordRequestRoles, c as ensureAppRole } from "./rls-enforcement-Ck-d8zdJ.js";
|
|
4
4
|
//#region src/security/request-role-migration.ts
|
|
5
5
|
var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
6
6
|
var sqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
@@ -147,4 +147,4 @@ async function migrateRequestRoles(run, options) {
|
|
|
147
147
|
//#endregion
|
|
148
148
|
export { migrateRequestRoles, planRequestRoleMigration };
|
|
149
149
|
|
|
150
|
-
//# sourceMappingURL=request-role-migration-
|
|
150
|
+
//# sourceMappingURL=request-role-migration-DTE3Owsh.js.map
|
package/dist/{request-role-migration-DQLiYJ4c.js.map → request-role-migration-DTE3Owsh.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-role-migration-DQLiYJ4c.js","names":[],"sources":["../src/security/request-role-migration.ts"],"sourcesContent":["import { ensureAppRole, recordRequestRoles, type RawSqlRunner } from \"./rls-enforcement\";\n\n/**\n * Move a database from one set of request roles to another — what\n * `rebase db request-role migrate --to …` runs.\n *\n * A role belongs to the cluster, so renaming one (`ALTER ROLE … RENAME`) moves\n * every database's grants at once, including another project's that shares\n * it. This instead creates the new role(s) and re-issues, in THIS database\n * only, every grant the old ones hold here: tables and views, columns,\n * sequences, schemas, functions, the default privileges this connection set,\n * and the memberships that carry other roles' policies (`rls.inheritRoles`).\n * Policies that name an old role in their `TO` list are re-pointed. The old\n * roles are left as they are — another database may still use them — and the\n * statements to take their grants back here are returned for the operator.\n */\nexport interface RequestRoleMigrationPlan {\n /** What to run, in order, to give the new roles what the old ones hold here. */\n statements: string[];\n /** What would take the old roles' grants back in this database, for the operator to run once satisfied. */\n revokeOld: string[];\n}\n\nconst quoteIdent = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\nconst sqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\nconst textArray = (values: readonly string[]): string =>\n values.length === 0 ? \"ARRAY[]::text[]\" : `ARRAY[${values.map(sqlLiteral).join(\", \")}]::text[]`;\n\n/** Which new role(s) each old role's grants go to: one old to every new, or pairwise. */\nfunction roleMapping(from: readonly string[], to: readonly string[]): Map<string, string[]> {\n if (from.length === 1) return new Map([[from[0], [...to]]]);\n if (from.length === to.length) return new Map(from.map((role, i) => [role, [to[i]]]));\n throw new Error(\n `Cannot map ${from.length} request roles (${from.join(\", \")}) onto ${to.length} (${to.join(\", \")}): ` +\n \"move from one role to any number, or between two lists of the same length (pairwise, in order).\"\n );\n}\n\n/**\n * Read the catalogue and plan the move. Writes nothing; {@link migrateRequestRoles}\n * runs the plan.\n */\nexport async function planRequestRoleMigration(\n run: RawSqlRunner,\n from: readonly string[],\n to: readonly string[]\n): Promise<RequestRoleMigrationPlan> {\n const mapping = roleMapping(from, to);\n const statements: string[] = [];\n const revokeOld: string[] = [];\n const grantee = `(SELECT oid FROM pg_roles WHERE rolname = r.name)`;\n const userSchemas = \"n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg\\\\_%'\";\n const oldRoles = textArray(from);\n\n const relations = await run(`\n SELECT r.name AS role, n.nspname AS schema, c.relname AS name, c.relkind AS kind,\n a.privilege_type AS privilege, a.is_grantable AS grantable\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_class c ON c.relacl IS NOT NULL\n JOIN pg_namespace n ON n.oid = c.relnamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(c.relacl) a\n WHERE a.grantee = ${grantee} AND c.relkind IN ('r', 'v', 'm', 'f', 'p', 'S')\n ORDER BY 2, 3, 5\n `);\n for (const row of relations) {\n const target = `${row.kind === \"S\" ? \"SEQUENCE\" : \"TABLE\"} ${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))}`;\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} ON ${target} TO ${quoteIdent(role)}${row.grantable === true ? \" WITH GRANT OPTION\" : \"\"}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} ON ${target} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const columns = await run(`\n SELECT r.name AS role, n.nspname AS schema, c.relname AS name, att.attname AS col, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_attribute att ON att.attacl IS NOT NULL AND NOT att.attisdropped\n JOIN pg_class c ON c.oid = att.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(att.attacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2, 3, 4\n `);\n for (const row of columns) {\n const target = `${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))}`;\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} (${quoteIdent(String(row.col))}) ON TABLE ${target} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} (${quoteIdent(String(row.col))}) ON TABLE ${target} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const schemas = await run(`\n SELECT r.name AS role, n.nspname AS schema, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_namespace n ON n.nspacl IS NOT NULL AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(n.nspacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2\n `);\n for (const row of schemas) {\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} ON SCHEMA ${quoteIdent(String(row.schema))} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} ON SCHEMA ${quoteIdent(String(row.schema))} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const functions = await run(`\n SELECT r.name AS role, p.oid::regprocedure::text AS signature\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_proc p ON p.proacl IS NOT NULL\n JOIN pg_namespace n ON n.oid = p.pronamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(p.proacl) a\n WHERE a.grantee = ${grantee} AND a.privilege_type = 'EXECUTE'\n ORDER BY 2\n `);\n for (const row of functions) {\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT EXECUTE ON FUNCTION ${row.signature} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE EXECUTE ON FUNCTION ${row.signature} FROM ${quoteIdent(String(row.role))}`);\n }\n\n // Default privileges this connection set: what makes tables created later\n // reachable. Ones another role set are that role's to change.\n const defaults = await run(`\n SELECT r.name AS role, n.nspname AS schema, d.defaclobjtype AS kind, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_default_acl d ON d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace\n CROSS JOIN LATERAL aclexplode(d.defaclacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2, 3, 4\n `);\n const objectKinds: Record<string, string> = { r: \"TABLES\", S: \"SEQUENCES\", f: \"FUNCTIONS\", T: \"TYPES\", n: \"SCHEMAS\" };\n for (const row of defaults) {\n const kind = objectKinds[String(row.kind)];\n if (!kind) continue;\n const scope = row.schema ? ` IN SCHEMA ${quoteIdent(String(row.schema))}` : \"\";\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`ALTER DEFAULT PRIVILEGES${scope} GRANT ${row.privilege} ON ${kind} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`ALTER DEFAULT PRIVILEGES${scope} REVOKE ${row.privilege} ON ${kind} FROM ${quoteIdent(String(row.role))}`);\n }\n\n // Memberships that carry another role's policies (rls.inheritRoles):\n // the inherit option goes with them, from PostgreSQL 16.\n // `inherit_option` is a column from 16 on, and naming it before then fails\n // the statement whatever a CASE around it says.\n const [server] = await run(\"SELECT current_setting('server_version_num')::int >= 160000 AS per_grant\");\n const memberships = await run(`\n SELECT r.name AS role, g.rolname AS member_of,\n ${server?.per_grant === true ? \"m.inherit_option\" : \"false\"} AS inherits\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_auth_members m ON m.member = ${grantee}\n JOIN pg_roles g ON g.oid = m.roleid\n ORDER BY 2\n `);\n for (const row of memberships) {\n const option = row.inherits === true ? \" WITH INHERIT TRUE, SET FALSE\" : \"\";\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${quoteIdent(String(row.member_of))} TO ${quoteIdent(role)}${option}`);\n }\n }\n\n // Policies that name an old role: re-pointed, keeping every other role.\n const policies = await run(`\n SELECT p.schemaname AS schema, p.tablename AS name, p.policyname AS policy, p.roles::text[] AS roles\n FROM pg_policies p\n WHERE p.roles && ${oldRoles}::name[]\n ORDER BY 1, 2, 3\n `);\n for (const row of policies) {\n const current = Array.isArray(row.roles)\n ? row.roles.map(String)\n : String(row.roles ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean);\n const next = Array.from(new Set(current.flatMap((r) => mapping.get(r) ?? [r])));\n statements.push(\n `ALTER POLICY ${quoteIdent(String(row.policy))} ON ${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))} ` +\n `TO ${next.map((r) => (r === \"public\" ? \"public\" : quoteIdent(r))).join(\", \")}`\n );\n }\n\n return { statements, revokeOld };\n}\n\n/**\n * Provision the new role(s), run the plan, and record the new roles — in one\n * transaction where the runner has one, so a failure leaves the database on\n * its old roles. Returns the plan that ran.\n */\nexport async function migrateRequestRoles(\n run: RawSqlRunner,\n options: { from: readonly string[]; to: readonly string[]; schemas: readonly string[] }\n): Promise<RequestRoleMigrationPlan> {\n const plan = await planRequestRoleMigration(run, options.from, options.to);\n // The role and the right to switch into it; the grants come from the plan.\n for (const role of options.to) await ensureAppRole(run, [...options.schemas], { role, grants: \"none\" });\n for (const statement of plan.statements) await run(statement);\n await recordRequestRoles(run, options.to);\n return plan;\n}\n"],"mappings":";;;;AAuBA,IAAM,cAAc,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;AAC5E,IAAM,cAAc,UAA0B,IAAI,MAAM,QAAQ,MAAM,IAAI,EAAE;AAC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IACpB,OAAO,IAAI,SAAS,EAAE,CAAC,CAAC,QAAQ,YAAY,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;EAC/E,MAAM,OAAO,MAAM,KAAK,IAAI,IAAI,QAAQ,SAAS,MAAM,QAAQ,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;EAC9E,WAAW,KACP,gBAAgB,WAAW,OAAO,IAAI,MAAM,CAAC,EAAE,MAAM,WAAW,OAAO,IAAI,MAAM,CAAC,EAAE,GAAG,WAAW,OAAO,IAAI,IAAI,CAAC,EAAE,MAC9G,KAAK,KAAK,MAAO,MAAM,WAAW,WAAW,WAAW,CAAC,CAAE,CAAC,CAAC,KAAK,IAAI,GAChF;CACJ;CAEA,OAAO;EAAE;EAAY;CAAU;AACnC;;;;;;AAOA,eAAsB,oBAClB,KACA,SACiC;CACjC,MAAM,OAAO,MAAM,yBAAyB,KAAK,QAAQ,MAAM,QAAQ,EAAE;CAEzE,KAAK,MAAM,QAAQ,QAAQ,IAAI,MAAM,cAAc,KAAK,CAAC,GAAG,QAAQ,OAAO,GAAG;EAAE;EAAM,QAAQ;CAAO,CAAC;CACtG,KAAK,MAAM,aAAa,KAAK,YAAY,MAAM,IAAI,SAAS;CAC5D,MAAM,mBAAmB,KAAK,QAAQ,EAAE;CACxC,OAAO;AACX"}
|
|
1
|
+
{"version":3,"file":"request-role-migration-DTE3Owsh.js","names":[],"sources":["../src/security/request-role-migration.ts"],"sourcesContent":["import { ensureAppRole, recordRequestRoles, type RawSqlRunner } from \"./rls-enforcement\";\n\n/**\n * Move a database from one set of request roles to another — what\n * `rebase db request-role migrate --to …` runs.\n *\n * A role belongs to the cluster, so renaming one (`ALTER ROLE … RENAME`) moves\n * every database's grants at once, including another project's that shares\n * it. This instead creates the new role(s) and re-issues, in THIS database\n * only, every grant the old ones hold here: tables and views, columns,\n * sequences, schemas, functions, the default privileges this connection set,\n * and the memberships that carry other roles' policies (`rls.inheritRoles`).\n * Policies that name an old role in their `TO` list are re-pointed. The old\n * roles are left as they are — another database may still use them — and the\n * statements to take their grants back here are returned for the operator.\n */\nexport interface RequestRoleMigrationPlan {\n /** What to run, in order, to give the new roles what the old ones hold here. */\n statements: string[];\n /** What would take the old roles' grants back in this database, for the operator to run once satisfied. */\n revokeOld: string[];\n}\n\nconst quoteIdent = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\nconst sqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\nconst textArray = (values: readonly string[]): string =>\n values.length === 0 ? \"ARRAY[]::text[]\" : `ARRAY[${values.map(sqlLiteral).join(\", \")}]::text[]`;\n\n/** Which new role(s) each old role's grants go to: one old to every new, or pairwise. */\nfunction roleMapping(from: readonly string[], to: readonly string[]): Map<string, string[]> {\n if (from.length === 1) return new Map([[from[0], [...to]]]);\n if (from.length === to.length) return new Map(from.map((role, i) => [role, [to[i]]]));\n throw new Error(\n `Cannot map ${from.length} request roles (${from.join(\", \")}) onto ${to.length} (${to.join(\", \")}): ` +\n \"move from one role to any number, or between two lists of the same length (pairwise, in order).\"\n );\n}\n\n/**\n * Read the catalogue and plan the move. Writes nothing; {@link migrateRequestRoles}\n * runs the plan.\n */\nexport async function planRequestRoleMigration(\n run: RawSqlRunner,\n from: readonly string[],\n to: readonly string[]\n): Promise<RequestRoleMigrationPlan> {\n const mapping = roleMapping(from, to);\n const statements: string[] = [];\n const revokeOld: string[] = [];\n const grantee = `(SELECT oid FROM pg_roles WHERE rolname = r.name)`;\n const userSchemas = \"n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg\\\\_%'\";\n const oldRoles = textArray(from);\n\n const relations = await run(`\n SELECT r.name AS role, n.nspname AS schema, c.relname AS name, c.relkind AS kind,\n a.privilege_type AS privilege, a.is_grantable AS grantable\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_class c ON c.relacl IS NOT NULL\n JOIN pg_namespace n ON n.oid = c.relnamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(c.relacl) a\n WHERE a.grantee = ${grantee} AND c.relkind IN ('r', 'v', 'm', 'f', 'p', 'S')\n ORDER BY 2, 3, 5\n `);\n for (const row of relations) {\n const target = `${row.kind === \"S\" ? \"SEQUENCE\" : \"TABLE\"} ${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))}`;\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} ON ${target} TO ${quoteIdent(role)}${row.grantable === true ? \" WITH GRANT OPTION\" : \"\"}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} ON ${target} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const columns = await run(`\n SELECT r.name AS role, n.nspname AS schema, c.relname AS name, att.attname AS col, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_attribute att ON att.attacl IS NOT NULL AND NOT att.attisdropped\n JOIN pg_class c ON c.oid = att.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(att.attacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2, 3, 4\n `);\n for (const row of columns) {\n const target = `${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))}`;\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} (${quoteIdent(String(row.col))}) ON TABLE ${target} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} (${quoteIdent(String(row.col))}) ON TABLE ${target} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const schemas = await run(`\n SELECT r.name AS role, n.nspname AS schema, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_namespace n ON n.nspacl IS NOT NULL AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(n.nspacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2\n `);\n for (const row of schemas) {\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} ON SCHEMA ${quoteIdent(String(row.schema))} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} ON SCHEMA ${quoteIdent(String(row.schema))} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const functions = await run(`\n SELECT r.name AS role, p.oid::regprocedure::text AS signature\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_proc p ON p.proacl IS NOT NULL\n JOIN pg_namespace n ON n.oid = p.pronamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(p.proacl) a\n WHERE a.grantee = ${grantee} AND a.privilege_type = 'EXECUTE'\n ORDER BY 2\n `);\n for (const row of functions) {\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT EXECUTE ON FUNCTION ${row.signature} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE EXECUTE ON FUNCTION ${row.signature} FROM ${quoteIdent(String(row.role))}`);\n }\n\n // Default privileges this connection set: what makes tables created later\n // reachable. Ones another role set are that role's to change.\n const defaults = await run(`\n SELECT r.name AS role, n.nspname AS schema, d.defaclobjtype AS kind, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_default_acl d ON d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace\n CROSS JOIN LATERAL aclexplode(d.defaclacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2, 3, 4\n `);\n const objectKinds: Record<string, string> = { r: \"TABLES\", S: \"SEQUENCES\", f: \"FUNCTIONS\", T: \"TYPES\", n: \"SCHEMAS\" };\n for (const row of defaults) {\n const kind = objectKinds[String(row.kind)];\n if (!kind) continue;\n const scope = row.schema ? ` IN SCHEMA ${quoteIdent(String(row.schema))}` : \"\";\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`ALTER DEFAULT PRIVILEGES${scope} GRANT ${row.privilege} ON ${kind} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`ALTER DEFAULT PRIVILEGES${scope} REVOKE ${row.privilege} ON ${kind} FROM ${quoteIdent(String(row.role))}`);\n }\n\n // Memberships that carry another role's policies (rls.inheritRoles):\n // the inherit option goes with them, from PostgreSQL 16.\n // `inherit_option` is a column from 16 on, and naming it before then fails\n // the statement whatever a CASE around it says.\n const [server] = await run(\"SELECT current_setting('server_version_num')::int >= 160000 AS per_grant\");\n const memberships = await run(`\n SELECT r.name AS role, g.rolname AS member_of,\n ${server?.per_grant === true ? \"m.inherit_option\" : \"false\"} AS inherits\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_auth_members m ON m.member = ${grantee}\n JOIN pg_roles g ON g.oid = m.roleid\n ORDER BY 2\n `);\n for (const row of memberships) {\n const option = row.inherits === true ? \" WITH INHERIT TRUE, SET FALSE\" : \"\";\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${quoteIdent(String(row.member_of))} TO ${quoteIdent(role)}${option}`);\n }\n }\n\n // Policies that name an old role: re-pointed, keeping every other role.\n const policies = await run(`\n SELECT p.schemaname AS schema, p.tablename AS name, p.policyname AS policy, p.roles::text[] AS roles\n FROM pg_policies p\n WHERE p.roles && ${oldRoles}::name[]\n ORDER BY 1, 2, 3\n `);\n for (const row of policies) {\n const current = Array.isArray(row.roles)\n ? row.roles.map(String)\n : String(row.roles ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean);\n const next = Array.from(new Set(current.flatMap((r) => mapping.get(r) ?? [r])));\n statements.push(\n `ALTER POLICY ${quoteIdent(String(row.policy))} ON ${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))} ` +\n `TO ${next.map((r) => (r === \"public\" ? \"public\" : quoteIdent(r))).join(\", \")}`\n );\n }\n\n return { statements, revokeOld };\n}\n\n/**\n * Provision the new role(s), run the plan, and record the new roles — in one\n * transaction where the runner has one, so a failure leaves the database on\n * its old roles. Returns the plan that ran.\n */\nexport async function migrateRequestRoles(\n run: RawSqlRunner,\n options: { from: readonly string[]; to: readonly string[]; schemas: readonly string[] }\n): Promise<RequestRoleMigrationPlan> {\n const plan = await planRequestRoleMigration(run, options.from, options.to);\n // The role and the right to switch into it; the grants come from the plan.\n for (const role of options.to) await ensureAppRole(run, [...options.schemas], { role, grants: \"none\" });\n for (const statement of plan.statements) await run(statement);\n await recordRequestRoles(run, options.to);\n return plan;\n}\n"],"mappings":";;;;AAuBA,IAAM,cAAc,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;AAC5E,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;;AAGzF,SAAS,YAAY,MAAyB,IAA8C;CACxF,IAAI,KAAK,WAAW,GAAG,uBAAO,IAAI,IAAI,CAAC,CAAC,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;CAC1D,IAAI,KAAK,WAAW,GAAG,QAAQ,OAAO,IAAI,IAAI,KAAK,KAAK,MAAM,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;CACpF,MAAM,IAAI,MACN,cAAc,KAAK,OAAO,kBAAkB,KAAK,KAAK,IAAI,EAAE,SAAS,GAAG,OAAO,IAAI,GAAG,KAAK,IAAI,EAAE,mGAErG;AACJ;;;;;AAMA,eAAsB,yBAClB,KACA,MACA,IACiC;CACjC,MAAM,UAAU,YAAY,MAAM,EAAE;CACpC,MAAM,aAAuB,CAAC;CAC9B,MAAM,YAAsB,CAAC;CAC7B,MAAM,UAAU;CAChB,MAAM,cAAc;CACpB,MAAM,WAAW,UAAU,IAAI;CAE/B,MAAM,YAAY,MAAM,IAAI;;;sBAGV,SAAS;;4DAE6B,YAAY;;4BAE5C,QAAQ;;KAE/B;CACD,KAAK,MAAM,OAAO,WAAW;E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E;CACxC,OAAO;AACX"}
|
|
@@ -2,7 +2,7 @@ import { createRequire as __createRequire } from "module";
|
|
|
2
2
|
__createRequire(import.meta.url);
|
|
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 {
|
|
5
|
+
import { ut as extractCauseMessage } from "./cli-schema-dir-CjDH_31U.js";
|
|
6
6
|
import { t as cliRlsSettings } from "./rls-settings-CmGK2U0a.js";
|
|
7
7
|
import { n as ADMIN_REQUEST_ROLE_SQL, t as ADMIN_POLICY_ROLE_SQL } from "./rls-bootstrap-sql-kPX4-MB1.js";
|
|
8
8
|
import { logger } from "@rebasepro/server";
|
|
@@ -1295,4 +1295,4 @@ async function validatePolicyPgRoles(run, tables, requestRoles = REBASE_USER_ROL
|
|
|
1295
1295
|
//#endregion
|
|
1296
1296
|
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 };
|
|
1297
1297
|
|
|
1298
|
-
//# sourceMappingURL=rls-enforcement-
|
|
1298
|
+
//# sourceMappingURL=rls-enforcement-Ck-d8zdJ.js.map
|