@rebasepro/server-postgres 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/{BranchService-USp1AvZB.js → BranchService-C8LtpMho.js} +3 -3
  2. package/dist/{BranchService-USp1AvZB.js.map → BranchService-C8LtpMho.js.map} +1 -1
  3. package/dist/{backup-cli-DbKyEj6c.js → backup-cli-DtV6n3oB.js} +3 -3
  4. package/dist/{backup-cli-DbKyEj6c.js.map → backup-cli-DtV6n3oB.js.map} +1 -1
  5. package/dist/{boot-ddl-5H2bL_80.js → boot-ddl-CSYhSSZD.js} +2 -2
  6. package/dist/{boot-ddl-5H2bL_80.js.map → boot-ddl-CSYhSSZD.js.map} +1 -1
  7. package/dist/{cli-console-DsRgGSBR.js → cli-console-Cu1DzqvR.js} +4 -4
  8. package/dist/{cli-console-DsRgGSBR.js.map → cli-console-Cu1DzqvR.js.map} +1 -1
  9. package/dist/{cli-schema-dir-CiN0ephV.js → cli-schema-dir-DuZIsF2e.js} +5 -5
  10. package/dist/{cli-schema-dir-CiN0ephV.js.map → cli-schema-dir-DuZIsF2e.js.map} +1 -1
  11. package/dist/cli.js +124 -36
  12. package/dist/cli.js.map +1 -1
  13. package/dist/{database-preflight-bfnIBnjM.js → database-preflight-CyTCWlfc.js} +2 -2
  14. package/dist/{database-preflight-bfnIBnjM.js.map → database-preflight-CyTCWlfc.js.map} +1 -1
  15. package/dist/{deferred-index-build-CcSDA7wE.js → deferred-index-build-ueYVUBZc.js} +4 -4
  16. package/dist/{deferred-index-build-CcSDA7wE.js.map → deferred-index-build-ueYVUBZc.js.map} +1 -1
  17. package/dist/{ensure-policies-rRmXb5bt.js → ensure-policies-13mHWjBs.js} +7 -7
  18. package/dist/{ensure-policies-rRmXb5bt.js.map → ensure-policies-13mHWjBs.js.map} +1 -1
  19. package/dist/{ensure-tables-Bvm-F2wW.js → ensure-tables-B3Kh2RwT.js} +7 -7
  20. package/dist/{ensure-tables-Bvm-F2wW.js.map → ensure-tables-B3Kh2RwT.js.map} +1 -1
  21. package/dist/{ensure-tables-CC8p_AK3.js → ensure-tables-DM1U9AZK.js} +3 -3
  22. package/dist/{ensure-tables-CC8p_AK3.js.map → ensure-tables-DM1U9AZK.js.map} +1 -1
  23. package/dist/{enum-labels-kept-FlX9SHdf.js → enum-labels-kept-CJDVtX14.js} +2 -2
  24. package/dist/{enum-labels-kept-FlX9SHdf.js.map → enum-labels-kept-CJDVtX14.js.map} +1 -1
  25. package/dist/{generate-drizzle-schema-SJMXxzPI.js → generate-drizzle-schema-B-Mkf8UI.js} +2 -2
  26. package/dist/{generate-drizzle-schema-SJMXxzPI.js.map → generate-drizzle-schema-B-Mkf8UI.js.map} +1 -1
  27. package/dist/{generate-files-tlJ9_lGI.js → generate-files-8MUP8UHC.js} +2 -2
  28. package/dist/{generate-files-tlJ9_lGI.js.map → generate-files-8MUP8UHC.js.map} +1 -1
  29. package/dist/{generate-postgres-ddl-logic-B8huc03c.js → generate-postgres-ddl-logic-CQof4iFH.js} +89 -45
  30. package/dist/generate-postgres-ddl-logic-CQof4iFH.js.map +1 -0
  31. package/dist/index.d.ts +7 -0
  32. package/dist/index.es.js +14 -14
  33. package/dist/{migrate-baseline-DZmekgpD.js → migrate-baseline-DnMlSDup.js} +9 -2
  34. package/dist/{migrate-baseline-DZmekgpD.js.map → migrate-baseline-DnMlSDup.js.map} +1 -1
  35. package/dist/{migrate-policy-stamps-B_acrUQB.js → migrate-policy-stamps-BpHyEFkk.js} +5 -5
  36. package/dist/{migrate-policy-stamps-B_acrUQB.js.map → migrate-policy-stamps-BpHyEFkk.js.map} +1 -1
  37. package/dist/{open-rebase-4kisUF_k.js → open-rebase-B2mAA7UE.js} +175 -38
  38. package/dist/open-rebase-B2mAA7UE.js.map +1 -0
  39. package/dist/{pg-error-utils-BT5NzGFZ.js → pg-error-utils-CpUiBkp-.js} +2 -2
  40. package/dist/{pg-error-utils-BT5NzGFZ.js.map → pg-error-utils-CpUiBkp-.js.map} +1 -1
  41. package/dist/{policy-drift-BVMyqHSa.js → policy-drift-C9xRcbsU.js} +4 -4
  42. package/dist/{policy-drift-BVMyqHSa.js.map → policy-drift-C9xRcbsU.js.map} +1 -1
  43. package/dist/{push-index-adoption-hpHTyXMR.js → push-index-adoption-D-ph6kBc.js} +2 -2
  44. package/dist/{push-index-adoption-hpHTyXMR.js.map → push-index-adoption-D-ph6kBc.js.map} +1 -1
  45. package/dist/{push-index-prebuild-Bty9F7bD.js → push-index-prebuild-DUKtH87s.js} +3 -3
  46. package/dist/{push-index-prebuild-Bty9F7bD.js.map → push-index-prebuild-DUKtH87s.js.map} +1 -1
  47. package/dist/{push-legacy-renames-bB4bM6br.js → push-legacy-renames-wLSsAg80.js} +3 -3
  48. package/dist/{push-legacy-renames-bB4bM6br.js.map → push-legacy-renames-wLSsAg80.js.map} +1 -1
  49. package/dist/{push-policy-plan-BI8U4BOD.js → push-policy-plan-I9RNoP_-.js} +3 -3
  50. package/dist/{push-policy-plan-BI8U4BOD.js.map → push-policy-plan-I9RNoP_-.js.map} +1 -1
  51. package/dist/{request-role-cli-BdRzdE87.js → request-role-cli-D9yWoeSl.js} +8 -8
  52. package/dist/{request-role-cli-BdRzdE87.js.map → request-role-cli-D9yWoeSl.js.map} +1 -1
  53. package/dist/{request-role-migration-C8aq_TO3.js → request-role-migration-DQLiYJ4c.js} +2 -2
  54. package/dist/{request-role-migration-C8aq_TO3.js.map → request-role-migration-DQLiYJ4c.js.map} +1 -1
  55. package/dist/{rls-enforcement-DB5HHj96.js → rls-enforcement-Cwh5SJRx.js} +2 -2
  56. package/dist/{rls-enforcement-DB5HHj96.js.map → rls-enforcement-Cwh5SJRx.js.map} +1 -1
  57. package/dist/schema/doctor-cli.js +5 -5
  58. package/dist/schema/generate-drizzle-schema.js +1 -1
  59. package/dist/schema/generate-postgres-ddl-logic.d.ts +51 -8
  60. package/dist/schema/generate-postgres-ddl.js +1 -1
  61. package/dist/schema/introspect-db.js +1 -1
  62. package/dist/services/cdc/capture-consumers.d.ts +65 -0
  63. package/dist/services/cdc/wal-cdc.d.ts +13 -0
  64. package/dist/services/realtimeService.d.ts +18 -2
  65. package/dist/{websocket-BevXvwfo.js → websocket-CSVNOYHC.js} +3 -3
  66. package/dist/{websocket-BevXvwfo.js.map → websocket-CSVNOYHC.js.map} +1 -1
  67. package/package.json +7 -7
  68. package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +0 -1
  69. package/dist/open-rebase-4kisUF_k.js.map +0 -1
@@ -1,13 +1,13 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { s as ensureAdminPolicyRole } from "./rls-bootstrap-sql-kPX4-MB1.js";
4
- import { v as revokeUserRoleSql } from "./rls-enforcement-DB5HHj96.js";
4
+ import { v as revokeUserRoleSql } from "./rls-enforcement-Cwh5SJRx.js";
5
5
  import { r as quoteSqlLiteral } from "./plan-schema-Hbtjhge3.js";
6
- import { u as planTablePolicies } from "./generate-postgres-ddl-logic-B8huc03c.js";
7
- import { a as assertSafeIdentifier } from "./deferred-index-build-CcSDA7wE.js";
8
- import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, o as isMultiStatementRefusal, r as atomicBatch } from "./boot-ddl-5H2bL_80.js";
9
- import { t as describeDriverError } from "./ensure-tables-Bvm-F2wW.js";
10
- import { a as isGeneratedPolicyName } from "./policy-drift-BVMyqHSa.js";
6
+ import { d as planTablePolicies } from "./generate-postgres-ddl-logic-CQof4iFH.js";
7
+ import { a as assertSafeIdentifier } from "./deferred-index-build-ueYVUBZc.js";
8
+ import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, o as isMultiStatementRefusal, r as atomicBatch } from "./boot-ddl-CSYhSSZD.js";
9
+ import { t as describeDriverError } from "./ensure-tables-B3Kh2RwT.js";
10
+ import { a as isGeneratedPolicyName } from "./policy-drift-C9xRcbsU.js";
11
11
  import { REBASE_ADMIN_ROLE } from "@rebasepro/types";
12
12
  import { ADMIN_REQUEST_POLICY_SUFFIX, toPostgresIdentifier } from "@rebasepro/utils";
13
13
  import { createHash } from "node:crypto";
