@rebasepro/server-postgres 0.29.1 → 0.29.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BranchService-BIIBF5ZL.js → BranchService-X9R505mP.js} +3 -3
- package/dist/{BranchService-BIIBF5ZL.js.map → BranchService-X9R505mP.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +64 -4
- package/dist/PostgresBootstrapper.d.ts +20 -0
- package/dist/auth/ensure-tables.d.ts +2 -2
- package/dist/auth/schema-version.d.ts +5 -5
- package/dist/auth/services.d.ts +9 -9
- package/dist/{backup-cli-QcOpmRpQ.js → backup-cli-CwiJEp_J.js} +3 -3
- package/dist/{backup-cli-QcOpmRpQ.js.map → backup-cli-CwiJEp_J.js.map} +1 -1
- package/dist/{boot-ddl-BSNpEUOS.js → boot-ddl-CbZj9ovZ.js} +2 -2
- package/dist/{boot-ddl-BSNpEUOS.js.map → boot-ddl-CbZj9ovZ.js.map} +1 -1
- package/dist/{cli-console-DTsm96lW.js → cli-console-DDkNetCz.js} +6 -6
- package/dist/{cli-console-DTsm96lW.js.map → cli-console-DDkNetCz.js.map} +1 -1
- package/dist/{cli-errors-DwqFRIWz.js → cli-errors-C73Qy7WJ.js} +5 -5
- package/dist/{cli-errors-DwqFRIWz.js.map → cli-errors-C73Qy7WJ.js.map} +1 -1
- package/dist/cli.js +165 -49
- package/dist/cli.js.map +1 -1
- package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
- package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
- package/dist/data-transformer.d.ts +2 -2
- package/dist/database-health.d.ts +2 -1
- package/dist/{database-preflight-D5JtPt8i.js → database-preflight-DIauc8i5.js} +36 -3
- package/dist/database-preflight-DIauc8i5.js.map +1 -0
- package/dist/{databasePoolManager-7hXVurmG.js → databasePoolManager-DIjzlTK4.js} +2 -2
- package/dist/{databasePoolManager-7hXVurmG.js.map → databasePoolManager-DIjzlTK4.js.map} +1 -1
- package/dist/{deferred-index-build-B8feKnUj.js → deferred-index-build-DDdnjaOW.js} +18 -6
- package/dist/deferred-index-build-DDdnjaOW.js.map +1 -0
- package/dist/{doctor-BaR11xUe.js → doctor-DwMXljiq.js} +11 -11
- package/dist/doctor-DwMXljiq.js.map +1 -0
- package/dist/{ensure-collection-policies-85HiG-k1.js → ensure-collection-policies-DJsOMpaI.js} +23 -13
- package/dist/ensure-collection-policies-DJsOMpaI.js.map +1 -0
- package/dist/{ensure-collection-tables-DR_WcxLA.js → ensure-collection-tables-h1mUO7Uu.js} +11 -8
- package/dist/ensure-collection-tables-h1mUO7Uu.js.map +1 -0
- package/dist/{ensure-tables-Dh5UP_Zs.js → ensure-tables-CUqYgMvo.js} +4 -4
- package/dist/ensure-tables-CUqYgMvo.js.map +1 -0
- package/dist/{enum-labels-kept-DSU8lAnd.js → enum-labels-kept-z7ustOl_.js} +3 -3
- package/dist/{enum-labels-kept-DSU8lAnd.js.map → enum-labels-kept-z7ustOl_.js.map} +1 -1
- package/dist/{generate-drizzle-schema-5spbTyQ6.js → generate-drizzle-schema-BIUqhSzh.js} +2 -2
- package/dist/{generate-drizzle-schema-5spbTyQ6.js.map → generate-drizzle-schema-BIUqhSzh.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js → generate-drizzle-schema-logic-BBXjxm5z.js} +3 -3
- package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js.map → generate-drizzle-schema-logic-BBXjxm5z.js.map} +1 -1
- package/dist/{generate-files-Bl3_D_oP.js → generate-files-BkiRFoV1.js} +3 -3
- package/dist/{generate-files-Bl3_D_oP.js.map → generate-files-BkiRFoV1.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-BC3JA93M.js → generate-postgres-ddl-logic-G9PvjHrr.js} +10 -5
- package/dist/{generate-postgres-ddl-logic-BC3JA93M.js.map → generate-postgres-ddl-logic-G9PvjHrr.js.map} +1 -1
- package/dist/{generated-schema-diff-Jm93vyJB.js → generated-schema-diff-D2soazQU.js} +8 -5
- package/dist/generated-schema-diff-D2soazQU.js.map +1 -0
- package/dist/history/HistoryService.d.ts +2 -3
- package/dist/history/ensure-history-table.d.ts +8 -3
- package/dist/index.es.js +15 -15
- package/dist/interfaces.d.ts +24 -2
- package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
- package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
- package/dist/{migrate-baseline-BfHmq3vN.js → migrate-baseline-CveNQli3.js} +163 -502
- package/dist/migrate-baseline-CveNQli3.js.map +1 -0
- package/dist/{migrate-policy-stamps-B4k1ggma.js → migrate-policy-stamps-C4qbQ0jK.js} +42 -13
- package/dist/migrate-policy-stamps-C4qbQ0jK.js.map +1 -0
- package/dist/{open-rebase-CiO_sjMT.js → open-rebase-Cvid3iwR.js} +1395 -656
- package/dist/open-rebase-Cvid3iwR.js.map +1 -0
- package/dist/open-rebase.d.ts +1 -1
- package/dist/{pg-error-utils-D1Nc0UML.js → pg-error-utils-80uTIHQs.js} +2 -2
- package/dist/{pg-error-utils-D1Nc0UML.js.map → pg-error-utils-80uTIHQs.js.map} +1 -1
- package/dist/pipelined-transaction.d.ts +24 -37
- package/dist/{plan-schema-BYxOzflz.js → plan-schema-CMhNYEYF.js} +21 -6
- package/dist/plan-schema-CMhNYEYF.js.map +1 -0
- package/dist/{policy-drift-DKuTJHfc.js → policy-drift-Bx6663KD.js} +29 -6
- package/dist/policy-drift-Bx6663KD.js.map +1 -0
- package/dist/push-index-adoption-C-TpM445.js +22 -0
- package/dist/push-index-adoption-C-TpM445.js.map +1 -0
- package/dist/{push-index-prebuild-bqXimSZz.js → push-index-prebuild-xbpgZEJK.js} +4 -4
- package/dist/{push-index-prebuild-bqXimSZz.js.map → push-index-prebuild-xbpgZEJK.js.map} +1 -1
- package/dist/{push-kept-defaults-CN9R8cHf.js → push-kept-defaults-D-JEv0Gn.js} +2 -2
- package/dist/{push-kept-defaults-CN9R8cHf.js.map → push-kept-defaults-D-JEv0Gn.js.map} +1 -1
- package/dist/{push-legacy-renames-CU_UYPbz.js → push-legacy-renames-7UKspspl.js} +4 -4
- package/dist/{push-legacy-renames-CU_UYPbz.js.map → push-legacy-renames-7UKspspl.js.map} +1 -1
- package/dist/{push-policy-plan-JcyK94bc.js → push-policy-plan-BOw5PtU8.js} +14 -8
- package/dist/push-policy-plan-BOw5PtU8.js.map +1 -0
- package/dist/read-routing.d.ts +10 -30
- package/dist/{render-ddl-DCdVP-pQ.js → render-ddl-Di-fTGti.js} +15 -2
- package/dist/render-ddl-Di-fTGti.js.map +1 -0
- package/dist/{request-role-cli-DSdRtvgH.js → request-role-cli-Bxxskru9.js} +10 -10
- package/dist/{request-role-cli-DSdRtvgH.js.map → request-role-cli-Bxxskru9.js.map} +1 -1
- package/dist/{request-role-migration-D9BZ5Uba.js → request-role-migration-BCW4v0rq.js} +2 -2
- package/dist/{request-role-migration-D9BZ5Uba.js.map → request-role-migration-BCW4v0rq.js.map} +1 -1
- package/dist/rls-bootstrap-sql-CxszeSc7.js +534 -0
- package/dist/rls-bootstrap-sql-CxszeSc7.js.map +1 -0
- package/dist/{rls-enforcement-BO618rnr.js → rls-enforcement-CyUCPDH8.js} +213 -10
- package/dist/rls-enforcement-CyUCPDH8.js.map +1 -0
- package/dist/{rls-settings-De5NoHHy.js → rls-settings-BCGMIig3.js} +23 -3
- package/dist/rls-settings-BCGMIig3.js.map +1 -0
- package/dist/schema/doctor-cli.js +9 -9
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/drizzle-ddl.d.ts +2 -2
- package/dist/schema/ensure-collection-policies.d.ts +15 -3
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -1
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/index-adoption.d.ts +99 -0
- package/dist/schema/introspect-db-logic.d.ts +2 -1
- package/dist/schema/introspect-db.js +3 -3
- package/dist/schema/migrate-policy-stamps.d.ts +19 -1
- package/dist/schema/plan/diff-plan.d.ts +8 -1
- package/dist/schema/plan/render-ddl.d.ts +7 -0
- package/dist/schema/plan/types.d.ts +2 -0
- package/dist/schema/push-index-adoption.d.ts +10 -0
- package/dist/schema/push-policy-plan.d.ts +5 -1
- package/dist/schema/rls-bootstrap-sql.d.ts +13 -2
- package/dist/schema/search-column.d.ts +2 -2
- package/dist/search-column-BM-GV6vH.js.map +1 -1
- package/dist/security/policy-drift.d.ts +19 -1
- package/dist/security/rls-enforcement.d.ts +87 -1
- package/dist/security/rls-settings.d.ts +33 -0
- package/dist/services/FetchService.d.ts +33 -8
- package/dist/services/PersistService.d.ts +75 -4
- package/dist/services/RelationService.d.ts +1 -1
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
- package/dist/services/channel-bus/index.d.ts +2 -2
- package/dist/services/channel-history.d.ts +2 -2
- package/dist/services/channel-presence.d.ts +3 -3
- package/dist/services/dataService.d.ts +6 -2
- package/dist/services/realtimeService.d.ts +18 -5
- package/dist/services/socket-liveness.d.ts +6 -1
- package/dist/types.d.ts +1 -1
- package/dist/utils/drizzle-conditions.d.ts +12 -0
- package/dist/utils/positional-params.d.ts +40 -0
- package/dist/{websocket-B33YjKhs.js → websocket-BSYV_KSw.js} +3 -3
- package/dist/websocket-BSYV_KSw.js.map +1 -0
- package/dist/websocket.d.ts +14 -3
- package/package.json +7 -7
- package/dist/database-preflight-D5JtPt8i.js.map +0 -1
- package/dist/deferred-index-build-B8feKnUj.js.map +0 -1
- package/dist/doctor-BaR11xUe.js.map +0 -1
- package/dist/ensure-collection-policies-85HiG-k1.js.map +0 -1
- package/dist/ensure-collection-tables-DR_WcxLA.js.map +0 -1
- package/dist/ensure-tables-Dh5UP_Zs.js.map +0 -1
- package/dist/generated-schema-diff-Jm93vyJB.js.map +0 -1
- package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
- package/dist/migrate-baseline-BfHmq3vN.js.map +0 -1
- package/dist/migrate-policy-stamps-B4k1ggma.js.map +0 -1
- package/dist/open-rebase-CiO_sjMT.js.map +0 -1
- package/dist/plan-schema-BYxOzflz.js.map +0 -1
- package/dist/policy-drift-DKuTJHfc.js.map +0 -1
- package/dist/push-policy-plan-JcyK94bc.js.map +0 -1
- package/dist/render-ddl-DCdVP-pQ.js.map +0 -1
- package/dist/rls-enforcement-BO618rnr.js.map +0 -1
- package/dist/rls-settings-De5NoHHy.js.map +0 -1
- package/dist/websocket-B33YjKhs.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ensure-collection-tables-DR_WcxLA.js","names":[],"sources":["../src/schema/ensure-collection-tables.ts"],"sourcesContent":["/**\n * Applying a schema plan to a database that is already running.\n *\n * ## What this module is\n *\n * A managed runtime boots someone else's compiled project against a database it\n * has never seen. Auth tables are ensured at boot already, but collection tables\n * were not created by anything: the platform ran the app and every `/api/data/*`\n * request answered 500 on a missing relation. `rebase db push` cannot help — it\n * is an Atlas-driven CLI command, and the runtime image ships no CLI.\n *\n * Two halves, and only one of them is here. *What the collections ask for* is\n * `schema/plan/plan-schema.ts`, shared with `db push` and the generated Drizzle\n * file; *what the database already has, and which of those statements are safe\n * to run against it* is `schema/plan/diff-plan.ts`. This module reads the\n * catalogue, runs the statements, and reports what happened.\n *\n * ## Why additive-only, forever\n *\n * This runs unattended, against a database with customers' data in it, with no\n * human reading a diff. So it may only ever do things that cannot lose data.\n * See `diff-plan.ts` for the whole of that argument.\n */\nimport {\n declaredDatabaseExtensions,\n REBASE_SCHEMA,\n type CollectionConfig\n} from \"@rebasepro/types\";\nimport { getTableName, relationalCollections } from \"@rebasepro/common\";\nimport { logger, isConcurrentDdlRace, isDuplicateObjectRace } from \"@rebasepro/server\";\nimport { SEARCH_STAMP_PREFIX } from \"./search-column\";\nimport { vectorExtensionHint } from \"./vector-index\";\nimport { planJunctionTables, quoteSqlLiteral } from \"./generate-postgres-ddl-logic\";\nimport { quoteRelation } from \"./introspect-db-queries\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { renderViewsDdl } from \"./plan/render-ddl\";\nimport type { SchemaPlan } from \"./plan/types\";\nimport {\n assertSafeIdentifier,\n describeHelperFunction,\n diffPlanAgainstCatalogue,\n helperFunctionKey,\n HELPER_FUNCTIONS,\n triggerArgumentsKey,\n type ConstraintPolicy,\n type DeferredIndexBuild,\n type DiffOptions,\n type EnsureAction,\n type EnsurePlan,\n type ExistingSchema,\n type LegacyForeignKey,\n type OrphanedRequiredColumn,\n type SearchColumnDrift,\n type WithheldConstraint\n} from \"./plan/diff-plan\";\nimport { extractCauseMessage, extractPgError } from \"../utils/pg-error-utils\";\nimport { atomicBatch, isLockTimeout, isMultiStatementRefusal, joinStatements, sleep } from \"./boot-ddl\";\nimport {\n buildDeferredIndexes,\n TABLE_BUSY_REASON,\n type DeferredIndexOutcome,\n type OpenIndexBuildSession\n} from \"./deferred-index-build\";\nimport { columnTypeDriftMessage, type ColumnTypeDrift } from \"./column-type-drift\";\n\nexport type {\n ConstraintPolicy,\n DeferredIndexBuild,\n EnsureAction,\n EnsurePlan,\n ExistingSchema,\n LegacyForeignKey,\n OrphanedRequiredColumn,\n SearchColumnDrift,\n WithheldConstraint\n};\n\n/**\n * The subset of a database handle this needs: run a statement, get rows back.\n *\n * Deliberately parameterless. Everything here is DDL or catalogue reads keyed by\n * schema name, and schema names are identifiers — they cannot be bound as\n * parameters anyway. They are validated by `assertSafeIdentifier` before they\n * reach a statement, so a config that somehow carried a quote is refused rather\n * than concatenated.\n */\nexport interface Queryable {\n query<T = unknown>(sql: string): Promise<{ rows: T[] }>;\n}\n\nexport interface EnsureOptions extends DiffOptions {\n /**\n * Server extensions the project's databases gave Rebase leave to install —\n * `declaredDatabaseExtensions()`. Absent means none, which is a refusal and\n * is the right default for a planner given no configuration at all.\n *\n * Explicit rather than read from the resource registry in here, because the\n * planner is pure and several callers plan against fixtures: reaching for a\n * process-wide registry would make the plan depend on whatever some other\n * module happened to import. `ensureCollectionTables` is the boundary that\n * reads the world.\n */\n databaseExtensions?: readonly string[];\n /**\n * Run each statement that changes an existing table under this\n * `lock_timeout` (ms), retrying a timeout with backoff — see\n * `schema/boot-ddl`. The boot sets it; absent, statements wait on locks for\n * as long as the connection's `statement_timeout` allows, as the live schema\n * editor's confirmed changes do.\n */\n lockTimeoutMs?: number;\n /**\n * Apply the statements that build tables this run creates — and the enum\n * types they use — in transactions of up to {@link NEW_TABLE_BATCH}\n * statements instead of one autocommit each. The boot sets it; see\n * `ensureCollectionTables`.\n */\n batchNewTables?: boolean;\n /**\n * Leave the indexes a live table is missing (or holds INVALID) to the\n * caller, in {@link EnsureOutcome.deferredIndexes}, instead of building\n * them before returning. The boot sets it and builds them in the\n * background once it serves — see `deferred-index-build`. A UNIQUE one is\n * built before returning either way: see {@link DeferredIndexBuild.unique}.\n */\n deferIndexBuilds?: boolean;\n /**\n * The connection those builds run on when they are not deferred. Absent,\n * they share `client` — fine for a small table, and cut short by the\n * pool's `statement_timeout` on a large one, which is why the boot hands\n * over a dedicated connection.\n */\n openIndexBuildSession?: OpenIndexBuildSession;\n}\n\n/**\n * Most statements in one new-table transaction. Bounds how many locks one\n * transaction holds — each new table is several relations (the heap, its TOAST\n * table, its key index) — well inside the default `max_locks_per_transaction`.\n */\nconst NEW_TABLE_BATCH = 100;\n\nexport interface EnsureOutcome extends EnsurePlan {\n /**\n * Actions that could not be applied and are non-fatal by nature.\n *\n * Two kinds qualify. A foreign key can only fail on data that already\n * violates it, and the column it would police exists either way, so the\n * collection still serves; refusing to boot over one would turn a\n * pre-existing data problem into an outage. A column comment is the search\n * fingerprint, which needs table ownership — losing it costs drift\n * detection on the next boot, not the deployment. Both are reported loudly.\n */\n failures: { kind: EnsureAction[\"kind\"]; target: string; error: string }[];\n /**\n * What happened to the indexes built here rather than left to the caller —\n * every one of {@link EnsurePlan.deferredIndexes}, or under\n * `deferIndexBuilds` the UNIQUE ones only; absent when there were none.\n * An index on a table that already exists reports here, not in\n * {@link failures}.\n */\n indexBuilds?: DeferredIndexOutcome;\n}\n\n/** The schema a collection lives in, validated before it reaches any DDL. */\nfunction schemaOf(collection: CollectionConfig): string {\n const schema = (collection as { schema?: string }).schema || \"public\";\n return assertSafeIdentifier(schema, \"schema name\");\n}\n\n/**\n * Decide what to add. Pure — the caller supplies what exists and runs the\n * result.\n *\n * A plan and a diff: the collections are read once, by `planSchema`, into the\n * same {@link SchemaPlan} `db push` renders `schema.sql` from, and the diff\n * subtracts what the database already has. Before that split this function had\n * its own reading of every `Property`, and the audit found twelve places where\n * it disagreed with the two generators — a required `author_id` that was\n * NOT NULL after a push and nullable after a boot among them, on the one path\n * with no developer in the loop.\n */\nexport function planCollectionSchemaEnsure(\n allCollections: CollectionConfig[],\n existing: ExistingSchema,\n options: EnsureOptions = {}\n): EnsurePlan {\n const plan = planSchema(allCollections, { databaseExtensions: options.databaseExtensions });\n return diffPlanAgainstCatalogue(plan, existing, { constraints: options.constraints });\n}\n\nexport interface ReadSchemaOptions {\n /**\n * The existing tables worth probing for rows, given every table's columns.\n *\n * Whether a table holds rows decides one thing: whether a NOT NULL or a\n * UNIQUE can be added with a column *being added* to it. So the boot asks\n * only about tables gaining a column — none at all on a boot that changes\n * nothing — rather than probing every table in the schema, adopted and\n * unmanaged ones included, on every boot. A table that is not probed is\n * reported as holding rows: the answer that never plans a constraint that\n * could fail against data. Absent, every table is probed.\n */\n probeTables?: (tables: ReadonlyMap<string, ReadonlySet<string>>) => Iterable<string>;\n}\n\n/** Read what the database has, for the schemas the collections live in. */\nexport async function readExistingSchema(\n client: Queryable,\n schemas: string[],\n options: ReadSchemaOptions = {}\n): Promise<ExistingSchema> {\n const tables = new Map<string, Set<string>>();\n const enums = new Set<string>();\n if (schemas.length === 0) return { tables, enums };\n\n const inList = schemas\n .map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`)\n .join(\", \");\n\n const notNullColumns = new Set<string>();\n // `udt_name` rather than `data_type`: `data_type` collapses every array to\n // the literal string `ARRAY` and every extension type to `USER-DEFINED`,\n // which cannot be compared with anything. `udt_name` names the actual type\n // — `int4`, `jsonb`, `_numeric`, `vector` — which is what the drift check\n // needs.\n const columnTypes = new Map<string, string>();\n // A NOT NULL column that has a DEFAULT is not a problem for a write that\n // omits it, so orphan detection needs the default as well as the nullability\n // — otherwise every `created_at DEFAULT now()` on a table whose collection\n // does not declare it would be reported as a blocker.\n const columnDefaults = new Set<string>();\n const { rows: columns } = await client.query<{\n table_schema: string;\n table_name: string;\n column_name: string;\n is_nullable: string;\n udt_name: string | null;\n column_default: string | null;\n numeric_precision: number | null;\n numeric_scale: number | null;\n }>(\n // `numeric_precision`/`numeric_scale` because `udt_name` is `numeric`\n // for both `NUMERIC` and `NUMERIC(10, 2)`, and a property that declares\n // a precision means it: money stored in an unbounded column keeps the\n // third decimal the rounding was supposed to remove. Only carried for\n // `numeric`, where the modifier changes what a value *is*; a `varchar`\n // width is a limit on the same family and `typesAgree` ignores it.\n `SELECT table_schema, table_name, column_name, is_nullable, udt_name, column_default,\n numeric_precision, numeric_scale\n FROM information_schema.columns\n WHERE table_schema IN (${inList})`\n );\n for (const row of columns) {\n const key = `${row.table_schema}.${row.table_name}`;\n if (!tables.has(key)) tables.set(key, new Set());\n tables.get(key)!.add(row.column_name);\n if (row.is_nullable === \"NO\") notNullColumns.add(`${key}.${row.column_name}`);\n if (row.udt_name) {\n const modifier = row.udt_name === \"numeric\" && row.numeric_precision !== null\n ? `(${row.numeric_precision},${row.numeric_scale ?? 0})`\n : \"\";\n columnTypes.set(`${key}.${row.column_name}`, `${row.udt_name}${modifier}`);\n }\n if (row.column_default !== null) columnDefaults.add(`${key}.${row.column_name}`);\n }\n\n // Trigger names, so `autoValue: \"on_update\"` is installed once rather than\n // re-issued on every boot. `tgisinternal` excludes the ones Postgres itself\n // creates to enforce foreign keys.\n // Each one is recorded twice: by name, and by name with its arguments\n // (`…name(a,b)`), which is how a `keep-tenant` binding whose bypass roles\n // changed is told apart from the current one.\n const triggers = new Set<string>();\n const { rows: triggerRows } = await client.query<{ schema: string; table: string; name: string; args: string | null }>(\n `SELECT n.nspname AS schema, c.relname AS table, t.tgname AS name,\n encode(t.tgargs, 'escape') AS args\n FROM pg_trigger t\n JOIN pg_class c ON t.tgrelid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE NOT t.tgisinternal AND n.nspname IN (${inList})`\n );\n for (const row of triggerRows) {\n const key = `${row.schema}.${row.table}.${row.name}`;\n triggers.add(key);\n triggers.add(triggerArgumentsKey(key, (row.args ?? \"\").split(\"\\\\000\").slice(0, -1)));\n }\n\n // Which tables hold rows. This is the only fact that decides whether a\n // NOT NULL can be added without reading the data, so it is worth a query.\n //\n // `reltuples` would be cheaper and is wrong for this: it is a planner\n // estimate, it is -1 on a table that has never been analyzed, and a table\n // that was full an hour ago still reads as full after a DELETE. A wrong\n // \"empty\" here means a boot that aborts on a constraint violation, so the\n // estimate is not good enough. `EXISTS … LIMIT 1` stops at the first row,\n // which makes the true cost one page read per table.\n //\n // Restricted to ordinary and partitioned tables: `information_schema.columns`\n // also lists views and materialized views, and probing those runs whatever\n // query defines them.\n //\n // Indexes come back from the same read: an index already in the catalogue\n // under its planned name is not planned again (see `diffPlanAgainstCatalogue`).\n const populatedTables = new Set<string>();\n const indexes = new Set<string>();\n const { rows: relations } = await client.query<{ schema: string; name: string; kind: string }>(\n `SELECT n.nspname AS schema, c.relname AS name, c.relkind::text AS kind\n FROM pg_class c\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE c.relkind IN ('r', 'p', 'i', 'I') AND n.nspname IN (${inList})`\n );\n const allRealTables = relations.filter(row => row.kind === \"r\" || row.kind === \"p\");\n for (const row of relations) {\n if (row.kind === \"i\" || row.kind === \"I\") indexes.add(`${row.schema}.${row.name}`);\n }\n // Only the tables the caller will ask about; every other one reads as\n // holding rows — see `ReadSchemaOptions.probeTables`.\n const wanted = options.probeTables ? new Set(options.probeTables(tables)) : undefined;\n const realTables = wanted\n ? allRealTables.filter(row => wanted.has(`${row.schema}.${row.name}`))\n : allRealTables;\n if (wanted) {\n for (const row of allRealTables) {\n const key = `${row.schema}.${row.name}`;\n if (!wanted.has(key)) populatedTables.add(key);\n }\n }\n // The names come from `pg_class`, not from the configuration, so on an\n // adopted database they include tables nobody declared — `2024_archive`,\n // `order-items`, `Sales Data`. Those are quoted, not refused: refusing a\n // name here refuses the boot over a table Rebase will never touch.\n if (realTables.length > 0) {\n const probes = realTables.map(row =>\n `SELECT ${quoteSqlLiteral(`${row.schema}.${row.name}`)} AS key, ` +\n `EXISTS(SELECT 1 FROM ${quoteRelation(row.schema, row.name)} LIMIT 1) AS populated`\n );\n const { rows: populationRows } = await client.query<{ key: string; populated: boolean }>(\n probes.join(\" UNION ALL \")\n );\n for (const row of populationRows) {\n if (row.populated) populatedTables.add(row.key);\n }\n }\n\n const enumValues = new Map<string, string[]>();\n const { rows: enumValueRows } = await client.query<{\n schema: string;\n name: string;\n value: string;\n }>(\n // Ordered by `enumsortorder`, not by label: an enum's order is part of\n // its meaning (it is what `<` compares), and reading it back sorted\n // alphabetically would make a correct type look drifted.\n `SELECT n.nspname AS schema, t.typname AS name, e.enumlabel AS value\n FROM pg_enum e\n JOIN pg_type t ON e.enumtypid = t.oid\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname IN (${inList})\n ORDER BY t.typname, e.enumsortorder`\n );\n for (const row of enumValueRows) {\n const key = `${row.schema}.${row.name}`;\n if (!enumValues.has(key)) enumValues.set(key, []);\n enumValues.get(key)!.push(row.value);\n }\n\n const { rows: enumRows } = await client.query<{ schema: string; name: string }>(\n `SELECT n.nspname AS schema, t.typname AS name\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE t.typtype = 'e' AND n.nspname IN (${inList})`\n );\n for (const row of enumRows) enums.add(`${row.schema}.${row.name}`);\n\n // `ADD CONSTRAINT` has no IF NOT EXISTS, so an existing foreign key is\n // skipped by name rather than guarded in SQL.\n const constraints = new Set<string>();\n const { rows: constraintRows } = await client.query<{\n schema: string;\n table: string;\n name: string;\n }>(\n `SELECT n.nspname AS schema, c.relname AS table, con.conname AS name\n FROM pg_constraint con\n JOIN pg_class c ON con.conrelid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE n.nspname IN (${inList})`\n );\n for (const row of constraintRows) constraints.add(`${row.schema}.${row.table}.${row.name}`);\n\n // Indexes a `CREATE INDEX CONCURRENTLY` left INVALID. They are in\n // `indexes` under their name, so without this a husk reads as built and\n // `IF NOT EXISTS` keeps skipping it — see `deferred-index-build`.\n const invalidIndexes = new Set<string>();\n const { rows: invalidRows } = await client.query<{ schema: string; name: string }>(\n `SELECT n.nspname AS schema, c.relname AS name\n FROM pg_index i\n JOIN pg_class c ON c.oid = i.indexrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE NOT i.indisvalid AND n.nspname IN (${inList})`\n );\n for (const row of invalidRows) invalidIndexes.add(`${row.schema}.${row.name}`);\n\n // Column comments, which is where a generated search column records the\n // expression it was built from. `objsubid > 0` is what makes a row a\n // *column* comment rather than the table's own.\n const columnComments = new Map<string, string>();\n const { rows: commentRows } = await client.query<{\n schema: string;\n table: string;\n column: string;\n comment: string | null;\n }>(\n `SELECT n.nspname AS schema, c.relname AS table, a.attname AS column, d.description AS comment\n FROM pg_description d\n JOIN pg_class c ON d.objoid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = d.objsubid\n WHERE d.objsubid > 0 AND n.nspname IN (${inList})`\n );\n for (const row of commentRows) {\n if (row.comment == null) continue;\n columnComments.set(`${row.schema}.${row.table}.${row.column}`, row.comment);\n }\n\n // The helper functions the plan `CREATE OR REPLACE`s, as the catalogue has\n // them, so an unchanged one is not rewritten on every boot. Looked up by\n // qualified name rather than by the schemas read above: `set_updated_at`\n // lives in `rebase`, which is auth's schema and not in that list.\n const functions = new Map<string, string>();\n const helperNames = HELPER_FUNCTIONS\n .map(qualified => qualified.split(\".\"))\n .map(([schema, name]) => `(${quoteSqlLiteral(schema)}, ${quoteSqlLiteral(name)})`)\n .join(\", \");\n const { rows: functionRows } = await client.query<{\n schema: string;\n name: string;\n args: string;\n returns: string;\n language: string;\n volatility: string;\n strict: boolean;\n parallel: string;\n security_definer: boolean;\n leakproof: boolean;\n cost: number | string;\n has_config: boolean;\n body: string;\n }>(\n `SELECT n.nspname AS schema, p.proname AS name, pg_get_function_identity_arguments(p.oid) AS args,\n format_type(p.prorettype, NULL) AS returns, l.lanname AS language,\n p.provolatile::text AS volatility, p.proisstrict AS strict, p.proparallel::text AS parallel,\n p.prosecdef AS security_definer, p.proleakproof AS leakproof, p.procost AS cost,\n p.proconfig IS NOT NULL AS has_config, p.prosrc AS body\n FROM pg_proc p\n JOIN pg_namespace n ON p.pronamespace = n.oid\n JOIN pg_language l ON p.prolang = l.oid\n WHERE (n.nspname, p.proname) IN (${helperNames})`\n );\n for (const row of functionRows) {\n functions.set(helperFunctionKey(row.schema, row.name, row.args), describeHelperFunction({\n returns: row.returns,\n language: row.language,\n volatility: row.volatility,\n strict: row.strict,\n parallel: row.parallel,\n securityDefiner: row.security_definer,\n leakproof: row.leakproof,\n cost: Number(row.cost),\n hasConfig: row.has_config,\n body: row.body\n }));\n }\n\n const extensions = new Set<string>();\n const { rows: extensionRows } = await client.query<{ name: string }>(\"SELECT extname AS name FROM pg_extension\");\n for (const row of extensionRows) extensions.add(row.name);\n\n return {\n tables, enums, constraints, columnComments, enumValues, notNullColumns, populatedTables, columnTypes,\n columnDefaults, triggers, indexes, invalidIndexes, extensions, functions\n };\n}\n\n/**\n * The planned tables that exist and lack at least one planned column — the\n * only ones whose emptiness the diff consults (a NOT NULL or UNIQUE arriving\n * with a new column). A superset, never a subset: a column the plan renames\n * from a legacy name reads as missing here too.\n */\nfunction tablesGainingColumns(plan: SchemaPlan, catalogue: ReadonlyMap<string, ReadonlySet<string>>): string[] {\n const gaining: string[] = [];\n for (const table of plan.tables) {\n const columns = catalogue.get(table.qualified);\n if (columns && table.columns.some(column => !columns.has(column.column))) gaining.push(table.qualified);\n }\n return gaining;\n}\n\n/**\n * What to tell an operator whose `search` block no longer matches its column.\n *\n * Every line here is doing work: naming the collection is not enough, because\n * the symptom (a search that finds nothing) points at the data, not the schema;\n * and the remediation has to be exact, because it is a table rewrite the\n * operator is being asked to schedule rather than discover.\n */\nfunction searchDriftMessage(drift: SearchColumnDrift[]): string {\n const blocks = drift.map(d =>\n ` \"${d.table}\".\"${d.column}\" was generated from a different \\`search\\` block ` +\n `(recorded ${d.found}, current ${d.expected}).\\n` +\n d.rebuild.map(s => ` ${s}`).join(\"\\n\")\n );\n return (\n \"The `search` block changed after its generated column was created, and Postgres cannot alter a \" +\n \"generated expression in place.\\n\" +\n \"Rebase will not rebuild it for you: dropping and re-adding a STORED generated column rewrites the whole \" +\n \"table under an ACCESS EXCLUSIVE lock and rebuilds its GIN index, which is an outage this unattended path \" +\n \"may not schedule on your behalf.\\n\" +\n \"Until it is rebuilt the column keeps indexing the previous fields, weights and language — searches for \" +\n \"anything added since return nothing, which reads from outside as \\\"no such row\\\".\\n\" +\n \"Run these (or revert the block to what the column was built from), then boot again:\\n\" +\n blocks.join(\"\\n\") +\n \"\\n The GIN index is dropped with the column and recreated concurrently on the next boot.\"\n );\n}\n\n\n/**\n * Read what the database looks like, for the schemas a set of collections\n * lives in.\n *\n * The same read `ensureCollectionTables` does at boot, exposed on its own for\n * the callers that want to *plan* against a real database without changing it —\n * the live schema editor, which has to tell somebody what a change would do\n * before they agree to it.\n */\nexport async function readSchemaFactsFor(\n client: Queryable,\n collections: CollectionConfig[]\n): Promise<ExistingSchema> {\n const relational = relationalCollections(collections);\n const junctions = planJunctionTables(relational);\n const schemas = Array.from(new Set([\n ...relational.map(schemaOf),\n ...junctions.map(junction => junction.schema)\n ]));\n // Row probes for the declared tables only: the classifier asks about the\n // collections it is given, never about a table nobody declared.\n const declared = [\n ...relational.map(collection => `${schemaOf(collection)}.${getTableName(collection)}`),\n ...junctions.map(junction => `${junction.schema}.${junction.table}`)\n ];\n return readExistingSchema(client, schemas, { probeTables: () => declared });\n}\n\n/**\n * Bring the database up to date. Returns what it did.\n *\n * Each statement runs on its own rather than in one transaction: they are all\n * independently safe and idempotent, and a single failure (an enum label that\n * cannot be added, say) should not roll back the tables that were created fine.\n * The error is surfaced with the statement that caused it.\n */\nexport async function ensureCollectionTables(\n client: Queryable,\n collections: CollectionConfig[],\n log?: (message: string) => void,\n options: EnsureOptions = {}\n): Promise<EnsureOutcome> {\n // This is the boundary, so this is where the world is read: the planner\n // itself takes the permission as an argument and never reaches for the\n // registry. By the time boot gets here `loadBundleResourceGraph` has\n // evaluated the project's `resources.ts`, so the declarations are there —\n // and a caller that already knows them can still say so.\n const schema = planSchema(collections, {\n databaseExtensions: options.databaseExtensions ?? declaredDatabaseExtensions()\n });\n\n // Junctions live alongside the collections that declare them, so their\n // schema has to be read too — otherwise an existing junction reads as\n // missing and its constraints as unplanned. Taken off the plan, which lists\n // both kinds of table.\n const schemas = Array.from(new Set(schema.tables.map(table => table.schema)));\n for (const name of schemas) {\n assertSafeIdentifier(name, \"schema name\");\n if (name !== \"public\") {\n await client.query(`CREATE SCHEMA IF NOT EXISTS \"${name}\";`);\n }\n }\n // `rebase` is where the `updated_at` trigger's function lives. Every real\n // boot has the schema by the time this runs (auth ensures it first) and\n // `db push` creates it in `schema.sql`, but this path is also driven by the\n // live schema editor and by tests, where \"the function's schema happens to\n // exist already\" is not a thing to rely on. Only when something needs it,\n // so a project with no trigger issues no statement — and not added to the\n // read set: what is *in* `rebase` is auth's business, not this planner's.\n if (schema.tables.some(table => table.triggers.length > 0)) {\n await client.query(`CREATE SCHEMA IF NOT EXISTS \"${REBASE_SCHEMA}\";`);\n }\n\n const existing = await readExistingSchema(client, schemas, {\n probeTables: catalogue => tablesGainingColumns(schema, catalogue)\n });\n // Every index on a table that already exists goes to the index builder,\n // which this function runs or hands to the caller — see `buildIndexes`.\n const plan = diffPlanAgainstCatalogue(schema, existing, { constraints: options.constraints, deferLiveIndexes: true });\n const failures: EnsureOutcome[\"failures\"] = [];\n\n // Reported, not warned: this is a rename the ensure is about to perform, and\n // the operator should be able to see in the log why a column changed name.\n // The interesting case is the one that no longer happens — before this,\n // ensure added the new column empty beside the populated old one, every\n // statement succeeded, and the relation read the empty one.\n for (const legacy of plan.legacyForeignKeys) {\n const message =\n `Renaming \"${legacy.table}\".\"${legacy.legacy}\" to \"${legacy.expected}\". The old name is ` +\n \"the one Rebase derived for this relation before it singularized properly; the column \" +\n \"keeps its data, indexes and constraints. To keep the old name instead, set \" +\n `\\`localKey: \"${legacy.legacy}\"\\` on the relation and this will stop.`;\n logger.info(`[schema] ${message}`);\n log?.(message);\n }\n\n // Before anything is applied: a `search` block that changed after its column\n // was generated cannot be honoured by an additive plan, and serving the old\n // index while the config describes a new one is the silent failure this\n // check exists to end. Refusing is the loud half — boot is fatal on purpose\n // (see `ensureCollectionSchema` in the server's boot) and the message\n // carries the exact statements that resolve it.\n if (plan.searchDrift.length > 0) {\n throw new Error(searchDriftMessage(plan.searchDrift));\n }\n\n // Said once per column, at the moment the stamp is applied: from here on a\n // change is detected, but whether *this* column matches the block it is\n // being stamped with is not knowable — it predates the stamp.\n for (const adopted of plan.searchAdopted) {\n const message =\n `Adopting the existing generated column \"${adopted.table}\".\"${adopted.column}\" and recording what the ` +\n \"current `search` block would generate. Any later change to that block will be detected and refused; a \" +\n \"change made *before* this version was deployed cannot be, so if search has been missing content, \" +\n `rebuild the column once: ALTER TABLE \"${adopted.table.split(\".\").join('\".\"')}\" DROP COLUMN \"${adopted.column}\"; and boot again.`;\n logger.info(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot: an unindexed vector column and an\n // indexed one behave identically apart from latency, so the only way anyone\n // learns which one they have is if the boot says so.\n for (const skip of plan.vectorIndexSkipped) {\n const message = `No ANN index on \"${skip.table}\".\"${skip.column}\": ${skip.reason}`;\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot, because the alternative is what this\n // whole feature exists to end: a column the configuration calls required,\n // sitting there nullable, with every surface reporting success. The boot\n // does not fail over it — the column is usable and the data is intact — but\n // it stops being invisible.\n for (const withheld of plan.withheldConstraints) {\n const message =\n `No ${withheld.kind === \"unique\" ? \"UNIQUE\" : \"NOT NULL\"} on \"${withheld.target}\": ` +\n `${withheld.reason} ${withheld.remedy}`;\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per drifted column, every boot, and this is the one report here\n // that describes a system which currently *looks* healthy. Everything else\n // in this function explains a statement that did not run; this explains a\n // statement that was never planned, on a deploy that reported success, and\n // whose first symptom is a write rejected long afterwards.\n for (const drift of plan.columnTypeDrift) {\n const message = columnTypeDriftMessage(drift);\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot, and it matters more than the rest here\n // because the table is not merely imperfect — it is unwritable, and the\n // error the API returns names a field the author has already deleted.\n // This is what a renamed property looks like to an additive provisioner.\n for (const orphan of plan.orphanedRequiredColumns) {\n const message =\n `\"${orphan.table}\".\"${orphan.column}\" is NOT NULL with no default, and the \"${orphan.slug}\" ` +\n \"collection no longer declares it. Every insert will be rejected for a field you cannot set \" +\n `(PG_23502, naming \"${orphan.column}\"). This is what a removed or renamed property looks like: ` +\n \"boot neither relaxes nor drops a column unattended. Fix it with ONE of (each shows the plan and asks):\\n\" +\n ` rebase schema reconcile -- keep the data, stop requiring it\\n` +\n ` rebase schema reconcile --drop ${orphan.slug}.${orphan.column} -- the column is no longer wanted\\n` +\n \" ...or declare the property again, if the column is still wanted.\";\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // The indexes of tables that already exist. Built here unless the caller\n // defers them — and a UNIQUE one is built here regardless, before this\n // returns, so nothing serves the collection without the promise it makes.\n const builtHere = options.deferIndexBuilds\n ? plan.deferredIndexes.filter(index => index.unique === true)\n : plan.deferredIndexes;\n const leftToCaller = options.deferIndexBuilds\n ? plan.deferredIndexes.filter(index => index.unique !== true)\n : plan.deferredIndexes;\n\n // After every action, so the columns they index exist — whether this run\n // added them or a previous one did.\n const buildIndexes = async (): Promise<DeferredIndexOutcome | undefined> => {\n if (builtHere.length === 0) return undefined;\n const outcome = await buildDeferredIndexes(\n options.openIndexBuildSession ?? (async () => ({\n query: <T>(sql: string) => client.query<T>(sql),\n dedicated: false,\n release: () => undefined\n })),\n builtHere,\n { log, lockTimeoutMs: options.lockTimeoutMs }\n );\n assertUniqueIndexesBuilt(builtHere, outcome);\n return outcome;\n };\n const finish = async (): Promise<EnsureOutcome> => {\n const indexBuilds = await buildIndexes();\n // Last: a view reads the tables everything above created. The block\n // creates a missing view, recreates one whose query changed and leaves\n // the rest alone (see `renderViewsDdl`).\n const views = renderViewsDdl(schema);\n if (views) {\n await client.query(views);\n log?.(`views: ${schema.views.map(view => view.qualified).join(\", \")}`);\n }\n return { ...plan, deferredIndexes: leftToCaller, failures, indexBuilds };\n };\n\n if (plan.actions.length === 0) {\n if (plan.deferredIndexes.length === 0) log?.(\"Schema is up to date; nothing to create.\");\n return finish();\n }\n\n const lockBudget = options.lockTimeoutMs !== undefined\n ? { lockTimeoutMs: options.lockTimeoutMs, atomic: true }\n : undefined;\n // Whether the handle takes a multi-statement string; shared with the lock\n // budget, which needs the same thing.\n const multi = lockBudget ?? { atomic: true };\n\n // A table this run creates has no rows, no readers and no writers, so its\n // statements — the CREATE, the ENABLE, every column, its triggers, the\n // indexes on it — can share a transaction: one commit instead of one per\n // statement. A first deploy of 200 collections was 3,767 autocommits, 11.7 s\n // on a disk that really flushes. If a batch fails for any reason, its\n // statements are applied again one at a time below, exactly as before, so\n // the races and survivable failures that path handles end the same way.\n const createdTables = new Set(plan.actions.filter(a => a.kind === \"create-table\").map(a => a.target));\n const batchable = (action: EnsureAction): boolean =>\n options.batchNewTables === true &&\n multi.atomic &&\n (action.kind === \"create-enum\" || createdTables.has(action.target.split(\".\").slice(0, 2).join(\".\"))) &&\n action.kind !== \"add-enum-value\" &&\n !CONCURRENTLY_RE.test(action.sql);\n\n const applyBatch = async (group: EnsureAction[]): Promise<boolean> => {\n const statements = group.map(action => action.sql);\n try {\n await client.query(lockBudget\n ? atomicBatch(statements, lockBudget.lockTimeoutMs)\n : joinStatements(statements));\n return true;\n } catch (err) {\n if (isMultiStatementRefusal(err)) {\n multi.atomic = false;\n } else {\n log?.(`${group.length} statement(s) for new tables failed as one transaction ` +\n `(${describeDriverError(err).split(\"\\n\")[0]}); applying them one at a time`);\n }\n return false;\n }\n };\n\n const applyOne = async (action: EnsureAction): Promise<void> => {\n try {\n if (await applyAction(client, action, lockBudget)) {\n log?.(`${action.kind}: ${action.target}`);\n } else {\n log?.(`${action.kind}: ${action.target} (already created by a peer)`);\n }\n } catch (err) {\n const message = describeDriverError(err);\n // A foreign key is the only action that can fail on the customer's\n // data rather than on the schema. The column it polices is already\n // there, so the collection serves either way — record it and carry\n // on rather than crash-looping the deployment.\n //\n // A comment is metadata about a column that was just created\n // successfully, and it can only fail on ownership (COMMENT requires\n // owning the table, which an adopted table may not grant). Losing\n // the stamp costs drift detection on the next boot; it must not cost\n // the deployment.\n //\n // An index that is not UNIQUE is an optimization, and losing an\n // optimization must not cost the deployment. This was the difference\n // between a slow collection and a tenant that would not boot: on a\n // managed runtime the throw killed the process, the pod never went\n // ready, and the deploy reported a 300-second readiness timeout — for\n // an ANN index whose absence changes latency and nothing else.\n //\n // UNIQUE is excluded because it is not an optimization. It is the\n // collection declaring that two rows cannot share a value, and\n // serving without it is serving a promise the database is not\n // keeping.\n const survivable =\n action.kind === \"add-constraint\" ||\n action.kind === \"comment-column\" ||\n (action.kind === \"create-index\" && !/CREATE\\s+UNIQUE\\s+INDEX/i.test(action.sql));\n if (survivable) {\n failures.push({ kind: action.kind, target: action.target, error: message });\n return;\n }\n const lockHint = isLockTimeout(err)\n ? \"\\n hint: another session held this table's lock for every attempt (a long transaction, a \" +\n \"report or a dump). Nothing was changed; boot again once it has finished.\"\n : \"\";\n throw new Error(\n `Failed to ${action.kind} ${action.target}: ${message}${vectorExtensionHint(message)}${lockHint}\\n ${action.sql}`\n );\n }\n };\n\n for (let i = 0; i < plan.actions.length;) {\n let end = i;\n while (end < plan.actions.length && end - i < NEW_TABLE_BATCH && batchable(plan.actions[end])) end++;\n if (end - i > 1 && await applyBatch(plan.actions.slice(i, end))) {\n for (const action of plan.actions.slice(i, end)) log?.(`${action.kind}: ${action.target}`);\n i = end;\n continue;\n }\n const last = Math.max(end, i + 1);\n for (; i < last; i++) await applyOne(plan.actions[i]);\n }\n return finish();\n}\n\n/**\n * Fail the ensure for a UNIQUE index on a live table that could not be built,\n * exactly as a failed UNIQUE `create-index` action always has (see `applyOne`).\n *\n * \"Another index on the table is being built\" counts: the table's lock is\n * held by a build that may run for minutes, and serving the collection\n * meanwhile would be serving a promise the database is not keeping. Another\n * instance building *this* index does not: once its build commits the\n * constraint holds, which is also what a peer's `IF NOT EXISTS` race meant.\n */\nfunction assertUniqueIndexesBuilt(indexes: readonly DeferredIndexBuild[], outcome: DeferredIndexOutcome): void {\n for (const index of indexes) {\n if (index.unique !== true) continue;\n const qualified = `${index.schema}.${index.indexName}`;\n const reason = outcome.failed.find(failure => failure.index === qualified)?.error\n ?? outcome.skipped.find(skip => skip.index === qualified && skip.reason === TABLE_BUSY_REASON)?.reason;\n if (reason === undefined) continue;\n throw new Error(`Failed to create-index ${index.schema}.${index.table}: ${qualified}: ${reason}\\n ${index.sql}`);\n }\n}\n\n/**\n * What actually went wrong, rather than what the ORM said about it.\n *\n * Drizzle wraps every driver error, and its `message` is literally\n * ``Failed query: ${sql}\\nparams: ${params}`` — the statement we already know,\n * and not one word of Postgres's answer. Reporting `err.message` therefore\n * produced a failure that named the statement twice and the *reason* zero\n * times, so four unrelated boot failures — a missing extension, a wrong\n * privilege, a bad index method, a constraint the rows violate — all read\n * identically to whoever had to fix them.\n *\n * Two consequences, both observed in the field before this existed:\n *\n * 1. On a managed deployment the reason never reaches anybody. Boot dies, the\n * pod never goes ready, and the deploy reports a readiness timeout — so the\n * one line that says why is the one line that was thrown away here.\n * 2. {@link vectorExtensionHint} matches on the error text. Against the\n * wrapper it matched nothing, so the hint written specifically to explain a\n * missing pgvector never fired on the path that raises it.\n *\n * `detail` and `hint` come along because they are the fields Postgres uses to\n * say which object it meant and what to do about it — `CREATE EXTENSION` names\n * the missing library there, and a rejected constraint names the row. This\n * writes into the tenant's own boot log, about the tenant's own database.\n */\nexport function describeDriverError(err: unknown): string {\n const pg = extractPgError(err);\n if (pg) {\n const parts = [pg.code ? `${pg.message} [${pg.code}]` : pg.message];\n if (pg.detail) parts.push(` detail: ${pg.detail}`);\n if (pg.hint) parts.push(` hint: ${pg.hint}`);\n return parts.join(\"\\n\");\n }\n // No SQLSTATE anywhere in the chain: not a database answer at all — a\n // socket that closed, a bug in this file. The deepest cause still beats the\n // wrapper, and the wrapper still beats nothing.\n const cause = extractCauseMessage(err);\n if (cause) return cause;\n return err instanceof Error ? err.message : String(err);\n}\n\n/** ` CONCURRENTLY ` as it appears in a rendered `CREATE [UNIQUE] INDEX`. */\nconst CONCURRENTLY_RE = /\\sCONCURRENTLY\\s/i;\n\n/**\n * `25001 active_sql_transaction` — \"cannot run inside a transaction block\".\n *\n * Only ever raised here by `CREATE INDEX CONCURRENTLY`, and only when the\n * connection we were handed is inside a transaction. Deliberately narrow: it\n * decides to retry a *different* statement, so it must not fire on anything it\n * has not been reasoned about.\n */\nfunction isTransactionBlockRefusal(err: unknown): boolean {\n return extractPgError(err)?.code === \"25001\";\n}\n\n/** Attempts per action, including the first. Matches the server's bootstraps. */\nconst DDL_ATTEMPTS = 4;\n\n/**\n * Attempts at an action whose table lock is held, including the first.\n *\n * Unlike a policy, a schema change cannot be deferred — the collection's code\n * expects the column — so a lock that never frees still fails the boot, as a\n * statement timeout did. Ten one-second attempts with backoff between them wait\n * about as long as the old 30 s statement timeout did, but a live query on that\n * table now waits at most one second at a time instead of thirty.\n */\nconst LOCK_ATTEMPTS = 10;\n\n/**\n * Whether an action may be sent as `SET LOCAL lock_timeout; <statement>` — one\n * implicit transaction. Not `CREATE INDEX CONCURRENTLY`, which Postgres refuses\n * inside any transaction block (and which waits on no lock a reader holds), and\n * not `ALTER TYPE … ADD VALUE`, which Postgres before 12 refuses there too and\n * which locks a type, not a table.\n */\nconst takesLockBudget = (action: EnsureAction, sql: string): boolean =>\n action.kind !== \"add-enum-value\" && !CONCURRENTLY_RE.test(sql);\n\n/**\n * Run one planned statement, surviving a simultaneous boot.\n *\n * Every statement in a plan is written to be idempotent, and that is not the\n * same as being safe to run concurrently: `CREATE … IF NOT EXISTS` reads the\n * catalog and then writes to it as two steps, so peers starting together both\n * see \"absent\" and the loser gets a duplicate key on a *catalog* index. Measured\n * against Postgres 18: five instances, 8 of 10 calls lost. `CREATE TYPE` is\n * worse, because Postgres has no `IF NOT EXISTS` for it at all.\n *\n * What made that fatal here rather than merely noisy is the loop this sits in.\n * A losing statement threw, and the throw abandoned **every remaining action in\n * the plan** — so a replica that lost one race came up missing tables it never\n * attempted, and the boot log blamed the one statement that failed.\n *\n * @returns `true` if this process applied the statement, `false` if a peer had\n * already created the object. The distinction is only for the log; both mean\n * the object is now there.\n * @throws the original error for anything that is not a race — a syntax error, a\n * permission failure, a unique constraint the customer's own rows violate.\n */\nasync function applyAction(\n client: Queryable,\n action: EnsureAction,\n lockBudget?: { lockTimeoutMs: number; atomic: boolean }\n): Promise<boolean> {\n let sqlText = action.sql;\n let lockAttempts = 0;\n for (let attempt = 1; ; attempt++) {\n const budgeted = lockBudget?.atomic === true && takesLockBudget(action, sqlText);\n try {\n await client.query(budgeted ? atomicBatch([sqlText], lockBudget.lockTimeoutMs) : sqlText);\n return true;\n } catch (err) {\n // A handle that takes one statement per query (extended protocol)\n // cannot carry the `SET LOCAL`. Nothing ran; say it once and send\n // every statement as it is from here on.\n if (budgeted && isMultiStatementRefusal(err)) {\n lockBudget.atomic = false;\n attempt--;\n continue;\n }\n // Something held the table for longer than the budget — a long\n // transaction, a report, a dump. The statement did nothing; let\n // the queue behind it drain, then ask again.\n if (budgeted && isLockTimeout(err) && ++lockAttempts < LOCK_ATTEMPTS) {\n logger.debug(\n `[schema] ${action.kind} ${action.target}: the table's lock is held by another session ` +\n `(attempt ${lockAttempts}/${LOCK_ATTEMPTS}) — retrying`\n );\n attempt--;\n await sleep(Math.min(500 * lockAttempts, 2_000) * (1 + Math.random()));\n continue;\n }\n // `CREATE INDEX CONCURRENTLY` is the one statement here Postgres\n // refuses inside a transaction block (25001), and whether we are in\n // one is not ours to know: the client is whatever handle the caller\n // bootstrapped with, and an application that builds its own adapter\n // can hand us a connection already inside a transaction. The plain\n // form is always correct and never refused — it takes a write lock\n // for the build, which is the cost of getting the index at all.\n if (isTransactionBlockRefusal(err) && CONCURRENTLY_RE.test(sqlText)) {\n sqlText = sqlText.replace(CONCURRENTLY_RE, \" \");\n logger.warn(\n `[schema] ${action.kind} ${action.target}: this connection is inside a transaction, ` +\n \"so the index is being built with a write lock rather than concurrently. Writes to \" +\n \"this table block until it finishes.\"\n );\n continue;\n }\n // Already there. Not \"retry\" — the end state this statement wanted\n // is the end state the database is in, so carry on to the next\n // action rather than spending three more attempts proving it.\n if (isDuplicateObjectRace(err)) {\n logger.debug(\n `[schema] ${action.kind} ${action.target}: already created by another instance`\n );\n return false;\n }\n // Retryable but not yet satisfied — a deadlock between two boots\n // taking catalog locks in step. The statement did nothing; run it\n // again after a jittered pause so peers that collided once do not\n // collide again in lockstep.\n if (isConcurrentDdlRace(err) && attempt < DDL_ATTEMPTS) {\n logger.debug(\n `[schema] ${action.kind} ${action.target}: lost a race with another instance ` +\n `(attempt ${attempt}/${DDL_ATTEMPTS}) — retrying`\n );\n await new Promise(resolve => setTimeout(resolve, 40 * attempt * (1 + Math.random())));\n continue;\n }\n throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4IA,IAAM,kBAAkB;;A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KAAK,GAAG,OAAO,OAAO,iKAG7C;IACA;GACJ;GAIA,IAAI,sBAAsB,GAAG,GAAG;IAC5B,OAAO,MACH,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,sCAC7C;IACA,OAAO;GACX;GAKA,IAAI,oBAAoB,GAAG,KAAK,UAAU,cAAc;IACpD,OAAO,MACH,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,+CAC7B,QAAQ,GAAG,aAAa,aACxC;IACA,MAAM,IAAI,SAAQ,YAAW,WAAW,SAAS,KAAK,WAAW,IAAI,KAAK,OAAO,EAAE,CAAC;IACpF;GACJ;GACA,MAAM;EACV;CACJ;AACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ensure-tables-Dh5UP_Zs.js","names":[],"sources":["../src/auth/schema-version.ts","../src/auth/ensure-tables.ts"],"sourcesContent":["import { sql } from \"drizzle-orm\";\nimport { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport type { CollectionConfig } from \"@rebasepro/types\";\n\n/**\n * The auth schema version this runtime expects to find in the database.\n *\n * Bump this whenever a migration in `ensureAuthTablesExist` makes the schema\n * unreadable by the runtime that came before it — that is, whenever a *previous*\n * version's auth queries would break against the migrated shape. Additive\n * changes (a new nullable column nobody older references) do not need a bump.\n *\n * History. Note that 1 is a label for an era, not a value any database holds:\n * stamping did not exist then, so an era-1 database reads as unstamped\n * (`null`), and 2 is the first version ever actually written. The numbering\n * starts at 2 only because two schema eras already existed when it was\n * introduced; it could just as well have started at 1. It is not worth\n * renumbering now — deployed databases already carry 2, and lowering the\n * constant would make them look newer than the runtime and refuse the boot.\n *\n * 1 — Device-session refresh tokens. A row *was* a session, identified by\n * `unique_device_session UNIQUE (uid, user_agent, ip_address)`, and\n * `createToken` upserted with `ON CONFLICT (uid, user_agent, ip_address)`.\n * 2 — Session-scoped, rotation-safe refresh tokens: `session_id`, `revoked`,\n * `rotated_at`, `session_started_at`, and `unique_device_session`\n * dropped because two live tokens of one session share all three columns.\n *\n * The 1 → 2 migration is why this file exists. Dropping the constraint is\n * one-way: a version-1 runtime deployed afterwards boots perfectly, logs\n * `✅ Auth tables ready` (its `CREATE TABLE IF NOT EXISTS` never revisits the\n * existing table, so it cannot re-add the constraint), answers `/health` with\n * 200 — and then fails every single login and refresh with SQLSTATE 42P10,\n * because its `ON CONFLICT` names a constraint that no longer exists. A silent\n * total auth outage behind a green health check. The stamp below turns that\n * into a boot refusal.\n */\nexport const AUTH_SCHEMA_VERSION = 2;\n\n/** Key under which the version is stored in the auth schema's meta table. */\nconst VERSION_KEY = \"auth_schema_version\";\n\n/**\n * Columns `refresh_tokens` must have for the current runtime's auth write path\n * to work. Checked by the health probe so a database that drifted *below* this\n * runtime is reported as unhealthy rather than discovered one failed login at a\n * time. Kept in step with the migration in `ensureAuthTablesExist`.\n */\nconst REQUIRED_REFRESH_TOKEN_COLUMNS = [\"session_id\", \"revoked\", \"rotated_at\", \"session_started_at\"];\n\n/**\n * A constraint whose *presence* means the database is still at version 1, in a\n * shape this runtime's rotation logic cannot write to: it makes two live tokens\n * of one rotating session collide.\n */\nconst RETIRED_REFRESH_TOKEN_CONSTRAINT = \"unique_device_session\";\n\n/**\n * Thrown when the database was migrated by a runtime newer than this one.\n *\n * Distinct class rather than a bare `Error` because `ensureAuthTablesExist`\n * wraps its migrations in a catch that deliberately swallows failures and\n * continues — every other problem there is better survived than crashed on.\n * This one is not, so the catch rethrows on this type specifically.\n */\nexport class AuthSchemaVersionError extends Error {\n readonly databaseVersion: number;\n readonly runtimeVersion: number;\n\n constructor(databaseVersion: number, runtimeVersion: number) {\n super(\n `Auth schema version mismatch: the database is at version ${databaseVersion}, ` +\n `but this runtime understands version ${runtimeVersion}.\\n\\n` +\n \"A newer version of the framework has already migrated this database. Running this \" +\n \"older runtime against it would boot cleanly and then fail every login and token \" +\n \"refresh, because the auth schema it expects no longer exists.\\n\\n\" +\n \"Refusing to start. Deploy a framework version at or above the one that migrated \" +\n \"this database, or restore the database from a backup taken before the upgrade.\"\n );\n this.name = \"AuthSchemaVersionError\";\n this.databaseVersion = databaseVersion;\n this.runtimeVersion = runtimeVersion;\n }\n}\n\n/**\n * The schema the auth tables live in, derived exactly as `ensureAuthTablesExist`\n * derives it. Shared so the two cannot drift: a stamp written to one schema and\n * read from another would read as \"never stamped\" forever.\n */\nexport function resolveAuthSchema(collection?: CollectionConfig): string {\n if (!collection) return \"rebase\";\n const usersSchema = (\"schema\" in collection && typeof collection.schema === \"string\")\n ? collection.schema\n : \"public\";\n return usersSchema === \"public\" ? \"rebase\" : usersSchema;\n}\n\n/**\n * Read the stamped version, or `null` when the database has never been stamped.\n *\n * `null` is not an error and must not be treated as one: every database\n * provisioned before this file existed is unstamped, and so is every fresh one.\n * Uses `to_regclass` rather than selecting straight from the table so a missing\n * schema or table is a `null` rather than a thrown 42P01.\n */\nexport async function readAuthSchemaVersion(\n db: NodePgDatabase,\n authSchema: string\n): Promise<number | null> {\n const qualified = `\"${authSchema}\".\"schema_meta\"`;\n const exists = await db.execute(sql`SELECT to_regclass(${qualified}) IS NOT NULL AS present`);\n if (!(exists.rows[0] as { present: boolean } | undefined)?.present) return null;\n\n const result = await db.execute(sql`\n SELECT value FROM ${sql.raw(qualified)} WHERE key = ${VERSION_KEY}\n `);\n const raw = (result.rows[0] as { value: string } | undefined)?.value;\n if (raw === undefined) return null;\n\n const parsed = Number.parseInt(raw, 10);\n // A meta row we cannot parse is treated as unstamped rather than as version\n // 0: refusing to boot over a garbled string would be a worse failure than\n // the drift it is meant to catch.\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/**\n * Refuse to run against a database a newer runtime has already migrated.\n *\n * Deliberately one-directional. A database *older* than this runtime is the\n * normal upgrade path — the migrations in `ensureAuthTablesExist` are about to\n * bring it forward, so it is not an error. Only the reverse is unrecoverable.\n */\nexport async function assertAuthSchemaCompatible(\n db: NodePgDatabase,\n authSchema: string\n): Promise<void> {\n const databaseVersion = await readAuthSchemaVersion(db, authSchema);\n if (databaseVersion !== null && databaseVersion > AUTH_SCHEMA_VERSION) {\n throw new AuthSchemaVersionError(databaseVersion, AUTH_SCHEMA_VERSION);\n }\n}\n\n/**\n * Record that this runtime's migrations have been applied.\n *\n * Called at the end of `ensureAuthTablesExist`, so a boot that failed partway\n * through leaves the older stamp in place and the next boot migrates again.\n */\nexport async function stampAuthSchemaVersion(\n db: NodePgDatabase,\n authSchema: string\n): Promise<void> {\n const qualified = `\"${authSchema}\".\"schema_meta\"`;\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS ${sql.raw(qualified)} (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL,\n updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL\n )\n `);\n await db.execute(sql`\n INSERT INTO ${sql.raw(qualified)} (key, value)\n VALUES (${VERSION_KEY}, ${String(AUTH_SCHEMA_VERSION)})\n ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()\n `);\n}\n\n/** What {@link probeAuthSchema} found. */\nexport interface AuthSchemaProbeResult {\n /** False when this runtime cannot be trusted to serve auth against this database. */\n healthy: boolean;\n /** The stamped version, or `null` on a database that predates stamping. */\n databaseVersion: number | null;\n /** {@link AUTH_SCHEMA_VERSION}. */\n runtimeVersion: number;\n /** Human-readable descriptions of each mismatch found. Empty when healthy. */\n problems: string[];\n}\n\n/**\n * Check that the auth schema is one this runtime can actually write to.\n *\n * Two independent checks, because either alone has a blind spot:\n *\n * - The **stamp** catches a runtime older than the database. It is the precise\n * signal, but it is blind on every database provisioned before stamping\n * existed — which today is all of them.\n * - The **structure** catches a database older than the runtime, and works on\n * unstamped databases. It is what makes this useful immediately rather than\n * one upgrade cycle from now.\n *\n * Never throws: a probe that fails to run reports unhealthy with the reason, so\n * a broken check surfaces as a degraded health response rather than a 500 from\n * the health endpoint itself.\n */\nexport async function probeAuthSchema(\n db: NodePgDatabase,\n authSchema: string\n): Promise<AuthSchemaProbeResult> {\n const problems: string[] = [];\n let databaseVersion: number | null = null;\n\n try {\n databaseVersion = await readAuthSchemaVersion(db, authSchema);\n if (databaseVersion !== null && databaseVersion > AUTH_SCHEMA_VERSION) {\n problems.push(\n `database is at auth schema version ${databaseVersion}, this runtime understands ` +\n `${AUTH_SCHEMA_VERSION} — it was migrated by a newer framework version`\n );\n }\n\n const refreshTokens = `\"${authSchema}\".\"refresh_tokens\"`;\n const present = await db.execute(sql`SELECT to_regclass(${refreshTokens}) IS NOT NULL AS present`);\n if (!(present.rows[0] as { present: boolean } | undefined)?.present) {\n // Not a problem in itself: auth may simply not be configured on this\n // deployment, and the table is created on demand at boot when it is.\n return { healthy: problems.length === 0, databaseVersion, runtimeVersion: AUTH_SCHEMA_VERSION, problems };\n }\n\n const columns = await db.execute(sql`\n SELECT column_name FROM information_schema.columns\n WHERE table_schema = ${authSchema} AND table_name = 'refresh_tokens'\n `);\n const found = new Set((columns.rows as { column_name: string }[]).map(row => row.column_name));\n const missing = REQUIRED_REFRESH_TOKEN_COLUMNS.filter(column => !found.has(column));\n if (missing.length > 0) {\n problems.push(\n `refresh_tokens is missing ${missing.join(\", \")} — the auth migrations have not been ` +\n \"applied to this database, so token rotation will fail\"\n );\n }\n\n const retired = await db.execute(sql`\n SELECT 1 FROM pg_constraint c\n JOIN pg_class t ON t.oid = c.conrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE n.nspname = ${authSchema}\n AND t.relname = 'refresh_tokens'\n AND c.conname = ${RETIRED_REFRESH_TOKEN_CONSTRAINT}\n `);\n if (retired.rows.length > 0) {\n problems.push(\n `refresh_tokens still carries ${RETIRED_REFRESH_TOKEN_CONSTRAINT} — concurrent token ` +\n \"rotation for one session will fail on it\"\n );\n }\n } catch (error: unknown) {\n problems.push(\n `auth schema probe failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n return {\n healthy: problems.length === 0,\n databaseVersion,\n runtimeVersion: AUTH_SCHEMA_VERSION,\n problems\n };\n}\n","import { sql } from \"drizzle-orm\";\nimport { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\nimport { revokeInternalTableAccess } from \"@rebasepro/common\";\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport { AUTH_USERS_COLUMNS, authUsersColumnSql } from \"../schema/auth-users-columns\";\nimport { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } from \"../schema/rls-bootstrap-sql\";\nimport { internalTablesGrantedToUserRole } from \"../security/rls-enforcement\";\nimport { BOOT_LOCK_TIMEOUT_MS } from \"../schema/boot-ddl\";\nimport {\n AuthSchemaVersionError,\n assertAuthSchemaCompatible,\n resolveAuthSchema,\n stampAuthSchemaVersion\n} from \"./schema-version\";\n\n\n/** A string literal for a catalogue lookup. The names come from config, never from a request. */\nconst literal = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\n\n/**\n * Every index name in these schemas, as `schema.name`.\n *\n * `CREATE INDEX IF NOT EXISTS` is not free when the index exists: Postgres\n * takes the table's SHARE lock — which blocks writers, and queues behind any\n * open write transaction — before it looks the name up. So the names are read\n * once and only a missing index is created. Read before anything is created:\n * this function never drops an index, so present then means present now.\n */\nasync function readIndexNames(db: NodePgDatabase, schemas: string[]): Promise<Set<string>> {\n const names = new Set<string>();\n const list = [...new Set(schemas)];\n if (list.length === 0) return names;\n const result = await db.execute(sql.raw(\n \"SELECT n.nspname AS schema, c.relname AS name FROM pg_class c \" +\n \"JOIN pg_namespace n ON n.oid = c.relnamespace \" +\n `WHERE c.relkind IN ('i', 'I') AND n.nspname IN (${list.map(literal).join(\", \")})`\n ));\n for (const row of result.rows as { schema: string; name: string }[]) names.add(`${row.schema}.${row.name}`);\n return names;\n}\n\n/**\n * A column default as `information_schema` reports it, reduced to what decides\n * equality: `(gen_random_uuid())::text` and `gen_random_uuid()::text` are the\n * same default, written two ways.\n */\nconst sameDefault = (actual: string | null, expected: string): boolean =>\n actual !== null && actual.toLowerCase().replace(/[\\s()]/g, \"\") === expected.toLowerCase().replace(/[\\s()]/g, \"\");\n\n/**\n * The plain `token_hash` indexes every era created next to the UNIQUE\n * constraint's own index on the same column. No longer created; dropped where\n * found — see {@link dropDuplicateTokenHashIndexesSql}.\n */\nconst DUPLICATE_TOKEN_HASH_INDEXES = [\n \"idx_refresh_tokens_hash\",\n \"idx_password_reset_tokens_hash\",\n \"idx_magic_link_tokens_hash\"\n] as const;\n\n/**\n * One statement that drops each named index — but only one that covers a\n * single column that a valid, unique, non-partial btree on the same table also\n * leads with. That is the UNIQUE (token_hash) constraint's index, which serves\n * every `token_hash = $1` lookup; a table that somehow lacks it keeps its\n * plain index, so no lookup is ever left without one.\n *\n * `DROP INDEX` takes the table's ACCESS EXCLUSIVE lock, on the tables every\n * sign-in and token refresh touches, so it runs under the boot lock budget\n * (`lock_timeout`, transaction-local to this statement — see `boot-ddl`).\n */\nexport function dropDuplicateTokenHashIndexesSql(schema: string, names: readonly string[]): string {\n return `\nDO $rebase_drop_hash_index$\nDECLARE duplicate record;\nBEGIN\n PERFORM set_config('lock_timeout', '${BOOT_LOCK_TIMEOUT_MS}ms', true);\n FOR duplicate IN\n SELECT ic.relname AS name\n FROM pg_index d\n JOIN pg_class ic ON ic.oid = d.indexrelid\n JOIN pg_namespace n ON n.oid = ic.relnamespace\n WHERE n.nspname = ${literal(schema)}\n AND ic.relname IN (${names.map(literal).join(\", \")})\n AND d.indnatts = 1\n AND EXISTS (\n SELECT 1 FROM pg_index o\n JOIN pg_class oc ON oc.oid = o.indexrelid\n JOIN pg_am am ON am.oid = oc.relam\n WHERE o.indrelid = d.indrelid AND o.indexrelid <> d.indexrelid\n AND o.indisvalid AND o.indisunique AND o.indpred IS NULL AND o.indexprs IS NULL\n AND am.amname = 'btree' AND o.indkey[0] = d.indkey[0])\n LOOP\n EXECUTE format('DROP INDEX IF EXISTS %I.%I', ${literal(schema)}, duplicate.name);\n END LOOP;\nEND\n$rebase_drop_hash_index$`.trim();\n}\n\n/**\n * Auto-create auth tables if they don't exist.\n *\n * @param db — Drizzle database instance\n * @param collection — The collection that represents auth users.\n * When omitted, a default `rebase.users` table is created.\n */\nexport async function ensureAuthTablesExist(db: NodePgDatabase, collection?: CollectionConfig): Promise<void> {\n logger.debug(\"🔍 Checking auth tables...\");\n\n // Before anything else, and deliberately outside the catch below: refuse to\n // run against a database that a newer framework version has already\n // migrated. Everything past this point is best-effort by design, which is\n // exactly the wrong posture for an incompatibility that would otherwise\n // surface as a fully booted server failing every login.\n await assertAuthSchemaCompatible(db, resolveAuthSchema(collection));\n\n try {\n // Resolve dynamic user table name and ID type from the collection\n let usersTableName = '\"rebase\".\"users\"';\n let userIdType = \"TEXT\";\n let usersSchema = \"rebase\";\n let resolvedTable = \"users\";\n if (collection) {\n resolvedTable = (\"table\" in collection && typeof collection.table === \"string\")\n ? collection.table\n : collection.slug;\n usersSchema = (\"schema\" in collection && typeof collection.schema === \"string\")\n ? collection.schema\n : \"public\";\n usersTableName = usersSchema === \"public\"\n ? `\"${resolvedTable}\"`\n : `\"${usersSchema}\".\"${resolvedTable}\"`;\n\n // Derive ID column type from collection properties.\n //\n // `\"increment\"`, not `\"autoincrement\"`. The latter was tested for\n // here and exists nowhere in the type system — the union is\n // `boolean | \"manual\" | \"increment\" | string` — so the INTEGER branch\n // was unreachable and an integer-keyed auth collection fell through\n // to TEXT. Introspection below hid it whenever the table already\n // existed; on a database where it did not, this created\n // `id TEXT DEFAULT gen_random_uuid()::text` for a collection that\n // declares a number, and every `uid` foreign key was typed to match\n // the wrong thing.\n const idProp = collection.properties?.id;\n if (idProp) {\n const isId = (\"isId\" in idProp) ? (idProp as Record<string, unknown>).isId : undefined;\n if (isId === \"uuid\") {\n userIdType = \"UUID\";\n } else if (isId === \"increment\") {\n userIdType = \"INTEGER\";\n }\n // Otherwise keep TEXT as default\n }\n }\n\n // Introspect the database to find the actual type of usersTableName's ID column if the table exists\n try {\n const result = await db.execute(sql`\n SELECT data_type \n FROM information_schema.columns \n WHERE table_schema = ${usersSchema} \n AND table_name = ${resolvedTable} \n AND column_name = 'id'\n `);\n if (result && result.rows && result.rows.length > 0) {\n const dbType = String((result.rows[0] as { data_type: string }).data_type).toUpperCase();\n if (dbType === \"UUID\") {\n userIdType = \"UUID\";\n } else if (dbType === \"INTEGER\" || dbType === \"SMALLINT\" || dbType === \"BIGINT\") {\n userIdType = \"INTEGER\";\n } else {\n userIdType = \"TEXT\";\n }\n logger.debug(`✨ Detected ${usersTableName}.id type from database: ${dbType}. Using user_id type: ${userIdType}`);\n }\n } catch (err) {\n // Ignore introspection errors, fallback to derived/default type\n logger.warn(`⚠️ Failed to introspect ${usersTableName}.id type from database, falling back to config type: ${userIdType}`, { error: err });\n }\n\n\n // ── Create schemas (idempotent) ──────────────────────────────────\n if (usersSchema !== \"public\") {\n await db.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.raw(usersSchema)}`);\n }\n await db.execute(sql`CREATE SCHEMA IF NOT EXISTS rebase`);\n\n const authSchema = usersSchema === \"public\" ? \"rebase\" : usersSchema;\n const indexNames = await readIndexNames(db, [usersSchema, authSchema]);\n const runRaw = async (text: string): Promise<Record<string, unknown>[]> =>\n (await db.execute(sql.raw(text))).rows as Record<string, unknown>[];\n /** Create an index only when it is missing — see {@link readIndexNames}. */\n const ensureIndex = async (schema: string, name: string, statement: ReturnType<typeof sql>): Promise<void> => {\n if (indexNames.has(`${schema}.${name}`)) return;\n await db.execute(statement);\n };\n const userIdentitiesTable = `\"${authSchema}\".\"user_identities\"`;\n const refreshTokensTableName = `\"${authSchema}\".\"refresh_tokens\"`;\n const passwordResetTokensTableName = `\"${authSchema}\".\"password_reset_tokens\"`;\n const appConfigTableName = `\"${authSchema}\".\"app_config\"`;\n\n // ── Create users table (idempotent) ─────────────────────────────\n // The users table MUST be created before any dependent auth tables\n // (user_identities, refresh_tokens, etc.) because they all hold\n // foreign keys referencing users(id). When a developer runs\n // `pnpm dev` for the first time without `db:migrate`, this ensures\n // the server can self-bootstrap.\n const idDefault = userIdType === \"UUID\"\n ? \"DEFAULT gen_random_uuid()\"\n : userIdType === \"INTEGER\"\n ? \"GENERATED ALWAYS AS IDENTITY\"\n : \"DEFAULT gen_random_uuid()::text\";\n\n // Identifiers for the constraint and indexes reconciled further down.\n // Derived from the resolved table name so two auth tables in different\n // schemas cannot collide, and truncated to Postgres's 63-byte identifier\n // limit here rather than letting the server truncate silently — the\n // `IF NOT EXISTS` guards below have to compare against the same name\n // Postgres actually stored, or they re-run forever.\n const authIdentifier = (suffix: string) => `${resolvedTable}_${suffix}`.slice(0, 63);\n const emailLengthConstraint = `\"${authIdentifier(\"email_length_check\")}\"`;\n const emailLowerUniqueIndex = authIdentifier(\"email_lower_key\");\n const verificationTokenIndex = authIdentifier(\"email_verification_token_idx\");\n const emailChangeTokenIndex = authIdentifier(\"email_change_token_idx\");\n\n // Every string column here is TEXT, deliberately. In Postgres VARCHAR(n)\n // and TEXT are the same type with the same storage and the same\n // performance; the only difference is a length check, and none of these\n // columns wants one. The widths this table used to carry were inherited\n // MySQL habit (255) and they were all wrong in the same direction —\n // `password_hash VARCHAR(255)` against a 193-char scrypt string left 62\n // characters of headroom in front of a KEY_LENGTH constant living in\n // another package, and `photo_url VARCHAR(500)` rejected the `data:` URIs\n // and long signed URLs that OAuth providers hand back. A limit worth\n // having is a CHECK — alterable without a table rewrite, unlike a type\n // modifier — which is why `email` has one and nothing else does.\n //\n // The column list comes from AUTH_USERS_COLUMNS rather than being spelled\n // out here, because this is not the only place that creates this table:\n // `db push` and the boot-time collection ensure do too, and when the\n // three lists were maintained separately they disagreed and boot order\n // silently decided which shape the database got. The `email` CHECK is\n // appended rather than listed there — it is a named constraint the\n // migration below has to be able to add separately, `NOT VALID`, to a\n // table that already holds rows.\n const usersColumnDdl = AUTH_USERS_COLUMNS\n .map((spec) => spec.column === \"email\"\n ? `${spec.column} ${authUsersColumnSql(spec)} CONSTRAINT ${emailLengthConstraint} CHECK (length(email) <= 320)`\n : `${spec.column} ${authUsersColumnSql(spec)}`)\n .join(\",\\n \");\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS ${sql.raw(usersTableName)} (\n id ${sql.raw(userIdType)} PRIMARY KEY ${sql.raw(idDefault)},\n ${sql.raw(usersColumnDdl)}\n )\n `);\n\n // ── Migration: auth FK column user_id → uid, phase 1 (expand) ───────\n // Must run BEFORE the dependent tables below: CREATE TABLE IF NOT\n // EXISTS never revisits an existing table, so a database provisioned\n // before this migration still lacks `uid` — and the\n // CREATE INDEX ... (uid) statements that follow would fail on it.\n //\n // Deliberately NOT a plain RENAME. Both Cloud Run and Kubernetes roll\n // deploys, so old and new pods serve the same database at the same time,\n // and a rollback puts old code back in front of a migrated database. A\n // rename breaks every auth query on whichever side is out of step.\n // Instead: add `uid`, backfill it, drop the NOT NULL on `user_id`, and\n // keep the two in sync with a trigger, so a backend of either era can\n // read and write. `scripts/drop-legacy-auth-user-id.sql` removes the\n // column once no old backend remains (phase 2, contract).\n //\n // Idempotent throughout: every step is guarded on catalogue state.\n const legacyFkTables = [\n \"user_identities\",\n \"refresh_tokens\",\n \"password_reset_tokens\",\n \"magic_link_tokens\",\n \"mfa_factors\",\n \"recovery_codes\"\n ];\n\n // Only on a database that actually carries the legacy column. This whole\n // block is a 0.x compatibility shim, and it used to run unconditionally —\n // so every brand-new database was provisioned with a trigger function\n // written to reconcile a column it can never have, permanently, as part\n // of its first boot. A fresh install should not ship someone else's\n // migration history.\n // The table list is inlined rather than bound: drizzle expands a JS\n // array into a parameter TUPLE — `ANY(($2, $3, …))` — which Postgres\n // rejects, and the thrown error is swallowed by the catch around this\n // whole function, so auth would silently stop provisioning. These are\n // module-level constants, not input.\n const legacyFkTableList = legacyFkTables.map(t => `'${t}'`).join(\", \");\n const legacyUserIdPresent = await db.execute(sql`\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = ${authSchema}\n AND table_name IN (${sql.raw(legacyFkTableList)})\n AND column_name = 'user_id'\n LIMIT 1\n `);\n\n if (legacyUserIdPresent.rows.length > 0) {\n await db.execute(sql`\n CREATE OR REPLACE FUNCTION ${sql.raw(`\"${authSchema}\"`)}.sync_uid_user_id() RETURNS trigger AS $$\n BEGIN\n IF NEW.uid IS NULL AND NEW.user_id IS NOT NULL THEN\n NEW.uid := NEW.user_id;\n ELSIF NEW.user_id IS NULL AND NEW.uid IS NOT NULL THEN\n NEW.user_id := NEW.uid;\n END IF;\n RETURN NEW;\n END $$ LANGUAGE plpgsql\n `);\n }\n\n for (const authTable of legacyUserIdPresent.rows.length > 0 ? legacyFkTables : []) {\n const qualified = `\"${authSchema}\".\"${authTable}\"`;\n await db.execute(sql`\n DO $$\n DECLARE\n has_legacy boolean;\n has_uid boolean;\n BEGIN\n SELECT\n bool_or(column_name = 'user_id'),\n bool_or(column_name = 'uid')\n INTO has_legacy, has_uid\n FROM information_schema.columns\n WHERE table_schema = ${sql.raw(`'${authSchema}'`)}\n AND table_name = ${sql.raw(`'${authTable}'`)};\n\n -- Table absent, or already uid-only (a fresh install, or\n -- phase 2 already run): nothing to do.\n IF has_legacy IS NOT TRUE THEN\n RETURN;\n END IF;\n\n IF has_uid IS NOT TRUE THEN\n EXECUTE ${sql.raw(`'ALTER TABLE ${qualified} ADD COLUMN uid ${userIdType} REFERENCES ${usersTableName}(id) ON DELETE CASCADE'`)};\n EXECUTE ${sql.raw(`'UPDATE ${qualified} SET uid = user_id WHERE uid IS NULL'`)};\n EXECUTE ${sql.raw(`'CREATE INDEX IF NOT EXISTS idx_${authTable}_uid ON ${qualified}(uid)'`)};\n END IF;\n\n -- New code inserts uid and never user_id, so the legacy\n -- column can no longer be NOT NULL. The trigger below\n -- backfills it, but the constraint is checked first.\n EXECUTE ${sql.raw(`'ALTER TABLE ${qualified} ALTER COLUMN user_id DROP NOT NULL'`)};\n\n EXECUTE ${sql.raw(`'DROP TRIGGER IF EXISTS sync_uid_user_id ON ${qualified}'`)};\n EXECUTE ${sql.raw(`'CREATE TRIGGER sync_uid_user_id BEFORE INSERT OR UPDATE ON ${qualified} FOR EACH ROW EXECUTE FUNCTION \"${authSchema}\".sync_uid_user_id()'`)};\n END $$\n `);\n }\n\n // ── Create dependent auth tables (idempotent) ───────────────────\n\n // Create user_identities table\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS ${sql.raw(userIdentitiesTable)} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n provider_id TEXT NOT NULL,\n profile_data JSONB,\n created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),\n updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),\n UNIQUE(provider, provider_id)\n )\n `);\n\n // Create indexes on user_identities\n await ensureIndex(authSchema, \"idx_user_identities_user\", sql`\n CREATE INDEX IF NOT EXISTS idx_user_identities_user\n ON ${sql.raw(userIdentitiesTable)}(uid)\n `);\n\n\n // Create refresh tokens table. One row per TOKEN, grouped into a\n // sign-in by session_id — deliberately without a uniqueness rule on\n // (uid, user_agent, ip_address); see the schema module for why that\n // constraint had to go.\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS ${sql.raw(refreshTokensTableName)} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,\n session_id TEXT NOT NULL DEFAULT gen_random_uuid()::text,\n token_hash TEXT NOT NULL UNIQUE,\n expires_at TIMESTAMP WITH TIME ZONE NOT NULL,\n revoked BOOLEAN DEFAULT FALSE NOT NULL,\n rotated_at TIMESTAMP WITH TIME ZONE,\n session_started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,\n user_agent TEXT,\n ip_address TEXT,\n created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n )\n `);\n\n // Create index on uid for cleanup operations\n await ensureIndex(authSchema, \"idx_refresh_tokens_user\", sql`\n CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user\n ON ${sql.raw(refreshTokensTableName)}(uid)\n `);\n\n // Create password reset tokens table\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS ${sql.raw(passwordResetTokensTableName)} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,\n token_hash TEXT NOT NULL UNIQUE,\n expires_at TIMESTAMP WITH TIME ZONE NOT NULL,\n used_at TIMESTAMP WITH TIME ZONE,\n created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n )\n `);\n\n // Create index on uid for password reset cleanup\n await ensureIndex(authSchema, \"idx_password_reset_tokens_user\", sql`\n CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_user\n ON ${sql.raw(passwordResetTokensTableName)}(uid)\n `);\n\n // Create magic link tokens table\n const magicLinkTokensTableName = `\"${authSchema}\".\"magic_link_tokens\"`;\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS ${sql.raw(magicLinkTokensTableName)} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,\n token_hash TEXT NOT NULL UNIQUE,\n expires_at TIMESTAMP WITH TIME ZONE NOT NULL,\n used_at TIMESTAMP WITH TIME ZONE,\n created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n )\n `);\n\n // Create index on uid for magic link cleanup\n await ensureIndex(authSchema, \"idx_magic_link_tokens_user\", sql`\n CREATE INDEX IF NOT EXISTS idx_magic_link_tokens_user\n ON ${sql.raw(magicLinkTokensTableName)}(uid)\n `);\n\n // Every lookup on the three token tables is `token_hash = $1`, which\n // the index behind each table's UNIQUE (token_hash) answers. Every era\n // also created `idx_<table>_hash`, a second btree on the same column,\n // which each sign-in, refresh, reset and magic link paid to maintain\n // and never used. Dropped where present — read from the catalogue\n // above, so a database without them issues nothing.\n const duplicateHashIndexes = DUPLICATE_TOKEN_HASH_INDEXES.filter(name => indexNames.has(`${authSchema}.${name}`));\n if (duplicateHashIndexes.length > 0) {\n try {\n await db.execute(sql.raw(dropDuplicateTokenHashIndexesSql(authSchema, duplicateHashIndexes)));\n } catch (err) {\n // Redundant, not wrong: a table whose lock another session\n // held for the whole budget keeps its extra index until a\n // later boot drops it.\n logger.warn(\n `⚠️ Left the duplicate token-hash index(es) ${duplicateHashIndexes.join(\", \")} in place for now: ` +\n (err instanceof Error ? err.message : String(err))\n );\n }\n }\n\n // Create app config table\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS ${sql.raw(appConfigTableName)} (\n key TEXT PRIMARY KEY,\n value JSONB NOT NULL,\n updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n )\n `);\n\n // The RLS helper functions every generated policy calls. They live in\n // `rebase`, alongside the tables above — Rebase creates exactly one\n // schema in a user's database. Advisory-locked so concurrent HMR\n // reloads cannot race on `CREATE OR REPLACE`.\n //\n // The same statements the migration preamble carries, from the same\n // constant — these definitions being identical across the boot path and\n // the migration stream is the whole point of having them in one place.\n // One call per statement: this handle speaks the extended query\n // protocol, which rejects multi-command strings.\n //\n // Only when the catalogue says they differ: replacing an unchanged\n // function still rewrites it, and invalidates every cached plan a\n // policy calling it is part of. See `rlsRuntimeIsCurrent`.\n if (!await rlsRuntimeIsCurrent(runRaw).catch(() => false)) {\n await db.transaction(async (tx) => {\n await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext('rebase_auth_functions_init'))`);\n for (const statement of RLS_BOOTSTRAP_STATEMENTS) {\n await tx.execute(sql.raw(statement));\n }\n });\n }\n\n // Seed default roles if none exist\n // (no-op: roles are now stored inline on the users table)\n\n // ── Migration: reconcile the full users column set (safe for existing tables) ──\n // CREATE TABLE IF NOT EXISTS never revisits an existing table, so a\n // database provisioned by an older framework era is missing every\n // column added since. Each column the auth services read or write must\n // be back-filled here, or upgraded deployments break on the first\n // statement that references it.\n //\n // `email` is skipped: it has existed since the first era, so it is never\n // the missing one, and `ADD COLUMN … NOT NULL` with no default fails on\n // a table with rows.\n //\n // Only the columns the table is missing are added. `ADD COLUMN IF NOT\n // EXISTS` on a column that exists changes nothing and still queues for\n // the table's ACCESS EXCLUSIVE lock — on the table every sign-in reads —\n // and it ran for every column on every boot.\n type UsersColumnRow = {\n column_name: string;\n data_type: string;\n is_nullable: \"YES\" | \"NO\";\n column_default: string | null;\n };\n // Which of the columns the table actually has. An adopted table — one\n // this framework did not create, which the column-name resolution in\n // `services.ts` exists to support — may be missing any of them, and every\n // statement past this point has to tolerate that rather than abort the\n // whole migration block.\n const readUsersColumns = async (): Promise<UsersColumnRow[]> => (await db.execute(sql`\n SELECT column_name, data_type, is_nullable, column_default\n FROM information_schema.columns\n WHERE table_schema = ${usersSchema} AND table_name = ${resolvedTable}\n `)).rows as UsersColumnRow[];\n let usersColumnRows = await readUsersColumns();\n const usersColumnsBefore = new Set(usersColumnRows.map(row => row.column_name));\n let usersColumnsAdded = false;\n for (const spec of AUTH_USERS_COLUMNS) {\n if (spec.column === \"email\") continue;\n if (usersColumnsBefore.has(spec.column)) continue;\n await db.execute(sql`\n ALTER TABLE ${sql.raw(usersTableName)}\n ADD COLUMN IF NOT EXISTS ${sql.raw(`${spec.column} ${authUsersColumnSql(spec)}`)}\n `);\n usersColumnsAdded = true;\n }\n if (usersColumnsAdded) usersColumnRows = await readUsersColumns();\n const usersColumnTypes = new Map(usersColumnRows.map(row => [row.column_name, row.data_type]));\n const usersColumnState = new Map(usersColumnRows.map(row => [row.column_name, row]));\n\n // ── Migration: restore defaults and NOT NULL that another creator dropped ──\n // `ADD COLUMN IF NOT EXISTS` above only creates what is MISSING. A column\n // that exists with the wrong shape stays wrong forever — and until\n // AUTH_USERS_COLUMNS became the single source, that was the normal\n // outcome rather than an edge case: whichever of `db push`, boot-ensure\n // and this function reached the table first decided its constraints, so\n // a managed deploy ended up with a nullable `email`, a `roles` with no\n // `'{}'` default, and an `email_verified` that could be NULL.\n //\n // Ordered DEFAULT → back-fill → SET NOT NULL, because SET NOT NULL is\n // checked against existing rows: without the back-fill it throws on the\n // very databases that need it. `email` can carry no default, so a NULL\n // there is not repairable automatically — say so and leave the column\n // alone rather than inventing an address.\n for (const spec of AUTH_USERS_COLUMNS) {\n const state = usersColumnState.get(spec.column);\n if (!state) continue;\n\n if (spec.default !== undefined && state.column_default === null) {\n await db.execute(sql`\n ALTER TABLE ${sql.raw(usersTableName)}\n ALTER COLUMN ${sql.raw(`\"${spec.column}\"`)} SET DEFAULT ${sql.raw(spec.default)}\n `);\n logger.info(`🔧 Restored the default on ${usersTableName}.${spec.column}`);\n }\n\n if (!spec.notNull || state.is_nullable !== \"YES\") continue;\n\n if (spec.default !== undefined) {\n await db.execute(sql`\n UPDATE ${sql.raw(usersTableName)}\n SET ${sql.raw(`\"${spec.column}\"`)} = ${sql.raw(spec.default)}\n WHERE ${sql.raw(`\"${spec.column}\"`)} IS NULL\n `);\n }\n try {\n await db.execute(sql`\n ALTER TABLE ${sql.raw(usersTableName)}\n ALTER COLUMN ${sql.raw(`\"${spec.column}\"`)} SET NOT NULL\n `);\n logger.info(`🔧 Restored NOT NULL on ${usersTableName}.${spec.column}`);\n } catch (err) {\n logger.warn(\n `⚠️ ${usersTableName}.${spec.column} should be NOT NULL but still holds NULLs, so the ` +\n \"constraint was not applied. Fill or remove those rows and restart: \" +\n (err instanceof Error ? err.message : String(err))\n );\n }\n }\n\n // ── Migration: VARCHAR(n) → TEXT on the users string columns ────────\n // Tables created before the widths came off still carry them. Postgres\n // treats varchar(n) → text as binary-coercible with no stricter\n // constraint, so this is a catalogue-only change: no table rewrite, no\n // index rebuild, just a brief ACCESS EXCLUSIVE lock. Guarded on the\n // current type so it runs once and is a pure catalogue read thereafter.\n for (const column of [\"email\", \"display_name\", \"photo_url\", \"password_hash\", \"email_verification_token\"]) {\n if (usersColumnTypes.get(column) !== \"character varying\") continue;\n await db.execute(sql`\n ALTER TABLE ${sql.raw(usersTableName)}\n ALTER COLUMN ${sql.raw(`\"${column}\"`)} TYPE TEXT\n `);\n logger.info(`🔧 Widened ${usersTableName}.${column} from VARCHAR(n) to TEXT`);\n }\n\n // ── Migration: case-insensitive email identity ──────────────────────\n // `getUserByEmail` has always searched `email.toLowerCase()` while the\n // write path stored whatever it was handed, leaving normalisation to a\n // convention every caller had to remember. A row that reached the table\n // with mixed case is then invisible to every lookup — the account exists,\n // login reports no such user, and the plain UNIQUE on `email` does not\n // stop a second row differing only in case, because it compares bytes.\n //\n // Fixed on both sides: `mapPayload` now folds on write, and this index\n // makes the database agree. A unique index on lower(email) is strictly\n // stronger than the byte-exact UNIQUE that older tables carry, so the\n // old constraint is left alone — it can no longer fire on anything the\n // new one would allow.\n //\n // Deliberately no AUTH_SCHEMA_VERSION bump: a runtime that predates this\n // migration keeps working against the migrated table (all of its own\n // write paths already lower-cased), which is exactly the additive case\n // the version stamp is documented not to cover.\n if (usersColumnTypes.has(\"email\")) {\n if (!indexNames.has(`${usersSchema}.${emailLowerUniqueIndex}`)) {\n // Case-collisions already in the table would make the unique\n // index impossible to build. Report them and leave the table\n // alone: the next boot retries, so fixing the rows is all the\n // operator has to do. Failing loudly beats folding the emails\n // and letting CREATE INDEX pick which account survives.\n const collisions = await db.execute(sql`\n SELECT lower(email) AS normalized, count(*)::int AS occurrences\n FROM ${sql.raw(usersTableName)}\n WHERE email IS NOT NULL\n GROUP BY lower(email)\n HAVING count(*) > 1\n LIMIT 10\n `);\n if (collisions.rows.length > 0) {\n const sample = (collisions.rows as { normalized: string; occurrences: number }[])\n .map(row => `${row.normalized} (×${row.occurrences})`)\n .join(\", \");\n logger.error(\n `❌ Cannot enforce case-insensitive email uniqueness on ${usersTableName}: ` +\n `these addresses already exist more than once, differing only in case — ${sample}. ` +\n \"Merge or delete the duplicates and restart; until then two accounts can share \" +\n \"one address and only the lower-cased one is reachable by login.\"\n );\n } else {\n const folded = await db.execute(sql`\n UPDATE ${sql.raw(usersTableName)}\n SET email = lower(email)\n WHERE email IS NOT NULL AND email <> lower(email)\n `);\n if (folded.rowCount) {\n logger.info(`🔧 Lower-cased ${folded.rowCount} email address(es) in ${usersTableName}`);\n }\n await db.execute(sql`\n CREATE UNIQUE INDEX IF NOT EXISTS ${sql.raw(`\"${emailLowerUniqueIndex}\"`)}\n ON ${sql.raw(usersTableName)} (lower(email))\n `);\n logger.info(`✅ Email uniqueness on ${usersTableName} is now case-insensitive`);\n }\n }\n }\n\n // ── Migration: bound the email column's length ──────────────────────\n // The only length limit on this table worth keeping. 320 is the RFC 5321\n // maximum (64-char local part + @ + 255-char domain), and it matters here\n // beyond tidiness: `email` carries a btree index, and a sufficiently long\n // value fails index insertion with an error that says nothing about\n // email. NOT VALID so an adopted table with a long row still migrates —\n // it binds all new writes, which is the part that matters.\n if (usersColumnTypes.has(\"email\")) {\n const checkPresent = await db.execute(sql`\n SELECT 1 FROM pg_constraint c\n JOIN pg_class t ON t.oid = c.conrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE n.nspname = ${usersSchema}\n AND t.relname = ${resolvedTable}\n AND c.conname = ${authIdentifier(\"email_length_check\")}\n `);\n if (checkPresent.rows.length === 0) {\n await db.execute(sql`\n ALTER TABLE ${sql.raw(usersTableName)}\n ADD CONSTRAINT ${sql.raw(emailLengthConstraint)} CHECK (length(email) <= 320) NOT VALID\n `);\n }\n }\n\n // ── Index: email verification token lookups ─────────────────────────\n // `getUserByVerificationToken` filters on this column, which had no\n // index — every click of a verification link was a sequential scan of\n // the whole users table. Partial, because the column is NULL for every\n // user who is not mid-verification, which is nearly all of them.\n if (usersColumnTypes.has(\"email_verification_token\")) {\n await ensureIndex(usersSchema, verificationTokenIndex, sql`\n CREATE INDEX IF NOT EXISTS ${sql.raw(`\"${verificationTokenIndex}\"`)}\n ON ${sql.raw(usersTableName)} (email_verification_token)\n WHERE email_verification_token IS NOT NULL\n `);\n }\n // The same for the address-change link, which is looked up the same way.\n if (usersColumnTypes.has(\"email_change_token\")) {\n await ensureIndex(usersSchema, emailChangeTokenIndex, sql`\n CREATE INDEX IF NOT EXISTS ${sql.raw(`\"${emailChangeTokenIndex}\"`)}\n ON ${sql.raw(usersTableName)} (email_change_token)\n WHERE email_change_token IS NOT NULL\n `);\n }\n\n // ── Migration: refresh_tokens become session-scoped, rotation-safe ──\n // Two shapes are reconciled here, on EVERY table named refresh_tokens\n // in whatever schema it lives (a database provisioned by an older era\n // can carry the table in a different schema than the one this run\n // derives, and auth would then read a table nobody migrated):\n //\n // 1. The new columns. A token is now a member of a session\n // (`session_id`) and is retained after rotation (`revoked`,\n // `rotated_at`) so a replayed token can be recognised instead of\n // looking like a forgery. `session_started_at` is carried across\n // rotations so `users.tokens_valid_after` cannot be outrun.\n // 2. The removal of `unique_device_session`. It made (uid,\n // user_agent, ip_address) the identity of a session, which evicted\n // a second browser profile behind one NAT and churned rows as\n // phones changed networks. UA and IP are metadata now.\n //\n // Every existing row is adopted rather than dropped: it keeps its\n // token_hash, gets a session of its own, and stays unrevoked — so the\n // sessions live in browsers right now survive the upgrade rather than\n // everyone being signed out by the fix for being signed out.\n try {\n const rtTables = await db.execute(sql`\n SELECT table_schema, table_name\n FROM information_schema.tables\n WHERE table_name = 'refresh_tokens'\n `);\n const found = (rtTables.rows as { table_schema: string; table_name: string }[]);\n logger.debug(`🔍 refresh_tokens reconcile: found ${found.length} table(s): ${found.map(r => `\"${r.table_schema}\".\"${r.table_name}\"`).join(\", \") || \"(none)\"}`);\n // What each of those tables already has, read once, so a table that\n // is already session-scoped gets no statement at all. Each step\n // below used to run on every boot: six `ADD COLUMN IF NOT EXISTS`,\n // two `SET DEFAULT`, two `SET NOT NULL` and a `DROP CONSTRAINT IF\n // EXISTS` — eleven waits for the ACCESS EXCLUSIVE lock on the table\n // every token refresh writes — and two `UPDATE … WHERE … IS NULL`\n // back-fills that scan the whole table, since nothing indexes them.\n const rtSchemas = found.map(r => r.table_schema);\n const rtColumnRows = rtSchemas.length === 0 ? [] : (await db.execute(sql.raw(\n \"SELECT table_schema, column_name, is_nullable, column_default FROM information_schema.columns \" +\n `WHERE table_name = 'refresh_tokens' AND table_schema IN (${rtSchemas.map(literal).join(\", \")})`\n ))).rows as { table_schema: string; column_name: string; is_nullable: \"YES\" | \"NO\"; column_default: string | null }[];\n const rtDeviceConstraint = new Set(rtSchemas.length === 0 ? [] : ((await db.execute(sql.raw(\n \"SELECT n.nspname AS schema FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid \" +\n \"JOIN pg_namespace n ON n.oid = t.relnamespace \" +\n \"WHERE t.relname = 'refresh_tokens' AND c.conname = 'unique_device_session' \" +\n `AND n.nspname IN (${rtSchemas.map(literal).join(\", \")})`\n ))).rows as { schema: string }[]).map(row => row.schema));\n const rtIndexNames = await readIndexNames(db, rtSchemas);\n for (const { table_schema } of found) {\n const qualified = `\"${table_schema}\".\"refresh_tokens\"`;\n const columns = new Map(rtColumnRows.filter(row => row.table_schema === table_schema).map(row => [row.column_name, row]));\n /** Missing, or present and nullable: a column the back-fill and SET NOT NULL still have to reach. */\n const nullable = (column: string) => columns.get(column)?.is_nullable !== \"NO\";\n const addColumn = async (column: string, statement: ReturnType<typeof sql>) => {\n if (!columns.has(column)) await db.execute(statement);\n };\n try {\n // Added nullable, then back-filled, then constrained: adding\n // `session_id NOT NULL DEFAULT gen_random_uuid()` in one step\n // would stamp every existing row with the SAME uuid on some\n // Postgres versions, silently merging every live session into\n // one that a single logout would then wipe.\n await addColumn(\"session_id\", sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS session_id TEXT`);\n await addColumn(\"revoked\", sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS revoked BOOLEAN DEFAULT FALSE NOT NULL`);\n await addColumn(\"rotated_at\", sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS rotated_at TIMESTAMP WITH TIME ZONE`);\n await addColumn(\"session_started_at\", sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS session_started_at TIMESTAMP WITH TIME ZONE`);\n // Nullable with no default and no back-fill: a row written\n // before this column existed says nothing about whether a\n // second factor was presented, and the reader treats \"says\n // nothing\" as `aal1` — the restrictive answer. Stamping\n // every existing row would be inventing evidence.\n await addColumn(\"aal\", sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS aal TEXT`);\n // How the sign-in happened, carried across rotations like\n // `aal`. Nullable and not back-filled for the same reason:\n // an older row reads as a password sign-in, which is what\n // every refresh answered before the column existed.\n await addColumn(\"method\", sql`ALTER TABLE ${sql.raw(qualified)} ADD COLUMN IF NOT EXISTS method TEXT`);\n\n // One session per pre-existing row: under the old model a row\n // WAS a device session, and there is no record of which rows\n // descended from the same sign-in. A NOT NULL column holds no\n // NULL to back-fill.\n if (nullable(\"session_id\")) {\n await db.execute(sql`\n UPDATE ${sql.raw(qualified)}\n SET session_id = gen_random_uuid()::text\n WHERE session_id IS NULL\n `);\n }\n if (nullable(\"session_started_at\")) {\n await db.execute(sql`\n UPDATE ${sql.raw(qualified)}\n SET session_started_at = COALESCE(created_at, NOW())\n WHERE session_started_at IS NULL\n `);\n }\n if (!sameDefault(columns.get(\"session_id\")?.column_default ?? null, \"gen_random_uuid()::text\")) {\n await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} ALTER COLUMN session_id SET DEFAULT gen_random_uuid()::text`);\n }\n if (!sameDefault(columns.get(\"session_started_at\")?.column_default ?? null, \"now()\")) {\n await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} ALTER COLUMN session_started_at SET DEFAULT NOW()`);\n }\n // SET NOT NULL only once the back-fill above has definitely\n // run; on a table that somehow still holds a NULL this throws\n // and is caught below rather than failing the boot.\n if (nullable(\"session_id\")) {\n await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} ALTER COLUMN session_id SET NOT NULL`);\n }\n if (nullable(\"session_started_at\")) {\n await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} ALTER COLUMN session_started_at SET NOT NULL`);\n }\n\n if (!rtIndexNames.has(`${table_schema}.idx_refresh_tokens_session`)) {\n await db.execute(sql`\n CREATE INDEX IF NOT EXISTS idx_refresh_tokens_session\n ON ${sql.raw(qualified)}(session_id)\n `);\n }\n\n // The device-session constraint is now actively harmful: two\n // live tokens of one session (a rotation in flight) share a\n // uid, and usually a user agent and IP too.\n if (rtDeviceConstraint.has(table_schema)) {\n await db.execute(sql`ALTER TABLE ${sql.raw(qualified)} DROP CONSTRAINT IF EXISTS unique_device_session`);\n }\n logger.debug(`✅ refresh_tokens reconciled for session-scoped rotation: ${qualified}`);\n } catch (perTableError: unknown) {\n logger.warn(`⚠️ refresh_tokens reconcile failed for ${qualified}: ${perTableError instanceof Error ? perTableError.message : String(perTableError)}`);\n }\n }\n } catch (migrationError: unknown) {\n logger.warn(`⚠️ refresh_tokens session migration skipped: ${migrationError instanceof Error ? migrationError.message : String(migrationError)}`);\n }\n\n // ── Migration: Copy roles from legacy junction table to inline column ──\n // If the old rebase.user_roles and rebase.roles tables exist, migrate\n // the data into the new TEXT[] column then drop the legacy tables.\n try {\n const legacyCheck = await db.execute(sql`\n SELECT EXISTS (\n SELECT 1 FROM information_schema.tables\n WHERE table_schema = 'rebase' AND table_name = 'user_roles'\n ) AS has_user_roles\n `);\n const hasLegacyTables = (legacyCheck.rows[0] as { has_user_roles: boolean }).has_user_roles;\n\n if (hasLegacyTables) {\n logger.info(\"🔄 Migrating roles from legacy user_roles table...\");\n // Update users' roles column from the junction table\n await db.execute(sql`\n UPDATE ${sql.raw(usersTableName)} u\n SET roles = COALESCE((\n SELECT array_agg(ur.role_id)\n FROM \"rebase\".\"user_roles\" ur\n WHERE ur.user_id = u.id\n ), '{}')\n WHERE u.roles = '{}' OR u.roles IS NULL\n `);\n\n // Drop legacy tables (junction first due to FK)\n await db.execute(sql`DROP TABLE IF EXISTS \"rebase\".\"user_roles\" CASCADE`);\n await db.execute(sql`DROP TABLE IF EXISTS \"rebase\".\"roles\" CASCADE`);\n logger.info(\"✅ Legacy roles tables migrated and dropped\");\n }\n } catch (migrationError: unknown) {\n // Non-fatal: log and continue — the column exists and will work\n logger.warn(`⚠️ Legacy roles migration skipped: ${migrationError instanceof Error ? migrationError.message : String(migrationError)}`);\n }\n\n // ── MFA tables ──────────────────────────────────────────────────────\n const mfaFactorsTableName = `\"${authSchema}\".\"mfa_factors\"`;\n const mfaChallengesTableName = `\"${authSchema}\".\"mfa_challenges\"`;\n const recoveryCodesTableName = `\"${authSchema}\".\"recovery_codes\"`;\n\n // Create mfa_factors table\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS ${sql.raw(mfaFactorsTableName)} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,\n factor_type TEXT NOT NULL DEFAULT 'totp',\n secret_encrypted TEXT NOT NULL,\n friendly_name TEXT,\n verified BOOLEAN DEFAULT FALSE,\n last_used_counter BIGINT,\n created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),\n updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n )\n `);\n\n // Create indexes on mfa_factors\n await ensureIndex(authSchema, \"idx_mfa_factors_user\", sql`\n CREATE INDEX IF NOT EXISTS idx_mfa_factors_user\n ON ${sql.raw(mfaFactorsTableName)}(uid)\n `);\n\n // Create mfa_challenges table\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS ${sql.raw(mfaChallengesTableName)} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n factor_id TEXT NOT NULL REFERENCES ${sql.raw(mfaFactorsTableName)}(id) ON DELETE CASCADE,\n created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),\n verified_at TIMESTAMP WITH TIME ZONE,\n ip_address TEXT,\n attempts INTEGER NOT NULL DEFAULT 0,\n expires_at TIMESTAMP WITH TIME ZONE NOT NULL\n )\n `);\n\n // Create indexes on mfa_challenges\n await ensureIndex(authSchema, \"idx_mfa_challenges_factor\", sql`\n CREATE INDEX IF NOT EXISTS idx_mfa_challenges_factor\n ON ${sql.raw(mfaChallengesTableName)}(factor_id)\n `);\n\n // ── Migration: replay and brute-force state on the MFA tables ───────\n // Both are additive and nullable-or-defaulted, so a runtime that\n // predates them reads the tables unchanged. `last_used_counter` records\n // the TOTP step a factor has already spent (RFC 6238 §5.2); `attempts`\n // bounds how many guesses one challenge will take before it is dead.\n // Without them the code paths degrade to \"no replay protection, rate\n // limiters only\" rather than failing, which is why this is a warn.\n // Read first, like the columns above: each was an ACCESS EXCLUSIVE wait\n // on every boot.\n try {\n const mfaColumns = new Set(((await db.execute(sql`\n SELECT table_name || '.' || column_name AS key\n FROM information_schema.columns\n WHERE table_schema = ${authSchema}\n AND table_name IN ('mfa_factors', 'mfa_challenges')\n AND column_name IN ('last_used_counter', 'attempts')\n `)).rows as { key: string }[]).map(row => row.key));\n if (!mfaColumns.has(\"mfa_factors.last_used_counter\")) {\n await db.execute(sql`ALTER TABLE ${sql.raw(mfaFactorsTableName)} ADD COLUMN IF NOT EXISTS last_used_counter BIGINT`);\n }\n if (!mfaColumns.has(\"mfa_challenges.attempts\")) {\n await db.execute(sql`ALTER TABLE ${sql.raw(mfaChallengesTableName)} ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0`);\n }\n } catch (mfaMigrationError: unknown) {\n logger.warn(`⚠️ MFA hardening columns skipped: ${mfaMigrationError instanceof Error ? mfaMigrationError.message : String(mfaMigrationError)}`);\n }\n\n // Create recovery_codes table\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS ${sql.raw(recoveryCodesTableName)} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n uid ${sql.raw(userIdType)} NOT NULL REFERENCES ${sql.raw(usersTableName)}(id) ON DELETE CASCADE,\n code_hash TEXT NOT NULL,\n used_at TIMESTAMP WITH TIME ZONE,\n created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n )\n `);\n\n // Create indexes on recovery_codes\n await ensureIndex(authSchema, \"idx_recovery_codes_user\", sql`\n CREATE INDEX IF NOT EXISTS idx_recovery_codes_user\n ON ${sql.raw(recoveryCodesTableName)}(uid)\n `);\n\n // ── Migration: clear stale FORCE ROW LEVEL SECURITY (older RLS model) ──\n // The current model never emits FORCE: privileged auth writes run as\n // the table owner and rely on the owner bypassing plain ENABLE RLS\n // (see generate-postgres-ddl-logic). A table still carrying FORCE from\n // an older framework era binds the owner too, so the first user\n // registration after an upgrade fails with SQLSTATE 42501. Reconcile\n // on boot; only tables actually flagged get the ALTER (and its lock).\n try {\n // Every table this function creates, not a subset. `magic_link_tokens`\n // and `schema_meta` were missing here while their six siblings were\n // listed — so on a database carrying FORCE from the older RLS model,\n // magic-link sign-in kept failing 42501 after the upgrade that was\n // supposed to fix exactly that, and only for the one auth method.\n const authTablePairs: [string, string][] = [\n [usersSchema, resolvedTable],\n [authSchema, \"user_identities\"],\n [authSchema, \"refresh_tokens\"],\n [authSchema, \"password_reset_tokens\"],\n [authSchema, \"magic_link_tokens\"],\n [authSchema, \"app_config\"],\n [authSchema, \"mfa_factors\"],\n [authSchema, \"mfa_challenges\"],\n [authSchema, \"recovery_codes\"],\n [authSchema, \"schema_meta\"]\n ];\n // One catalogue read for all of them, not one per table.\n const forced = new Set(((await db.execute(sql.raw(\n \"SELECT n.nspname AS schema, c.relname AS name FROM pg_class c \" +\n \"JOIN pg_namespace n ON n.oid = c.relnamespace \" +\n \"WHERE c.relforcerowsecurity AND (n.nspname, c.relname) IN (\" +\n authTablePairs.map(([schemaName, tableName]) => `(${literal(schemaName)}, ${literal(tableName)})`).join(\", \") +\n \")\"\n ))).rows as { schema: string; name: string }[]).map(row => `${row.schema}.${row.name}`));\n for (const [schemaName, tableName] of authTablePairs) {\n if (forced.has(`${schemaName}.${tableName}`)) {\n await db.execute(sql`\n ALTER TABLE ${sql.raw(`\"${schemaName}\".\"${tableName}\"`)}\n NO FORCE ROW LEVEL SECURITY\n `);\n logger.warn(\n `🔧 Cleared stale FORCE ROW LEVEL SECURITY on \"${schemaName}\".\"${tableName}\" ` +\n \"(legacy RLS model — it binds the owner connection and breaks privileged auth writes)\"\n );\n }\n }\n } catch (rlsReconcileError: unknown) {\n // Non-fatal: the connection may lack ownership on a pre-provisioned\n // table; registration will still fail loudly (42501) if FORCE remains.\n logger.warn(\n `⚠️ Could not reconcile FORCE ROW LEVEL SECURITY on auth tables: ` +\n `${rlsReconcileError instanceof Error ? rlsReconcileError.message : String(rlsReconcileError)}`\n );\n }\n\n // Stamped last of the MIGRATIONS, so a boot that died partway through\n // the ones above leaves the older stamp in place and the next boot runs\n // them again.\n await stampAuthSchemaVersion(db, authSchema);\n\n // ── Keep the end-user role out of auth's tables ─────────────────────\n // These carry session token hashes, TOTP secrets and recovery codes, and\n // none of them has RLS — they are not collections, so nothing ever\n // compiled a policy for them. Meanwhile the role provisioning grants\n // `rebase_user` DML on every table in this schema, and its\n // ALTER DEFAULT PRIVILEGES reaches the ones created right here, after it\n // ran. So the grant has to come back off; see `revokeInternalTableSql`\n // for why a revoke rather than an empty RLS policy set.\n //\n // After the stamp deliberately: `schema_meta` is created BY the stamp,\n // so revoking first would leave the one table holding this database's\n // schema version writable by every signed-in user until the next boot.\n // Nothing below re-runs the migrations, so the stamp's guarantee holds.\n //\n // Only the tables the user role still holds a privilege on — one read\n // instead of a `REVOKE` per name, each rewriting the table's catalogue\n // row on every boot. A read that fails sweeps every name, as before.\n const stillGranted = await internalTablesGrantedToUserRole(runRaw, authSchema).catch(() => undefined);\n if (stillGranted === undefined || stillGranted.length > 0) {\n await revokeInternalTableAccess(\n async (text) => { await db.execute(sql.raw(text)); },\n authSchema,\n {\n tables: stillGranted,\n onError: (table, err) => logger.warn(\n `🔐 Could not revoke authenticated-role access to \"${authSchema}\".\"${table}\": ` +\n (err instanceof Error ? err.message : String(err))\n )\n }\n );\n }\n\n logger.debug(\"✅ Auth tables ready\");\n } catch (error) {\n // The one failure that must not be survived. Continuing here is what\n // produced a server that answered /health with 200 while every login\n // returned 500 — the incompatibility is total, so crashing is the\n // kinder outcome: an orchestrator will not route traffic to a pod that\n // never came up.\n if (error instanceof AuthSchemaVersionError) throw error;\n logger.error(\"❌ Failed to create auth tables\", { error });\n logger.warn(\"⚠️ Continuing without creating auth tables.\");\n }\n}\n\n"],"mappings":";;;;;;;;;;;AAuCA,IAAM,cAAc;;;;;;;AAQpB,IAAM,iCAAiC;CAAC;CAAc;CAAW;CAAc;AAAoB;;;;;;AAOnG,IAAM,mCAAmC;;;;;;;;;AAUzC,IAAa,yBAAb,cAA4C,MAAM;CAC9C;CACA;CAEA,YAAY,iBAAyB,gBAAwB;EACzD,MACI,4DAA4D,gBAAgB,yCACpC,eAAe;;+JAM3D;EACA,KAAK,OAAO;EACZ,KAAK,kBAAkB;EACvB,KAAK,iBAAiB;CAC1B;AACJ;;;;;;AAOA,SAAgB,kBAAkB,YAAuC;CACrE,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,cAAe,YAAY,cAAc,OAAO,WAAW,WAAW,WACtE,WAAW,SACX;CACN,OAAO,gBAAgB,WAAW,WAAW;AACjD;;;;;;;;;AAUA,eAAsB,sBAClB,IACA,YACsB;CACtB,MAAM,YAAY,IAAI,WAAW;CAEjC,IAAI,EAAE,MADe,GAAG,QAAQ,GAAG,sBAAsB,UAAU,yBAAyB,EAAA,CAC/E,KAAK,EAAE,EAAuC,SAAS,OAAO;CAK3E,MAAM,OAAO,MAHQ,GAAG,QAAQ,GAAG;4BACX,IAAI,IAAI,SAAS,EAAE,eAAe,YAAY;KACrE,EAAA,CACmB,KAAK,EAAE,EAAoC;CAC/D,IAAI,QAAQ,KAAA,GAAW,OAAO;CAE9B,MAAM,SAAS,OAAO,SAAS,KAAK,EAAE;CAItC,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC9C;;;;;;;;AASA,eAAsB,2BAClB,IACA,YACa;CACb,MAAM,kBAAkB,MAAM,sBAAsB,IAAI,UAAU;CAClE,IAAI,oBA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