@rebasepro/server-postgres 0.29.2 → 0.29.3
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-X9R505mP.js → BranchService-CrXvcES2.js} +3 -3
- package/dist/{BranchService-X9R505mP.js.map → BranchService-CrXvcES2.js.map} +1 -1
- package/dist/PostgresBootstrapper.d.ts +7 -0
- package/dist/{backup-cli-CwiJEp_J.js → backup-cli-CTKCOLpX.js} +3 -3
- package/dist/{backup-cli-CwiJEp_J.js.map → backup-cli-CTKCOLpX.js.map} +1 -1
- package/dist/{boot-ddl-CbZj9ovZ.js → boot-ddl-CqGIwSYx.js} +2 -2
- package/dist/{boot-ddl-CbZj9ovZ.js.map → boot-ddl-CqGIwSYx.js.map} +1 -1
- package/dist/{cli-console-DDkNetCz.js → cli-console-DBPw-oAz.js} +5 -5
- package/dist/{cli-console-DDkNetCz.js.map → cli-console-DBPw-oAz.js.map} +1 -1
- package/dist/{cli-errors-C73Qy7WJ.js → cli-errors-DYTxnLbW.js} +5 -5
- package/dist/{cli-errors-C73Qy7WJ.js.map → cli-errors-DYTxnLbW.js.map} +1 -1
- package/dist/cli.js +62 -42
- package/dist/cli.js.map +1 -1
- package/dist/{database-preflight-DIauc8i5.js → database-preflight-iBpT7-vv.js} +2 -2
- package/dist/{database-preflight-DIauc8i5.js.map → database-preflight-iBpT7-vv.js.map} +1 -1
- package/dist/{deferred-index-build-DDdnjaOW.js → deferred-index-build-BCU9RoHK.js} +6 -6
- package/dist/{deferred-index-build-DDdnjaOW.js.map → deferred-index-build-BCU9RoHK.js.map} +1 -1
- package/dist/{doctor-DwMXljiq.js → doctor-Kg1oUK0Q.js} +6 -6
- package/dist/{doctor-DwMXljiq.js.map → doctor-Kg1oUK0Q.js.map} +1 -1
- package/dist/{ensure-collection-policies-DJsOMpaI.js → ensure-collection-policies-Bo-_fDAy.js} +12 -12
- package/dist/ensure-collection-policies-Bo-_fDAy.js.map +1 -0
- package/dist/{ensure-collection-tables-h1mUO7Uu.js → ensure-collection-tables-DCJINkT_.js} +9 -9
- package/dist/{ensure-collection-tables-h1mUO7Uu.js.map → ensure-collection-tables-DCJINkT_.js.map} +1 -1
- package/dist/{ensure-tables-CUqYgMvo.js → ensure-tables-BPGaGh0y.js} +4 -4
- package/dist/{ensure-tables-CUqYgMvo.js.map → ensure-tables-BPGaGh0y.js.map} +1 -1
- package/dist/{enum-labels-kept-z7ustOl_.js → enum-labels-kept-YAgOZS4I.js} +3 -3
- package/dist/{enum-labels-kept-z7ustOl_.js.map → enum-labels-kept-YAgOZS4I.js.map} +1 -1
- package/dist/{generate-drizzle-schema-BIUqhSzh.js → generate-drizzle-schema-DcrFr7YX.js} +2 -2
- package/dist/{generate-drizzle-schema-BIUqhSzh.js.map → generate-drizzle-schema-DcrFr7YX.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-BBXjxm5z.js → generate-drizzle-schema-logic-LTLZvt6r.js} +2 -2
- package/dist/{generate-drizzle-schema-logic-BBXjxm5z.js.map → generate-drizzle-schema-logic-LTLZvt6r.js.map} +1 -1
- package/dist/{generate-files-BkiRFoV1.js → generate-files-CsaVzatS.js} +3 -3
- package/dist/{generate-files-BkiRFoV1.js.map → generate-files-CsaVzatS.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-G9PvjHrr.js → generate-postgres-ddl-logic-Dg0bcENZ.js} +39 -6
- package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +1 -0
- package/dist/{generated-schema-diff-D2soazQU.js → generated-schema-diff-By4dxyTH.js} +2 -2
- package/dist/{generated-schema-diff-D2soazQU.js.map → generated-schema-diff-By4dxyTH.js.map} +1 -1
- package/dist/index.es.js +12 -12
- package/dist/{migrate-baseline-CveNQli3.js → migrate-baseline-CmWXL7qx.js} +2 -2
- package/dist/{migrate-baseline-CveNQli3.js.map → migrate-baseline-CmWXL7qx.js.map} +1 -1
- package/dist/{migrate-policy-stamps-C4qbQ0jK.js → migrate-policy-stamps-BN_Qad6c.js} +6 -6
- package/dist/{migrate-policy-stamps-C4qbQ0jK.js.map → migrate-policy-stamps-BN_Qad6c.js.map} +1 -1
- package/dist/{open-rebase-Cvid3iwR.js → open-rebase-40paQfVW.js} +31 -24
- package/dist/{open-rebase-Cvid3iwR.js.map → open-rebase-40paQfVW.js.map} +1 -1
- package/dist/{pg-error-utils-80uTIHQs.js → pg-error-utils-DJHjCF7-.js} +2 -2
- package/dist/{pg-error-utils-80uTIHQs.js.map → pg-error-utils-DJHjCF7-.js.map} +1 -1
- package/dist/{plan-schema-CMhNYEYF.js → plan-schema-vJd3UEmT.js} +24 -9
- package/dist/plan-schema-vJd3UEmT.js.map +1 -0
- package/dist/{policy-drift-Bx6663KD.js → policy-drift-C-m0uWHH.js} +53 -8
- package/dist/policy-drift-C-m0uWHH.js.map +1 -0
- package/dist/{push-index-adoption-C-TpM445.js → push-index-adoption-Cp7oZxSl.js} +3 -3
- package/dist/{push-index-adoption-C-TpM445.js.map → push-index-adoption-Cp7oZxSl.js.map} +1 -1
- package/dist/{push-index-prebuild-xbpgZEJK.js → push-index-prebuild-DbwKGtQT.js} +4 -4
- package/dist/{push-index-prebuild-xbpgZEJK.js.map → push-index-prebuild-DbwKGtQT.js.map} +1 -1
- package/dist/{push-kept-defaults-D-JEv0Gn.js → push-kept-defaults-CLcgsEPt.js} +2 -2
- package/dist/{push-kept-defaults-D-JEv0Gn.js.map → push-kept-defaults-CLcgsEPt.js.map} +1 -1
- package/dist/{push-legacy-renames-7UKspspl.js → push-legacy-renames-BthD0E9W.js} +4 -4
- package/dist/{push-legacy-renames-7UKspspl.js.map → push-legacy-renames-BthD0E9W.js.map} +1 -1
- package/dist/{push-policy-plan-BOw5PtU8.js → push-policy-plan-BgcrroxQ.js} +3 -3
- package/dist/{push-policy-plan-BOw5PtU8.js.map → push-policy-plan-BgcrroxQ.js.map} +1 -1
- package/dist/{render-ddl-Di-fTGti.js → render-ddl-Ci3S_SoI.js} +23 -5
- package/dist/render-ddl-Ci3S_SoI.js.map +1 -0
- package/dist/{request-role-cli-Bxxskru9.js → request-role-cli-Dy1EgJU9.js} +8 -8
- package/dist/{request-role-cli-Bxxskru9.js.map → request-role-cli-Dy1EgJU9.js.map} +1 -1
- package/dist/{request-role-migration-BCW4v0rq.js → request-role-migration-GHTJnPMV.js} +2 -2
- package/dist/{request-role-migration-BCW4v0rq.js.map → request-role-migration-GHTJnPMV.js.map} +1 -1
- package/dist/{rls-bootstrap-sql-CxszeSc7.js → rls-bootstrap-sql-kPX4-MB1.js} +18 -3
- package/dist/rls-bootstrap-sql-kPX4-MB1.js.map +1 -0
- package/dist/{rls-enforcement-CyUCPDH8.js → rls-enforcement-Cc_UhOxb.js} +109 -6
- package/dist/rls-enforcement-Cc_UhOxb.js.map +1 -0
- package/dist/schema/doctor-cli.js +7 -7
- package/dist/schema/ensure-collection-policies.d.ts +8 -0
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +9 -0
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/introspect-db.js +1 -1
- package/dist/schema/plan/types.d.ts +13 -0
- package/dist/schema/rls-bootstrap-sql.d.ts +6 -0
- package/dist/security/policy-drift.d.ts +13 -1
- package/dist/security/rls-enforcement.d.ts +31 -0
- package/dist/{websocket-BSYV_KSw.js → websocket-B7ex6AQM.js} +3 -3
- package/dist/{websocket-BSYV_KSw.js.map → websocket-B7ex6AQM.js.map} +1 -1
- package/package.json +7 -7
- package/dist/ensure-collection-policies-DJsOMpaI.js.map +0 -1
- package/dist/generate-postgres-ddl-logic-G9PvjHrr.js.map +0 -1
- package/dist/plan-schema-CMhNYEYF.js.map +0 -1
- package/dist/policy-drift-Bx6663KD.js.map +0 -1
- package/dist/render-ddl-Di-fTGti.js.map +0 -1
- package/dist/rls-bootstrap-sql-CxszeSc7.js.map +0 -1
- package/dist/rls-enforcement-CyUCPDH8.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render-ddl-Ci3S_SoI.js","names":[],"sources":["../src/schema/plan/render-ddl.ts"],"sourcesContent":["/**\n * The SQL files, rendered from a {@link SchemaPlan}.\n *\n * Four files, because Atlas owns exactly one of them:\n *\n * - `schema.sql` — the desired state Atlas diffs the database against.\n * - `policies.sql` — the RLS policies. Atlas has no model for a policy.\n * - `search.sql` — the generated `tsvector` column, its GIN index and the\n * IMMUTABLE helpers its expression calls. Atlas's free tier refuses to\n * *parse* a file containing a function, and it wipes the dev database it\n * diffs against, so a helper seeded there is gone by the time the plan runs.\n * - `vector.sql` — the `vector` columns and their ANN indexes. Atlas cannot\n * *execute* these: it materialises `schema.sql` in a dev database that is\n * created empty and emptied again on every run, so `VECTOR(384)` resolves\n * against a database that structurally cannot have pgvector.\n * - `triggers.sql` — `autoValue: \"on_update\"`, which is a function plus a\n * binding, so it is out for the same reason search is.\n *\n * Everything not in `schema.sql` is excluded from Atlas's view by pattern\n * (`…ExcludePatterns` below) and applied by Rebase — at push time by the CLI,\n * at boot by the schema ensure. Without the excludes a desired state that omits\n * an object reads to Atlas as an instruction to drop it.\n */\nimport { REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE } from \"@rebasepro/types\";\nimport { adminRequestPolicyName } from \"@rebasepro/utils\";\nimport { ADMIN_POLICY_ROLE_SQL } from \"../rls-bootstrap-sql\";\nimport {\n fuzzyColumnDefinition,\n searchColumnDefinition,\n searchColumnStamps,\n searchExtensionStatements,\n searchHelperFunctions,\n searchIndexNames,\n searchIndexStatements,\n searchStampGuards\n} from \"../search-column\";\nimport {\n VECTOR_EXTENSION_OPT_IN,\n vectorColumnDefinition,\n vectorDimensionGuard,\n vectorExtensionDeclared,\n vectorExtensionStatement,\n vectorIndexNames,\n vectorIndexStatements\n} from \"../vector-index\";\nimport { atlasExcludePattern } from \"../atlas-exclude\";\nimport { collectionIndexStatements } from \"../collection-index\";\nimport { quoteSqlLiteral } from \"./plan-schema\";\nimport { triggerStatements } from \"./updated-at-trigger\";\nimport { VIEW_ROWS_COMMENT_PREFIX, viewRowsName } from \"./view-names\";\nimport { REBASE_USER_ROLE } from \"@rebasepro/common\";\nimport type { ColumnPlan, PgType, PolicyPlan, SchemaPlan, TablePlan, ViewPlan } from \"./types\";\n\n/** What `schema.sql` may leave out, because another file owns it. */\nexport interface DdlRenderOptions {\n /** RLS policies. `false` puts them in `policies.sql` alone. */\n includePolicies?: boolean;\n /** The search column, its helpers and its index. See `search.sql`. */\n includeSearch?: boolean;\n /** The vector columns and their ANN indexes. See `vector.sql`. */\n includeVector?: boolean;\n}\n\n/**\n * A {@link PgType} as Postgres spells it.\n *\n * The one place. `getSqlColumnType` and `getDrizzleColumn` each carried their\n * own ladder and disagreed about `VARCHAR` widths, about `geopoint`, and about\n * whether an `increment` id honours `columnType`.\n */\nexport const renderPgType = (type: PgType): string => {\n switch (type.kind) {\n case \"text\": return \"TEXT\";\n case \"varchar\": return `VARCHAR(${type.length})`;\n case \"char\": return `CHAR(${type.length})`;\n case \"uuid\": return \"UUID\";\n case \"enum\": return `\"${type.schema}\".\"${type.name}\"`;\n case \"smallint\": return \"SMALLINT\";\n case \"integer\": return \"INTEGER\";\n case \"bigint\": return \"BIGINT\";\n case \"smallserial\": return \"SMALLSERIAL\";\n case \"serial\": return \"SERIAL\";\n case \"bigserial\": return \"BIGSERIAL\";\n case \"real\": return \"REAL\";\n case \"doublePrecision\": return \"DOUBLE PRECISION\";\n case \"numeric\":\n if (type.precision === undefined) return \"NUMERIC\";\n return type.scale === undefined\n ? `NUMERIC(${type.precision})`\n : `NUMERIC(${type.precision}, ${type.scale})`;\n case \"boolean\": return \"BOOLEAN\";\n case \"timestamptz\": return \"TIMESTAMP WITH TIME ZONE\";\n case \"date\": return \"DATE\";\n case \"time\": return \"TIME\";\n case \"json\": return \"JSON\";\n case \"jsonb\": return \"JSONB\";\n case \"vector\": return `VECTOR(${type.dimensions})`;\n case \"bytea\": return \"BYTEA\";\n case \"tsvector\": return \"tsvector\";\n case \"array\": return `${renderPgType(type.of)}[]`;\n }\n};\n\n/**\n * Everything after the column name, in one order for every SQL emitter.\n *\n * `CREATE TABLE` and `ADD COLUMN` used to assemble this separately, which is\n * how a required relation column came out `NOT NULL` after `db push` and\n * nullable after a boot-ensure. `identity` is part of the type rather than a\n * DEFAULT, which is why it is rendered here and not in the DEFAULT slot.\n */\nexport const renderColumnDefinition = (column: ColumnPlan): string => {\n // `auth-users-columns` is the single description of what an auth user\n // table's columns must be, and it hands over a rendered definition.\n if (column.sqlDefinition) return column.sqlDefinition;\n\n if (column.generated) {\n return `${renderPgType(column.type)} GENERATED ALWAYS AS (${column.generated.expression}) STORED`;\n }\n\n let definition = renderPgType(column.type);\n if (column.default?.kind === \"identity\") definition += \" GENERATED BY DEFAULT AS IDENTITY\";\n if (column.primaryKey) definition += \" PRIMARY KEY\";\n if (column.unique) definition += \" UNIQUE\";\n if (column.default && column.default.kind !== \"identity\") {\n definition += ` DEFAULT ${column.default.kind === \"sql\" ? column.default.expression : column.default.sql}`;\n }\n if (!column.nullable && !column.primaryKey) definition += \" NOT NULL\";\n return definition;\n};\n\n/**\n * `PRIMARY KEY (\"a\", \"b\")`, the clause a composite key takes inside a\n * `CREATE TABLE`. Shared by `schema.sql` and boot-ensure's `CREATE TABLE`, so\n * the two cannot list the columns differently.\n */\nexport const renderPrimaryKeyConstraint = (table: Pick<TablePlan, \"primaryKey\">): string =>\n `PRIMARY KEY (${table.primaryKey.map(c => `\"${c}\"`).join(\", \")})`;\n\n/** `\"col\" TYPE …`, as it appears inside a `CREATE TABLE`. */\nconst renderColumn = (column: ColumnPlan): string =>\n `\"${column.column}\" ${renderColumnDefinition(column)}`;\n\n// ── Policies ─────────────────────────────────────────────────────────────────\n\n/**\n * One policy as its `DROP` / `CREATE` pair — each a complete statement.\n *\n * This is the primitive the boot-time RLS applier runs one statement at a time\n * (the runtime's DB handle speaks the extended query protocol, which forbids\n * multiple commands in one execute), while `db push` writes the joined string.\n */\nexport const renderPolicyStatements = (\n table: Pick<TablePlan, \"schema\" | \"table\">,\n policy: PolicyPlan\n): string[] => {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n let create = `CREATE POLICY \"${policy.name}\" ON ${target} AS ${policy.mode.toUpperCase()} ` +\n `FOR ${policy.operation.toUpperCase()} TO ${policy.roles.map(r => `\"${r}\"`).join(\", \")}`;\n if (policy.using) create += ` USING (${policy.using})`;\n if (policy.withCheck) create += ` WITH CHECK (${policy.withCheck})`;\n // The one policy an older naming stored this rule's operations under —\n // see `PolicyPlan.supersedes`. In the same per-table transaction, so a\n // request sees the old policy or the new ones, never neither.\n const superseded = (policy.supersedes ?? []).map(name => `DROP POLICY IF EXISTS \"${name}\" ON ${target};`);\n // The admin-request companion a boot may have written beside this policy\n // (`USING (true)` for every admin) goes with it unless the policy, as\n // written now, still earns one: a rule narrowed to `admin AND owner`, moved\n // TO public, or changed in any way that keeps its name must not leave\n // every admin reading every row. Here rather than in the boot alone, so\n // `db push`, a migration and a boot that provisions nothing all drop it.\n //\n // A policy that does earn one keeps it — unless the one there was written\n // for something else under the same name: a named rule moved from SELECT\n // to DELETE keeps its name, and the SELECT companion would go on admitting\n // every admin to every row nobody may read now. Dropped then, by a check in\n // the statement itself, so the DDL heals whoever runs it.\n const keepsCompanion = policy.adminRequestCompanion !== undefined && policy.roles.includes(REBASE_ADMIN_ROLE);\n const isCompanion = policy.roles.includes(REBASE_ADMIN_REQUEST_ROLE);\n const companionName = adminRequestPolicyName(policy.name);\n const companion = isCompanion\n ? []\n : keepsCompanion\n ? [mismatchedCompanionDropSql(table, companionName, policy.operation)]\n : [`DROP POLICY IF EXISTS \"${companionName}\" ON ${target};`];\n return [...superseded, ...companion, `DROP POLICY IF EXISTS \"${policy.name}\" ON ${target};`, `${create};`];\n};\n\n/**\n * Drop the companion `name` on the table unless it is exactly what a boot\n * writes for a policy of this operation: permissive, `TO rebase_admin_request`\n * alone, `FOR <operation>`, its clauses `true` or absent. One `DO` statement,\n * so it runs on a handle that refuses several commands in one string.\n */\nfunction mismatchedCompanionDropSql(table: Pick<TablePlan, \"schema\" | \"table\">, name: string, operation: string): string {\n const literal = (value: string) => `'${value.replace(/'/g, \"''\")}'`;\n const ident = (value: string) => `\"${value.replace(/\"/g, \"\\\"\\\"\")}\"`;\n // One line, as every policy statement is: the boot sends a table's\n // statements joined by newlines, one per line.\n return `DO $rebase_companion$ BEGIN IF EXISTS (SELECT 1 FROM pg_policies p ` +\n `WHERE p.schemaname = ${literal(table.schema)} AND p.tablename = ${literal(table.table)} AND p.policyname = ${literal(name)} ` +\n `AND NOT (p.cmd = ${literal(operation.toUpperCase())} AND p.permissive = 'PERMISSIVE' ` +\n `AND p.roles = ARRAY[${literal(REBASE_ADMIN_REQUEST_ROLE)}]::name[] ` +\n `AND COALESCE(p.qual, 'true') = 'true' AND COALESCE(p.with_check, 'true') = 'true')) ` +\n `THEN EXECUTE ${literal(`DROP POLICY ${ident(name)} ON ${ident(table.schema)}.${ident(table.table)}`)}; END IF; END $rebase_companion$;`;\n}\n\n/**\n * A restrictive policy, under its own name, command and roles, that passes no\n * row: `USING (false)` / `WITH CHECK (false)` for the clauses its command takes.\n *\n * What the boot applier puts in place of a restrictive policy whose own\n * `CREATE` failed. A restrictive policy is a gate ANDed over every permissive\n * one, so its absence does not deny — it opens whatever the permissive policies\n * grant. Standing in for it with a gate nothing passes keeps the failure on\n * the denying side until the rule can be created.\n */\nexport const renderDenyingPolicyStatements = (\n table: Pick<TablePlan, \"schema\" | \"table\">,\n policy: PolicyPlan\n): string[] => {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n let create = `CREATE POLICY \"${policy.name}\" ON ${target} AS RESTRICTIVE ` +\n `FOR ${policy.operation.toUpperCase()} TO ${policy.roles.map(r => `\"${r}\"`).join(\", \")}`;\n if (policy.operation !== \"insert\") create += \" USING (false)\";\n if (policy.operation !== \"select\" && policy.operation !== \"delete\") create += \" WITH CHECK (false)\";\n return [`DROP POLICY IF EXISTS \"${policy.name}\" ON ${target};`, `${create};`];\n};\n\n/** `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` — every generated table is locked. */\nexport const renderEnableRls = (table: Pick<TablePlan, \"schema\" | \"table\">): string =>\n `ALTER TABLE \"${table.schema}\".\"${table.table}\" ENABLE ROW LEVEL SECURITY;`;\n\nconst statementsToDdl = (statements: string[]): string => statements.map(s => `${s}\\n`).join(\"\");\n\n// ── schema.sql ───────────────────────────────────────────────────────────────\n\nexport function renderPostgresDdl(plan: SchemaPlan, options: DdlRenderOptions = {}): string {\n const includePolicies = options.includePolicies !== false;\n const includeSearch = options.includeSearch !== false;\n const includeVector = options.includeVector !== false;\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\\n\";\n\n // 1. Custom schemas.\n //\n // `rebase` is unconditional and load-bearing. The RLS helper functions live\n // in it, so the migration preamble creates it — which puts it in Atlas's\n // replayed state, and anything in that state but absent from this desired\n // schema gets a `DROP SCHEMA … CASCADE` planned against it. That would take\n // the auth tables.\n plan.schemas.forEach(schema => { ddl += `CREATE SCHEMA IF NOT EXISTS \"${schema}\";\\n`; });\n if (plan.schemas.length > 0) ddl += \"\\n\";\n\n // 1b. Search support, for collections that opted in.\n //\n // Extensions and helper functions come before every CREATE TABLE because a\n // generated column's expression is resolved at creation time: a table whose\n // search column calls `rebase_search_text` cannot be created before that\n // function exists. Both are `IF NOT EXISTS` / `OR REPLACE`, so a file\n // replayed against a live database is a no-op here.\n const searchTables = plan.tables.filter(t => t.search);\n if (searchTables.length > 0) {\n if (!includeSearch) {\n ddl += \"-- Full-text search support lives in `search.sql`, applied separately.\\n\\n\";\n } else {\n const extensions = Array.from(new Set(searchTables.flatMap(t => searchExtensionStatements(t.search!))));\n const helpers = Array.from(new Set(searchTables.flatMap(t => searchHelperFunctions(t.search!))));\n ddl += \"-- Full-text search support (collections declaring a `search` block)\\n\";\n extensions.forEach(s => { ddl += `${s}\\n`; });\n if (extensions.length > 0) ddl += \"\\n\";\n helpers.forEach(s => { ddl += `${s}\\n\\n`; });\n }\n }\n\n // 1c. Vector support. Only ever a note, never a statement — unlike 1b.\n // `CREATE EXTENSION vector` is the one thing this file must never carry\n // whichever way the flag goes: Atlas rejects an extension in a desired\n // state as a paid feature.\n if (!includeVector && plan.tables.some(t => t.vectorColumns.length > 0)) {\n ddl += \"-- Vector columns and their ANN indexes live in `vector.sql`, applied separately.\\n\\n\";\n }\n\n // 1d. `autoValue: \"on_update\"`. A trigger is a function plus a binding, so\n // it is out of Atlas's sight for the reason search is — and out\n // unconditionally, because `schema.sql` has no flag that would make Atlas\n // able to read one.\n if (plan.tables.some(t => t.triggers.length > 0)) {\n ddl += \"-- `autoValue: \\\"on_update\\\"` triggers live in `triggers.sql`, applied separately.\\n\\n\";\n }\n\n // 2. Enum types.\n plan.enums.forEach(enumPlan => {\n ddl += `CREATE TYPE \"${enumPlan.schema}\".\"${enumPlan.name}\" AS ENUM (${enumPlan.labels.map(quoteSqlLiteral).join(\", \")});\\n`;\n });\n if (ddl.endsWith(\";\\n\")) ddl += \"\\n\";\n\n // 3. Tables, in the plan's order — each collection, then any junction its\n // relations imply.\n const fkStatements: string[] = [];\n // Indexes follow the tables for the same reason the FK constraints do: the\n // table has to exist first.\n const indexStatements: string[] = [];\n // Policies are emitted after every CREATE TABLE, like the FK constraints: a\n // policy may reference other tables (a junction's derived policies always\n // reference both endpoints; `policy.existsIn` references a join table), and\n // CREATE POLICY validates those relations at creation time.\n const policyStatements: string[] = [];\n\n for (const table of plan.tables) {\n const emitted = table.columns.filter(column => {\n // A vector column is not Atlas's — `vector.sql` adds it. Filtered\n // here rather than upstream so the column keeps its place in the\n // generator's order when it *is* included, which is what the\n // derived-names contract renders.\n if (!includeVector && column.type.kind === \"vector\") return false;\n if (!includeSearch && column.source.kind === \"search\") return false;\n // A declared property already emits this column (an explicit\n // `postId` beside the `belongsTo` that uses it); the relation\n // contributes only the constraint.\n if (column.columnOwnedByProperty) return false;\n return true;\n });\n\n ddl += `CREATE TABLE \"${table.schema}\".\"${table.table}\" (\\n`;\n const lines = emitted.map(column => ` ${renderColumn(column)}`);\n // A key over several columns — a junction's two endpoints, or a\n // collection with several `isId` properties — is one table constraint;\n // a single-column key is already inline on its column.\n if (table.primaryKey.length > 1) {\n lines.push(` ${renderPrimaryKeyConstraint(table)}`);\n }\n ddl += lines.join(\",\\n\");\n ddl += \"\\n);\\n\\n\";\n\n for (const column of table.columns) {\n if (column.foreignKey) fkStatements.push(`${column.foreignKey.sql};`);\n }\n\n if (includeSearch && table.search) {\n indexStatements.push(...searchIndexStatements(table.search));\n }\n // ANN indexes are emitted with the other indexes rather than inline,\n // because `CREATE INDEX` is a statement and a column definition is not\n // — and because a column too wide for pgvector to index still needs its\n // column. Absent alongside their column when vector is carved out.\n if (includeVector && table.vector) {\n indexStatements.push(...vectorIndexStatements(table.vector));\n for (const skip of table.vector.skipped) {\n indexStatements.push(`-- No ANN index on \"${skip.schema}\".\"${skip.table}\".\"${skip.column}\": ${skip.reason}`);\n }\n }\n // The collection's own `indexes:` block. Last of the three index\n // producers, and the only one the developer wrote deliberately rather\n // than getting as a side effect of another feature.\n indexStatements.push(...collectionIndexStatements(table.indexes));\n\n if (includePolicies) {\n // No FORCE: authenticated requests run as the non-owner\n // `rebase_user` role, which plain ENABLE already binds. The owner\n // (server context) must bypass — it is the trusted plane.\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n for (const policy of table.policies) {\n policyStatements.push(statementsToDdl(renderPolicyStatements(table, policy)));\n }\n }\n }\n\n // Indexes before foreign keys. Today every FK targets a primary key created\n // inline, so the order is safe by accident; the moment a declared\n // `unique: true` index can back an FK target, a constraint emitted first\n // would reference an index that does not exist yet.\n if (indexStatements.length > 0) {\n ddl += \"-- Indexes\\n\";\n ddl += indexStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (fkStatements.length > 0) {\n ddl += \"-- Foreign Key Constraints\\n\";\n ddl += fkStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (policyStatements.length > 0) {\n ddl += \"-- Row Level Security Policies\\n\";\n ddl += adminRolePreamble(plan);\n ddl += policyStatements.join(\"\");\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n// ── policies.sql ─────────────────────────────────────────────────────────────\n\n/**\n * The statement that creates `rebase_admin`, when a policy in the plan is\n * written `TO` it — so a file of policies is self-contained, as it is for the\n * RLS helpers: CREATE POLICY refuses a role that does not exist. Empty when no\n * policy names it (`rls.adminPolicies: \"public\"`).\n */\nexport function adminRolePreamble(plan: SchemaPlan): string {\n const named = plan.tables.some(table => table.policies.some(policy => policy.roles.includes(REBASE_ADMIN_ROLE)));\n return named ? `${ADMIN_POLICY_ROLE_SQL};\\n\\n` : \"\";\n}\n\nexport function renderPoliciesDdl(plan: SchemaPlan): string {\n let ddl = \"-- This file contains RLS policies generated by Rebase. Applied separately from migrations.\\n\\n\";\n ddl += adminRolePreamble(plan);\n\n // Collections first, then the junctions no collection declares — the order\n // the boot-time applier plans them in.\n for (const table of plan.tables.filter(t => t.kind === \"collection\")) {\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n if (table.policies.length === 0) continue;\n let announced: string | undefined;\n for (const policy of table.policies) {\n // Say which policies the author did not write. They are permissive,\n // so they OR with the declared rules and widen the final ACL beyond\n // what `securityRules` reads like — and re-appear after any manual\n // DROP, because a push asserts the declared state. Once per *rule*:\n // one rule with four operations is one thing the author did not\n // write, not four.\n if (policy.injected && policy.ruleKey !== announced) {\n ddl += \"-- Injected by Rebase (not from this collection's securityRules).\\n\";\n ddl += `-- Set \\`disableDefaultPolicies: true\\` on \"${table.slug}\" to drop these and own its RLS outright.\\n`;\n }\n announced = policy.ruleKey;\n ddl += statementsToDdl(renderPolicyStatements(table, policy));\n }\n ddl += \"\\n\";\n }\n\n for (const table of plan.tables.filter(t => t.kind === \"junction\")) {\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n if (table.policies.length === 0) continue;\n const declaringSlugs = (table.declaringSlugs ?? []).join('\", \"');\n ddl += `-- Derived by Rebase for the junction \"${table.table}\" (no collection declares it).\\n`;\n ddl += \"-- Reads require both endpoint rows to be visible; writes follow the update\\n\";\n ddl += `-- rules of \"${declaringSlugs}\". Set \\`disableDefaultPolicies: true\\` on the\\n`;\n ddl += \"-- declaring collection(s) to drop these and police the junction yourself.\\n\";\n for (const policy of table.policies) {\n ddl += statementsToDdl(renderPolicyStatements(table, policy));\n }\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n// ── search.sql ───────────────────────────────────────────────────────────────\n\nexport function renderSearchDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.search);\n if (tables.length === 0) return \"\";\n\n const extensions = Array.from(new Set(tables.flatMap(t => searchExtensionStatements(t.search!))));\n const helpers = Array.from(new Set(tables.flatMap(t => searchHelperFunctions(t.search!))));\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- Full-text search for the collections declaring a `search` block.\\n\";\n ddl += \"-- Applied by Rebase, not by Atlas — see generatePostgresSearchDdl.\\n\\n\";\n\n extensions.forEach(s => { ddl += `${s}\\n`; });\n if (extensions.length > 0) ddl += \"\\n\";\n helpers.forEach(s => { ddl += `${s}\\n\\n`; });\n\n for (const table of tables) {\n const spec = table.search!;\n const target = `\"${table.schema}\".\"${table.table}\"`;\n // ADD COLUMN IF NOT EXISTS rather than the inline definition the\n // CREATE TABLE would use: by the time this runs the table exists,\n // whether Atlas just created it or it has been live for a year. The\n // guard first, because `ADD COLUMN IF NOT EXISTS` is a no-op against an\n // existing column — without it the file would report success, leave the\n // old expression in place, and then stamp it as current.\n searchStampGuards(spec).forEach(s => { ddl += `${s}\\n`; });\n ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${searchColumnDefinition(spec)};\\n`;\n const fuzzy = fuzzyColumnDefinition(spec);\n if (fuzzy) ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${fuzzy};\\n`;\n searchColumnStamps(spec).forEach(s => { ddl += `${s.sql}\\n`; });\n searchIndexStatements(spec).forEach(s => { ddl += `${s}\\n`; });\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n/**\n * Glob patterns telling Atlas to leave an object alone.\n *\n * Fully qualified, `schema.table.object`, matching the include list. The\n * two-part form is what Atlas wants when the connection URL scopes it to one\n * schema and is *silently ignored* otherwise: it reads `posts.search_vector` as\n * a table named `search_vector` in a schema named `posts`, matches nothing, and\n * reports no error for the pattern that never fired. Each name is spelled by\n * `atlasExcludePattern`, so one holding a `.` or glob syntax still matches.\n */\nexport const searchExcludePatternsOf = (plan: SchemaPlan): string[] => {\n const patterns: string[] = [];\n for (const table of plan.tables) {\n if (!table.search) continue;\n for (const column of table.columns) {\n if (column.source.kind !== \"search\") continue;\n patterns.push(atlasExcludePattern(table.schema, table.table, column.column));\n }\n for (const index of searchIndexNames(table.search)) {\n patterns.push(atlasExcludePattern(table.schema, table.table, index));\n }\n }\n return patterns;\n};\n\n// ── vector.sql ───────────────────────────────────────────────────────────────\n\nexport function renderVectorDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.vectorColumns.length > 0);\n if (tables.length === 0) return \"\";\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- Vector columns and their ANN indexes, for the collections declaring a\\n\";\n ddl += \"-- `vector` property. Applied by Rebase, not by Atlas — see\\n\";\n ddl += \"-- generatePostgresVectorDdl.\\n\\n\";\n // The note is not decoration. Someone reading this file after a failed push\n // is looking for the reason the type does not exist, and \"no CREATE\n // EXTENSION here\" is invisible unless it is written down.\n ddl += vectorExtensionDeclared(plan.options.databaseExtensions)\n ? `${vectorExtensionStatement()}\\n\\n`\n : \"-- pgvector is not installed from here: no database declared it. To let Rebase\\n\" +\n `-- install it, add ${VECTOR_EXTENSION_OPT_IN} in config/resources.ts.\\n` +\n \"-- Otherwise install it once by hand; the column below needs the type either way.\\n\\n\";\n\n for (const table of tables) {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n for (const spec of table.vectorColumns) {\n // Guard before the ADD, so a changed `dimensions` is reported\n // rather than skipped over — see `vectorDimensionGuard`.\n ddl += `${vectorDimensionGuard(spec)}\\n`;\n ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${vectorColumnDefinition(spec)};\\n`;\n }\n if (table.vector) {\n vectorIndexStatements(table.vector).forEach(s => { ddl += `${s}\\n`; });\n for (const skip of table.vector.skipped) {\n ddl += `-- No ANN index on \"${skip.schema}\".\"${skip.table}\".\"${skip.column}\": ${skip.reason}\\n`;\n }\n }\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n/** @see searchExcludePatternsOf */\nexport const vectorExcludePatternsOf = (plan: SchemaPlan): string[] => {\n const patterns: string[] = [];\n for (const table of plan.tables) {\n const names = [\n ...table.vectorColumns.map(spec => spec.column),\n ...(table.vector ? vectorIndexNames(table.vector) : [])\n ];\n for (const name of names) patterns.push(atlasExcludePattern(table.schema, table.table, name));\n }\n return patterns;\n};\n\n// ── triggers.sql ─────────────────────────────────────────────────────────────\n\n/**\n * `autoValue: \"on_update\"`, as the file Rebase applies itself.\n *\n * Empty when nothing declares one — the caller writes no file then, and removes\n * a stale one.\n */\nexport function renderTriggersDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.triggers.length > 0);\n if (tables.length === 0) return \"\";\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- `updated_at` triggers, for the properties declaring `autoValue: \\\"on_update\\\"`,\\n\";\n ddl += \"-- and the triggers that keep a row in its tenant.\\n\";\n ddl += \"-- Applied by Rebase, not by Atlas — a trigger is a function plus a binding,\\n\";\n ddl += \"-- and Atlas's free tier refuses to parse a desired state containing one.\\n\\n\";\n\n for (const statement of plan.functions.filter(isTriggerFunction)) {\n ddl += `${statement}\\n\\n`;\n }\n for (const table of tables) {\n for (const trigger of table.triggers) {\n triggerStatements(trigger).forEach(s => { ddl += `${s}\\n`; });\n }\n ddl += \"\\n\";\n }\n return ddl;\n}\n\nconst isTriggerFunction = (statement: string): boolean => statement.includes(\"RETURNS trigger\");\n\n/** @see searchExcludePatternsOf */\nexport const triggerExcludePatternsOf = (plan: SchemaPlan): string[] =>\n plan.tables.flatMap(table => table.triggers.map(t => atlasExcludePattern(table.schema, table.table, t.name)));\n\nconst quoteIdentifier = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** The comment a view Rebase created carries: `rebase:view:<hash>`. */\nexport const viewComment = (view: ViewPlan): string => `rebase:view:${view.hash}`;\n\n/** A dollar-quote tag the text does not contain, so the text can be quoted whole. */\nfunction dollarTag(text: string): string {\n let tag = \"$rebase_view$\";\n for (let i = 1; text.includes(tag); i++) tag = `$rebase_view_${i}$`;\n return tag;\n}\n\n/**\n * The statements that create one view as planned, comment included, for\n * `EXECUTE`. A plain view runs as the caller (`security_invoker`), so the\n * policies of the tables it reads decide what each caller sees.\n *\n * A materialized view is two objects (see `view-names.ts`): its rows, stored\n * under {@link viewRowsName} with a unique index on the id columns (which\n * `REFRESH … CONCURRENTLY` needs), and the gate under the collection's name —\n * a `security_barrier` view that reads them with the owner's rights and serves\n * them to the collection's roles and to the server (no uid). It reads the\n * settings directly rather than through `rebase.roles()`, which a first boot\n * creates after the views. It carries each row's `xmin`, for `fingerprint()`;\n * the catalogue reader leaves that column out of the collection.\n */\nexport function viewCreateStatements(view: ViewPlan): string[] {\n const qualified = `${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`;\n if (!view.materialized) {\n return [\n `CREATE VIEW ${qualified} WITH (security_invoker = true) AS\\n${view.query}`,\n `COMMENT ON VIEW ${qualified} IS '${viewComment(view)}'`\n ];\n }\n const stored = `${quoteIdentifier(view.schema)}.${quoteIdentifier(viewRowsName(view.name))}`;\n const roles = view.roles.map(role => `'${role.replace(/'/g, \"''\")}'`).join(\", \");\n const statements = [`CREATE MATERIALIZED VIEW ${stored} AS\\n${view.query}\\nWITH DATA`];\n if (view.idColumns.length > 0) {\n statements.push(`CREATE UNIQUE INDEX ${quoteIdentifier(`${view.name}_rebase_id`)} ON ${stored} (${view.idColumns.map(quoteIdentifier).join(\", \")})`);\n }\n statements.push(...view.indexes);\n statements.push(\n `COMMENT ON MATERIALIZED VIEW ${stored} IS '${VIEW_ROWS_COMMENT_PREFIX}${view.hash}'`,\n `REVOKE ALL ON ${stored} FROM PUBLIC`,\n `CREATE VIEW ${qualified} WITH (security_barrier = true) AS\\n` +\n `SELECT rows.*, rows.xmin AS xmin FROM ${stored} rows\\n` +\n \"WHERE NULLIF(current_setting('app.uid', true), '') IS NULL\\n\" +\n ` OR string_to_array(COALESCE(current_setting('app.user_roles', true), ''), ',') && ARRAY[${roles || \"NULL\"}]::text[]`,\n `COMMENT ON VIEW ${qualified} IS '${viewComment(view)}'`\n );\n return statements;\n}\n\n/**\n * `views.sql`: the views of the collections that declare one, as the file\n * Rebase applies itself — Atlas manages no views on its free tier.\n *\n * Idempotent, in two passes. The first drops, last first, every view whose\n * comment no longer matches its plan and every view that reads one of those\n * (Postgres will not drop a view another still reads, and will not change a\n * view's columns in place); the second creates, in order, every view that is\n * not there. A view that is up to date is left alone, rows and all. A table or\n * a view Rebase did not create under the same name is refused, never dropped.\n *\n * Empty when no collection declares a view.\n */\nexport function renderViewsDdl(plan: SchemaPlan): string {\n if (plan.views.length === 0) return \"\";\n const literal = (text: string) => `'${text.replace(/'/g, \"''\")}'`;\n const regclass = (view: ViewPlan) => `to_regclass(${literal(`${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`)})`;\n const stale = (view: ViewPlan) =>\n `(${regclass(view)} IS NOT NULL AND obj_description(${regclass(view)}, 'pg_class') IS DISTINCT FROM ${literal(viewComment(view))})`;\n // Every planned view a view reads, directly or through another.\n const readsOf = (view: ViewPlan, seen = new Set<string>()): ViewPlan[] =>\n view.dependsOn.flatMap(name => {\n if (seen.has(name)) return [];\n seen.add(name);\n const target = plan.views.find(other => other.qualified === name);\n return target ? [target, ...readsOf(target, seen)] : [];\n });\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- The views of the collections that declare `view`. Applied by Rebase, not by Atlas.\\n\\n\";\n ddl += \"DO $rebase_views$\\nDECLARE\\n kind \\\"char\\\";\\n note text;\\nBEGIN\\n\";\n for (const view of [...plan.views].reverse()) {\n const qualified = `${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`;\n const reasons = [view, ...readsOf(view)].map(stale).join(\"\\n OR \");\n ddl += ` SELECT c.relkind, obj_description(c.oid, 'pg_class') INTO kind, note FROM pg_class c WHERE c.oid = ${regclass(view)};\\n`;\n ddl += \" IF kind IS NOT NULL AND (kind NOT IN ('v', 'm') OR note IS NULL OR note NOT LIKE 'rebase:view:%') THEN\\n\";\n ddl += ` RAISE EXCEPTION 'Rebase will not replace %: it is a table or a view Rebase did not create. Rename or drop it, or give the collection another table.', ${literal(view.qualified)};\\n`;\n ddl += \" END IF;\\n\";\n ddl += ` IF ${reasons} THEN\\n`;\n ddl += ` IF kind = 'm' THEN EXECUTE ${literal(`DROP MATERIALIZED VIEW ${qualified}`)}; ELSE EXECUTE ${literal(`DROP VIEW ${qualified}`)}; END IF;\\n`;\n ddl += \" END IF;\\n\";\n }\n for (const view of plan.views) {\n const rows = `${quoteIdentifier(view.schema)}.${quoteIdentifier(viewRowsName(view.name))}`;\n ddl += ` IF ${regclass(view)} IS NULL THEN\\n`;\n // A gate that is gone leaves its rows: they are this view's, recomputed below.\n if (view.materialized) {\n ddl += ` IF to_regclass(${literal(rows)}) IS NOT NULL THEN EXECUTE ${literal(`DROP MATERIALIZED VIEW ${rows}`)}; END IF;\\n`;\n }\n for (const statement of viewCreateStatements(view)) {\n const tag = dollarTag(statement);\n ddl += ` EXECUTE ${tag}${statement}${tag};\\n`;\n }\n if (view.materialized) {\n ddl += ` IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(REBASE_USER_ROLE)}) THEN EXECUTE ${literal(`REVOKE ALL ON ${rows} FROM ${REBASE_USER_ROLE}`)}; END IF;\\n`;\n }\n ddl += \" END IF;\\n\";\n }\n ddl += \"END\\n$rebase_views$;\\n\";\n return ddl;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,gBAAgB,SAAyB;CAClD,QAAQ,KAAK,MAAb;EACI,KAAK,QAAQ,OAAO;EACpB,KAAK,WAAW,OAAO,WAAW,KAAK,OAAO;EAC9C,KAAK,QAAQ,OAAO,QAAQ,KAAK,OAAO;EACxC,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO,IAAI,KAAK,OAAO,KAAK,KAAK,KAAK;EACnD,KAAK,YAAY,OAAO;EACxB,KAAK,WAAW,OAAO;EACvB,KAAK,UAAU,OAAO;EACtB,KAAK,eAAe,OAAO;EAC3B,KAAK,UAAU,OAAO;EACtB,KAAK,aAAa,OAAO;EACzB,KAAK,QAAQ,OAAO;EACpB,KAAK,mBAAmB,OAAO;EAC/B,KAAK;GACD,IAAI,KAAK,cAAc,KAAA,GAAW,OAAO;GACzC,OAAO,KAAK,UAAU,KAAA,IAChB,WAAW,KAAK,UAAU,KAC1B,WAAW,KAAK,UAAU,IAAI,KAAK,MAAM;EACnD,KAAK,WAAW,OAAO;EACvB,KAAK,eAAe,OAAO;EAC3B,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO;EACpB,KAAK,SAAS,OAAO;EACrB,KAAK,UAAU,OAAO,UAAU,KAAK,WAAW;EAChD,KAAK,SAAS,OAAO;EACrB,KAAK,YAAY,OAAO;EACxB,KAAK,SAAS,OAAO,GAAG,aAAa,KAAK,EAAE,EAAE;CAClD;AACJ;;;;;;;;;AAUA,IAAa,0BAA0B,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AAE,iBAAiB,QAAQ,iBAAiB,KAAK,QAAQ,kBAAkB,EAAE;EAE7K,OAAO;CACX;CACA,OAAO;CACP,OAAO;AACX"}
|
|
@@ -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 { it as redactConnectionPasswords } from "./cli-errors-
|
|
4
|
+
import { it as redactConnectionPasswords } from "./cli-errors-DYTxnLbW.js";
|
|
5
5
|
import { n as resolveRlsSettings } from "./rls-settings-BCGMIig3.js";
|
|
6
6
|
import { a as outWarn, i as outError, r as out, t as chalk } from "./source-fZb92pN8.js";
|
|
7
|
-
import { _ as closestWord, y as parseCommandFlags } from "./migrate-baseline-
|
|
7
|
+
import { _ as closestWord, y as parseCommandFlags } from "./migrate-baseline-CmWXL7qx.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-errors-
|
|
167
|
-
const { appRoleSetupInstructions, readRecordedRequestRoles } = await import("./rls-enforcement-
|
|
166
|
+
const { withAppClient } = await import("./cli-errors-DYTxnLbW.js").then((n) => n.v);
|
|
167
|
+
const { appRoleSetupInstructions, readRecordedRequestRoles } = await import("./rls-enforcement-Cc_UhOxb.js").then((n) => n.y);
|
|
168
168
|
const { cliRlsSettings } = await import("./rls-settings-BCGMIig3.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-errors-
|
|
199
|
-
const { AppRoleSetupError, readRecordedRequestRoles } = await import("./rls-enforcement-
|
|
200
|
-
const { migrateRequestRoles, planRequestRoleMigration } = await import("./request-role-migration-
|
|
198
|
+
const { withAppClient } = await import("./cli-errors-DYTxnLbW.js").then((n) => n.v);
|
|
199
|
+
const { AppRoleSetupError, readRecordedRequestRoles } = await import("./rls-enforcement-Cc_UhOxb.js").then((n) => n.y);
|
|
200
|
+
const { migrateRequestRoles, planRequestRoleMigration } = await import("./request-role-migration-GHTJnPMV.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-Dy1EgJU9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-role-cli-Bxxskru9.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;;;;;;AAeA,SAAgB,cAAc,OAAe,MAAwB;CACjE,MAAM,QAAQ,MAAM,KAAK,IAAI,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC;CACvF,IAAI,MAAM,WAAW,GAAG,MAAM,IAAI,MAAM,GAAG,KAAK,sCAAsC,KAAK,gBAAgB;CAC3G,KAAK,MAAM,QAAQ,OACf,IAAI;EACA,mBAAmB,EAAE,aAAa,KAAK,CAAC;CAC5C,SAAS,KAAK;EACV,MAAM,IAAI,MAAM,GAAG,KAAK,GAAG,KAAK,IAAI,eAAe,QAAQ,IAAI,QAAQ,QAAQ,cAAc,EAAE,IAAI,OAAO,GAAG,GAAG;CACpH;CAEJ,OAAO;AACX;;;;;;AAOA,SAAgB,qBAAqB,SAA6C;CAC9E,MAAM,SAAS,QAAQ;CACvB,IAAI,WAAW,KAAA,KAAa,OAAO,WAAW,GAAG,GAC7C,MAAM,IAAI,MACN,iHACJ;CAEJ,IAAI,CAAC,qBAAqB,MAAM,UAAU,UAAU,MAAM,GAAG;EACzD,MAAM,OAAO,YAAY,QAAQ,oBAAoB;EACrD,MAAM,IAAI,MACN,6CAA6C,0BAA0B,MAAM,EAAE,MAC9E,OAAO,mBAAmB,KAAK,KAAK,eAAe,qBAAqB,KAAK,IAAI,EAAE,MACpF,mBACJ;CACJ;CACA,MAAM,OAAO,kBAAkB,oBAAoB,CA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;EACA,IAAI,CAAE,MAAM,iBAAiB,KAAK,GAAG,GAAI;GACrC,QAAQ,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
|
+
{"version":3,"file":"request-role-cli-Dy1EgJU9.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;;;;;;AAeA,SAAgB,cAAc,OAAe,MAAwB;CACjE,MAAM,QAAQ,MAAM,KAAK,IAAI,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC;CACvF,IAAI,MAAM,WAAW,GAAG,MAAM,IAAI,MAAM,GAAG,KAAK,sCAAsC,KAAK,gBAAgB;CAC3G,KAAK,MAAM,QAAQ,OACf,IAAI;EACA,mBAAmB,EAAE,aAAa,KAAK,CAAC;CAC5C,SAAS,KAAK;EACV,MAAM,IAAI,MAAM,GAAG,KAAK,GAAG,KAAK,IAAI,eAAe,QAAQ,IAAI,QAAQ,QAAQ,cAAc,EAAE,IAAI,OAAO,GAAG,GAAG;CACpH;CAEJ,OAAO;AACX;;;;;;AAOA,SAAgB,qBAAqB,SAA6C;CAC9E,MAAM,SAAS,QAAQ;CACvB,IAAI,WAAW,KAAA,KAAa,OAAO,WAAW,GAAG,GAC7C,MAAM,IAAI,MACN,iHACJ;CAEJ,IA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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-Cc_UhOxb.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-GHTJnPMV.js.map
|
package/dist/{request-role-migration-BCW4v0rq.js.map → request-role-migration-GHTJnPMV.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-role-migration-BCW4v0rq.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;EACzB,MAAM,SAAS,GAAG,IAAI,SAAS,MAAM,aAAa,QAAQ,GAAG,WAAW,OAAO,IAAI,MAAM,CAAC,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ration.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;A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nC;;;;;;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,11 +1,12 @@
|
|
|
1
1
|
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
|
-
import { LEGACY_RLS_SCHEMA, REBASE_ADMIN_ROLE, REBASE_SCHEMA } from "@rebasepro/types";
|
|
4
|
+
import { LEGACY_RLS_SCHEMA, REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, REBASE_SCHEMA } from "@rebasepro/types";
|
|
5
5
|
import { sqlRows } from "@rebasepro/common";
|
|
6
6
|
//#region src/schema/rls-bootstrap-sql.ts
|
|
7
7
|
var rls_bootstrap_sql_exports = /* @__PURE__ */ __exportAll({
|
|
8
8
|
ADMIN_POLICY_ROLE_SQL: () => ADMIN_POLICY_ROLE_SQL,
|
|
9
|
+
ADMIN_REQUEST_ROLE_SQL: () => ADMIN_REQUEST_ROLE_SQL,
|
|
9
10
|
DROP_LEGACY_AUTH_SCHEMA_SQL: () => DROP_LEGACY_AUTH_SCHEMA_SQL,
|
|
10
11
|
LEGACY_AUTH_SCHEMA_CONTENTS_SQL: () => LEGACY_AUTH_SCHEMA_CONTENTS_SQL,
|
|
11
12
|
LEGACY_RLS_DEPENDENTS_SQL: () => LEGACY_RLS_DEPENDENTS_SQL,
|
|
@@ -523,12 +524,26 @@ EXCEPTION
|
|
|
523
524
|
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.';
|
|
524
525
|
END
|
|
525
526
|
$rebase_admin_role$`;
|
|
527
|
+
/**
|
|
528
|
+
* Create {@link REBASE_ADMIN_REQUEST_ROLE} unless it exists. Unlike
|
|
529
|
+
* {@link ADMIN_POLICY_ROLE_SQL} it is never in `policies.sql` or a migration:
|
|
530
|
+
* only a boot makes it, and a boot that cannot just plans no companions.
|
|
531
|
+
*/
|
|
532
|
+
var ADMIN_REQUEST_ROLE_SQL = `DO $rebase_admin_request_role$
|
|
533
|
+
BEGIN
|
|
534
|
+
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_REQUEST_ROLE}') THEN
|
|
535
|
+
CREATE ROLE ${REBASE_ADMIN_REQUEST_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;
|
|
536
|
+
END IF;
|
|
537
|
+
EXCEPTION
|
|
538
|
+
WHEN duplicate_object OR unique_violation THEN NULL;
|
|
539
|
+
END
|
|
540
|
+
$rebase_admin_request_role$`;
|
|
526
541
|
/** Create {@link REBASE_ADMIN_ROLE} unless it exists — one read when it does. */
|
|
527
542
|
async function ensureAdminPolicyRole(run) {
|
|
528
543
|
const [row] = await run(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') AS present`);
|
|
529
544
|
if (row?.present !== true) await run(ADMIN_POLICY_ROLE_SQL);
|
|
530
545
|
}
|
|
531
546
|
//#endregion
|
|
532
|
-
export {
|
|
547
|
+
export { RLS_BOOTSTRAP_STATEMENTS as a, rlsRuntimeIsCurrent as c, RLS_BOOTSTRAP_SQL as i, rls_bootstrap_sql_exports as l, ADMIN_REQUEST_ROLE_SQL as n, dropLegacyAuthSchema as o, REQUEST_ROLE_FUNCTION_SQL as r, ensureAdminPolicyRole as s, ADMIN_POLICY_ROLE_SQL as t };
|
|
533
548
|
|
|
534
|
-
//# sourceMappingURL=rls-bootstrap-sql-
|
|
549
|
+
//# sourceMappingURL=rls-bootstrap-sql-kPX4-MB1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rls-bootstrap-sql-kPX4-MB1.js","names":[],"sources":["../src/schema/rls-bootstrap-sql.ts"],"sourcesContent":["import { LEGACY_RLS_SCHEMA, REBASE_ADMIN_REQUEST_ROLE, 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/**\n * Create {@link REBASE_ADMIN_REQUEST_ROLE} unless it exists. Unlike\n * {@link ADMIN_POLICY_ROLE_SQL} it is never in `policies.sql` or a migration:\n * only a boot makes it, and a boot that cannot just plans no companions.\n */\nexport const ADMIN_REQUEST_ROLE_SQL = `DO $rebase_admin_request_role$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_REQUEST_ROLE}') THEN\n CREATE ROLE ${REBASE_ADMIN_REQUEST_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\nEXCEPTION\n WHEN duplicate_object OR unique_violation THEN NULL;\nEND\n$rebase_admin_request_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,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