@@ -696,4 +696,4 @@ async function giveUp(client, table, lastError, lock, result) {
696
696
  //#endregion
697
697
  export { describeRulesDropped, ensureTablePolicies, lockTables, policyStampSql, probeRenderedPolicies, readPolicyStamps, tablesRlsWouldEnable };
698
698
 
699
- //# sourceMappingURL=ensure-policies-rRmXb5bt.js.map
699
+ //# sourceMappingURL=ensure-policies-13mHWjBs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ensure-policies-rRmXb5bt.js","names":[],"sources":["../src/schema/ensure-policies.ts"],"sourcesContent":["/**\n * Applying a bundle's RLS policies to a database at boot, idempotently.\n *\n * ## Why this exists\n *\n * {@link ensureTables} creates the collection *tables* a managed\n * runtime boots against, but a table with row-level security disabled and no\n * policies is not servable: authenticated requests run as the restricted\n * `rebase_user` role, so a read with no `SELECT` policy returns nothing (a\n * public table answered 401) and a write with no `INSERT`/`UPDATE` policy\n * is denied. The policies live in the tables' `rls`; nothing at\n * boot applied them. `rebase db push` does — but it drives Atlas against a\n * local `DATABASE_URL`, and a managed tenant's database is reachable only from\n * inside the cluster, by the runtime that is already connected to it. So the\n * runtime is the only thing that *can* apply them, and this is where it does.\n *\n * ## Why this is safe to run on every boot\n *\n * Every statement is idempotent: `ENABLE ROW LEVEL SECURITY` is only issued for\n * a table the catalogue reports RLS-off (on one that has it, it changes nothing\n * and still queues for an ACCESS EXCLUSIVE lock), and each policy is a `DROP\n * POLICY IF EXISTS` immediately followed by a `CREATE POLICY`, so re-applying\n * asserts exactly the declared state. It adds\n * and replaces; it never drops data. (It does not *reconcile* — a policy a\n * previous push left behind under an old name is not removed here; that stays a\n * `db push` / `db migrate` concern, alongside destructive schema changes.)\n *\n * ## A table whose policies are already the declared ones is left alone\n *\n * Every policy this module writes carries a stamp, `COMMENT ON POLICY … IS\n * 'rebase:<hash>'` (see {@link policyStampSql}). The hash covers the\n * `CREATE POLICY` statement that was rendered *and* the definition Postgres\n * stored for it — command, mode, roles, and the deparsed `USING` / `WITH\n * CHECK` — as read back in the same transaction. A boot recomputes it from the\n * statement it would run now and the definition the catalogue holds now, and\n * re-applies a table only when that differs for any of its policies, a declared\n * policy is missing, a superseded one is still there, or RLS is off.\n *\n * So both halves of \"the declared state\" still win: a rule whose compiled SQL\n * changed (a new rule under the same name, a compiler change) misses on the\n * first half, and a policy someone altered by hand — `ALTER POLICY`, a\n * different role list — misses on the second, and either is re-applied exactly\n * as every boot used to re-apply everything. A boot that changes nothing runs\n * two catalogue reads here, no DDL and takes no table lock. It used to drop and\n * re-create every policy, one ACCESS EXCLUSIVE lock per table: about 1 s at 200\n * tables, and under a `pg_dump` up to the whole retry budget.\n *\n * A policy without a stamp — written by `db push`, by hand, or by a release\n * that predates stamps — counts as different, so the first boot after either\n * re-applies its table once and stamps it. Nothing else reads the comment:\n * drift checks, `doctor`, rls-check and Studio compare names, roles, commands\n * and clauses, never descriptions.\n *\n * Unlike table creation, a failure here is not fatal: RLS stays enabled, so a\n * table whose policies could not be applied fails **closed** (denies) rather\n * than leaking rows. One collection's policy failing (e.g. a rule that\n * references a table a real migration has not created yet) must not crash-loop\n * the whole deployment and take the other collections' working routes down with\n * it. Failures are reported loudly and per-table so the operator can see\n * exactly which collection is not yet servable and why.\n */\nimport { createHash } from \"node:crypto\";\nimport { REBASE_ADMIN_ROLE, type CompiledTable } from \"@rebasepro/types\";\nimport { ADMIN_REQUEST_POLICY_SUFFIX, toPostgresIdentifier } from \"@rebasepro/utils\";\nimport { planTablePolicies, type TablePolicyPlan } from \"./generate-postgres-ddl-logic\";\nimport { isGeneratedPolicyName } from \"../security/policy-drift\";\nimport { describeDriverError, type Queryable } from \"./ensure-tables\";\nimport { assertSafeIdentifier } from \"./plan/diff-plan\";\nimport { quoteSqlLiteral } from \"./generate-postgres-ddl-logic\";\nimport { revokeUserRoleSql } from \"../security/rls-enforcement\";\nimport { ensureAdminPolicyRole } from \"./rls-bootstrap-sql\";\nimport {\n atomicBatch,\n isLockTimeout,\n isMultiStatementRefusal,\n resolveBootLockOptions,\n sleep,\n type BootLockOptions,\n type ResolvedBootLockOptions\n} from \"./boot-ddl\";\n\nexport interface PolicyEnsureResult {\n /** `CREATE POLICY` statements that ran successfully. */\n policiesApplied: number;\n /** Tables that had RLS enabled — including the {@link unchanged} ones, which already had it. */\n tablesSecured: number;\n /**\n * Tables whose policies were already exactly the declared ones, RLS on, by\n * the stamp each policy carries — left alone: no statement, no lock.\n */\n unchanged: number;\n /** Declared tables absent from the database — left to a real migration. */\n skipped: { table: string; reason: string }[];\n /**\n * Tables that have RLS on but did not get every policy. They deny — RLS\n * with no matching policy is deny-all — so they are safe but not servable.\n */\n failures: { table: string; error: string }[];\n /**\n * Tables RLS could not be enabled on, whose DML grant was withdrawn instead.\n *\n * This state had no name, and that was the bug: `ENABLE ROW LEVEL SECURITY`\n * failing was recorded as a `failure` and reported with the same \"it stays\n * locked (denies)\" wording as a failed policy — but the two are opposites.\n * A policy statement failing leaves RLS on and the table denying. `enableRls`\n * failing leaves RLS *off*, and the schema-wide grant to the user role has\n * already been made by `ensureRlsEnforcement`, so the table is readable and\n * writable by every authenticated request with no row filtering at all.\n */\n unsecured: { table: string; error: string; grantWithdrawn: boolean }[];\n /**\n * Generated policies removed because no current rule produces them.\n *\n * A policy's name embeds a hash of the rule's semantics, so editing a rule\n * does not update a policy — it creates a new one and abandons the old.\n * Postgres ORs permissive policies, so the abandoned one keeps granting:\n * a `USING (true)` tightened to an owner check went on admitting everyone,\n * forever, while the deploy logged success.\n *\n * `db push` reconciles this, and cannot reach a managed tenant's in-cluster\n * database — which is the reason this module exists. So boot has to do it.\n */\n orphansDropped: number;\n /**\n * Tables whose policies were not re-applied because another session held\n * the table's lock for every attempt — a long transaction, a report, a\n * dump. Each table's policy statements run in one transaction, so a table\n * here was left exactly as it was: RLS on, its existing policies in force.\n * `rulesChanged` says whether those differ from the declared ones by name\n * (a rule whose policy is missing, or an orphan still granting), in which\n * case the new rules are not in force on this table until a later boot.\n */\n deferred: { table: string; error: string; rulesChanged: boolean }[];\n /**\n * Tables that declare no rule of their own (`rls: \"admin-only\"`, or\n * `\"inherit\"` of an admin-only `defaultRls`) and which still held\n * generated rule policies, all of them dropped: the generated policies, by\n * name, the boot is to warn about.\n *\n * An edited rule supersedes its old policy, and that drop is the point of\n * {@link PolicyEnsureResult.orphansDropped}. A table with no rule at all is\n * something else: what a table looks like when the `defaultRls` it meant\n * to inherit never reached it — a server handed another schema directory,\n * say. Dropping is still right (the declared state wins, and the table is\n * left admin-only rather than open), but it changes who can read the table\n * on every server sharing the database, so it is not done in silence.\n */\n rulesDropped: { table: string; policies: string[] }[];\n}\n\nconst isCreatePolicy = (statement: string): boolean => /^\\s*CREATE POLICY/i.test(statement);\n\n/**\n * The name a `CREATE POLICY` statement's policy is stored under, or undefined\n * for any other statement.\n *\n * Postgres keeps the first 63 bytes of an identifier, and a rule's policy name\n * can be longer (`<table>_<op>_<hash>_<i>` on a 48-byte table is 65). Every\n * name read back from the catalogue is the stored one, so the plan's names are\n * compared in that form too. Compared as written, the policy just created was\n * not among the planned names, matched the generated shape once cut, and the\n * next boot dropped it as an orphan — a restrictive gate included, leaving the\n * grants beside it to answer alone.\n */\nconst createdPolicyName = (statement: string): string | undefined => {\n const match = /^\\s*CREATE POLICY\\s+\"([^\"]+)\"/i.exec(statement);\n return match ? toPostgresIdentifier(match[1]) : undefined;\n};\n\n/** The policy names a plan creates, as Postgres stores them. */\nconst plannedPolicyNames = (plan: TablePolicyPlan): Set<string> => {\n const expected = new Set<string>();\n for (const statement of plan.policyStatements) {\n const name = createdPolicyName(statement);\n if (name) expected.add(name);\n }\n return expected;\n};\n\n/**\n * Generated policies on this table that the current plan does not produce.\n *\n * Scoped hard, because dropping a policy is destructive: only this one table,\n * only names matching the generated `<table>_<op>_<sha1>` shape, and only names\n * absent from the plan. A hand-written policy, or one belonging to another\n * table, is never touched — `isGeneratedPolicyName` is the same predicate `db\n * push` uses to draw that line.\n *\n * Computed from the names read before anything is applied. The plan only ever\n * drops and re-creates its own names, so \"present before, not planned\" is the\n * same set the old read-after-apply found.\n */\nconst orphansOf = (plan: TablePolicyPlan, present: readonly string[]): string[] => {\n const expected = plannedPolicyNames(plan);\n // An admin-request companion not planned is dropped too: it is planned only\n // where the boot made its role safe, and must not outlive that check.\n return present.filter(name => !expected.has(name)\n && (isGeneratedPolicyName(name, plan.table) || ADMIN_REQUEST_POLICY_SUFFIX.test(name)));\n};\n\nconst dropPolicySql = (plan: TablePolicyPlan, name: string): string =>\n `DROP POLICY IF EXISTS \"${name}\" ON \"${plan.schema}\".\"${plan.table}\"`;\n\n/** What every policy stamp starts with. See {@link policyStampSql}. */\nexport const POLICY_STAMP_PREFIX = \"rebase:\";\n\nconst sha256Hex = (text: string): string => createHash(\"sha256\").update(text, \"utf8\").digest(\"hex\");\n\n/** The same digest, computed by Postgres: hex SHA-256 of the text's UTF-8 bytes. */\nconst sha256Sql = (expression: string): string => `encode(sha256(convert_to(${expression}, 'UTF8')), 'hex')`;\n\n/**\n * The definition Postgres holds for the `pg_policy` row aliased `p`, as one\n * text: command, permissive/restrictive, the role OIDs, and the deparsed\n * `USING` and `WITH CHECK` (`-` for an absent clause, so absent and empty\n * differ). Everything `ALTER POLICY` can change, and everything a `CREATE\n * POLICY` sets.\n *\n * Read back with `pg_get_expr`, whose spelling depends on `search_path` (a\n * name on the path prints unqualified). The stamp is written and checked by\n * the same boot connections, so the two agree; a process with a different\n * path would only disagree, and re-apply — what every boot did before stamps.\n */\nconst liveDefinitionSql = (p: string): string =>\n `concat_ws(E'\\\\n', ${p}.polcmd::text, ${p}.polpermissive::text, ${p}.polroles::text, ` +\n `coalesce(pg_get_expr(${p}.polqual, ${p}.polrelid), '-'), ` +\n `coalesce(pg_get_expr(${p}.polwithcheck, ${p}.polrelid), '-'))`;\n\n/** The stamp a policy rendered as `renderedHash` carries when its stored definition hashes to `liveHash`. */\nconst stampOf = (renderedHash: string, liveHash: string): string =>\n `${POLICY_STAMP_PREFIX}${sha256Hex(`${renderedHash}:${liveHash}`)}`;\n\n/** The policies a plan creates, by name, each with the hash of its `CREATE POLICY` statement. */\nconst renderedHashes = (plan: TablePolicyPlan): Map<string, string> => {\n const hashes = new Map<string, string>();\n for (const statement of plan.policyStatements) {\n const name = createdPolicyName(statement);\n if (name) hashes.set(name, sha256Hex(statement.trim()));\n }\n return hashes;\n};\n\n/**\n * One statement that stamps every policy the plan just created on its table:\n * `COMMENT ON POLICY … IS 'rebase:<hash>'`, the hash taken over the rendered\n * statement's hash and the definition Postgres stored — read back here, after\n * the `CREATE`s, in the same transaction. A `DO` block because the stored\n * definition is only known once the policy exists, and a `COMMENT` takes a\n * literal. One line, and it names only this table.\n *\n * `undefined` for a table the plan gives no policies.\n *\n * @param only the names to stamp, when not every policy on the table is known\n * to be what its statement makes — see `stampPoliciesStoredAsRendered`.\n */\nexport function policyStampSql(plan: TablePolicyPlan, only?: ReadonlySet<string>): string | undefined {\n const hashes = new Map([...renderedHashes(plan)].filter(([name]) => !only || only.has(name)));\n if (hashes.size === 0) return undefined;\n const target = `\"${plan.schema}\".\"${plan.table}\"`;\n const values = [...hashes].map(([name, hash]) => `(${quoteSqlLiteral(name)}, '${hash}')`).join(\", \");\n const stamp = `${quoteSqlLiteral(POLICY_STAMP_PREFIX)} || ${sha256Sql(`s.rendered || ':' || ${sha256Sql(liveDefinitionSql(\"p\"))}`)}`;\n return \"DO $rebase_policy_stamp$ DECLARE r record; BEGIN \" +\n `FOR r IN SELECT p.polname AS name, ${stamp} AS stamp FROM pg_policy p ` +\n `JOIN (VALUES ${values}) AS s(name, rendered) ON s.name = p.polname ` +\n `WHERE p.polrelid = ${quoteSqlLiteral(target)}::regclass LOOP ` +\n `EXECUTE 'COMMENT ON POLICY ' || quote_ident(r.name) || ${quoteSqlLiteral(` ON ${target} IS `)} || quote_literal(r.stamp); ` +\n \"END LOOP; END $rebase_policy_stamp$;\";\n}\n\n/** One policy as the catalogue has it. */\ninterface LivePolicy {\n /** Its comment — a stamp, when this module wrote it. */\n stamp: string | null;\n /** Hex SHA-256 of {@link liveDefinitionSql}. */\n live: string;\n}\n\n/**\n * Every policy on every table in the declared schemas — name, stamp and a hash\n * of its stored definition — in one read. It replaced a `pg_policies` query\n * per table, and later the name-only read that preceded stamps.\n */\nasync function readLivePolicies(client: Queryable, schemas: string[]): Promise<Map<string, Map<string, LivePolicy>>> {\n const policies = new Map<string, Map<string, LivePolicy>>();\n if (schemas.length === 0) return policies;\n const inList = schemas.map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`).join(\", \");\n const { rows } = await client.query<{\n schemaname: string; tablename: string; policyname: string; stamp?: string | null; live?: string | null;\n }>(\n `SELECT n.nspname AS schemaname, c.relname AS tablename, p.polname AS policyname,\n obj_description(p.oid, 'pg_policy') AS stamp, ${sha256Sql(liveDefinitionSql(\"p\"))} AS live\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 n.nspname IN (${inList})`\n );\n for (const row of rows) {\n const key = `${row.schemaname}.${row.tablename}`;\n if (!policies.has(key)) policies.set(key, new Map());\n policies.get(key)!.set(row.policyname, { stamp: row.stamp ?? null, live: row.live ?? \"\" });\n }\n return policies;\n}\n\n/**\n * Whether every policy the plan declares is on the table, stamped for exactly\n * the statement the plan would run and exactly the definition it holds now.\n */\nconst policiesAreCurrent = (plan: TablePolicyPlan, present: Map<string, LivePolicy>): boolean => {\n for (const [name, renderedHash] of renderedHashes(plan)) {\n const policy = present.get(name);\n if (!policy || policy.stamp !== stampOf(renderedHash, policy.live)) return false;\n }\n return true;\n};\n\n/**\n * What its stamp says of a declared policy the database has: written by Rebase\n * from the statement the plan renders now and still holding that definition\n * (`current`), stamped once but changed since — the rule's SQL, or the policy\n * by hand (`stale`), or carrying no stamp at all, so nothing tells whether a\n * re-apply changes it (`unstamped`).\n */\nexport type PolicyStampState = \"current\" | \"stale\" | \"unstamped\";\n\n/**\n * Every declared policy the database holds, by `schema.table`, then name, with\n * its {@link PolicyStampState}. The comparison a boot makes to leave a table\n * alone, read for each policy instead of each table.\n *\n * The stored definition is read with `pg_get_expr`, whose spelling depends on\n * `search_path`: call it under the path the stamps were written under (a\n * boot's, `public` unless the URL pins one), or a current stamp reads stale.\n */\nexport async function readPolicyStamps(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n options: { adminRoleAvailable?: boolean } = {}\n): Promise<Map<string, Map<string, PolicyStampState>>> {\n // Stamped from the statement the boot or the push rendered: `TO public`\n // for the server-or-admin policies where the admin switch is not live.\n const plans = planTablePolicies(compiledTables, { adminRoleAvailable: options.adminRoleAvailable });\n const live = await readLivePolicies(client, Array.from(new Set(plans.map(p => p.schema))));\n const states = new Map<string, Map<string, PolicyStampState>>();\n for (const plan of plans) {\n const present = live.get(plan.qualified);\n if (!present) continue;\n const table = new Map<string, PolicyStampState>();\n for (const [name, renderedHash] of renderedHashes(plan)) {\n const policy = present.get(name);\n if (!policy) continue;\n table.set(name, policy.stamp === null || !policy.stamp.startsWith(POLICY_STAMP_PREFIX)\n ? \"unstamped\"\n : policy.stamp === stampOf(renderedHash, policy.live) ? \"current\" : \"stale\");\n }\n states.set(plan.qualified, table);\n }\n return states;\n}\n\n/** The name a probed policy is made under, in a transaction nothing commits. */\nconst PROBE_POLICY = \"rebase_policy_probe\";\n\n/**\n * For each of `policies`, whether the `CREATE POLICY` the plan renders for it\n * stores the definition the database holds now: made under a probe name on\n * the same table, read back, compared with the one there, and rolled back.\n *\n * What a stamp cannot answer. A stamp covers the statement as rendered, so a\n * rule whose text differs from the one that made the policy reads as changed\n * though Postgres would store the same thing: `schema introspect` writes a role\n * rule back as its deparsed SQL, and every such policy was planned as a\n * replacement of itself. A policy `db migrate` created has no stamp at all.\n *\n * One short transaction per policy, which takes the table's lock for as long\n * as it lasts and gives up on it after two seconds. A policy that could not be\n * probed — no statement for it, a lock not granted, a rule that does not\n * parse — is left out of the answer, and the caller keeps what the stamp said.\n * Keyed `schema.table.name`.\n */\nexport async function probeRenderedPolicies(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n policies: readonly { schema: string; table: string; name: string }[],\n options: { searchPath?: string; adminRoleAvailable?: boolean } = {}\n): Promise<Map<string, boolean>> {\n const statements = new Map<string, string>();\n for (const plan of planTablePolicies(compiledTables, { adminRoleAvailable: options.adminRoleAvailable })) {\n for (const statement of plan.policyStatements) {\n const name = createdPolicyName(statement);\n if (name) statements.set(`${plan.schema}.${plan.table}.${name}`, statement.trim());\n }\n }\n const answers = new Map<string, boolean>();\n for (const policy of policies) {\n const key = `${policy.schema}.${policy.table}.${policy.name}`;\n const statement = statements.get(key);\n if (!statement) continue;\n const probe = statement.replace(/^(\\s*CREATE POLICY\\s+)\"[^\"]+\"/i, `$1\"${PROBE_POLICY}\"`);\n const target = `\"${policy.schema.replace(/\"/g, '\"\"')}\".\"${policy.table.replace(/\"/g, '\"\"')}\"`;\n // Literals rather than parameters: a boot's `Queryable` takes none.\n const definition = (name: string): string =>\n `(SELECT ${liveDefinitionSql(\"p\")} FROM pg_policy p ` +\n `WHERE p.polrelid = ${quoteSqlLiteral(target)}::regclass AND p.polname = ${quoteSqlLiteral(name)})`;\n try {\n await client.query(\"BEGIN\");\n await client.query(\"SET LOCAL lock_timeout = '2s'\");\n if (options.searchPath) await client.query(`SET LOCAL search_path TO ${options.searchPath}`);\n await client.query(probe);\n const { rows } = await client.query<{ same: boolean | null }>(\n `SELECT ${definition(PROBE_POLICY)} IS NOT DISTINCT FROM ${definition(policy.name)} AS same`\n );\n if (typeof rows[0]?.same === \"boolean\") answers.set(key, rows[0].same);\n } catch {\n // Not probed; see above.\n } finally {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n }\n }\n return answers;\n}\n\n/**\n * Every declared schema's tables, and whether each has row-level security on.\n *\n * One catalogue read for the whole step. It replaced a full `readExistingSchema`\n * — eight catalogue queries and a row probe of every table, of which only the\n * table names were used — and it carries the one fact that lets a boot leave an\n * already-locked table alone: `relrowsecurity`.\n *\n * Presence is still decided by `information_schema.columns`, as it was: the\n * same relations (views included, which have no RLS and are closed by revoking,\n * exactly as before) and the same privilege filter.\n */\nasync function readTableSecurity(client: Queryable, schemas: string[]): Promise<Map<string, { rls: boolean }>> {\n const tables = new Map<string, { rls: boolean }>();\n if (schemas.length === 0) return tables;\n const inList = schemas.map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`).join(\", \");\n const { rows } = await client.query<{ table_schema: string; table_name: string; rls: boolean | null }>(\n `SELECT t.table_schema, t.table_name, c.relrowsecurity AS rls\n FROM (SELECT DISTINCT table_schema, table_name FROM information_schema.columns\n WHERE table_schema IN (${inList})) t\n JOIN pg_namespace n ON n.nspname = t.table_schema\n JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = t.table_name`\n );\n for (const row of rows) tables.set(`${row.table_schema}.${row.table_name}`, { rls: row.rls === true });\n return tables;\n}\n\n/**\n * Whether the catalogue says RLS is on for one table, read fresh. `false` when\n * it cannot be read, which sends the caller down the fail-closed path.\n */\nasync function rlsIsOn(client: Queryable, plan: TablePolicyPlan): Promise<boolean> {\n try {\n const { rows } = await client.query<{ rls: boolean }>(\n `SELECT c.relrowsecurity AS rls FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ${quoteSqlLiteral(plan.schema)} AND c.relname = ${quoteSqlLiteral(plan.table)}`\n );\n return rows[0]?.rls === true;\n } catch {\n return false;\n }\n}\n\n/** What one table's `ENABLE ROW LEVEL SECURITY` came to. */\ntype TableLock =\n | { locked: true }\n | { locked: false; error: string; grantWithdrawn: boolean };\n\n/**\n * Switch RLS on for one table, or — when Postgres refuses — take the user\n * role's privileges on it back, so the table is unreachable rather than\n * unprotected.\n *\n * A table the catalogue already reports RLS-on is left alone. `ENABLE` on it\n * changes nothing, and it is not free: it queues for an `ACCESS EXCLUSIVE` lock,\n * so a boot that met a long reader held every live query on that table behind\n * it — and when the wait ended in a timeout, the catch below revoked the user\n * role's privileges on a table that had been protected all along. Every\n * replica shares the grants, so one boot during a `pg_dump` closed the\n * collection for the whole deployment until the next clean boot.\n */\nasync function lockTable(\n client: Queryable,\n plan: TablePolicyPlan,\n rlsOn: boolean,\n run: (sql: string) => Promise<unknown> = sql => client.query(sql)\n): Promise<TableLock> {\n if (rlsOn) return { locked: true };\n try {\n await run(plan.enableRls);\n return { locked: true };\n } catch (err) {\n // The database's own answer, not the ORM's wrapper — see\n // `describeDriverError`. This is the most consequential message in\n // the file: it is what the operator reads about a table that is now\n // denying every request, and `Failed query: <the statement>` told\n // them nothing they did not already have.\n const error = describeDriverError(err);\n // A failed statement says nothing about the state it meant to reach: a\n // lock or statement timeout, a cancelled query, a peer that enabled it\n // first. Ask the catalogue. Only a table that really is RLS-off is\n // revoked — that safety is unchanged; a read that fails counts as off.\n if (await rlsIsOn(client, plan)) return { locked: true };\n // Take the privilege back rather than serve an unprotected table.\n // This is the fail-closed step the old code assumed it already had:\n // per-table, so one collection cannot take the rest of the\n // deployment down, but leaving nothing readable without RLS.\n //\n // Quoted, like every other statement here: unquoted, Postgres folds\n // the name to lower case, so a mixed-case adopted table (`\"User\"`)\n // was revoked as `public.user` — which fails, and a table that could\n // have been closed refused the boot instead.\n return withdrawGrant(client, plan, error);\n }\n}\n\n/**\n * Take the user role's privileges on a table back, so an RLS-off table is\n * unreachable rather than unprotected. `REVOKE` waits for no table lock a\n * reader holds, so it runs as a plain statement.\n */\nasync function withdrawGrant(client: Queryable, plan: TablePolicyPlan, error: string): Promise<TableLock> {\n try {\n await client.query(revokeUserRoleSql(plan.schema, plan.table));\n return { locked: false, error, grantWithdrawn: true };\n } catch {\n // Reported with `grantWithdrawn: false`, which the caller escalates.\n // There is nothing else this can do to make the table safe.\n return { locked: false, error, grantWithdrawn: false };\n }\n}\n\nexport interface TableLockResult {\n /** Tables RLS is now on for. */\n locked: number;\n /** Tables it could not be switched on for. See {@link PolicyEnsureResult.unsecured}. */\n unsecured: PolicyEnsureResult[\"unsecured\"];\n}\n\n/**\n * Switch RLS on for every table the tables declare — each collection's\n * and each junction's — and do nothing else.\n *\n * The first thing `rebase db push` does once Atlas has committed. Atlas cannot\n * carry `ENABLE ROW LEVEL SECURITY` (its free tier neither plans nor reads it),\n * so a table it creates arrives with RLS off — while the user role already\n * holds DML on it through the schema's default privileges. Everything push runs\n * after Atlas can refuse: the vector, search and trigger DDL, the policies\n * themselves. Locking first means none of those failures can leave a table\n * open: RLS with no policy denies, which is a state a failed push may leave.\n *\n * A declared table that is not in the database is skipped — nothing can reach\n * a table that does not exist, and the step that creates it locks it.\n */\nexport async function lockTables(\n client: Queryable,\n compiledTables: readonly CompiledTable[]\n): Promise<TableLockResult> {\n const result: TableLockResult = { locked: 0, unsecured: [] };\n for (const { plan, rls } of await declaredTablesPresent(client, compiledTables)) {\n const lock = await lockTable(client, plan, rls);\n if (lock.locked) {\n result.locked++;\n } else {\n result.unsecured.push({ table: plan.qualified, error: lock.error, grantWithdrawn: lock.grantWithdrawn });\n }\n }\n return result;\n}\n\n/**\n * The declared tables {@link lockTables} would switch row-level\n * security on for: those in the database with it off. What `db push\n * --dry-run` lists, read the way the push's lock step reads it.\n */\nexport async function tablesRlsWouldEnable(client: Queryable, compiledTables: readonly CompiledTable[]): Promise<string[]> {\n return (await declaredTablesPresent(client, compiledTables)).filter(table => !table.rls).map(table => table.plan.qualified);\n}\n\n/** Each declared table the database has, with whether its RLS is on. */\nasync function declaredTablesPresent(\n client: Queryable,\n compiledTables: readonly CompiledTable[]\n): Promise<{ plan: TablePolicyPlan; rls: boolean }[]> {\n const plans = planTablePolicies(compiledTables);\n if (plans.length === 0) return [];\n const tables = await readTableSecurity(client, Array.from(new Set(plans.map(p => p.schema))));\n return plans.flatMap(plan => {\n const table = tables.get(plan.qualified);\n return table ? [{ plan, rls: table.rls }] : [];\n });\n}\n\n/** One declared table that exists, and what the catalogue said about it. */\ninterface TableWork {\n plan: TablePolicyPlan;\n rlsOn: boolean;\n orphans: string[];\n /** Whether the policy names on the table differ from the plan's. */\n rulesChanged: boolean;\n /** Whether the plan holds no generated rule of its own, so the orphans are every rule the table had. */\n declaresNoRule: boolean;\n}\n\ntype AtomicOutcome =\n | { kind: \"applied\" }\n | { kind: \"lock-timeout\"; error: string }\n | { kind: \"unsupported\" }\n | { kind: \"failed\"; error: string };\n\n/**\n * Bring the declared collections' RLS policies up to date. Returns what it did.\n *\n * Only tables that already exist are touched: the boot-time table creator runs\n * first, so anything still missing is a table this additive path did not\n * create (it creates junctions too) — one a failed boot DDL left out, or a\n * project whose schema a migration owns. Enabling RLS on a\n * non-existent table would error, so those are recorded as skipped, not failed.\n *\n * ## One transaction per table\n *\n * Each table's statements — `ENABLE` when RLS is off, every `DROP POLICY IF\n * EXISTS` / `CREATE POLICY` pair, the orphan drops — go to Postgres as one\n * string, which it runs as one transaction (see `boot-ddl`). Before, each was\n * its own autocommit: at 240 tables, 4,080 commits and 4,080 ACCESS EXCLUSIVE\n * lock acquisitions per boot, 6–22 s on a disk that really flushes. And between\n * a policy's DROP and its CREATE, every other replica evaluated the table with\n * that policy missing — a user's continuous reads of their own row came back\n * empty once per boot (measured, Postgres 18). Now a concurrent request sees the\n * old policies or the new ones, never neither.\n *\n * If the transaction fails for any reason but a lock timeout, the table is\n * applied again one statement at a time — so a rule that cannot be created (a\n * function a migration has not added yet) leaves the table in a deny-leaning\n * partial state rather than rolling back to the old, possibly looser,\n * policies. Deny-leaning holds for restrictive rules too: they are applied\n * first, and one that cannot be created is replaced by a restrictive policy\n * that passes nothing, never left out from under the grants.\n *\n * ## Lock budget\n *\n * The transaction runs under `lock_timeout` (`boot-ddl`), so a table that a\n * long transaction, a report or a dump is holding costs live traffic one\n * second, not the statement timeout. A contended table is retried after the\n * others, with backoff, within a retry budget for the whole step; one still\n * held after that is reported in `deferred` — its transaction rolled back, so\n * it is exactly as it was before this boot — or, if RLS was off on it, closed\n * by revoking the user role's grant, like every table RLS cannot be enabled on.\n */\nexport async function ensureTablePolicies(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n log?: (message: string) => void,\n options: BootLockOptions & {\n /**\n * Whether this server's admin switch is live (`settleAdminSwitch`).\n * `false` writes the server-or-admin policies `TO public` and creates\n * no role: written `TO rebase_admin` while admin requests run as the\n * request role, they would refuse every admin caller. Left out, they\n * go `TO rebase_admin` wherever that role exists or can be made.\n */\n adminRoleAvailable?: boolean;\n /**\n * Whether the admin-only policies get their `TO rebase_admin_request\n * USING (true)` companions — see `planTablePolicies`. Only a boot\n * that has made that role safe (`settleAdminRequestGroup`) says so;\n * anywhere else they are not planned, and any in the database are\n * dropped as orphans.\n */\n adminRequestRoleAvailable?: boolean;\n } = {}\n): Promise<PolicyEnsureResult> {\n const result: PolicyEnsureResult = {\n policiesApplied: 0, tablesSecured: 0, unchanged: 0, skipped: [], failures: [], unsecured: [],\n orphansDropped: 0, deferred: [], rulesDropped: []\n };\n\n let plans = planTablePolicies(compiledTables, { adminRequestRoleAvailable: options.adminRequestRoleAvailable });\n if (plans.length === 0) return result;\n // The server-or-admin policies are written `TO rebase_admin`\n // (`rls.adminPolicies: \"adminRole\"`), and CREATE POLICY refuses a role that\n // does not exist; nothing guarantees this step runs after the one that\n // makes it. Where it cannot be made — a connection without CREATEROLE, a\n // role nobody pre-created — those policies are written `TO public`, as they\n // were before, rather than dropped and left uncreatable: admin requests then\n // keep running as the request role (`settleAdminRequestRoles`), which is\n // what `TO public` serves. A boot whose admin switch is not live says so\n // (`adminRoleAvailable: false`), and gets the same: an existing\n // `rebase_admin` — another project's, a privileged push's — is not enough.\n if (options.adminRoleAvailable === false) {\n plans = planTablePolicies(compiledTables, { adminRoleAvailable: false });\n } else if (plans.some(plan => plan.policies.some(policy => policy.adminTarget))) {\n const run = async (text: string) => (await client.query<Record<string, unknown>>(text)).rows;\n const available = await ensureAdminPolicyRole(run).then(() => true, (err: unknown) => {\n log?.(`the \"${REBASE_ADMIN_ROLE}\" role does not exist and could not be created (${describeDriverError(err)}); ` +\n \"the server-or-admin policies stay TO public, and signed-in users' owner-scoped reads keep scanning\");\n return false;\n });\n if (!available) plans = planTablePolicies(compiledTables, { adminRoleAvailable: false });\n }\n const lock = resolveBootLockOptions(options);\n\n const schemas = Array.from(new Set(plans.map(p => p.schema)));\n const tables = await readTableSecurity(client, schemas);\n const livePolicies = await readLivePolicies(client, schemas);\n\n const work: TableWork[] = [];\n for (const plan of plans) {\n const table = tables.get(plan.qualified);\n if (!table) {\n result.skipped.push({\n table: plan.qualified,\n reason: \"table is not present in the database; create it with `rebase db push` / `rebase db migrate`\"\n });\n continue;\n }\n const live = livePolicies.get(plan.qualified) ?? new Map<string, LivePolicy>();\n const present = [...live.keys()];\n const orphans = orphansOf(plan, present);\n // Already exactly what the plan would leave: nothing to run, no lock to take.\n if (table.rls && orphans.length === 0 && policiesAreCurrent(plan, live)) {\n result.tablesSecured++;\n result.unchanged++;\n continue;\n }\n const presentSet = new Set(present);\n const rulesChanged = orphans.length > 0 || [...plannedPolicyNames(plan)].some(name => !presentSet.has(name));\n const declaresNoRule = ![...plannedPolicyNames(plan)].some(name => isGeneratedPolicyName(name, plan.table));\n work.push({ plan, rlsOn: table.rls, orphans, rulesChanged, declaresNoRule });\n }\n if (result.unchanged > 0) {\n log?.(`${result.unchanged} table(s) already have exactly the declared policies; left as they are`);\n }\n\n // Until the handle refuses a multi-statement string (an extended-protocol\n // driver), after which every table goes one statement at a time.\n let atomic = true;\n let retryBudget = lock.retryBudgetMs;\n let queue = work;\n let lastError = new Map<TableWork, string>();\n\n for (let attempt = 1; queue.length > 0; attempt++) {\n if (attempt > 1) {\n if (attempt > lock.attempts || retryBudget <= 0) break;\n await sleep(lock.backoffMs(attempt - 1));\n }\n const contended: TableWork[] = [];\n const errors = new Map<TableWork, string>();\n for (const table of queue) {\n if (attempt > 1 && retryBudget <= 0) {\n contended.push(table);\n errors.set(table, lastError.get(table) ?? \"\");\n continue;\n }\n if (atomic) {\n const outcome = await applyAtomically(client, table, lock);\n if (outcome.kind === \"applied\") {\n record(result, table, log);\n continue;\n }\n if (outcome.kind === \"lock-timeout\") {\n if (attempt > 1) retryBudget -= lock.lockTimeoutMs;\n contended.push(table);\n errors.set(table, outcome.error);\n continue;\n }\n if (outcome.kind === \"unsupported\") {\n atomic = false;\n } else {\n log?.(`${table.plan.qualified}: applying its policies in one transaction failed ` +\n `(${outcome.error}); applying them one statement at a time`);\n }\n }\n await applyEachStatement(client, table, result, log, atomic ? lock : undefined);\n }\n queue = contended;\n lastError = errors;\n }\n\n // Still contended after every attempt the budget allowed.\n for (const table of queue) {\n await giveUp(client, table, lastError.get(table) ?? \"\", lock, result);\n }\n\n return result;\n}\n\n/**\n * The table's statements, in the order they must run — the stamp last, so it\n * reads back the policies this same transaction created.\n */\nconst statementsOf = (table: TableWork): string[] => {\n const stamp = policyStampSql(table.plan);\n return [\n ...(table.rlsOn ? [] : [table.plan.enableRls]),\n ...table.plan.policyStatements,\n ...table.orphans.map(name => dropPolicySql(table.plan, name)),\n ...(stamp ? [stamp] : [])\n ];\n};\n\nasync function applyAtomically(\n client: Queryable,\n table: TableWork,\n lock: ResolvedBootLockOptions\n): Promise<AtomicOutcome> {\n const statements = statementsOf(table);\n if (statements.length === 0) return { kind: \"applied\" };\n try {\n await client.query(atomicBatch(statements, lock.lockTimeoutMs));\n return { kind: \"applied\" };\n } catch (err) {\n if (isLockTimeout(err)) return { kind: \"lock-timeout\", error: describeDriverError(err) };\n if (isMultiStatementRefusal(err)) return { kind: \"unsupported\" };\n return { kind: \"failed\", error: describeDriverError(err) };\n }\n}\n\n/**\n * The warning a boot gives for one entry of {@link PolicyEnsureResult.rulesDropped}:\n * each policy, what it means for the table, and the likely cause.\n */\nexport function describeRulesDropped(dropped: { table: string; policies: string[] }): string {\n return `🔐 [rls] \"${dropped.table}\" is \\`rls: \"admin-only\"\\` now, so the policies its rules had made were dropped: ` +\n `${dropped.policies.join(\", \")}. Only administrators reach its rows now, on every server sharing this database. ` +\n \"If the table says `rls: \\\"inherit\\\"`, the `defaultRls` it inherits is \\\"admin-only\\\": check what \" +\n \"backend/schema/index.ts exports as `defaultRls`, and that this server was handed that schema directory. \" +\n \"If the rules were removed on purpose, this is that change.\";\n}\n\n/** The orphans just dropped, when they were every rule the table had. See {@link PolicyEnsureResult.rulesDropped}. */\nfunction recordRulesDropped(result: PolicyEnsureResult, table: TableWork): void {\n if (table.declaresNoRule && table.orphans.length > 0) {\n result.rulesDropped.push({ table: table.plan.qualified, policies: [...table.orphans].sort() });\n }\n}\n\nfunction record(result: PolicyEnsureResult, table: TableWork, log?: (message: string) => void): void {\n const created = table.plan.policyStatements.filter(isCreatePolicy).length;\n result.tablesSecured++;\n result.policiesApplied += created;\n result.orphansDropped += table.orphans.length;\n recordRulesDropped(result, table);\n log?.(`${table.plan.qualified}: RLS enabled, ${created} policy(ies) applied` +\n (table.orphans.length > 0 ? `, ${table.orphans.length} orphan(s) dropped` : \"\"));\n}\n\n/**\n * The table applied one statement at a time — the path every table took before\n * the per-table transaction, kept as its fallback so a failure ends exactly\n * where it always did.\n *\n * Each statement still carries the lock budget when the handle can take it.\n */\nasync function applyEachStatement(\n client: Queryable,\n table: TableWork,\n result: PolicyEnsureResult,\n log: ((message: string) => void) | undefined,\n lock: ResolvedBootLockOptions | undefined\n): Promise<void> {\n const { plan } = table;\n const run = (sql: string) => client.query(lock ? atomicBatch([sql], lock.lockTimeoutMs) : sql);\n\n // Enabling RLS is its own step, because its failure is the opposite of\n // every other failure here. Once RLS is on, anything that goes wrong\n // afterwards leaves the table denying; while it is off, the grant made\n // earlier in boot leaves the table wide open. Sharing one `try` meant\n // the dangerous case was reported in the safe case's words.\n const locked = await lockTable(client, plan, table.rlsOn, run);\n if (!locked.locked) {\n result.unsecured.push({ table: plan.qualified, error: locked.error, grantWithdrawn: locked.grantWithdrawn });\n return;\n }\n result.tablesSecured++;\n\n // The restrictive gates go in before any grant, and a gate that cannot be\n // created is replaced by one that passes nothing. A restrictive policy is\n // ANDed over the permissive ones, so a missing gate is not a denial: the\n // grants made beside it would answer alone, and a tenancy or admin-write\n // gate that failed to apply let every grant through it.\n let created = 0;\n let gateError: string | undefined;\n for (const policy of plan.policies.filter(p => p.restrictive)) {\n try {\n for (const statement of policy.statements) await run(statement);\n result.policiesApplied++;\n created++;\n } catch (err) {\n gateError ??= `${policy.name}: ${describeDriverError(err)}`;\n try {\n for (const statement of policy.denying ?? []) await run(statement);\n } catch (denyErr) {\n // Neither the gate nor its stand-in is in place, so the grants\n // already on the table answer alone: closed the way a table RLS\n // cannot be enabled on is.\n result.tablesSecured--;\n const closed = await withdrawGrant(client, plan,\n `restrictive policy ${gateError}; its denying stand-in failed too: ${describeDriverError(denyErr)}`);\n if (!closed.locked) {\n result.unsecured.push({ table: plan.qualified, error: closed.error, grantWithdrawn: closed.grantWithdrawn });\n }\n return;\n }\n }\n }\n\n try {\n for (const policy of plan.policies.filter(p => !p.restrictive)) {\n for (const statement of policy.statements) await run(statement);\n result.policiesApplied++;\n created++;\n }\n if (gateError) throw new Error(`restrictive policy ${gateError}; it denies every row until it can be created`);\n for (const name of table.orphans) {\n await run(dropPolicySql(plan, name));\n result.orphansDropped++;\n }\n recordRulesDropped(result, table);\n log?.(`${plan.qualified}: RLS enabled, ${created} policy(ies) applied` +\n (table.orphans.length > 0 ? `, ${table.orphans.length} orphan(s) dropped` : \"\"));\n } catch (err) {\n result.failures.push({\n table: plan.qualified,\n error: describeDriverError(err)\n });\n return;\n }\n\n // Only once every policy is in. A stamp that cannot be written costs the\n // next boot a re-apply of this table — what every boot did before stamps —\n // so it is reported, not failed.\n const stamp = policyStampSql(plan);\n if (!stamp) return;\n try {\n await run(stamp);\n } catch (err) {\n log?.(`${plan.qualified}: policies applied, but not stamped (${describeDriverError(err)}); ` +\n \"the next boot applies them again\");\n }\n}\n\n/**\n * A table whose lock was held for every attempt. Its transaction rolled back\n * each time, so it is exactly as it was before this boot.\n *\n * With RLS on, that is a safe state to leave it in — reported, not failed. With\n * RLS off it is an open table over the schema-wide grant, so it is closed the\n * way any table RLS cannot be enabled on is: the catalogue is asked once more,\n * and only a table that really is RLS-off has the user role's grant withdrawn.\n */\nasync function giveUp(\n client: Queryable,\n table: TableWork,\n lastError: string,\n lock: ResolvedBootLockOptions,\n result: PolicyEnsureResult\n): Promise<void> {\n const { plan } = table;\n const error =\n `another session held the table's lock for every attempt (lock_timeout ${lock.lockTimeoutMs} ms` +\n `${lastError ? `: ${lastError.split(\"\\n\")[0]}` : \"\"}) — a long transaction, a report or a dump`;\n if (table.rlsOn || await rlsIsOn(client, plan)) {\n result.tablesSecured++;\n result.deferred.push({ table: plan.qualified, error, rulesChanged: table.rulesChanged });\n return;\n }\n const closed = await withdrawGrant(client, plan, error);\n if (!closed.locked) {\n result.unsecured.push({ table: plan.qualified, error: closed.error, grantWithdrawn: closed.grantWithdrawn });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsJA,IAAM,kBAAkB,cAA+B,qBAAqB,KAAK,SAAS;;;;;;;;;;;;;AAc1F,IAAM,qBAAqB,cAA0C;CACjE,MAAM,QAAQ,iCAAiC,KAAK,SAAS;CAC7D,OAAO,QAAQ,qBAAqB,MAAM,EAAE,IAAI,KAAA;AACpD;;AAGA,IAAM,sBAAsB,SAAuC;CAC/D,MAAM,2BAAW,IAAI,IAAY;CACjC,KAAK,MAAM,aAAa,KAAK,kBAAkB;EAC3C,MAAM,OAAO,kBAAkB,SAAS;EACxC,IAAI,MAAM,SAAS,IAAI,IAAI;CAC/B;CACA,OAAO;AACX;;;;;;;;;;;;;;AAeA,IAAM,aAAa,MAAuB,YAAyC;CAC/E,MAAM,WAAW,mBAAmB,IAAI;CAGxC,OAAO,QAAQ,QAAO,SAAQ,CAAC,SAAS,IAAI,IAAI,MACxC,sBAAsB,MAAM,KAAK,KAAK,KAAK,4BAA4B,KAAK,IAAI,EAAE;AAC9F;AAEA,IAAM,iBAAiB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CAAC;EACD;CACJ;CAKA,MAAM,QAAQ,eAAe,IAAI;CACjC,IAAI,CAAC,OAAO;CACZ,IAAI;EACA,MAAM,IAAI,KAAK;CACnB,SAAS,KAAK;EACV,MAAM,GAAG,KAAK,UAAU,uCAAuC,oBAAoB,GAAG,EAAE,oCAClD;CAC1C;AACJ;;;;;;;;;;AAWA,eAAe,OACX,QACA,OACA,WACA,MACA,QACa;CACb,MAAM,EAAE,SAAS;CACjB,MAAM,QACF,yEAAyE,KAAK,cAAc,KACzF,YAAY,KAAK,UAAU,MAAM,IAAI,CAAC,CAAC,OAAO,GAAG;CACxD,IAAI,MAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI,GAAG;EAC5C,OAAO;EACP,OAAO,SAAS,KAAK;GAAE,OAAO,KAAK;GAAW;GAAO,cAAc,MAAM;EAAa,CAAC;EACvF;CACJ;CACA,MAAM,SAAS,MAAM,cAAc,QAAQ,MAAM,KAAK;CACtD,IAAI,CAAC,OAAO,QACR,OAAO,UAAU,KAAK;EAAE,OAAO,KAAK;EAAW,OAAO,OAAO;EAAO,gBAAgB,OAAO;CAAe,CAAC;AAEnH"}
1
+ {"version":3,"file":"ensure-policies-13mHWjBs.js","names":[],"sources":["../src/schema/ensure-policies.ts"],"sourcesContent":["/**\n * Applying a bundle's RLS policies to a database at boot, idempotently.\n *\n * ## Why this exists\n *\n * {@link ensureTables} creates the collection *tables* a managed\n * runtime boots against, but a table with row-level security disabled and no\n * policies is not servable: authenticated requests run as the restricted\n * `rebase_user` role, so a read with no `SELECT` policy returns nothing (a\n * public table answered 401) and a write with no `INSERT`/`UPDATE` policy\n * is denied. The policies live in the tables' `rls`; nothing at\n * boot applied them. `rebase db push` does — but it drives Atlas against a\n * local `DATABASE_URL`, and a managed tenant's database is reachable only from\n * inside the cluster, by the runtime that is already connected to it. So the\n * runtime is the only thing that *can* apply them, and this is where it does.\n *\n * ## Why this is safe to run on every boot\n *\n * Every statement is idempotent: `ENABLE ROW LEVEL SECURITY` is only issued for\n * a table the catalogue reports RLS-off (on one that has it, it changes nothing\n * and still queues for an ACCESS EXCLUSIVE lock), and each policy is a `DROP\n * POLICY IF EXISTS` immediately followed by a `CREATE POLICY`, so re-applying\n * asserts exactly the declared state. It adds\n * and replaces; it never drops data. (It does not *reconcile* — a policy a\n * previous push left behind under an old name is not removed here; that stays a\n * `db push` / `db migrate` concern, alongside destructive schema changes.)\n *\n * ## A table whose policies are already the declared ones is left alone\n *\n * Every policy this module writes carries a stamp, `COMMENT ON POLICY … IS\n * 'rebase:<hash>'` (see {@link policyStampSql}). The hash covers the\n * `CREATE POLICY` statement that was rendered *and* the definition Postgres\n * stored for it — command, mode, roles, and the deparsed `USING` / `WITH\n * CHECK` — as read back in the same transaction. A boot recomputes it from the\n * statement it would run now and the definition the catalogue holds now, and\n * re-applies a table only when that differs for any of its policies, a declared\n * policy is missing, a superseded one is still there, or RLS is off.\n *\n * So both halves of \"the declared state\" still win: a rule whose compiled SQL\n * changed (a new rule under the same name, a compiler change) misses on the\n * first half, and a policy someone altered by hand — `ALTER POLICY`, a\n * different role list — misses on the second, and either is re-applied exactly\n * as every boot used to re-apply everything. A boot that changes nothing runs\n * two catalogue reads here, no DDL and takes no table lock. It used to drop and\n * re-create every policy, one ACCESS EXCLUSIVE lock per table: about 1 s at 200\n * tables, and under a `pg_dump` up to the whole retry budget.\n *\n * A policy without a stamp — written by `db push`, by hand, or by a release\n * that predates stamps — counts as different, so the first boot after either\n * re-applies its table once and stamps it. Nothing else reads the comment:\n * drift checks, `doctor`, rls-check and Studio compare names, roles, commands\n * and clauses, never descriptions.\n *\n * Unlike table creation, a failure here is not fatal: RLS stays enabled, so a\n * table whose policies could not be applied fails **closed** (denies) rather\n * than leaking rows. One collection's policy failing (e.g. a rule that\n * references a table a real migration has not created yet) must not crash-loop\n * the whole deployment and take the other collections' working routes down with\n * it. Failures are reported loudly and per-table so the operator can see\n * exactly which collection is not yet servable and why.\n */\nimport { createHash } from \"node:crypto\";\nimport { REBASE_ADMIN_ROLE, type CompiledTable } from \"@rebasepro/types\";\nimport { ADMIN_REQUEST_POLICY_SUFFIX, toPostgresIdentifier } from \"@rebasepro/utils\";\nimport { planTablePolicies, type TablePolicyPlan } from \"./generate-postgres-ddl-logic\";\nimport { isGeneratedPolicyName } from \"../security/policy-drift\";\nimport { describeDriverError, type Queryable } from \"./ensure-tables\";\nimport { assertSafeIdentifier } from \"./plan/diff-plan\";\nimport { quoteSqlLiteral } from \"./generate-postgres-ddl-logic\";\nimport { revokeUserRoleSql } from \"../security/rls-enforcement\";\nimport { ensureAdminPolicyRole } from \"./rls-bootstrap-sql\";\nimport {\n atomicBatch,\n isLockTimeout,\n isMultiStatementRefusal,\n resolveBootLockOptions,\n sleep,\n type BootLockOptions,\n type ResolvedBootLockOptions\n} from \"./boot-ddl\";\n\nexport interface PolicyEnsureResult {\n /** `CREATE POLICY` statements that ran successfully. */\n policiesApplied: number;\n /** Tables that had RLS enabled — including the {@link unchanged} ones, which already had it. */\n tablesSecured: number;\n /**\n * Tables whose policies were already exactly the declared ones, RLS on, by\n * the stamp each policy carries — left alone: no statement, no lock.\n */\n unchanged: number;\n /** Declared tables absent from the database — left to a real migration. */\n skipped: { table: string; reason: string }[];\n /**\n * Tables that have RLS on but did not get every policy. They deny — RLS\n * with no matching policy is deny-all — so they are safe but not servable.\n */\n failures: { table: string; error: string }[];\n /**\n * Tables RLS could not be enabled on, whose DML grant was withdrawn instead.\n *\n * This state had no name, and that was the bug: `ENABLE ROW LEVEL SECURITY`\n * failing was recorded as a `failure` and reported with the same \"it stays\n * locked (denies)\" wording as a failed policy — but the two are opposites.\n * A policy statement failing leaves RLS on and the table denying. `enableRls`\n * failing leaves RLS *off*, and the schema-wide grant to the user role has\n * already been made by `ensureRlsEnforcement`, so the table is readable and\n * writable by every authenticated request with no row filtering at all.\n */\n unsecured: { table: string; error: string; grantWithdrawn: boolean }[];\n /**\n * Generated policies removed because no current rule produces them.\n *\n * A policy's name embeds a hash of the rule's semantics, so editing a rule\n * does not update a policy — it creates a new one and abandons the old.\n * Postgres ORs permissive policies, so the abandoned one keeps granting:\n * a `USING (true)` tightened to an owner check went on admitting everyone,\n * forever, while the deploy logged success.\n *\n * `db push` reconciles this, and cannot reach a managed tenant's in-cluster\n * database — which is the reason this module exists. So boot has to do it.\n */\n orphansDropped: number;\n /**\n * Tables whose policies were not re-applied because another session held\n * the table's lock for every attempt — a long transaction, a report, a\n * dump. Each table's policy statements run in one transaction, so a table\n * here was left exactly as it was: RLS on, its existing policies in force.\n * `rulesChanged` says whether those differ from the declared ones by name\n * (a rule whose policy is missing, or an orphan still granting), in which\n * case the new rules are not in force on this table until a later boot.\n */\n deferred: { table: string; error: string; rulesChanged: boolean }[];\n /**\n * Tables that declare no rule of their own (`rls: \"admin-only\"`, or\n * `\"inherit\"` of an admin-only `defaultRls`) and which still held\n * generated rule policies, all of them dropped: the generated policies, by\n * name, the boot is to warn about.\n *\n * An edited rule supersedes its old policy, and that drop is the point of\n * {@link PolicyEnsureResult.orphansDropped}. A table with no rule at all is\n * something else: what a table looks like when the `defaultRls` it meant\n * to inherit never reached it — a server handed another schema directory,\n * say. Dropping is still right (the declared state wins, and the table is\n * left admin-only rather than open), but it changes who can read the table\n * on every server sharing the database, so it is not done in silence.\n */\n rulesDropped: { table: string; policies: string[] }[];\n}\n\nconst isCreatePolicy = (statement: string): boolean => /^\\s*CREATE POLICY/i.test(statement);\n\n/**\n * The name a `CREATE POLICY` statement's policy is stored under, or undefined\n * for any other statement.\n *\n * Postgres keeps the first 63 bytes of an identifier, and a rule's policy name\n * can be longer (`<table>_<op>_<hash>_<i>` on a 48-byte table is 65). Every\n * name read back from the catalogue is the stored one, so the plan's names are\n * compared in that form too. Compared as written, the policy just created was\n * not among the planned names, matched the generated shape once cut, and the\n * next boot dropped it as an orphan — a restrictive gate included, leaving the\n * grants beside it to answer alone.\n */\nconst createdPolicyName = (statement: string): string | undefined => {\n const match = /^\\s*CREATE POLICY\\s+\"([^\"]+)\"/i.exec(statement);\n return match ? toPostgresIdentifier(match[1]) : undefined;\n};\n\n/** The policy names a plan creates, as Postgres stores them. */\nconst plannedPolicyNames = (plan: TablePolicyPlan): Set<string> => {\n const expected = new Set<string>();\n for (const statement of plan.policyStatements) {\n const name = createdPolicyName(statement);\n if (name) expected.add(name);\n }\n return expected;\n};\n\n/**\n * Generated policies on this table that the current plan does not produce.\n *\n * Scoped hard, because dropping a policy is destructive: only this one table,\n * only names matching the generated `<table>_<op>_<sha1>` shape, and only names\n * absent from the plan. A hand-written policy, or one belonging to another\n * table, is never touched — `isGeneratedPolicyName` is the same predicate `db\n * push` uses to draw that line.\n *\n * Computed from the names read before anything is applied. The plan only ever\n * drops and re-creates its own names, so \"present before, not planned\" is the\n * same set the old read-after-apply found.\n */\nconst orphansOf = (plan: TablePolicyPlan, present: readonly string[]): string[] => {\n const expected = plannedPolicyNames(plan);\n // An admin-request companion not planned is dropped too: it is planned only\n // where the boot made its role safe, and must not outlive that check.\n return present.filter(name => !expected.has(name)\n && (isGeneratedPolicyName(name, plan.table) || ADMIN_REQUEST_POLICY_SUFFIX.test(name)));\n};\n\nconst dropPolicySql = (plan: TablePolicyPlan, name: string): string =>\n `DROP POLICY IF EXISTS \"${name}\" ON \"${plan.schema}\".\"${plan.table}\"`;\n\n/** What every policy stamp starts with. See {@link policyStampSql}. */\nexport const POLICY_STAMP_PREFIX = \"rebase:\";\n\nconst sha256Hex = (text: string): string => createHash(\"sha256\").update(text, \"utf8\").digest(\"hex\");\n\n/** The same digest, computed by Postgres: hex SHA-256 of the text's UTF-8 bytes. */\nconst sha256Sql = (expression: string): string => `encode(sha256(convert_to(${expression}, 'UTF8')), 'hex')`;\n\n/**\n * The definition Postgres holds for the `pg_policy` row aliased `p`, as one\n * text: command, permissive/restrictive, the role OIDs, and the deparsed\n * `USING` and `WITH CHECK` (`-` for an absent clause, so absent and empty\n * differ). Everything `ALTER POLICY` can change, and everything a `CREATE\n * POLICY` sets.\n *\n * Read back with `pg_get_expr`, whose spelling depends on `search_path` (a\n * name on the path prints unqualified). The stamp is written and checked by\n * the same boot connections, so the two agree; a process with a different\n * path would only disagree, and re-apply — what every boot did before stamps.\n */\nconst liveDefinitionSql = (p: string): string =>\n `concat_ws(E'\\\\n', ${p}.polcmd::text, ${p}.polpermissive::text, ${p}.polroles::text, ` +\n `coalesce(pg_get_expr(${p}.polqual, ${p}.polrelid), '-'), ` +\n `coalesce(pg_get_expr(${p}.polwithcheck, ${p}.polrelid), '-'))`;\n\n/** The stamp a policy rendered as `renderedHash` carries when its stored definition hashes to `liveHash`. */\nconst stampOf = (renderedHash: string, liveHash: string): string =>\n `${POLICY_STAMP_PREFIX}${sha256Hex(`${renderedHash}:${liveHash}`)}`;\n\n/** The policies a plan creates, by name, each with the hash of its `CREATE POLICY` statement. */\nconst renderedHashes = (plan: TablePolicyPlan): Map<string, string> => {\n const hashes = new Map<string, string>();\n for (const statement of plan.policyStatements) {\n const name = createdPolicyName(statement);\n if (name) hashes.set(name, sha256Hex(statement.trim()));\n }\n return hashes;\n};\n\n/**\n * One statement that stamps every policy the plan just created on its table:\n * `COMMENT ON POLICY … IS 'rebase:<hash>'`, the hash taken over the rendered\n * statement's hash and the definition Postgres stored — read back here, after\n * the `CREATE`s, in the same transaction. A `DO` block because the stored\n * definition is only known once the policy exists, and a `COMMENT` takes a\n * literal. One line, and it names only this table.\n *\n * `undefined` for a table the plan gives no policies.\n *\n * @param only the names to stamp, when not every policy on the table is known\n * to be what its statement makes — see `stampPoliciesStoredAsRendered`.\n */\nexport function policyStampSql(plan: TablePolicyPlan, only?: ReadonlySet<string>): string | undefined {\n const hashes = new Map([...renderedHashes(plan)].filter(([name]) => !only || only.has(name)));\n if (hashes.size === 0) return undefined;\n const target = `\"${plan.schema}\".\"${plan.table}\"`;\n const values = [...hashes].map(([name, hash]) => `(${quoteSqlLiteral(name)}, '${hash}')`).join(\", \");\n const stamp = `${quoteSqlLiteral(POLICY_STAMP_PREFIX)} || ${sha256Sql(`s.rendered || ':' || ${sha256Sql(liveDefinitionSql(\"p\"))}`)}`;\n return \"DO $rebase_policy_stamp$ DECLARE r record; BEGIN \" +\n `FOR r IN SELECT p.polname AS name, ${stamp} AS stamp FROM pg_policy p ` +\n `JOIN (VALUES ${values}) AS s(name, rendered) ON s.name = p.polname ` +\n `WHERE p.polrelid = ${quoteSqlLiteral(target)}::regclass LOOP ` +\n `EXECUTE 'COMMENT ON POLICY ' || quote_ident(r.name) || ${quoteSqlLiteral(` ON ${target} IS `)} || quote_literal(r.stamp); ` +\n \"END LOOP; END $rebase_policy_stamp$;\";\n}\n\n/** One policy as the catalogue has it. */\ninterface LivePolicy {\n /** Its comment — a stamp, when this module wrote it. */\n stamp: string | null;\n /** Hex SHA-256 of {@link liveDefinitionSql}. */\n live: string;\n}\n\n/**\n * Every policy on every table in the declared schemas — name, stamp and a hash\n * of its stored definition — in one read. It replaced a `pg_policies` query\n * per table, and later the name-only read that preceded stamps.\n */\nasync function readLivePolicies(client: Queryable, schemas: string[]): Promise<Map<string, Map<string, LivePolicy>>> {\n const policies = new Map<string, Map<string, LivePolicy>>();\n if (schemas.length === 0) return policies;\n const inList = schemas.map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`).join(\", \");\n const { rows } = await client.query<{\n schemaname: string; tablename: string; policyname: string; stamp?: string | null; live?: string | null;\n }>(\n `SELECT n.nspname AS schemaname, c.relname AS tablename, p.polname AS policyname,\n obj_description(p.oid, 'pg_policy') AS stamp, ${sha256Sql(liveDefinitionSql(\"p\"))} AS live\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 n.nspname IN (${inList})`\n );\n for (const row of rows) {\n const key = `${row.schemaname}.${row.tablename}`;\n if (!policies.has(key)) policies.set(key, new Map());\n policies.get(key)!.set(row.policyname, { stamp: row.stamp ?? null, live: row.live ?? \"\" });\n }\n return policies;\n}\n\n/**\n * Whether every policy the plan declares is on the table, stamped for exactly\n * the statement the plan would run and exactly the definition it holds now.\n */\nconst policiesAreCurrent = (plan: TablePolicyPlan, present: Map<string, LivePolicy>): boolean => {\n for (const [name, renderedHash] of renderedHashes(plan)) {\n const policy = present.get(name);\n if (!policy || policy.stamp !== stampOf(renderedHash, policy.live)) return false;\n }\n return true;\n};\n\n/**\n * What its stamp says of a declared policy the database has: written by Rebase\n * from the statement the plan renders now and still holding that definition\n * (`current`), stamped once but changed since — the rule's SQL, or the policy\n * by hand (`stale`), or carrying no stamp at all, so nothing tells whether a\n * re-apply changes it (`unstamped`).\n */\nexport type PolicyStampState = \"current\" | \"stale\" | \"unstamped\";\n\n/**\n * Every declared policy the database holds, by `schema.table`, then name, with\n * its {@link PolicyStampState}. The comparison a boot makes to leave a table\n * alone, read for each policy instead of each table.\n *\n * The stored definition is read with `pg_get_expr`, whose spelling depends on\n * `search_path`: call it under the path the stamps were written under (a\n * boot's, `public` unless the URL pins one), or a current stamp reads stale.\n */\nexport async function readPolicyStamps(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n options: { adminRoleAvailable?: boolean } = {}\n): Promise<Map<string, Map<string, PolicyStampState>>> {\n // Stamped from the statement the boot or the push rendered: `TO public`\n // for the server-or-admin policies where the admin switch is not live.\n const plans = planTablePolicies(compiledTables, { adminRoleAvailable: options.adminRoleAvailable });\n const live = await readLivePolicies(client, Array.from(new Set(plans.map(p => p.schema))));\n const states = new Map<string, Map<string, PolicyStampState>>();\n for (const plan of plans) {\n const present = live.get(plan.qualified);\n if (!present) continue;\n const table = new Map<string, PolicyStampState>();\n for (const [name, renderedHash] of renderedHashes(plan)) {\n const policy = present.get(name);\n if (!policy) continue;\n table.set(name, policy.stamp === null || !policy.stamp.startsWith(POLICY_STAMP_PREFIX)\n ? \"unstamped\"\n : policy.stamp === stampOf(renderedHash, policy.live) ? \"current\" : \"stale\");\n }\n states.set(plan.qualified, table);\n }\n return states;\n}\n\n/** The name a probed policy is made under, in a transaction nothing commits. */\nconst PROBE_POLICY = \"rebase_policy_probe\";\n\n/**\n * For each of `policies`, whether the `CREATE POLICY` the plan renders for it\n * stores the definition the database holds now: made under a probe name on\n * the same table, read back, compared with the one there, and rolled back.\n *\n * What a stamp cannot answer. A stamp covers the statement as rendered, so a\n * rule whose text differs from the one that made the policy reads as changed\n * though Postgres would store the same thing: `schema introspect` writes a role\n * rule back as its deparsed SQL, and every such policy was planned as a\n * replacement of itself. A policy `db migrate` created has no stamp at all.\n *\n * One short transaction per policy, which takes the table's lock for as long\n * as it lasts and gives up on it after two seconds. A policy that could not be\n * probed — no statement for it, a lock not granted, a rule that does not\n * parse — is left out of the answer, and the caller keeps what the stamp said.\n * Keyed `schema.table.name`.\n */\nexport async function probeRenderedPolicies(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n policies: readonly { schema: string; table: string; name: string }[],\n options: { searchPath?: string; adminRoleAvailable?: boolean } = {}\n): Promise<Map<string, boolean>> {\n const statements = new Map<string, string>();\n for (const plan of planTablePolicies(compiledTables, { adminRoleAvailable: options.adminRoleAvailable })) {\n for (const statement of plan.policyStatements) {\n const name = createdPolicyName(statement);\n if (name) statements.set(`${plan.schema}.${plan.table}.${name}`, statement.trim());\n }\n }\n const answers = new Map<string, boolean>();\n for (const policy of policies) {\n const key = `${policy.schema}.${policy.table}.${policy.name}`;\n const statement = statements.get(key);\n if (!statement) continue;\n const probe = statement.replace(/^(\\s*CREATE POLICY\\s+)\"[^\"]+\"/i, `$1\"${PROBE_POLICY}\"`);\n const target = `\"${policy.schema.replace(/\"/g, '\"\"')}\".\"${policy.table.replace(/\"/g, '\"\"')}\"`;\n // Literals rather than parameters: a boot's `Queryable` takes none.\n const definition = (name: string): string =>\n `(SELECT ${liveDefinitionSql(\"p\")} FROM pg_policy p ` +\n `WHERE p.polrelid = ${quoteSqlLiteral(target)}::regclass AND p.polname = ${quoteSqlLiteral(name)})`;\n try {\n await client.query(\"BEGIN\");\n await client.query(\"SET LOCAL lock_timeout = '2s'\");\n if (options.searchPath) await client.query(`SET LOCAL search_path TO ${options.searchPath}`);\n await client.query(probe);\n const { rows } = await client.query<{ same: boolean | null }>(\n `SELECT ${definition(PROBE_POLICY)} IS NOT DISTINCT FROM ${definition(policy.name)} AS same`\n );\n if (typeof rows[0]?.same === \"boolean\") answers.set(key, rows[0].same);\n } catch {\n // Not probed; see above.\n } finally {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n }\n }\n return answers;\n}\n\n/**\n * Every declared schema's tables, and whether each has row-level security on.\n *\n * One catalogue read for the whole step. It replaced a full `readExistingSchema`\n * — eight catalogue queries and a row probe of every table, of which only the\n * table names were used — and it carries the one fact that lets a boot leave an\n * already-locked table alone: `relrowsecurity`.\n *\n * Presence is still decided by `information_schema.columns`, as it was: the\n * same relations (views included, which have no RLS and are closed by revoking,\n * exactly as before) and the same privilege filter.\n */\nasync function readTableSecurity(client: Queryable, schemas: string[]): Promise<Map<string, { rls: boolean }>> {\n const tables = new Map<string, { rls: boolean }>();\n if (schemas.length === 0) return tables;\n const inList = schemas.map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`).join(\", \");\n const { rows } = await client.query<{ table_schema: string; table_name: string; rls: boolean | null }>(\n `SELECT t.table_schema, t.table_name, c.relrowsecurity AS rls\n FROM (SELECT DISTINCT table_schema, table_name FROM information_schema.columns\n WHERE table_schema IN (${inList})) t\n JOIN pg_namespace n ON n.nspname = t.table_schema\n JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = t.table_name`\n );\n for (const row of rows) tables.set(`${row.table_schema}.${row.table_name}`, { rls: row.rls === true });\n return tables;\n}\n\n/**\n * Whether the catalogue says RLS is on for one table, read fresh. `false` when\n * it cannot be read, which sends the caller down the fail-closed path.\n */\nasync function rlsIsOn(client: Queryable, plan: TablePolicyPlan): Promise<boolean> {\n try {\n const { rows } = await client.query<{ rls: boolean }>(\n `SELECT c.relrowsecurity AS rls FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ${quoteSqlLiteral(plan.schema)} AND c.relname = ${quoteSqlLiteral(plan.table)}`\n );\n return rows[0]?.rls === true;\n } catch {\n return false;\n }\n}\n\n/** What one table's `ENABLE ROW LEVEL SECURITY` came to. */\ntype TableLock =\n | { locked: true }\n | { locked: false; error: string; grantWithdrawn: boolean };\n\n/**\n * Switch RLS on for one table, or — when Postgres refuses — take the user\n * role's privileges on it back, so the table is unreachable rather than\n * unprotected.\n *\n * A table the catalogue already reports RLS-on is left alone. `ENABLE` on it\n * changes nothing, and it is not free: it queues for an `ACCESS EXCLUSIVE` lock,\n * so a boot that met a long reader held every live query on that table behind\n * it — and when the wait ended in a timeout, the catch below revoked the user\n * role's privileges on a table that had been protected all along. Every\n * replica shares the grants, so one boot during a `pg_dump` closed the\n * collection for the whole deployment until the next clean boot.\n */\nasync function lockTable(\n client: Queryable,\n plan: TablePolicyPlan,\n rlsOn: boolean,\n run: (sql: string) => Promise<unknown> = sql => client.query(sql)\n): Promise<TableLock> {\n if (rlsOn) return { locked: true };\n try {\n await run(plan.enableRls);\n return { locked: true };\n } catch (err) {\n // The database's own answer, not the ORM's wrapper — see\n // `describeDriverError`. This is the most consequential message in\n // the file: it is what the operator reads about a table that is now\n // denying every request, and `Failed query: <the statement>` told\n // them nothing they did not already have.\n const error = describeDriverError(err);\n // A failed statement says nothing about the state it meant to reach: a\n // lock or statement timeout, a cancelled query, a peer that enabled it\n // first. Ask the catalogue. Only a table that really is RLS-off is\n // revoked — that safety is unchanged; a read that fails counts as off.\n if (await rlsIsOn(client, plan)) return { locked: true };\n // Take the privilege back rather than serve an unprotected table.\n // This is the fail-closed step the old code assumed it already had:\n // per-table, so one collection cannot take the rest of the\n // deployment down, but leaving nothing readable without RLS.\n //\n // Quoted, like every other statement here: unquoted, Postgres folds\n // the name to lower case, so a mixed-case adopted table (`\"User\"`)\n // was revoked as `public.user` — which fails, and a table that could\n // have been closed refused the boot instead.\n return withdrawGrant(client, plan, error);\n }\n}\n\n/**\n * Take the user role's privileges on a table back, so an RLS-off table is\n * unreachable rather than unprotected. `REVOKE` waits for no table lock a\n * reader holds, so it runs as a plain statement.\n */\nasync function withdrawGrant(client: Queryable, plan: TablePolicyPlan, error: string): Promise<TableLock> {\n try {\n await client.query(revokeUserRoleSql(plan.schema, plan.table));\n return { locked: false, error, grantWithdrawn: true };\n } catch {\n // Reported with `grantWithdrawn: false`, which the caller escalates.\n // There is nothing else this can do to make the table safe.\n return { locked: false, error, grantWithdrawn: false };\n }\n}\n\nexport interface TableLockResult {\n /** Tables RLS is now on for. */\n locked: number;\n /** Tables it could not be switched on for. See {@link PolicyEnsureResult.unsecured}. */\n unsecured: PolicyEnsureResult[\"unsecured\"];\n}\n\n/**\n * Switch RLS on for every table the tables declare — each collection's\n * and each junction's — and do nothing else.\n *\n * The first thing `rebase db push` does once Atlas has committed. Atlas cannot\n * carry `ENABLE ROW LEVEL SECURITY` (its free tier neither plans nor reads it),\n * so a table it creates arrives with RLS off — while the user role already\n * holds DML on it through the schema's default privileges. Everything push runs\n * after Atlas can refuse: the vector, search and trigger DDL, the policies\n * themselves. Locking first means none of those failures can leave a table\n * open: RLS with no policy denies, which is a state a failed push may leave.\n *\n * A declared table that is not in the database is skipped — nothing can reach\n * a table that does not exist, and the step that creates it locks it.\n */\nexport async function lockTables(\n client: Queryable,\n compiledTables: readonly CompiledTable[]\n): Promise<TableLockResult> {\n const result: TableLockResult = { locked: 0, unsecured: [] };\n for (const { plan, rls } of await declaredTablesPresent(client, compiledTables)) {\n const lock = await lockTable(client, plan, rls);\n if (lock.locked) {\n result.locked++;\n } else {\n result.unsecured.push({ table: plan.qualified, error: lock.error, grantWithdrawn: lock.grantWithdrawn });\n }\n }\n return result;\n}\n\n/**\n * The declared tables {@link lockTables} would switch row-level\n * security on for: those in the database with it off. What `db push\n * --dry-run` lists, read the way the push's lock step reads it.\n */\nexport async function tablesRlsWouldEnable(client: Queryable, compiledTables: readonly CompiledTable[]): Promise<string[]> {\n return (await declaredTablesPresent(client, compiledTables)).filter(table => !table.rls).map(table => table.plan.qualified);\n}\n\n/** Each declared table the database has, with whether its RLS is on. */\nasync function declaredTablesPresent(\n client: Queryable,\n compiledTables: readonly CompiledTable[]\n): Promise<{ plan: TablePolicyPlan; rls: boolean }[]> {\n const plans = planTablePolicies(compiledTables);\n if (plans.length === 0) return [];\n const tables = await readTableSecurity(client, Array.from(new Set(plans.map(p => p.schema))));\n return plans.flatMap(plan => {\n const table = tables.get(plan.qualified);\n return table ? [{ plan, rls: table.rls }] : [];\n });\n}\n\n/** One declared table that exists, and what the catalogue said about it. */\ninterface TableWork {\n plan: TablePolicyPlan;\n rlsOn: boolean;\n orphans: string[];\n /** Whether the policy names on the table differ from the plan's. */\n rulesChanged: boolean;\n /** Whether the plan holds no generated rule of its own, so the orphans are every rule the table had. */\n declaresNoRule: boolean;\n}\n\ntype AtomicOutcome =\n | { kind: \"applied\" }\n | { kind: \"lock-timeout\"; error: string }\n | { kind: \"unsupported\" }\n | { kind: \"failed\"; error: string };\n\n/**\n * Bring the declared collections' RLS policies up to date. Returns what it did.\n *\n * Only tables that already exist are touched: the boot-time table creator runs\n * first, so anything still missing is a table this additive path did not\n * create (it creates junctions too) — one a failed boot DDL left out, or a\n * project whose schema a migration owns. Enabling RLS on a\n * non-existent table would error, so those are recorded as skipped, not failed.\n *\n * ## One transaction per table\n *\n * Each table's statements — `ENABLE` when RLS is off, every `DROP POLICY IF\n * EXISTS` / `CREATE POLICY` pair, the orphan drops — go to Postgres as one\n * string, which it runs as one transaction (see `boot-ddl`). Before, each was\n * its own autocommit: at 240 tables, 4,080 commits and 4,080 ACCESS EXCLUSIVE\n * lock acquisitions per boot, 6–22 s on a disk that really flushes. And between\n * a policy's DROP and its CREATE, every other replica evaluated the table with\n * that policy missing — a user's continuous reads of their own row came back\n * empty once per boot (measured, Postgres 18). Now a concurrent request sees the\n * old policies or the new ones, never neither.\n *\n * If the transaction fails for any reason but a lock timeout, the table is\n * applied again one statement at a time — so a rule that cannot be created (a\n * function a migration has not added yet) leaves the table in a deny-leaning\n * partial state rather than rolling back to the old, possibly looser,\n * policies. Deny-leaning holds for restrictive rules too: they are applied\n * first, and one that cannot be created is replaced by a restrictive policy\n * that passes nothing, never left out from under the grants.\n *\n * ## Lock budget\n *\n * The transaction runs under `lock_timeout` (`boot-ddl`), so a table that a\n * long transaction, a report or a dump is holding costs live traffic one\n * second, not the statement timeout. A contended table is retried after the\n * others, with backoff, within a retry budget for the whole step; one still\n * held after that is reported in `deferred` — its transaction rolled back, so\n * it is exactly as it was before this boot — or, if RLS was off on it, closed\n * by revoking the user role's grant, like every table RLS cannot be enabled on.\n */\nexport async function ensureTablePolicies(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n log?: (message: string) => void,\n options: BootLockOptions & {\n /**\n * Whether this server's admin switch is live (`settleAdminSwitch`).\n * `false` writes the server-or-admin policies `TO public` and creates\n * no role: written `TO rebase_admin` while admin requests run as the\n * request role, they would refuse every admin caller. Left out, they\n * go `TO rebase_admin` wherever that role exists or can be made.\n */\n adminRoleAvailable?: boolean;\n /**\n * Whether the admin-only policies get their `TO rebase_admin_request\n * USING (true)` companions — see `planTablePolicies`. Only a boot\n * that has made that role safe (`settleAdminRequestGroup`) says so;\n * anywhere else they are not planned, and any in the database are\n * dropped as orphans.\n */\n adminRequestRoleAvailable?: boolean;\n } = {}\n): Promise<PolicyEnsureResult> {\n const result: PolicyEnsureResult = {\n policiesApplied: 0, tablesSecured: 0, unchanged: 0, skipped: [], failures: [], unsecured: [],\n orphansDropped: 0, deferred: [], rulesDropped: []\n };\n\n let plans = planTablePolicies(compiledTables, { adminRequestRoleAvailable: options.adminRequestRoleAvailable });\n if (plans.length === 0) return result;\n // The server-or-admin policies are written `TO rebase_admin`\n // (`rls.adminPolicies: \"adminRole\"`), and CREATE POLICY refuses a role that\n // does not exist; nothing guarantees this step runs after the one that\n // makes it. Where it cannot be made — a connection without CREATEROLE, a\n // role nobody pre-created — those policies are written `TO public`, as they\n // were before, rather than dropped and left uncreatable: admin requests then\n // keep running as the request role (`settleAdminRequestRoles`), which is\n // what `TO public` serves. A boot whose admin switch is not live says so\n // (`adminRoleAvailable: false`), and gets the same: an existing\n // `rebase_admin` — another project's, a privileged push's — is not enough.\n if (options.adminRoleAvailable === false) {\n plans = planTablePolicies(compiledTables, { adminRoleAvailable: false });\n } else if (plans.some(plan => plan.policies.some(policy => policy.adminTarget))) {\n const run = async (text: string) => (await client.query<Record<string, unknown>>(text)).rows;\n const available = await ensureAdminPolicyRole(run).then(() => true, (err: unknown) => {\n log?.(`the \"${REBASE_ADMIN_ROLE}\" role does not exist and could not be created (${describeDriverError(err)}); ` +\n \"the server-or-admin policies stay TO public, and signed-in users' owner-scoped reads keep scanning\");\n return false;\n });\n if (!available) plans = planTablePolicies(compiledTables, { adminRoleAvailable: false });\n }\n const lock = resolveBootLockOptions(options);\n\n const schemas = Array.from(new Set(plans.map(p => p.schema)));\n const tables = await readTableSecurity(client, schemas);\n const livePolicies = await readLivePolicies(client, schemas);\n\n const work: TableWork[] = [];\n for (const plan of plans) {\n const table = tables.get(plan.qualified);\n if (!table) {\n result.skipped.push({\n table: plan.qualified,\n reason: \"table is not present in the database; create it with `rebase db push` / `rebase db migrate`\"\n });\n continue;\n }\n const live = livePolicies.get(plan.qualified) ?? new Map<string, LivePolicy>();\n const present = [...live.keys()];\n const orphans = orphansOf(plan, present);\n // Already exactly what the plan would leave: nothing to run, no lock to take.\n if (table.rls && orphans.length === 0 && policiesAreCurrent(plan, live)) {\n result.tablesSecured++;\n result.unchanged++;\n continue;\n }\n const presentSet = new Set(present);\n const rulesChanged = orphans.length > 0 || [...plannedPolicyNames(plan)].some(name => !presentSet.has(name));\n const declaresNoRule = ![...plannedPolicyNames(plan)].some(name => isGeneratedPolicyName(name, plan.table));\n work.push({ plan, rlsOn: table.rls, orphans, rulesChanged, declaresNoRule });\n }\n if (result.unchanged > 0) {\n log?.(`${result.unchanged} table(s) already have exactly the declared policies; left as they are`);\n }\n\n // Until the handle refuses a multi-statement string (an extended-protocol\n // driver), after which every table goes one statement at a time.\n let atomic = true;\n let retryBudget = lock.retryBudgetMs;\n let queue = work;\n let lastError = new Map<TableWork, string>();\n\n for (let attempt = 1; queue.length > 0; attempt++) {\n if (attempt > 1) {\n if (attempt > lock.attempts || retryBudget <= 0) break;\n await sleep(lock.backoffMs(attempt - 1));\n }\n const contended: TableWork[] = [];\n const errors = new Map<TableWork, string>();\n for (const table of queue) {\n if (attempt > 1 && retryBudget <= 0) {\n contended.push(table);\n errors.set(table, lastError.get(table) ?? \"\");\n continue;\n }\n if (atomic) {\n const outcome = await applyAtomically(client, table, lock);\n if (outcome.kind === \"applied\") {\n record(result, table, log);\n continue;\n }\n if (outcome.kind === \"lock-timeout\") {\n if (attempt > 1) retryBudget -= lock.lockTimeoutMs;\n contended.push(table);\n errors.set(table, outcome.error);\n continue;\n }\n if (outcome.kind === \"unsupported\") {\n atomic = false;\n } else {\n log?.(`${table.plan.qualified}: applying its policies in one transaction failed ` +\n `(${outcome.error}); applying them one statement at a time`);\n }\n }\n await applyEachStatement(client, table, result, log, atomic ? lock : undefined);\n }\n queue = contended;\n lastError = errors;\n }\n\n // Still contended after every attempt the budget allowed.\n for (const table of queue) {\n await giveUp(client, table, lastError.get(table) ?? \"\", lock, result);\n }\n\n return result;\n}\n\n/**\n * The table's statements, in the order they must run — the stamp last, so it\n * reads back the policies this same transaction created.\n */\nconst statementsOf = (table: TableWork): string[] => {\n const stamp = policyStampSql(table.plan);\n return [\n ...(table.rlsOn ? [] : [table.plan.enableRls]),\n ...table.plan.policyStatements,\n ...table.orphans.map(name => dropPolicySql(table.plan, name)),\n ...(stamp ? [stamp] : [])\n ];\n};\n\nasync function applyAtomically(\n client: Queryable,\n table: TableWork,\n lock: ResolvedBootLockOptions\n): Promise<AtomicOutcome> {\n const statements = statementsOf(table);\n if (statements.length === 0) return { kind: \"applied\" };\n try {\n await client.query(atomicBatch(statements, lock.lockTimeoutMs));\n return { kind: \"applied\" };\n } catch (err) {\n if (isLockTimeout(err)) return { kind: \"lock-timeout\", error: describeDriverError(err) };\n if (isMultiStatementRefusal(err)) return { kind: \"unsupported\" };\n return { kind: \"failed\", error: describeDriverError(err) };\n }\n}\n\n/**\n * The warning a boot gives for one entry of {@link PolicyEnsureResult.rulesDropped}:\n * each policy, what it means for the table, and the likely cause.\n */\nexport function describeRulesDropped(dropped: { table: string; policies: string[] }): string {\n return `🔐 [rls] \"${dropped.table}\" is \\`rls: \"admin-only\"\\` now, so the policies its rules had made were dropped: ` +\n `${dropped.policies.join(\", \")}. Only administrators reach its rows now, on every server sharing this database. ` +\n \"If the table says `rls: \\\"inherit\\\"`, the `defaultRls` it inherits is \\\"admin-only\\\": check what \" +\n \"backend/schema/index.ts exports as `defaultRls`, and that this server was handed that schema directory. \" +\n \"If the rules were removed on purpose, this is that change.\";\n}\n\n/** The orphans just dropped, when they were every rule the table had. See {@link PolicyEnsureResult.rulesDropped}. */\nfunction recordRulesDropped(result: PolicyEnsureResult, table: TableWork): void {\n if (table.declaresNoRule && table.orphans.length > 0) {\n result.rulesDropped.push({ table: table.plan.qualified, policies: [...table.orphans].sort() });\n }\n}\n\nfunction record(result: PolicyEnsureResult, table: TableWork, log?: (message: string) => void): void {\n const created = table.plan.policyStatements.filter(isCreatePolicy).length;\n result.tablesSecured++;\n result.policiesApplied += created;\n result.orphansDropped += table.orphans.length;\n recordRulesDropped(result, table);\n log?.(`${table.plan.qualified}: RLS enabled, ${created} policy(ies) applied` +\n (table.orphans.length > 0 ? `, ${table.orphans.length} orphan(s) dropped` : \"\"));\n}\n\n/**\n * The table applied one statement at a time — the path every table took before\n * the per-table transaction, kept as its fallback so a failure ends exactly\n * where it always did.\n *\n * Each statement still carries the lock budget when the handle can take it.\n */\nasync function applyEachStatement(\n client: Queryable,\n table: TableWork,\n result: PolicyEnsureResult,\n log: ((message: string) => void) | undefined,\n lock: ResolvedBootLockOptions | undefined\n): Promise<void> {\n const { plan } = table;\n const run = (sql: string) => client.query(lock ? atomicBatch([sql], lock.lockTimeoutMs) : sql);\n\n // Enabling RLS is its own step, because its failure is the opposite of\n // every other failure here. Once RLS is on, anything that goes wrong\n // afterwards leaves the table denying; while it is off, the grant made\n // earlier in boot leaves the table wide open. Sharing one `try` meant\n // the dangerous case was reported in the safe case's words.\n const locked = await lockTable(client, plan, table.rlsOn, run);\n if (!locked.locked) {\n result.unsecured.push({ table: plan.qualified, error: locked.error, grantWithdrawn: locked.grantWithdrawn });\n return;\n }\n result.tablesSecured++;\n\n // The restrictive gates go in before any grant, and a gate that cannot be\n // created is replaced by one that passes nothing. A restrictive policy is\n // ANDed over the permissive ones, so a missing gate is not a denial: the\n // grants made beside it would answer alone, and a tenancy or admin-write\n // gate that failed to apply let every grant through it.\n let created = 0;\n let gateError: string | undefined;\n for (const policy of plan.policies.filter(p => p.restrictive)) {\n try {\n for (const statement of policy.statements) await run(statement);\n result.policiesApplied++;\n created++;\n } catch (err) {\n gateError ??= `${policy.name}: ${describeDriverError(err)}`;\n try {\n for (const statement of policy.denying ?? []) await run(statement);\n } catch (denyErr) {\n // Neither the gate nor its stand-in is in place, so the grants\n // already on the table answer alone: closed the way a table RLS\n // cannot be enabled on is.\n result.tablesSecured--;\n const closed = await withdrawGrant(client, plan,\n `restrictive policy ${gateError}; its denying stand-in failed too: ${describeDriverError(denyErr)}`);\n if (!closed.locked) {\n result.unsecured.push({ table: plan.qualified, error: closed.error, grantWithdrawn: closed.grantWithdrawn });\n }\n return;\n }\n }\n }\n\n try {\n for (const policy of plan.policies.filter(p => !p.restrictive)) {\n for (const statement of policy.statements) await run(statement);\n result.policiesApplied++;\n created++;\n }\n if (gateError) throw new Error(`restrictive policy ${gateError}; it denies every row until it can be created`);\n for (const name of table.orphans) {\n await run(dropPolicySql(plan, name));\n result.orphansDropped++;\n }\n recordRulesDropped(result, table);\n log?.(`${plan.qualified}: RLS enabled, ${created} policy(ies) applied` +\n (table.orphans.length > 0 ? `, ${table.orphans.length} orphan(s) dropped` : \"\"));\n } catch (err) {\n result.failures.push({\n table: plan.qualified,\n error: describeDriverError(err)\n });\n return;\n }\n\n // Only once every policy is in. A stamp that cannot be written costs the\n // next boot a re-apply of this table — what every boot did before stamps —\n // so it is reported, not failed.\n const stamp = policyStampSql(plan);\n if (!stamp) return;\n try {\n await run(stamp);\n } catch (err) {\n log?.(`${plan.qualified}: policies applied, but not stamped (${describeDriverError(err)}); ` +\n \"the next boot applies them again\");\n }\n}\n\n/**\n * A table whose lock was held for every attempt. Its transaction rolled back\n * each time, so it is exactly as it was before this boot.\n *\n * With RLS on, that is a safe state to leave it in — reported, not failed. With\n * RLS off it is an open table over the schema-wide grant, so it is closed the\n * way any table RLS cannot be enabled on is: the catalogue is asked once more,\n * and only a table that really is RLS-off has the user role's grant withdrawn.\n */\nasync function giveUp(\n client: Queryable,\n table: TableWork,\n lastError: string,\n lock: ResolvedBootLockOptions,\n result: PolicyEnsureResult\n): Promise<void> {\n const { plan } = table;\n const error =\n `another session held the table's lock for every attempt (lock_timeout ${lock.lockTimeoutMs} ms` +\n `${lastError ? `: ${lastError.split(\"\\n\")[0]}` : \"\"}) — a long transaction, a report or a dump`;\n if (table.rlsOn || await rlsIsOn(client, plan)) {\n result.tablesSecured++;\n result.deferred.push({ table: plan.qualified, error, rulesChanged: table.rulesChanged });\n return;\n }\n const closed = await withdrawGrant(client, plan, error);\n if (!closed.locked) {\n result.unsecured.push({ table: plan.qualified, error: closed.error, grantWithdrawn: closed.grantWithdrawn });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsJA,IAAM,kBAAkB,cAA+B,qBAAqB,KAAK,SAAS;;;;;;;;;;;;;AAc1F,IAAM,qBAAqB,cAA0C;CACjE,MAAM,QAAQ,iCAAiC,KAAK,SAAS;CAC7D,OAAO,QAAQ,qBAAqB,MAAM,EAAE,IAAI,KAAA;AACpD;;AAGA,IAAM,sBAAsB,SAAuC;CAC/D,MAAM,2BAAW,IAAI,IAAY;CAC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,sBAAsB,UAAU,8CAA8C;EAC7G,KAAK,MAAM,QAAQ,MAAM,SAAS;GAC9B,MAAM,IAAI,cAAc,MAAM,IAAI,CAAC;GACnC,OAAO;EACX;EACA,mBAAmB,QAAQ,KAAK;EAChC,MAAM,GAAG,KAAK,UAAU,iBAAiB,QAAQ,yBAC5C,MAAM,QAAQ,SAAS,IAAI,KAAK,MAAM,QAAQ,OAAO,sBAAsB,GAAG;CACvF,SAAS,KAAK;EACV,OAAO,SAAS,KAAK;GACjB,OAAO,KAAK;GACZ,OAAO,oBAAoB,GAAG;EAClC,CAAC;EACD;CACJ;CAKA,MAAM,QAAQ,eAAe,IAAI;CACjC,IAAI,CAAC,OAAO;CACZ,IAAI;EACA,MAAM,IAAI,KAAK;CACnB,SAAS,KAAK;EACV,MAAM,GAAG,KAAK,UAAU,uCAAuC,oBAAoB,GAAG,EAAE,oCAClD;CAC1C;AACJ;;;;;;;;;;AAWA,eAAe,OACX,QACA,OACA,WACA,MACA,QACa;CACb,MAAM,EAAE,SAAS;CACjB,MAAM,QACF,yEAAyE,KAAK,cAAc,KACzF,YAAY,KAAK,UAAU,MAAM,IAAI,CAAC,CAAC,OAAO,GAAG;CACxD,IAAI,MAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI,GAAG;EAC5C,OAAO;EACP,OAAO,SAAS,KAAK;GAAE,OAAO,KAAK;GAAW;GAAO,cAAc,MAAM;EAAa,CAAC;EACvF;CACJ;CACA,MAAM,SAAS,MAAM,cAAc,QAAQ,MAAM,KAAK;CACtD,IAAI,CAAC,OAAO,QACR,OAAO,UAAU,KAAK;EAAE,OAAO,KAAK;EAAW,OAAO,OAAO;EAAO,gBAAgB,OAAO;CAAe,CAAC;AAEnH"}
@@ -1,16 +1,16 @@
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 { ct as extractCauseMessage } from "./cli-schema-dir-CiN0ephV.js";
5
- import { n as extractPgError } from "./pg-error-utils-BT5NzGFZ.js";
4
+ import { ct as extractCauseMessage } from "./cli-schema-dir-DuZIsF2e.js";
5
+ import { n as extractPgError } from "./pg-error-utils-CpUiBkp-.js";
6
6
  import { s as vectorExtensionHint } from "./vector-index-VSh3ufTd.js";
7
7
  import { n as planSchema, r as quoteSqlLiteral } from "./plan-schema-Hbtjhge3.js";
8
8
  import { f as renderViewsDdl } from "./render-ddl-D4n86NHz.js";
9
- import { c as planJunctionTables } from "./generate-postgres-ddl-logic-B8huc03c.js";
9
+ import { c as planJunctionTables } from "./generate-postgres-ddl-logic-CQof4iFH.js";
10
10
  import { r as quoteRelation } from "./introspect-db-queries-BgiRQqtR.js";
11
- import { E as readIndexShapes } from "./migrate-baseline-DZmekgpD.js";
12
- import { a as assertSafeIdentifier, c as helperFunctionKey, i as HELPER_FUNCTIONS, l as triggerArgumentsKey, n as buildDeferredIndexes, o as describeHelperFunction, s as diffPlanAgainstCatalogue, u as columnTypeDriftMessage } from "./deferred-index-build-CcSDA7wE.js";
13
- import { a as isLockTimeout, l as sleep, o as isMultiStatementRefusal, r as atomicBatch, s as joinStatements } from "./boot-ddl-5H2bL_80.js";
11
+ import { E as readIndexShapes } from "./migrate-baseline-DnMlSDup.js";
12
+ import { a as assertSafeIdentifier, c as helperFunctionKey, i as HELPER_FUNCTIONS, l as triggerArgumentsKey, n as buildDeferredIndexes, o as describeHelperFunction, s as diffPlanAgainstCatalogue, u as columnTypeDriftMessage } from "./deferred-index-build-ueYVUBZc.js";
13
+ import { a as isLockTimeout, l as sleep, o as isMultiStatementRefusal, r as atomicBatch, s as joinStatements } from "./boot-ddl-CSYhSSZD.js";
14
14
  import { isConcurrentDdlRace, isDuplicateObjectRace, logger } from "@rebasepro/server";
15
15
  import { REBASE_SCHEMA, declaredDatabaseExtensions } from "@rebasepro/types";
16
16
  //#region src/schema/ensure-tables.ts
@@ -549,4 +549,4 @@ async function applyAction(client, action, lockBudget) {
549
549
  //#endregion
550
550
  export { readSchemaFactsFor as a, readExistingSchema as i, ensure_tables_exports as n, planTableSchemaEnsure as r, describeDriverError as t };
551
551
 
552
- //# sourceMappingURL=ensure-tables-Bvm-F2wW.js.map
552
+ //# sourceMappingURL=ensure-tables-B3Kh2RwT.js.map