@rebasepro/server-postgres 0.28.2 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BranchService-BPssiD8_.js → BranchService-JiYJ_n9E.js} +3 -3
- package/dist/{BranchService-BPssiD8_.js.map → BranchService-JiYJ_n9E.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +147 -1
- package/dist/PostgresBootstrapper.d.ts +34 -1
- package/dist/{backup-cli-C1wcj-rc.js → backup-cli-D_aKXPyX.js} +3 -3
- package/dist/{backup-cli-C1wcj-rc.js.map → backup-cli-D_aKXPyX.js.map} +1 -1
- package/dist/{boot-ddl-CIGoIGcC.js → boot-ddl-D4W9o9xE.js} +2 -2
- package/dist/{boot-ddl-CIGoIGcC.js.map → boot-ddl-D4W9o9xE.js.map} +1 -1
- package/dist/{cli-console-C0FYkICX.js → cli-console-DPdZCWTi.js} +6 -6
- package/dist/{cli-console-C0FYkICX.js.map → cli-console-DPdZCWTi.js.map} +1 -1
- package/dist/{cli-errors-DYets7cp.js → cli-errors-D8s4z_3g.js} +26 -6
- package/dist/cli-errors-D8s4z_3g.js.map +1 -0
- package/dist/cli-helpers.d.ts +10 -0
- package/dist/cli.js +41 -35
- package/dist/cli.js.map +1 -1
- package/dist/{connection-czvI7TZL.js → connection-COuS5Fm-.js} +126 -36
- package/dist/connection-COuS5Fm-.js.map +1 -0
- package/dist/connection.d.ts +63 -0
- package/dist/database-health.d.ts +23 -0
- package/dist/{databasePoolManager-BjoVvuAq.js → databasePoolManager-7hXVurmG.js} +2 -2
- package/dist/{databasePoolManager-BjoVvuAq.js.map → databasePoolManager-7hXVurmG.js.map} +1 -1
- package/dist/{deferred-index-build-BcJ_oulu.js → deferred-index-build-F2GWu009.js} +34 -5
- package/dist/{deferred-index-build-BcJ_oulu.js.map → deferred-index-build-F2GWu009.js.map} +1 -1
- package/dist/{doctor-TJApVglQ.js → doctor-_g2tHRtG.js} +20 -6
- package/dist/doctor-_g2tHRtG.js.map +1 -0
- package/dist/{ensure-collection-policies-BNwSQfVx.js → ensure-collection-policies-DUpWJb5D.js} +8 -8
- package/dist/{ensure-collection-policies-BNwSQfVx.js.map → ensure-collection-policies-DUpWJb5D.js.map} +1 -1
- package/dist/{ensure-collection-tables-CSbgkTBx.js → ensure-collection-tables-BK--gDo6.js} +15 -9
- package/dist/ensure-collection-tables-BK--gDo6.js.map +1 -0
- package/dist/{ensure-tables-CF-8zgYA.js → ensure-tables-Bx1DYarz.js} +4 -4
- package/dist/{ensure-tables-CF-8zgYA.js.map → ensure-tables-Bx1DYarz.js.map} +1 -1
- package/dist/{enum-labels-kept-BCgFGAbJ.js → enum-labels-kept-DyFE4Gaq.js} +3 -3
- package/dist/{enum-labels-kept-BCgFGAbJ.js.map → enum-labels-kept-DyFE4Gaq.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js → generate-drizzle-schema-logic-DpFA1UVd.js} +2 -2
- package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js.map → generate-drizzle-schema-logic-DpFA1UVd.js.map} +1 -1
- package/dist/{generate-drizzle-schema-BAIp9nKT.js → generate-drizzle-schema-taNTu3xv.js} +2 -2
- package/dist/{generate-drizzle-schema-BAIp9nKT.js.map → generate-drizzle-schema-taNTu3xv.js.map} +1 -1
- package/dist/{generate-files-DutUrsSS.js → generate-files-DbwU8Btx.js} +11 -4
- package/dist/generate-files-DbwU8Btx.js.map +1 -0
- package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js → generate-postgres-ddl-logic-ISVgsP34.js} +11 -4
- package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js.map → generate-postgres-ddl-logic-ISVgsP34.js.map} +1 -1
- package/dist/{generated-schema-diff-ChFg6UxI.js → generated-schema-diff-4lOC0g1_.js} +21 -6
- package/dist/generated-schema-diff-4lOC0g1_.js.map +1 -0
- package/dist/index.d.ts +5 -2
- package/dist/index.es.js +13 -13
- package/dist/{migrate-baseline-DPawvckr.js → migrate-baseline-BeepEphh.js} +2 -2
- package/dist/{migrate-baseline-DPawvckr.js.map → migrate-baseline-BeepEphh.js.map} +1 -1
- package/dist/{migrate-policy-stamps-B-8vTSIm.js → migrate-policy-stamps-cYMJ_9Ha.js} +7 -7
- package/dist/{migrate-policy-stamps-B-8vTSIm.js.map → migrate-policy-stamps-cYMJ_9Ha.js.map} +1 -1
- package/dist/{open-rebase-D9n8idex.js → open-rebase-CTNBmmH8.js} +1712 -164
- package/dist/open-rebase-CTNBmmH8.js.map +1 -0
- package/dist/{pg-error-utils-BIHfsGZL.js → pg-error-utils-BLOVXK67.js} +2 -2
- package/dist/{pg-error-utils-BIHfsGZL.js.map → pg-error-utils-BLOVXK67.js.map} +1 -1
- package/dist/pipelined-transaction.d.ts +131 -0
- package/dist/{plan-schema-DMVh77yb.js → plan-schema-CMNWvqIa.js} +62 -3
- package/dist/plan-schema-CMNWvqIa.js.map +1 -0
- package/dist/{policy-drift-0Cp4Lc0x.js → policy-drift-IjD2AUD-.js} +2 -2
- package/dist/{policy-drift-0Cp4Lc0x.js.map → policy-drift-IjD2AUD-.js.map} +1 -1
- package/dist/pooled-database.d.ts +38 -0
- package/dist/{push-index-prebuild-DR3P4yOw.js → push-index-prebuild-CIvajIrL.js} +4 -4
- package/dist/{push-index-prebuild-DR3P4yOw.js.map → push-index-prebuild-CIvajIrL.js.map} +1 -1
- package/dist/{push-kept-defaults-BSqPzp0T.js → push-kept-defaults-CLbsuSmo.js} +2 -2
- package/dist/{push-kept-defaults-BSqPzp0T.js.map → push-kept-defaults-CLbsuSmo.js.map} +1 -1
- package/dist/{push-legacy-renames-BIxBmVLl.js → push-legacy-renames-DeW_HTLJ.js} +4 -4
- package/dist/{push-legacy-renames-BIxBmVLl.js.map → push-legacy-renames-DeW_HTLJ.js.map} +1 -1
- package/dist/{push-policy-plan-BHsasXa7.js → push-policy-plan--oRXOj4X.js} +4 -4
- package/dist/{push-policy-plan-BHsasXa7.js.map → push-policy-plan--oRXOj4X.js.map} +1 -1
- package/dist/read-routing.d.ts +139 -0
- package/dist/{render-ddl-NpPPDACz.js → render-ddl-CzVcbbR1.js} +77 -3
- package/dist/render-ddl-CzVcbbR1.js.map +1 -0
- package/dist/{rls-enforcement-BOHuHVlc.js → rls-enforcement-jZTv1yci.js} +48 -16
- package/dist/{rls-enforcement-BOHuHVlc.js.map → rls-enforcement-jZTv1yci.js.map} +1 -1
- package/dist/schema/deferred-index-build.d.ts +9 -0
- package/dist/schema/doctor-cli.js +4 -4
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-files.d.ts +2 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +6 -0
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/introspect-db.js +2 -2
- package/dist/schema/introspect-runtime.d.ts +10 -1
- package/dist/schema/plan/plan-schema.d.ts +9 -1
- package/dist/schema/plan/render-ddl.d.ts +25 -1
- package/dist/schema/plan/types.d.ts +24 -0
- package/dist/security/rls-enforcement.d.ts +11 -0
- package/dist/services/FetchService.d.ts +12 -12
- package/dist/services/PersistService.d.ts +59 -0
- package/dist/services/collection-helpers.d.ts +3 -1
- package/dist/services/view-access.d.ts +21 -0
- package/dist/{websocket-D4wrzF3b.js → websocket-D2y88dOa.js} +3 -3
- package/dist/{websocket-D4wrzF3b.js.map → websocket-D2y88dOa.js.map} +1 -1
- package/package.json +7 -7
- package/dist/cli-errors-DYets7cp.js.map +0 -1
- package/dist/connection-czvI7TZL.js.map +0 -1
- package/dist/doctor-TJApVglQ.js.map +0 -1
- package/dist/ensure-collection-tables-CSbgkTBx.js.map +0 -1
- package/dist/generate-files-DutUrsSS.js.map +0 -1
- package/dist/generated-schema-diff-ChFg6UxI.js.map +0 -1
- package/dist/open-rebase-D9n8idex.js.map +0 -1
- package/dist/plan-schema-DMVh77yb.js.map +0 -1
- package/dist/render-ddl-NpPPDACz.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rls-enforcement-BOHuHVlc.js","names":[],"sources":["../src/security/rls-enforcement.ts"],"sourcesContent":["import { sql as drizzleSql, SQL } from \"drizzle-orm\";\nimport { ANONYMOUS_USER_ID, PolicyExpression, SecurityRule } from \"@rebasepro/types\";\nimport {\n AnonymousGrantRisk,\n findAnonymousGrants,\n REBASE_INTERNAL_TABLES,\n REBASE_USER_ROLE,\n revokeInternalTableAccess,\n securityRuleToConditions\n} from \"@rebasepro/common\";\nimport { REBASE_SCHEMA, usesLegacyRlsFunctions } from \"@rebasepro/types\";\nimport { logger } from \"@rebasepro/server\";\n\n/**\n * Unified RLS enforcement — the \"user context vs server context\" model.\n *\n * Every operation runs in one of two contexts:\n *\n * - **User context** — a request authenticated (or anonymous) via\n * `driver.withAuth(user)`. Runs as the restricted `rebase_user` role: a\n * non-owner, NOSUPERUSER, NOBYPASSRLS role, so Postgres RLS binds *every*\n * statement (SELECT, INSERT, UPDATE, DELETE). The collection's\n * `securityRules` are the whole authorization model; app-layer callbacks\n * are validation/side-effects, not a security boundary.\n *\n * - **Server context** — the base (owner) connection: auth flows, migrations,\n * and raw `rebase.sql`. As table owner it bypasses RLS. This is the trusted\n * plane, equivalent to Supabase's `service_role`.\n *\n * `rebase.dataAsAdmin` is **not** in it, despite the name. `init.ts` scopes\n * that driver with `withAuth(SERVICE_IDENTITY)`, so it arrives as user\n * context above — `rebase_user`, `app.uid = 'service'`, policies evaluated —\n * and clears the default policies through their admin arm rather than the\n * `rebase.uid() IS NULL` one.\n *\n * This module provides the three pieces:\n *\n * 1. {@link detectConnectionPosture} — is the connection subject to RLS at\n * all? (superuser / BYPASSRLS / table owner ⇒ no)\n * 2. {@link ensureAppRole} — idempotently provision `rebase_user` with\n * SELECT/INSERT/UPDATE/DELETE grants (+ default privileges so future\n * tables stay covered).\n * 3. {@link applyAuthContext} — per-transaction: set the `app.*` GUCs the\n * policies read (`rebase.uid()` etc.) and the transaction-local role\n * `rebase_user` so RLS binds, in one statement. Transaction-scoped, so it\n * composes with poolers.\n *\n * Provisioning runs from the framework's own bootstrap/migrate (which already\n * self-creates the `auth` schema and functions) — enforcement is default-on,\n * not an operator opt-in.\n */\n\n/**\n * The restricted role every authenticated (user-context) request runs as.\n *\n * Re-exported, not re-declared: the same name is needed by\n * `@rebasepro/common`'s internal-table revokes, and two spellings of a role name\n * fail as a silent no-op rather than an error.\n */\nexport { REBASE_USER_ROLE };\n\n/** Minimal SQL runner so callers can adapt drizzle or pg.Client. */\nexport type RawSqlRunner = (sqlText: string) => Promise<Record<string, unknown>[]>;\n\n/** Minimal transaction surface needed by {@link applyAuthContext}. */\nexport interface SqlTx {\n execute(query: SQL): Promise<unknown>;\n}\n\nexport interface ConnectionPosture {\n /** The connection's `current_user`. */\n role: string;\n superuser: boolean;\n bypassRLS: boolean;\n /**\n * Owns at least one user table — owners bypass non-FORCE RLS.\n *\n * \"Owns\" in Postgres's sense, not by name: a role that INHERITs the owner is\n * the owner for every ownership test the planner makes, including the one\n * that decides whether a policy applies at all.\n */\n ownsTables: boolean;\n /**\n * May create tables somewhere the server writes — and would then own them.\n *\n * The reason this is part of the posture rather than a separate question:\n * the posture is decided ONCE, at boot, and on a fresh database the\n * catalogue has nothing to report yet. The process that asks then goes on to\n * create every table in the schema and owns all of them for the rest of its\n * life. Asking only what is already there answers about the wrong instant.\n */\n canCreateTables: boolean;\n /** True when RLS would NOT constrain this connection. */\n privileged: boolean;\n}\n\nexport interface AuthContext {\n uid: string;\n /** Raw roles as carried on the user (strings or `{ id }` objects). */\n roles: unknown[];\n /**\n * Whether this session came from anonymous sign-in rather than an account.\n *\n * Anonymous sign-in mints a real user row and a real uid, so a guest was\n * indistinguishable from a registered account inside a policy: same\n * `rebase.uid()`, same default role. Every rule meaning \"a signed-in\n * person\" was therefore also a rule about anybody who had called\n * `POST /auth/anonymous`, which asks for no email, no password and no\n * agreement to anything.\n *\n * Optional, and absent reads as `false`: a caller that predates this — a\n * realtime subscription, a custom validator — keeps the behaviour it had\n * rather than having every one of its users reclassified as guests.\n */\n isAnonymous?: boolean;\n /**\n * The **custom** claims on the caller's token, as `rebase.jwt()` reports\n * them.\n *\n * This is how a policy reaches a fact about the session that is neither the\n * uid nor the roles — which, before this, it could not: `app.jwt` was built\n * from three fields the driver already had, so `rebase.jwt()`, documented\n * as \"full JWT claims as JSONB\", returned a three-key object that never had\n * a claim in it.\n *\n * Multi-tenancy's `claim` form is the first caller — `policy.authClaim(…)`\n * compiles to `rebase.jwt() ->> '<name>'`. Identity claims are stripped out\n * before they reach here (`AccessTokenPayload.claims`) and the identity\n * fields are written *over* them below, so nothing a hook put on a token\n * can assert a uid, roles or guest status.\n */\n claims?: Record<string, unknown>;\n}\n\nconst quoteIdent = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** DML the user role holds on managed tables (RLS still filters per row). */\nconst USER_TABLE_PRIVILEGES = \"SELECT, INSERT, UPDATE, DELETE\";\n\n/**\n * Take every privilege the user role holds on one table back — what a table\n * gets when RLS cannot be switched on for it, so it is unreachable rather than\n * unprotected. Quoted exactly: a mixed-case adopted table (`\"User\"`) folded to\n * lower case names a table that does not exist.\n */\nexport const revokeUserRoleSql = (schema: string, table: string): string =>\n `REVOKE ALL PRIVILEGES ON ${quoteIdent(schema)}.${quoteIdent(table)} FROM ${quoteIdent(REBASE_USER_ROLE)}`;\n\n/**\n * Warn when the connection role shares its name with an existing schema.\n *\n * Postgres resolves unqualified names through `search_path`, which defaults to\n * `\"$user\", public` — and `$user` is the connection ROLE. When a schema of that\n * name exists it sits ahead of `public`, so every unqualified statement\n * silently operates on it instead:\n *\n * CREATE TABLE posts (...); -- you meant public.posts; you got <role>.posts\n *\n * Nothing errors. You get a second table of the same name in the wrong schema,\n * and reads that pin `public` cannot see it — which reads as \"missing table\" and\n * sends people to re-run a push that creates a *third* copy. The bootstrapper\n * has a whole branch dedicated to recognising the symptom after the fact.\n *\n * Rebase shipped straight into this: it creates a schema named `rebase` while\n * every template named the database role `rebase` too. The scaffold uses\n * `rebase_app` now, and every pool Rebase opens pins `search_path=public`\n * (`pinSearchPath`), which covers the paths the framework controls. This covers\n * the ones it does not — `psql`, `pg_dump`, drizzle-kit, a colleague's script,\n * a hand-written migration — because the hazard is a property of the two NAMES,\n * not of any one connection.\n *\n * A warning rather than a boot failure: the database works, the framework's own\n * traffic is pinned, and refusing to start over a naming choice a user may have\n * inherited would be worse than the risk.\n */\nexport async function warnOnRoleSchemaCollision(run: RawSqlRunner): Promise<void> {\n try {\n const rows = await run(`\n SELECT current_user AS role,\n EXISTS (\n SELECT 1 FROM pg_namespace n WHERE n.nspname = current_user\n ) AS collides\n `);\n if (rows[0]?.collides !== true) return;\n const role = String(rows[0]?.role ?? \"the connection role\");\n logger.warn(\n `⚠️ The database role \"${role}\" has the same name as a schema. Postgres resolves unqualified ` +\n `names through \\`search_path\\`, which defaults to \\`\"$user\", public\\` — so \"${role}\" is searched ` +\n `BEFORE public, and any unqualified \\`CREATE TABLE\\`/\\`SELECT\\` from a tool that does not pin the ` +\n `path (psql, pg_dump, drizzle-kit, a hand-written migration) silently lands in \"${role}\" instead. ` +\n `Rebase's own connections pin \\`search_path=public\\`, so the server is unaffected. To remove the ` +\n `hazard entirely, connect as a role whose name is not also a schema — the scaffold uses ` +\n `\"rebase_app\".`\n );\n } catch {\n // A diagnostic must never be the reason a boot fails.\n }\n}\n\n/**\n * Would RLS actually constrain this connection?\n *\n * Four ways the answer is no, and only two of them are obvious. Superuser and\n * BYPASSRLS announce themselves in `pg_roles`. The other two are about\n * ownership, and both used to read as \"no bypass here\":\n *\n * - **Ownership through membership.** The old query compared\n * `pg_tables.tableowner` to `current_user` as a string. Postgres does not: a\n * role that INHERITs the owner passes every ownership test the planner makes,\n * including the one that decides whether a policy applies. So a perfectly\n * ordinary \"app role that is a member of the owner role\" setup reported\n * unprivileged and bypassed every policy — permanently, since no restart\n * changes a string comparison's answer.\n *\n * - **Ownership that has not happened yet.** The posture is decided once, at\n * boot, and on a fresh database there is nothing in the catalogue to find. The\n * same process then creates every table and owns all of them. The first boot\n * of a new deployment therefore served every request unconstrained, the log\n * said RLS was fine, and the SECOND boot silently fixed it — which is the\n * worst possible shape for a security check, because the state that reproduces\n * it is gone by the time anyone looks. Asking \"may this role create tables\n * where the server provisions?\" answers about the process's whole life rather\n * than about one instant of it.\n *\n * `schemas` narrows the CREATE question to where the server actually writes.\n * Omitted, it asks about every schema the role can see, which is the safe\n * direction: over-reporting costs a role switch that was not strictly needed,\n * under-reporting costs the entire authorization model.\n */\nexport async function detectConnectionPosture(\n run: RawSqlRunner,\n schemas?: string[]\n): Promise<ConnectionPosture> {\n // Identifiers, and they reach SQL as literals in a catalogue comparison —\n // but they arrive from collection configs, so they are quoted as string\n // literals rather than interpolated as names, and a quote inside one is\n // escaped rather than trusted.\n const schemaFilter = schemas?.length\n ? `AND n.nspname IN (${Array.from(new Set(schemas))\n .map((s) => `'${s.replace(/'/g, \"''\")}'`)\n .join(\", \")})`\n : \"\";\n\n const rows = await run(`\n SELECT current_user AS role,\n r.rolsuper AS superuser,\n r.rolbypassrls AS bypassrls,\n EXISTS (\n SELECT 1 FROM pg_tables t\n WHERE pg_has_role(current_user, t.tableowner, 'USAGE')\n AND t.schemaname NOT IN ('pg_catalog', 'information_schema')\n ) AS owns_tables,\n EXISTS (\n SELECT 1 FROM pg_namespace n\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND n.nspname NOT LIKE 'pg\\\\_toast%'\n AND n.nspname NOT LIKE 'pg\\\\_temp%'\n ${schemaFilter}\n AND has_schema_privilege(current_user, n.oid, 'CREATE')\n ) AS can_create\n FROM pg_roles r\n WHERE r.rolname = current_user\n `);\n const row = rows[0] ?? {};\n const superuser = row.superuser === true;\n const bypassRLS = row.bypassrls === true;\n const ownsTables = row.owns_tables === true;\n const canCreateTables = row.can_create === true;\n return {\n role: String(row.role ?? \"unknown\"),\n superuser,\n bypassRLS,\n ownsTables,\n canCreateTables,\n privileged: superuser || bypassRLS || ownsTables || canCreateTables\n };\n}\n\n/**\n * Human-actionable instructions for when the connection cannot provision the\n * user role itself (no CREATEROLE and role not pre-created by the platform).\n */\nexport function appRoleSetupInstructions(connectionRole: string, schemas: string[]): string {\n const grants = schemas.map((s) =>\n `GRANT USAGE ON SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};\\n` +\n `GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};\\n` +\n `GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};`\n ).join(\"\\n\");\n return (\n `Rebase enforces row-level security by running authenticated requests as ` +\n `the restricted role \"${REBASE_USER_ROLE}\", but the connection role ` +\n `\"${connectionRole}\" bypasses RLS and cannot create that role itself.\\n` +\n `Run the following as a database administrator, then restart:\\n\\n` +\n `CREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\\n` +\n `GRANT ${REBASE_USER_ROLE} TO ${quoteIdent(connectionRole)};\\n` +\n grants\n );\n}\n\n/**\n * Idempotently provision the `rebase_user` role, membership for the current\n * connection role, and DML grants (+ default privileges for future tables)\n * on every existing schema in `schemas`.\n *\n * Split into privilege tiers so it works both when the connection is a\n * superuser (creates everything) and when the platform pre-created the role\n * and membership (e.g. CNPG `postInitApplicationSQL`) and the connection is\n * merely the table owner — owners can always run the grant tier themselves.\n *\n * RLS still filters every row: these grants only make the tables *reachable*\n * by the role; the policies decide which rows/commands actually pass.\n *\n * Throws with precise setup instructions when the role is missing and the\n * connection cannot create it.\n */\nexport async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promise<void> {\n const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));\n\n // Tier 1 — role existence.\n const roleRows = await run(`SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}'`);\n if (roleRows.length === 0) {\n try {\n // Guarded in the statement as well as by the probe above. A role\n // belongs to the cluster, not the database, so a recorded\n // provisioning run (REBASE_PROVISION_SQL_OUT) replayed into another\n // database on a cluster that already has the role must find this a\n // no-op rather than its first error.\n await run(`\n DO $rebase_role$\n BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}') THEN\n CREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\n END\n $rebase_role$\n `);\n } catch (err) {\n throw new Error(\n `Failed to create the \"${REBASE_USER_ROLE}\" role: ${err instanceof Error ? err.message : String(err)}\\n\\n` +\n appRoleSetupInstructions(\"current connection role\", uniqueSchemas)\n );\n }\n }\n\n // Tier 2 — membership, so a non-superuser connection may SET ROLE to it.\n const memberRows = await run(`\n SELECT (pg_has_role(current_user, '${REBASE_USER_ROLE}', 'MEMBER')\n OR (SELECT rolsuper FROM pg_roles WHERE rolname = current_user)) AS can_set,\n current_user AS role\n `);\n if (memberRows[0]?.can_set !== true) {\n try {\n await run(`GRANT ${REBASE_USER_ROLE} TO CURRENT_USER`);\n } catch (err) {\n throw new Error(\n `The connection role is not a member of \"${REBASE_USER_ROLE}\" and cannot grant itself membership: ` +\n `${err instanceof Error ? err.message : String(err)}\\n\\n` +\n appRoleSetupInstructions(String(memberRows[0]?.role ?? \"current connection role\"), uniqueSchemas)\n );\n }\n }\n\n // Tier 3 — grants.\n await ensureAppRoleGrants(run, uniqueSchemas);\n\n logger.debug(`🔐 [rls] User role \"${REBASE_USER_ROLE}\" provisioned (schemas: ${uniqueSchemas.join(\", \")})`);\n}\n\n/** A string literal for a catalogue read. Names come from config and constants, never from a request. */\nconst sqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\nconst textArray = (values: readonly string[]): string =>\n values.length === 0 ? \"ARRAY[]::text[]\" : `ARRAY[${values.map(sqlLiteral).join(\", \")}]::text[]`;\n\n/**\n * The framework's internal tables in `schemas` that the request role can\n * reach — `schema.table`, sorted — when nothing is left to take it back off.\n *\n * Every provisioning boot repairs this: each store revokes on its own table\n * and {@link ensureAppRole}'s sweep revokes on the rest, because the grant\n * tier hands the request role DML on whole schemas. A backend that changes\n * nothing in its database runs neither, so a database whose `rebase_user` can\n * read `refresh_tokens` or `api_keys` would stay that way for as long as it\n * served. This is the question the sweep would have answered, asked instead.\n *\n * \"Can reach\" is what the role can actually do — through a grant to it, to a\n * role it inherits, or to PUBLIC, on the table or on any of its columns —\n * because that, not how the ACL is spelled, is what a request running as it\n * gets. A table with RLS on is somebody's collection by that same rule as the\n * sweep's, and is left out.\n */\nexport async function findExposedInternalTables(run: RawSqlRunner, schemas: string[]): Promise<string[]> {\n const rows = await run(`\n SELECT n.nspname || '.' || c.relname AS name\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY(${textArray(Array.from(new Set(schemas)))})\n AND c.relname = ANY(${textArray(REBASE_INTERNAL_TABLES)})\n AND c.relkind IN ('r', 'p')\n AND NOT c.relrowsecurity\n AND (has_table_privilege(${sqlLiteral(REBASE_USER_ROLE)}, c.oid, 'SELECT, INSERT, UPDATE, DELETE')\n OR has_any_column_privilege(${sqlLiteral(REBASE_USER_ROLE)}, c.oid, 'SELECT, INSERT, UPDATE'))\n ORDER BY 1\n `);\n return rows.map(row => String(row.name));\n}\n\n/** What the grant tier would find already in place in one schema. */\ninterface SchemaGrants {\n /** `USAGE` on the schema, granted by its owner. */\n usage: boolean;\n /**\n * Every relation `GRANT … ON ALL TABLES` reaches already has all four DML\n * privileges from its owner — Rebase's own RLS-off tables aside, which the\n * sweep takes back right after and so never keep them.\n */\n tables: boolean;\n /** Every sequence already has `USAGE, SELECT` from its owner. */\n sequences: boolean;\n /** This role's default privileges in the schema already grant the table DML. */\n defaultTables: boolean;\n /** …and the sequence `USAGE, SELECT`. */\n defaultSequences: boolean;\n /**\n * Rebase's own RLS-off tables a `REVOKE` would still change: the user role\n * holds a privilege on them, or the table has never had an ACL written —\n * `NULL`, which a `REVOKE` (like the grant-and-revoke it replaces) turns\n * into the owner's explicit default. Same access either way; the same\n * catalogue only this way.\n */\n internalGranted: string[];\n}\n\n/**\n * The grant tier's state for every existing schema in `schemas`, in one read.\n *\n * A grant counts as present only as the statement this tier runs would record\n * it — grantor the object's owner, which is what a GRANT by the owner, a member\n * of the owning role or a superuser records — so skipping it leaves the ACL\n * exactly as running it would. Anything else reads as missing, and the\n * statement runs as it always did.\n */\nasync function readSchemaGrants(run: RawSqlRunner, schemas: string[]): Promise<Map<string, SchemaGrants>> {\n const internal = textArray(REBASE_INTERNAL_TABLES);\n const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(REBASE_USER_ROLE)})`;\n /** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */\n const held = (acl: string, privileges: string[], grantor?: string): string =>\n `(SELECT count(DISTINCT a.privilege_type) FROM aclexplode(${acl}) a WHERE a.grantee = ${target}` +\n `${grantor ? ` AND a.grantor = ${grantor}` : \"\"} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(\", \")}))`;\n const DML = [\"SELECT\", \"INSERT\", \"UPDATE\", \"DELETE\"];\n const SEQ = [\"USAGE\", \"SELECT\"];\n const rows = await run(`\n SELECT n.nspname AS schema,\n ${held(\"n.nspacl\", [\"USAGE\"], \"n.nspowner\")} = 1 AS usage,\n NOT EXISTS (\n SELECT 1 FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')\n AND NOT (c.relname = ANY(${internal}) AND NOT c.relrowsecurity)\n AND ${held(\"c.relacl\", DML, \"c.relowner\")} < ${DML.length}\n ) AS tables,\n NOT EXISTS (\n SELECT 1 FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relkind = 'S'\n AND ${held(\"c.relacl\", SEQ, \"c.relowner\")} < ${SEQ.length}\n ) AS sequences,\n EXISTS (\n SELECT 1 FROM pg_default_acl d\n WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'r'\n AND ${held(\"d.defaclacl\", DML)} = ${DML.length}\n ) AS default_tables,\n EXISTS (\n SELECT 1 FROM pg_default_acl d\n WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'S'\n AND ${held(\"d.defaclacl\", SEQ)} = ${SEQ.length}\n ) AS default_sequences,\n ARRAY(\n SELECT c.relname::text FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relname = ANY(${internal}) AND NOT c.relrowsecurity\n AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))\n ORDER BY 1\n ) AS internal_granted\n FROM pg_namespace n\n WHERE n.nspname = ANY(${textArray(schemas)})\n `);\n const grants = new Map<string, SchemaGrants>();\n for (const row of rows) {\n const internalGranted = row.internal_granted;\n grants.set(String(row.schema), {\n usage: row.usage === true,\n tables: row.tables === true,\n sequences: row.sequences === true,\n defaultTables: row.default_tables === true,\n defaultSequences: row.default_sequences === true,\n internalGranted: Array.isArray(internalGranted)\n ? internalGranted.map(String)\n // A driver that hands arrays back as text: `{a,b}`.\n : String(internalGranted ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean)\n });\n }\n return grants;\n}\n\n/**\n * The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing\n * schema in `schemas`, DML on its tables and `USAGE, SELECT` on its\n * sequences, the default privileges that cover what this role creates later,\n * and Rebase's own tables taken back — for a role and membership already\n * provisioned.\n *\n * Every statement is issued only when the catalogue says it would change\n * something. They used to run unconditionally, twice per boot (at connect, and\n * again in the final posture check): a `GRANT … ON ALL TABLES` rewrites every\n * table's `pg_class` row whether or not the ACL changes, which invalidates\n * every table's cached plans on every connection, and the internal-table sweep\n * ran 23 `REVOKE`s per schema. A boot against a database whose grants already\n * hold now reads one catalogue query and writes nothing; one that is missing\n * any of them runs exactly the statements it always ran.\n *\n * Table owners (the expected non-superuser posture) can always grant on their\n * own objects, so this needs no extra privilege.\n */\nexport async function ensureAppRoleGrants(run: RawSqlRunner, schemas: string[]): Promise<void> {\n const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));\n const grants = await readSchemaGrants(run, uniqueSchemas);\n for (const schema of uniqueSchemas) {\n const state = grants.get(schema);\n // Not there (yet): a later call, once provisioning has created it, grants it.\n if (!state) continue;\n const s = quoteIdent(schema);\n if (!state.usage) await run(`GRANT USAGE ON SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n if (!state.tables) await run(`GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n if (!state.sequences) await run(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n // Cover objects created later by the CURRENT role (the role that runs\n // migrations), so a migrate can never strand the user role.\n if (!state.defaultTables) {\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${REBASE_USER_ROLE}`);\n }\n if (!state.defaultSequences) {\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${REBASE_USER_ROLE}`);\n }\n\n // The grants above are deliberately schema-wide — a project's own\n // collections may live in `rebase`, and future tables must be reachable\n // or a migration strands the role. Rebase's OWN tables are the exception:\n // refresh tokens, MFA secrets, API keys and the rest carry no RLS and no\n // row an end user should ever address. Taking the privilege back here\n // covers every table that already exists; each creator revokes on the\n // table it just made, for the boot that creates them for the first time.\n //\n // All of them right after the schema-wide grant, which has just handed\n // them out; otherwise only the ones the catalogue says still hold one.\n const tables = state.tables ? state.internalGranted : undefined;\n if (tables && tables.length === 0) continue;\n await revokeInternalTableAccess(async (text) => { await run(text); }, schema, {\n tables,\n onError: (table, error) => logger.warn(\n `🔐 [rls] Could not revoke \"${REBASE_USER_ROLE}\" access to \"${schema}\".\"${table}\" — ` +\n \"it stays reachable by authenticated requests: \" +\n (error instanceof Error ? error.message : String(error))\n )\n });\n }\n}\n\n/**\n * Rebase's own RLS-off tables in `schema` that a `revokeInternalTableAccess`\n * sweep would change — the user role holds a privilege on them, or their ACL\n * has never been written. One read; the sweep it narrows is one `DO` per\n * table name.\n */\nexport async function internalTablesGrantedToUserRole(run: RawSqlRunner, schema: string): Promise<string[]> {\n return (await readSchemaGrants(run, [schema])).get(schema)?.internalGranted ?? [];\n}\n\n/**\n * Apply the authenticated context to a transaction: the `app.*` GUCs that RLS\n * policies read via `rebase.uid()` / `rebase.roles()` / `rebase.jwt()`, and — when\n * `userRole` is set — the `LOCAL` role switch, in the same statement, so RLS\n * binds every statement in this transaction (reads *and* writes).\n *\n * GUCs are set with `is_local = true` and the role switch is `LOCAL`: both\n * reset at commit/rollback, so pooled connections are never polluted.\n *\n * Fails closed by construction: if the role switch errors, the transaction\n * aborts instead of proceeding privileged.\n *\n * SECURITY: this function is only ever called on the **user** path (the server\n * context uses the base/owner driver and never calls it). The default policies\n * treat `rebase.uid() IS NULL` as the trusted server context, and `rebase.uid()`\n * is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would\n * be read as NULL and silently escalate a user request to server privileges.\n * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,\n * rather than trusting every caller (e.g. realtime subscription auth) to do it.\n * That sentinel is exported from `@rebasepro/types` because it leaks into rule\n * semantics: it is why `rebase.uid() IS NOT NULL` is true for anonymous requests.\n */\nexport async function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void> {\n const uid = typeof auth.uid === \"string\" && auth.uid.trim() !== \"\" ? auth.uid : ANONYMOUS_USER_ID;\n const normalizedRoles = auth.roles.map((r: unknown) =>\n typeof r === \"string\" ? r : (r as Record<string, unknown>)?.id ?? String(r)\n );\n // `app.user_id` is the pre-rename spelling, still written because policies\n // are data: a database provisioned before the rename holds rules compiled\n // to `current_setting('app.user_id')`, and those predicates would evaluate\n // to NULL — failing open or locking out — if we stopped setting it. Drop\n // the alias only once no live database carries a legacy policy.\n // A guest is a signed-in caller with no account behind them, and until this\n // the database could not tell the difference — see `rebase.is_anonymous()`.\n // Written as a string because that is what `set_config` takes.\n const isAnonymous = auth.isAnonymous === true ? \"true\" : \"false\";\n\n await tx.execute(drizzleSql`\n SELECT\n set_config('app.uid', ${uid}, true),\n set_config('app.user_id', ${uid}, true),\n set_config('app.user_roles', ${normalizedRoles.join(\",\")}, true),\n set_config('app.is_anonymous', ${isAnonymous}, true),\n set_config('app.jwt', ${JSON.stringify({\n // The caller's custom claims, FIRST, so the identity keys below\n // overwrite them rather than the other way round. Same ordering, and\n // the same reason, as `generateAccessToken`: a claims hook is a place\n // to add facts about a session, not the place its subject is decided.\n // `verifyAccessToken` already strips the identity claims out of this\n // object; the ordering is the second lock on the same door.\n ...(auth.claims ?? {}),\n sub: uid,\n roles: auth.roles,\n // In the claims too, so a policy reading `rebase.jwt()` — which is\n // how a rule reaches anything that is not uid or roles — sees the\n // same fact as `rebase.is_anonymous()`. Two sources that could\n // disagree would be worse than one.\n is_anonymous: auth.isAnonymous === true\n })}, true)${userRole\n // The role switch, in the same statement rather than a `SET LOCAL ROLE`\n // round trip of its own on every transaction. Postgres implements\n // `SET ROLE` as the `role` setting: `set_config('role', name, true)`\n // runs the same membership check, fails with the same SQLSTATE and\n // message (42501 \"permission denied to set role\", 22023 for an unknown\n // role — `isRoleSwitchingPermissionError` still reads it), takes the\n // name verbatim as the quoted identifier did, and resets at COMMIT and\n // ROLLBACK like `LOCAL`. Last in the list, after the GUCs; a refusal\n // fails the whole statement, so the transaction aborts rather than\n // running on as the connection owner. auth-context-one-statement.test.ts.\n ? drizzleSql`,\n set_config('role', ${userRole}, true)`\n : drizzleSql``}\n `);\n}\n\n/** Role names from other BaaS platforms that people reach for out of habit. */\nconst FOREIGN_CONVENTION_ROLES: Record<string, string> = {\n authenticated: \"Supabase\",\n anon: \"Supabase\",\n service_role: \"Supabase\"\n};\n\n/**\n * Warn about rules that read as \"signed-in users only\" but admit anonymous\n * callers — `rebase.uid() IS NOT NULL`, or a comparison against another\n * platform's magic user id such as `'anon'`.\n *\n * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling\n * of the same habit. A foreign `pgRoles` value makes a policy unreachable and\n * the table reads empty — loud, and that guard throws. These do the opposite:\n * the rule compiles to a grant, and nothing looks wrong until the data is\n * already public.\n *\n * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are\n * serving traffic today: refusing to boot would take an app offline to report a\n * problem it already has, and on the read path it would take it offline\n * *because* its data was exposed. Rewriting the author's SQL is not an option\n * either — this is the escape hatch whose whole promise is that it means what it\n * says. So: say so, loudly, and leave the rule alone.\n */\nexport function warnOnAnonymousGrants(\n collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]\n): void {\n // Grouped by the mistake, not by the rule: one habit typically repeats\n // across every collection an author wrote, and a per-rule list would repeat\n // the same paragraph dozens of times and get skimmed.\n const byRisk = new Map<string, { risk: AnonymousGrantRisk; sites: string[] }>();\n\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n const risks = [usingExpr, withCheckExpr]\n .filter((e): e is PolicyExpression => e !== null)\n .flatMap(findAnonymousGrants);\n\n for (const risk of risks) {\n const key = `${risk.pattern}:${risk.detail}`;\n const site = `${collection.slug ?? \"(unnamed)\"} → \"${rule.name ?? \"(unnamed rule)\"}\"`;\n const entry = byRisk.get(key) ?? { risk, sites: [] };\n if (!entry.sites.includes(site)) entry.sites.push(site);\n byRisk.set(key, entry);\n }\n }\n }\n\n if (byRisk.size === 0) return;\n\n const problems = [...byRisk.values()].map(({ risk, sites }) =>\n ` • ${risk.explanation}\\n ${sites.length} rule(s): ${sites.join(\", \")}`\n );\n\n logger.warn(\n `Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a ` +\n `client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are ` +\n `true for everyone:\\n\\n` +\n problems.join(\"\\n\\n\") + \"\\n\"\n );\n}\n\n/**\n * Name the collections whose raw policy SQL still calls the pre-1.0 helpers.\n *\n * The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the\n * database, so nothing is broken and no policy is wrong — which is exactly why\n * this has to be said out loud. A silent rewrite that works forever is not a\n * migration, it is a second supported spelling nobody wrote down, and the next\n * person to read those rules will copy the old one.\n *\n * Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,\n * `policy.rolesOverlap(...)`) compile from the model and were never affected.\n */\nexport function warnOnLegacyRlsFunctions(\n collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]\n): void {\n const sites: string[] = [];\n\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n const carriesLegacy = [usingExpr, withCheckExpr]\n .filter((e): e is PolicyExpression => e !== null)\n .some(containsLegacyRlsCall);\n if (!carriesLegacy) continue;\n\n const site = `${collection.slug ?? \"(unnamed)\"} → \"${rule.name ?? \"(unnamed rule)\"}\"`;\n if (!sites.includes(site)) sites.push(site);\n }\n }\n\n if (sites.length === 0) return;\n\n logger.warn(\n `These security rules call the pre-1.0 RLS helpers (\\`auth.uid()\\`, \\`auth.roles()\\`, \\`auth.jwt()\\`). ` +\n `They still work — the compiler rewrites them — but the functions now live in the \\`rebase\\` schema, ` +\n `and the \\`auth\\` one is Supabase's. Update the raw SQL in these rules to \\`${REBASE_SCHEMA}.uid()\\` ` +\n `and friends, or switch them to the structured helpers (\\`policy.authUid()\\`, \\`policy.rolesOverlap()\\`), ` +\n `which never had to be spelled by hand:\\n\\n` +\n sites.map(s => ` • ${s}`).join(\"\\n\") + \"\\n\"\n );\n}\n\n/** Whether any `raw` expression in the tree calls a pre-1.0 helper. */\nfunction containsLegacyRlsCall(expr: PolicyExpression): boolean {\n switch (expr.kind) {\n case \"raw\":\n return usesLegacyRlsFunctions(expr.sql);\n case \"and\":\n case \"or\":\n return expr.operands.some(containsLegacyRlsCall);\n case \"not\":\n return containsLegacyRlsCall(expr.operand);\n case \"existsIn\":\n return containsLegacyRlsCall(expr.where);\n default:\n return false;\n }\n}\n\n/**\n * Reject `pgRoles` that this server can never satisfy.\n *\n * `pgRoles` sets the `TO` clause of a generated policy, so a policy naming a\n * role the request never runs as simply never applies — and RLS then filters\n * every row. The table reads as empty, which is indistinguishable from having\n * no data, so the mistake survives review and ships.\n *\n * Requests run as `rebase_user`, so a policy is only reachable if it targets\n * `public` or a role `rebase_user` holds. Anything else is a configuration\n * error worth failing the boot for.\n */\nexport async function validatePolicyPgRoles(\n run: RawSqlRunner,\n collections: { slug?: string; securityRules?: readonly { name?: string; pgRoles?: readonly string[] }[] }[],\n /** The role requests actually run as: `rebase_user` when the connection is\n * privileged enough to switch, otherwise the connection role itself. */\n requestRole: string = REBASE_USER_ROLE\n): Promise<void> {\n const wanted = new Map<string, string[]>();\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n for (const role of rule.pgRoles ?? []) {\n if (role === \"public\") continue;\n wanted.set(role, [...(wanted.get(role) ?? []), collection.slug ?? \"(unnamed)\"]);\n }\n }\n }\n if (wanted.size === 0) return;\n\n const names = [...wanted.keys()].map((r) => `'${r.replace(/'/g, \"''\")}'`).join(\",\");\n const escapedRequestRole = requestRole.replace(/'/g, \"''\");\n const rows = await run(`\n SELECT r.rolname AS role,\n COALESCE(pg_has_role(to_regrole('${escapedRequestRole}'), r.oid, 'MEMBER'), false) AS reachable\n FROM pg_roles r\n WHERE r.rolname IN (${names})\n `);\n\n const reachable = new Map(rows.map((row) => [String(row.role), row.reachable === true]));\n const problems: string[] = [];\n\n for (const [role, slugs] of wanted) {\n if (reachable.get(role) === true) continue;\n\n const why = reachable.has(role)\n ? `\"${requestRole}\" is not a member of it`\n : \"no such role exists in this database\";\n const platform = FOREIGN_CONVENTION_ROLES[role];\n const hint = platform\n ? `\"${role}\" is a ${platform} convention, not a PostgreSQL role. Application roles belong in \\`roles: [\"${role === \"service_role\" ? \"admin\" : role}\"]\\`, which is checked inside the policy via rebase.roles().`\n : `Either grant it (GRANT ${role} TO ${requestRole}) or drop \\`pgRoles\\` so the policy targets \\`public\\`.`;\n\n problems.push(\n ` • pgRoles: [\"${role}\"] on ${slugs.join(\", \")} — ${why}.\\n ${hint}`\n );\n }\n\n if (problems.length > 0) {\n throw new Error(\n `Security rules target PostgreSQL roles this server cannot use. Requests run as ` +\n `\"${requestRole}\", so these policies would never apply and every row would be ` +\n `filtered out — the collections would look empty rather than error.\\n\\n` +\n problems.join(\"\\n\\n\") + \"\\n\"\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsIA,IAAM,cAAc,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;;AAG5E,IAAM,wBAAwB;;;;;;;AAQ9B,IAAa,qBAAqB,QAAgB,UAC9C,4BAA4B,WAAW,MAAM,EAAE,GAAG,WAAW,KAAK,EAAE,QAAQ,WAAW,kBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6B3G,eAAsB,0BAA0B,KAAkC;CAC9E,IAAI;EACA,MAAM,OAAO,MAAM,IAAI;;;;;SAKtB;EACD,IAAI,KAAK,EAAE,EAAE,aAAa,MAAM;EAChC,MAAM,OAAO,OAAO,KAAK,EAAE,EAAE,QAAQ,qBAAqB;EAC1D,OAAO,KACH,0BAA0B,KAAK,4IAC+C,KAAK,gMAED,KAAK,gNAI3F;CACJ,QAAQ,CAER;AACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,wBAClB,KACA,SAC0B;CA+B1B,MAAM,OAAM,MApBO,IAAI;;;;;;;;;;;;;;uBANF,SAAS,SACxB,qBAAqB,MAAM,KAAK,IAAI,IAAI,OAAO,CAAC,CAAC,CAC9C,KAAK,MAAM,IAAI,EAAE,QAAQ,MAAM,IAAI,EAAE,EAAE,CAAC,CACxC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;;8BAEvC,MAAM;KAC/B;CAED,MAAM,YAAY,IAAI,IAAI,KAAK,KAAK,QAAQ,CAAC,OAAO,IAAI,IAAI,GAAG,IAAI,cAAc,IAAI,CAAC,CAAC;CACvF,MAAM,WAAqB,CAAC;CAE5B,KAAK,MAAM,CAAC,MAAM,UAAU,QAAQ;EAChC,IAAI,UAAU,IAAI,IAAI,MAAM,MAAM;EAElC,MAAM,MAAM,UAAU,IAAI,IAAI,IACxB,IAAI,YAAY,2BAChB;EACN,MAAM,WAAW,yBAAyB;EAC1C,MAAM,OAAO,WACP,IAAI,KAAK,SAAS,SAAS,6EAA6E,SAAS,iBAAiB,UAAU,KAAK,gEACjJ,0BAA0B,KAAK,MAAM,YAAY;EAEvD,SAAS,KACL,kBAAkB,KAAK,QAAQ,MAAM,KAAK,IAAI,EAAE,KAAK,IAAI,SAAS,MACtE;CACJ;CAEA,IAAI,SAAS,SAAS,GAClB,MAAM,IAAI,MACN,mFACI,YAAY,wIAEhB,SAAS,KAAK,MAAM,IAAI,IAC5B;AAER"}
|
|
1
|
+
{"version":3,"file":"rls-enforcement-jZTv1yci.js","names":[],"sources":["../src/security/rls-enforcement.ts"],"sourcesContent":["import { sql as drizzleSql, SQL } from \"drizzle-orm\";\nimport { ANONYMOUS_USER_ID, PolicyExpression, SecurityRule } from \"@rebasepro/types\";\nimport {\n AnonymousGrantRisk,\n findAnonymousGrants,\n REBASE_INTERNAL_TABLES,\n REBASE_USER_ROLE,\n revokeInternalTableAccess,\n securityRuleToConditions\n} from \"@rebasepro/common\";\nimport { REBASE_SCHEMA, usesLegacyRlsFunctions } from \"@rebasepro/types\";\nimport { logger } from \"@rebasepro/server\";\n\n/**\n * Unified RLS enforcement — the \"user context vs server context\" model.\n *\n * Every operation runs in one of two contexts:\n *\n * - **User context** — a request authenticated (or anonymous) via\n * `driver.withAuth(user)`. Runs as the restricted `rebase_user` role: a\n * non-owner, NOSUPERUSER, NOBYPASSRLS role, so Postgres RLS binds *every*\n * statement (SELECT, INSERT, UPDATE, DELETE). The collection's\n * `securityRules` are the whole authorization model; app-layer callbacks\n * are validation/side-effects, not a security boundary.\n *\n * - **Server context** — the base (owner) connection: auth flows, migrations,\n * and raw `rebase.sql`. As table owner it bypasses RLS. This is the trusted\n * plane, equivalent to Supabase's `service_role`.\n *\n * `rebase.dataAsAdmin` is **not** in it, despite the name. `init.ts` scopes\n * that driver with `withAuth(SERVICE_IDENTITY)`, so it arrives as user\n * context above — `rebase_user`, `app.uid = 'service'`, policies evaluated —\n * and clears the default policies through their admin arm rather than the\n * `rebase.uid() IS NULL` one.\n *\n * This module provides the three pieces:\n *\n * 1. {@link detectConnectionPosture} — is the connection subject to RLS at\n * all? (superuser / BYPASSRLS / table owner ⇒ no)\n * 2. {@link ensureAppRole} — idempotently provision `rebase_user` with\n * SELECT/INSERT/UPDATE/DELETE grants (+ default privileges so future\n * tables stay covered).\n * 3. {@link applyAuthContext} — per-transaction: set the `app.*` GUCs the\n * policies read (`rebase.uid()` etc.) and the transaction-local role\n * `rebase_user` so RLS binds, in one statement. Transaction-scoped, so it\n * composes with poolers.\n *\n * Provisioning runs from the framework's own bootstrap/migrate (which already\n * self-creates the `auth` schema and functions) — enforcement is default-on,\n * not an operator opt-in.\n */\n\n/**\n * The restricted role every authenticated (user-context) request runs as.\n *\n * Re-exported, not re-declared: the same name is needed by\n * `@rebasepro/common`'s internal-table revokes, and two spellings of a role name\n * fail as a silent no-op rather than an error.\n */\nexport { REBASE_USER_ROLE };\n\n/** Minimal SQL runner so callers can adapt drizzle or pg.Client. */\nexport type RawSqlRunner = (sqlText: string) => Promise<Record<string, unknown>[]>;\n\n/** Minimal transaction surface needed by {@link applyAuthContext}. */\nexport interface SqlTx {\n execute(query: SQL): Promise<unknown>;\n}\n\nexport interface ConnectionPosture {\n /** The connection's `current_user`. */\n role: string;\n superuser: boolean;\n bypassRLS: boolean;\n /**\n * Owns at least one user table — owners bypass non-FORCE RLS.\n *\n * \"Owns\" in Postgres's sense, not by name: a role that INHERITs the owner is\n * the owner for every ownership test the planner makes, including the one\n * that decides whether a policy applies at all.\n */\n ownsTables: boolean;\n /**\n * May create tables somewhere the server writes — and would then own them.\n *\n * The reason this is part of the posture rather than a separate question:\n * the posture is decided ONCE, at boot, and on a fresh database the\n * catalogue has nothing to report yet. The process that asks then goes on to\n * create every table in the schema and owns all of them for the rest of its\n * life. Asking only what is already there answers about the wrong instant.\n */\n canCreateTables: boolean;\n /** True when RLS would NOT constrain this connection. */\n privileged: boolean;\n}\n\nexport interface AuthContext {\n uid: string;\n /** Raw roles as carried on the user (strings or `{ id }` objects). */\n roles: unknown[];\n /**\n * Whether this session came from anonymous sign-in rather than an account.\n *\n * Anonymous sign-in mints a real user row and a real uid, so a guest was\n * indistinguishable from a registered account inside a policy: same\n * `rebase.uid()`, same default role. Every rule meaning \"a signed-in\n * person\" was therefore also a rule about anybody who had called\n * `POST /auth/anonymous`, which asks for no email, no password and no\n * agreement to anything.\n *\n * Optional, and absent reads as `false`: a caller that predates this — a\n * realtime subscription, a custom validator — keeps the behaviour it had\n * rather than having every one of its users reclassified as guests.\n */\n isAnonymous?: boolean;\n /**\n * The **custom** claims on the caller's token, as `rebase.jwt()` reports\n * them.\n *\n * This is how a policy reaches a fact about the session that is neither the\n * uid nor the roles — which, before this, it could not: `app.jwt` was built\n * from three fields the driver already had, so `rebase.jwt()`, documented\n * as \"full JWT claims as JSONB\", returned a three-key object that never had\n * a claim in it.\n *\n * Multi-tenancy's `claim` form is the first caller — `policy.authClaim(…)`\n * compiles to `rebase.jwt() ->> '<name>'`. Identity claims are stripped out\n * before they reach here (`AccessTokenPayload.claims`) and the identity\n * fields are written *over* them below, so nothing a hook put on a token\n * can assert a uid, roles or guest status.\n */\n claims?: Record<string, unknown>;\n}\n\nconst quoteIdent = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** DML the user role holds on managed tables (RLS still filters per row). */\nconst USER_TABLE_PRIVILEGES = \"SELECT, INSERT, UPDATE, DELETE\";\n\n/**\n * Take every privilege the user role holds on one table back — what a table\n * gets when RLS cannot be switched on for it, so it is unreachable rather than\n * unprotected. Quoted exactly: a mixed-case adopted table (`\"User\"`) folded to\n * lower case names a table that does not exist.\n */\nexport const revokeUserRoleSql = (schema: string, table: string): string =>\n `REVOKE ALL PRIVILEGES ON ${quoteIdent(schema)}.${quoteIdent(table)} FROM ${quoteIdent(REBASE_USER_ROLE)}`;\n\n/**\n * Warn when the connection role shares its name with an existing schema.\n *\n * Postgres resolves unqualified names through `search_path`, which defaults to\n * `\"$user\", public` — and `$user` is the connection ROLE. When a schema of that\n * name exists it sits ahead of `public`, so every unqualified statement\n * silently operates on it instead:\n *\n * CREATE TABLE posts (...); -- you meant public.posts; you got <role>.posts\n *\n * Nothing errors. You get a second table of the same name in the wrong schema,\n * and reads that pin `public` cannot see it — which reads as \"missing table\" and\n * sends people to re-run a push that creates a *third* copy. The bootstrapper\n * has a whole branch dedicated to recognising the symptom after the fact.\n *\n * Rebase shipped straight into this: it creates a schema named `rebase` while\n * every template named the database role `rebase` too. The scaffold uses\n * `rebase_app` now, and every pool Rebase opens pins `search_path=public`\n * (`pinSearchPath`), which covers the paths the framework controls. This covers\n * the ones it does not — `psql`, `pg_dump`, drizzle-kit, a colleague's script,\n * a hand-written migration — because the hazard is a property of the two NAMES,\n * not of any one connection.\n *\n * A warning rather than a boot failure: the database works, the framework's own\n * traffic is pinned, and refusing to start over a naming choice a user may have\n * inherited would be worse than the risk.\n */\nexport async function warnOnRoleSchemaCollision(run: RawSqlRunner): Promise<void> {\n try {\n const rows = await run(`\n SELECT current_user AS role,\n EXISTS (\n SELECT 1 FROM pg_namespace n WHERE n.nspname = current_user\n ) AS collides\n `);\n if (rows[0]?.collides !== true) return;\n const role = String(rows[0]?.role ?? \"the connection role\");\n logger.warn(\n `⚠️ The database role \"${role}\" has the same name as a schema. Postgres resolves unqualified ` +\n `names through \\`search_path\\`, which defaults to \\`\"$user\", public\\` — so \"${role}\" is searched ` +\n `BEFORE public, and any unqualified \\`CREATE TABLE\\`/\\`SELECT\\` from a tool that does not pin the ` +\n `path (psql, pg_dump, drizzle-kit, a hand-written migration) silently lands in \"${role}\" instead. ` +\n `Rebase's own connections pin \\`search_path=public\\`, so the server is unaffected. To remove the ` +\n `hazard entirely, connect as a role whose name is not also a schema — the scaffold uses ` +\n `\"rebase_app\".`\n );\n } catch {\n // A diagnostic must never be the reason a boot fails.\n }\n}\n\n/**\n * Would RLS actually constrain this connection?\n *\n * Four ways the answer is no, and only two of them are obvious. Superuser and\n * BYPASSRLS announce themselves in `pg_roles`. The other two are about\n * ownership, and both used to read as \"no bypass here\":\n *\n * - **Ownership through membership.** The old query compared\n * `pg_tables.tableowner` to `current_user` as a string. Postgres does not: a\n * role that INHERITs the owner passes every ownership test the planner makes,\n * including the one that decides whether a policy applies. So a perfectly\n * ordinary \"app role that is a member of the owner role\" setup reported\n * unprivileged and bypassed every policy — permanently, since no restart\n * changes a string comparison's answer.\n *\n * - **Ownership that has not happened yet.** The posture is decided once, at\n * boot, and on a fresh database there is nothing in the catalogue to find. The\n * same process then creates every table and owns all of them. The first boot\n * of a new deployment therefore served every request unconstrained, the log\n * said RLS was fine, and the SECOND boot silently fixed it — which is the\n * worst possible shape for a security check, because the state that reproduces\n * it is gone by the time anyone looks. Asking \"may this role create tables\n * where the server provisions?\" answers about the process's whole life rather\n * than about one instant of it.\n *\n * `schemas` narrows the CREATE question to where the server actually writes.\n * Omitted, it asks about every schema the role can see, which is the safe\n * direction: over-reporting costs a role switch that was not strictly needed,\n * under-reporting costs the entire authorization model.\n */\nexport async function detectConnectionPosture(\n run: RawSqlRunner,\n schemas?: string[]\n): Promise<ConnectionPosture> {\n // Identifiers, and they reach SQL as literals in a catalogue comparison —\n // but they arrive from collection configs, so they are quoted as string\n // literals rather than interpolated as names, and a quote inside one is\n // escaped rather than trusted.\n const schemaFilter = schemas?.length\n ? `AND n.nspname IN (${Array.from(new Set(schemas))\n .map((s) => `'${s.replace(/'/g, \"''\")}'`)\n .join(\", \")})`\n : \"\";\n\n const rows = await run(`\n SELECT current_user AS role,\n r.rolsuper AS superuser,\n r.rolbypassrls AS bypassrls,\n EXISTS (\n SELECT 1 FROM pg_tables t\n WHERE pg_has_role(current_user, t.tableowner, 'USAGE')\n AND t.schemaname NOT IN ('pg_catalog', 'information_schema')\n ) AS owns_tables,\n EXISTS (\n SELECT 1 FROM pg_namespace n\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND n.nspname NOT LIKE 'pg\\\\_toast%'\n AND n.nspname NOT LIKE 'pg\\\\_temp%'\n ${schemaFilter}\n AND has_schema_privilege(current_user, n.oid, 'CREATE')\n ) AS can_create\n FROM pg_roles r\n WHERE r.rolname = current_user\n `);\n const row = rows[0] ?? {};\n const superuser = row.superuser === true;\n const bypassRLS = row.bypassrls === true;\n const ownsTables = row.owns_tables === true;\n const canCreateTables = row.can_create === true;\n return {\n role: String(row.role ?? \"unknown\"),\n superuser,\n bypassRLS,\n ownsTables,\n canCreateTables,\n privileged: superuser || bypassRLS || ownsTables || canCreateTables\n };\n}\n\n/**\n * Human-actionable instructions for when the connection cannot provision the\n * user role itself (no CREATEROLE and role not pre-created by the platform).\n */\nexport function appRoleSetupInstructions(connectionRole: string, schemas: string[]): string {\n const grants = schemas.map((s) =>\n `GRANT USAGE ON SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};\\n` +\n `GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};\\n` +\n `GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE};`\n ).join(\"\\n\");\n return (\n `Rebase enforces row-level security by running authenticated requests as ` +\n `the restricted role \"${REBASE_USER_ROLE}\", but the connection role ` +\n `\"${connectionRole}\" bypasses RLS and cannot create that role itself.\\n` +\n `Run the following as a database administrator, then restart:\\n\\n` +\n `CREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\\n` +\n `GRANT ${REBASE_USER_ROLE} TO ${quoteIdent(connectionRole)};\\n` +\n grants\n );\n}\n\n/**\n * Idempotently provision the `rebase_user` role, membership for the current\n * connection role, and DML grants (+ default privileges for future tables)\n * on every existing schema in `schemas`.\n *\n * Split into privilege tiers so it works both when the connection is a\n * superuser (creates everything) and when the platform pre-created the role\n * and membership (e.g. CNPG `postInitApplicationSQL`) and the connection is\n * merely the table owner — owners can always run the grant tier themselves.\n *\n * RLS still filters every row: these grants only make the tables *reachable*\n * by the role; the policies decide which rows/commands actually pass.\n *\n * Throws with precise setup instructions when the role is missing and the\n * connection cannot create it.\n */\nexport async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promise<void> {\n const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));\n\n // Tier 1 — role existence.\n const roleRows = await run(`SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}'`);\n if (roleRows.length === 0) {\n try {\n // Guarded in the statement as well as by the probe above. A role\n // belongs to the cluster, not the database, so a recorded\n // provisioning run (REBASE_PROVISION_SQL_OUT) replayed into another\n // database on a cluster that already has the role must find this a\n // no-op rather than its first error.\n await run(`\n DO $rebase_role$\n BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}') THEN\n CREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\n END\n $rebase_role$\n `);\n } catch (err) {\n throw new Error(\n `Failed to create the \"${REBASE_USER_ROLE}\" role: ${err instanceof Error ? err.message : String(err)}\\n\\n` +\n appRoleSetupInstructions(\"current connection role\", uniqueSchemas)\n );\n }\n }\n\n // Tier 2 — membership, so a non-superuser connection may SET ROLE to it.\n const memberRows = await run(`\n SELECT (pg_has_role(current_user, '${REBASE_USER_ROLE}', 'MEMBER')\n OR (SELECT rolsuper FROM pg_roles WHERE rolname = current_user)) AS can_set,\n current_user AS role\n `);\n if (memberRows[0]?.can_set !== true) {\n try {\n await run(`GRANT ${REBASE_USER_ROLE} TO CURRENT_USER`);\n } catch (err) {\n throw new Error(\n `The connection role is not a member of \"${REBASE_USER_ROLE}\" and cannot grant itself membership: ` +\n `${err instanceof Error ? err.message : String(err)}\\n\\n` +\n appRoleSetupInstructions(String(memberRows[0]?.role ?? \"current connection role\"), uniqueSchemas)\n );\n }\n }\n\n // Tier 3 — grants.\n await ensureAppRoleGrants(run, uniqueSchemas);\n\n logger.debug(`🔐 [rls] User role \"${REBASE_USER_ROLE}\" provisioned (schemas: ${uniqueSchemas.join(\", \")})`);\n}\n\n/** A string literal for a catalogue read. Names come from config and constants, never from a request. */\nconst sqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\nconst textArray = (values: readonly string[]): string =>\n values.length === 0 ? \"ARRAY[]::text[]\" : `ARRAY[${values.map(sqlLiteral).join(\", \")}]::text[]`;\n\n/**\n * The framework's internal tables in `schemas` that the request role can\n * reach — `schema.table`, sorted — when nothing is left to take it back off.\n *\n * Every provisioning boot repairs this: each store revokes on its own table\n * and {@link ensureAppRole}'s sweep revokes on the rest, because the grant\n * tier hands the request role DML on whole schemas. A backend that changes\n * nothing in its database runs neither, so a database whose `rebase_user` can\n * read `refresh_tokens` or `api_keys` would stay that way for as long as it\n * served. This is the question the sweep would have answered, asked instead.\n *\n * \"Can reach\" is what the role can actually do — through a grant to it, to a\n * role it inherits, or to PUBLIC, on the table or on any of its columns —\n * because that, not how the ACL is spelled, is what a request running as it\n * gets. A table with RLS on is somebody's collection by that same rule as the\n * sweep's, and is left out.\n */\nexport async function findExposedInternalTables(run: RawSqlRunner, schemas: string[]): Promise<string[]> {\n const rows = await run(`\n SELECT n.nspname || '.' || c.relname AS name\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY(${textArray(Array.from(new Set(schemas)))})\n AND c.relname = ANY(${textArray(REBASE_INTERNAL_TABLES)})\n AND c.relkind IN ('r', 'p')\n AND NOT c.relrowsecurity\n AND (has_table_privilege(${sqlLiteral(REBASE_USER_ROLE)}, c.oid, 'SELECT, INSERT, UPDATE, DELETE')\n OR has_any_column_privilege(${sqlLiteral(REBASE_USER_ROLE)}, c.oid, 'SELECT, INSERT, UPDATE'))\n ORDER BY 1\n `);\n return rows.map(row => String(row.name));\n}\n\n/** What the grant tier would find already in place in one schema. */\ninterface SchemaGrants {\n /** `USAGE` on the schema, granted by its owner. */\n usage: boolean;\n /**\n * Every relation `GRANT … ON ALL TABLES` reaches already has all four DML\n * privileges from its owner — Rebase's own RLS-off tables aside, which the\n * sweep takes back right after and so never keep them.\n */\n tables: boolean;\n /** Every sequence already has `USAGE, SELECT` from its owner. */\n sequences: boolean;\n /** This role's default privileges in the schema already grant the table DML. */\n defaultTables: boolean;\n /** …and the sequence `USAGE, SELECT`. */\n defaultSequences: boolean;\n /**\n * Rebase's own RLS-off tables a `REVOKE` would still change: the user role\n * holds a privilege on them, or the table has never had an ACL written —\n * `NULL`, which a `REVOKE` (like the grant-and-revoke it replaces) turns\n * into the owner's explicit default. Same access either way; the same\n * catalogue only this way.\n */\n internalGranted: string[];\n}\n\n/**\n * The grant tier's state for every existing schema in `schemas`, in one read.\n *\n * A grant counts as present only as the statement this tier runs would record\n * it — grantor the object's owner, which is what a GRANT by the owner, a member\n * of the owning role or a superuser records — so skipping it leaves the ACL\n * exactly as running it would. Anything else reads as missing, and the\n * statement runs as it always did.\n */\nasync function readSchemaGrants(run: RawSqlRunner, schemas: string[]): Promise<Map<string, SchemaGrants>> {\n const internal = textArray(REBASE_INTERNAL_TABLES);\n const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(REBASE_USER_ROLE)})`;\n /** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */\n const held = (acl: string, privileges: string[], grantor?: string): string =>\n `(SELECT count(DISTINCT a.privilege_type) FROM aclexplode(${acl}) a WHERE a.grantee = ${target}` +\n `${grantor ? ` AND a.grantor = ${grantor}` : \"\"} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(\", \")}))`;\n const DML = [\"SELECT\", \"INSERT\", \"UPDATE\", \"DELETE\"];\n const SEQ = [\"USAGE\", \"SELECT\"];\n const rows = await run(`\n SELECT n.nspname AS schema,\n ${held(\"n.nspacl\", [\"USAGE\"], \"n.nspowner\")} = 1 AS usage,\n NOT EXISTS (\n SELECT 1 FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')\n AND NOT (c.relname = ANY(${internal}) AND NOT c.relrowsecurity)\n AND ${held(\"c.relacl\", DML, \"c.relowner\")} < ${DML.length}\n ) AS tables,\n NOT EXISTS (\n SELECT 1 FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relkind = 'S'\n AND ${held(\"c.relacl\", SEQ, \"c.relowner\")} < ${SEQ.length}\n ) AS sequences,\n EXISTS (\n SELECT 1 FROM pg_default_acl d\n WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'r'\n AND ${held(\"d.defaclacl\", DML)} = ${DML.length}\n ) AS default_tables,\n EXISTS (\n SELECT 1 FROM pg_default_acl d\n WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'S'\n AND ${held(\"d.defaclacl\", SEQ)} = ${SEQ.length}\n ) AS default_sequences,\n ARRAY(\n SELECT c.relname::text FROM pg_class c\n WHERE c.relnamespace = n.oid AND c.relname = ANY(${internal}) AND NOT c.relrowsecurity\n AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))\n ORDER BY 1\n ) AS internal_granted\n FROM pg_namespace n\n WHERE n.nspname = ANY(${textArray(schemas)})\n `);\n const grants = new Map<string, SchemaGrants>();\n for (const row of rows) {\n const internalGranted = row.internal_granted;\n grants.set(String(row.schema), {\n usage: row.usage === true,\n tables: row.tables === true,\n sequences: row.sequences === true,\n defaultTables: row.default_tables === true,\n defaultSequences: row.default_sequences === true,\n internalGranted: Array.isArray(internalGranted)\n ? internalGranted.map(String)\n // A driver that hands arrays back as text: `{a,b}`.\n : String(internalGranted ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean)\n });\n }\n return grants;\n}\n\n/**\n * The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing\n * schema in `schemas`, DML on its tables and `USAGE, SELECT` on its\n * sequences, the default privileges that cover what this role creates later,\n * and Rebase's own tables taken back — for a role and membership already\n * provisioned.\n *\n * Every statement is issued only when the catalogue says it would change\n * something. They used to run unconditionally, twice per boot (at connect, and\n * again in the final posture check): a `GRANT … ON ALL TABLES` rewrites every\n * table's `pg_class` row whether or not the ACL changes, which invalidates\n * every table's cached plans on every connection, and the internal-table sweep\n * ran 23 `REVOKE`s per schema. A boot against a database whose grants already\n * hold now reads one catalogue query and writes nothing; one that is missing\n * any of them runs exactly the statements it always ran.\n *\n * Table owners (the expected non-superuser posture) can always grant on their\n * own objects, so this needs no extra privilege.\n */\nexport async function ensureAppRoleGrants(run: RawSqlRunner, schemas: string[]): Promise<void> {\n const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));\n const grants = await readSchemaGrants(run, uniqueSchemas);\n for (const schema of uniqueSchemas) {\n const state = grants.get(schema);\n // Not there (yet): a later call, once provisioning has created it, grants it.\n if (!state) continue;\n const s = quoteIdent(schema);\n if (!state.usage) await run(`GRANT USAGE ON SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n if (!state.tables) await run(`GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n if (!state.sequences) await run(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n // Cover objects created later by the CURRENT role (the role that runs\n // migrations), so a migrate can never strand the user role.\n if (!state.defaultTables) {\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${REBASE_USER_ROLE}`);\n }\n if (!state.defaultSequences) {\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${REBASE_USER_ROLE}`);\n }\n\n // The grants above are deliberately schema-wide — a project's own\n // collections may live in `rebase`, and future tables must be reachable\n // or a migration strands the role. Rebase's OWN tables are the exception:\n // refresh tokens, MFA secrets, API keys and the rest carry no RLS and no\n // row an end user should ever address. Taking the privilege back here\n // covers every table that already exists; each creator revokes on the\n // table it just made, for the boot that creates them for the first time.\n //\n // All of them right after the schema-wide grant, which has just handed\n // them out; otherwise only the ones the catalogue says still hold one.\n const tables = state.tables ? state.internalGranted : undefined;\n if (tables && tables.length === 0) continue;\n await revokeInternalTableAccess(async (text) => { await run(text); }, schema, {\n tables,\n onError: (table, error) => logger.warn(\n `🔐 [rls] Could not revoke \"${REBASE_USER_ROLE}\" access to \"${schema}\".\"${table}\" — ` +\n \"it stays reachable by authenticated requests: \" +\n (error instanceof Error ? error.message : String(error))\n )\n });\n }\n}\n\n/**\n * Rebase's own RLS-off tables in `schema` that a `revokeInternalTableAccess`\n * sweep would change — the user role holds a privilege on them, or their ACL\n * has never been written. One read; the sweep it narrows is one `DO` per\n * table name.\n */\nexport async function internalTablesGrantedToUserRole(run: RawSqlRunner, schema: string): Promise<string[]> {\n return (await readSchemaGrants(run, [schema])).get(schema)?.internalGranted ?? [];\n}\n\n/**\n * Apply the authenticated context to a transaction: the `app.*` GUCs that RLS\n * policies read via `rebase.uid()` / `rebase.roles()` / `rebase.jwt()`, and — when\n * `userRole` is set — the `LOCAL` role switch, in the same statement, so RLS\n * binds every statement in this transaction (reads *and* writes).\n *\n * GUCs are set with `is_local = true` and the role switch is `LOCAL`: both\n * reset at commit/rollback, so pooled connections are never polluted.\n *\n * Fails closed by construction: if the role switch errors, the transaction\n * aborts instead of proceeding privileged.\n *\n * SECURITY: this function is only ever called on the **user** path (the server\n * context uses the base/owner driver and never calls it). The default policies\n * treat `rebase.uid() IS NULL` as the trusted server context, and `rebase.uid()`\n * is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would\n * be read as NULL and silently escalate a user request to server privileges.\n * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,\n * rather than trusting every caller (e.g. realtime subscription auth) to do it.\n * That sentinel is exported from `@rebasepro/types` because it leaks into rule\n * semantics: it is why `rebase.uid() IS NOT NULL` is true for anonymous requests.\n */\nexport async function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void> {\n const settings = authContextSettings(auth, userRole);\n await tx.execute(drizzleSql`SELECT ${drizzleSql.join(\n settings.map(([name, value]) => drizzleSql`${drizzleSql.raw(`set_config(${settingNameLiteral(name)}, `)}${value}, true)`),\n drizzleSql`, `\n )}`);\n}\n\n/**\n * {@link applyAuthContext} as one statement and its values, for a transaction\n * that sends it in the same batch as its first query\n * (`pipelined-transaction.ts`). `before` are settings of the transaction's own\n * — what a pooled connection could not carry at connect — set ahead of the\n * caller's, in the same statement.\n */\nexport function authContextStatement(\n auth: AuthContext,\n userRole?: string,\n before: readonly (readonly [string, string])[] = []\n): { text: string; values: string[] } {\n const settings = [...before, ...authContextSettings(auth, userRole)];\n return {\n text: `SELECT ${settings.map(([name], i) => `set_config(${settingNameLiteral(name)}, $${i + 1}, true)`).join(\", \")}`,\n values: settings.map(([, value]) => value)\n };\n}\n\n/**\n * A setting's name as a SQL literal. Names are this module's constants (and\n * the pooled settings' two), never a caller's value, which is a bound\n * parameter; written into the text so a statement log reads as the settings\n * it sets.\n */\nfunction settingNameLiteral(name: string): string {\n return `'${name.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * The transaction-local settings that make a transaction the caller's, in the\n * order they are set: the `app.*` GUCs, then the role.\n */\nfunction authContextSettings(auth: AuthContext, userRole?: string): [string, string][] {\n const uid = typeof auth.uid === \"string\" && auth.uid.trim() !== \"\" ? auth.uid : ANONYMOUS_USER_ID;\n const normalizedRoles = auth.roles.map((r: unknown) =>\n typeof r === \"string\" ? r : (r as Record<string, unknown>)?.id ?? String(r)\n );\n // `app.user_id` is the pre-rename spelling, still written because policies\n // are data: a database provisioned before the rename holds rules compiled\n // to `current_setting('app.user_id')`, and those predicates would evaluate\n // to NULL — failing open or locking out — if we stopped setting it. Drop\n // the alias only once no live database carries a legacy policy.\n // A guest is a signed-in caller with no account behind them, and until this\n // the database could not tell the difference — see `rebase.is_anonymous()`.\n // Written as a string because that is what `set_config` takes.\n const isAnonymous = auth.isAnonymous === true ? \"true\" : \"false\";\n\n const settings: [string, string][] = [\n [\"app.uid\", uid],\n [\"app.user_id\", uid],\n [\"app.user_roles\", normalizedRoles.join(\",\")],\n [\"app.is_anonymous\", isAnonymous],\n [\"app.jwt\", JSON.stringify({\n // The caller's custom claims, FIRST, so the identity keys below\n // overwrite them rather than the other way round. Same ordering, and\n // the same reason, as `generateAccessToken`: a claims hook is a place\n // to add facts about a session, not the place its subject is decided.\n // `verifyAccessToken` already strips the identity claims out of this\n // object; the ordering is the second lock on the same door.\n ...(auth.claims ?? {}),\n sub: uid,\n roles: auth.roles,\n // In the claims too, so a policy reading `rebase.jwt()` — which is\n // how a rule reaches anything that is not uid or roles — sees the\n // same fact as `rebase.is_anonymous()`. Two sources that could\n // disagree would be worse than one.\n is_anonymous: auth.isAnonymous === true\n })]\n ];\n // The role switch, in the same statement rather than a `SET LOCAL ROLE`\n // round trip of its own on every transaction. Postgres implements\n // `SET ROLE` as the `role` setting: `set_config('role', name, true)`\n // runs the same membership check, fails with the same SQLSTATE and\n // message (42501 \"permission denied to set role\", 22023 for an unknown\n // role — `isRoleSwitchingPermissionError` still reads it), takes the\n // name verbatim as the quoted identifier did, and resets at COMMIT and\n // ROLLBACK like `LOCAL`. Last in the list, after the GUCs; a refusal\n // fails the whole statement, so the transaction aborts rather than\n // running on as the connection owner. auth-context-one-statement.test.ts.\n if (userRole) settings.push([\"role\", userRole]);\n return settings;\n}\n\n/** Role names from other BaaS platforms that people reach for out of habit. */\nconst FOREIGN_CONVENTION_ROLES: Record<string, string> = {\n authenticated: \"Supabase\",\n anon: \"Supabase\",\n service_role: \"Supabase\"\n};\n\n/**\n * Warn about rules that read as \"signed-in users only\" but admit anonymous\n * callers — `rebase.uid() IS NOT NULL`, or a comparison against another\n * platform's magic user id such as `'anon'`.\n *\n * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling\n * of the same habit. A foreign `pgRoles` value makes a policy unreachable and\n * the table reads empty — loud, and that guard throws. These do the opposite:\n * the rule compiles to a grant, and nothing looks wrong until the data is\n * already public.\n *\n * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are\n * serving traffic today: refusing to boot would take an app offline to report a\n * problem it already has, and on the read path it would take it offline\n * *because* its data was exposed. Rewriting the author's SQL is not an option\n * either — this is the escape hatch whose whole promise is that it means what it\n * says. So: say so, loudly, and leave the rule alone.\n */\nexport function warnOnAnonymousGrants(\n collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]\n): void {\n // Grouped by the mistake, not by the rule: one habit typically repeats\n // across every collection an author wrote, and a per-rule list would repeat\n // the same paragraph dozens of times and get skimmed.\n const byRisk = new Map<string, { risk: AnonymousGrantRisk; sites: string[] }>();\n\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n const risks = [usingExpr, withCheckExpr]\n .filter((e): e is PolicyExpression => e !== null)\n .flatMap(findAnonymousGrants);\n\n for (const risk of risks) {\n const key = `${risk.pattern}:${risk.detail}`;\n const site = `${collection.slug ?? \"(unnamed)\"} → \"${rule.name ?? \"(unnamed rule)\"}\"`;\n const entry = byRisk.get(key) ?? { risk, sites: [] };\n if (!entry.sites.includes(site)) entry.sites.push(site);\n byRisk.set(key, entry);\n }\n }\n }\n\n if (byRisk.size === 0) return;\n\n const problems = [...byRisk.values()].map(({ risk, sites }) =>\n ` • ${risk.explanation}\\n ${sites.length} rule(s): ${sites.join(\", \")}`\n );\n\n logger.warn(\n `Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a ` +\n `client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are ` +\n `true for everyone:\\n\\n` +\n problems.join(\"\\n\\n\") + \"\\n\"\n );\n}\n\n/**\n * Name the collections whose raw policy SQL still calls the pre-1.0 helpers.\n *\n * The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the\n * database, so nothing is broken and no policy is wrong — which is exactly why\n * this has to be said out loud. A silent rewrite that works forever is not a\n * migration, it is a second supported spelling nobody wrote down, and the next\n * person to read those rules will copy the old one.\n *\n * Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,\n * `policy.rolesOverlap(...)`) compile from the model and were never affected.\n */\nexport function warnOnLegacyRlsFunctions(\n collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]\n): void {\n const sites: string[] = [];\n\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n const carriesLegacy = [usingExpr, withCheckExpr]\n .filter((e): e is PolicyExpression => e !== null)\n .some(containsLegacyRlsCall);\n if (!carriesLegacy) continue;\n\n const site = `${collection.slug ?? \"(unnamed)\"} → \"${rule.name ?? \"(unnamed rule)\"}\"`;\n if (!sites.includes(site)) sites.push(site);\n }\n }\n\n if (sites.length === 0) return;\n\n logger.warn(\n `These security rules call the pre-1.0 RLS helpers (\\`auth.uid()\\`, \\`auth.roles()\\`, \\`auth.jwt()\\`). ` +\n `They still work — the compiler rewrites them — but the functions now live in the \\`rebase\\` schema, ` +\n `and the \\`auth\\` one is Supabase's. Update the raw SQL in these rules to \\`${REBASE_SCHEMA}.uid()\\` ` +\n `and friends, or switch them to the structured helpers (\\`policy.authUid()\\`, \\`policy.rolesOverlap()\\`), ` +\n `which never had to be spelled by hand:\\n\\n` +\n sites.map(s => ` • ${s}`).join(\"\\n\") + \"\\n\"\n );\n}\n\n/** Whether any `raw` expression in the tree calls a pre-1.0 helper. */\nfunction containsLegacyRlsCall(expr: PolicyExpression): boolean {\n switch (expr.kind) {\n case \"raw\":\n return usesLegacyRlsFunctions(expr.sql);\n case \"and\":\n case \"or\":\n return expr.operands.some(containsLegacyRlsCall);\n case \"not\":\n return containsLegacyRlsCall(expr.operand);\n case \"existsIn\":\n return containsLegacyRlsCall(expr.where);\n default:\n return false;\n }\n}\n\n/**\n * Reject `pgRoles` that this server can never satisfy.\n *\n * `pgRoles` sets the `TO` clause of a generated policy, so a policy naming a\n * role the request never runs as simply never applies — and RLS then filters\n * every row. The table reads as empty, which is indistinguishable from having\n * no data, so the mistake survives review and ships.\n *\n * Requests run as `rebase_user`, so a policy is only reachable if it targets\n * `public` or a role `rebase_user` holds. Anything else is a configuration\n * error worth failing the boot for.\n */\nexport async function validatePolicyPgRoles(\n run: RawSqlRunner,\n collections: { slug?: string; securityRules?: readonly { name?: string; pgRoles?: readonly string[] }[] }[],\n /** The role requests actually run as: `rebase_user` when the connection is\n * privileged enough to switch, otherwise the connection role itself. */\n requestRole: string = REBASE_USER_ROLE\n): Promise<void> {\n const wanted = new Map<string, string[]>();\n for (const collection of collections) {\n for (const rule of collection.securityRules ?? []) {\n for (const role of rule.pgRoles ?? []) {\n if (role === \"public\") continue;\n wanted.set(role, [...(wanted.get(role) ?? []), collection.slug ?? \"(unnamed)\"]);\n }\n }\n }\n if (wanted.size === 0) return;\n\n const names = [...wanted.keys()].map((r) => `'${r.replace(/'/g, \"''\")}'`).join(\",\");\n const escapedRequestRole = requestRole.replace(/'/g, \"''\");\n const rows = await run(`\n SELECT r.rolname AS role,\n COALESCE(pg_has_role(to_regrole('${escapedRequestRole}'), r.oid, 'MEMBER'), false) AS reachable\n FROM pg_roles r\n WHERE r.rolname IN (${names})\n `);\n\n const reachable = new Map(rows.map((row) => [String(row.role), row.reachable === true]));\n const problems: string[] = [];\n\n for (const [role, slugs] of wanted) {\n if (reachable.get(role) === true) continue;\n\n const why = reachable.has(role)\n ? `\"${requestRole}\" is not a member of it`\n : \"no such role exists in this database\";\n const platform = FOREIGN_CONVENTION_ROLES[role];\n const hint = platform\n ? `\"${role}\" is a ${platform} convention, not a PostgreSQL role. Application roles belong in \\`roles: [\"${role === \"service_role\" ? \"admin\" : role}\"]\\`, which is checked inside the policy via rebase.roles().`\n : `Either grant it (GRANT ${role} TO ${requestRole}) or drop \\`pgRoles\\` so the policy targets \\`public\\`.`;\n\n problems.push(\n ` • pgRoles: [\"${role}\"] on ${slugs.join(\", \")} — ${why}.\\n ${hint}`\n );\n }\n\n if (problems.length > 0) {\n throw new Error(\n `Security rules target PostgreSQL roles this server cannot use. Requests run as ` +\n `\"${requestRole}\", so these policies would never apply and every row would be ` +\n `filtered out — the collections would look empty rather than error.\\n\\n` +\n problems.join(\"\\n\\n\") + \"\\n\"\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsIA,IAAM,cAAc,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;;AAG5E,IAAM,wBAAwB;;;;;;;AAQ9B,IAAa,qBAAqB,QAAgB,UAC9C,4BAA4B,WAAW,MAAM,EAAE,GAAG,WAAW,KAAK,EAAE,QAAQ,WAAW,kBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6B3G,eAAsB,0BAA0B,KAAkC;CAC9E,IAAI;EACA,MAAM,OAAO,MAAM,IAAI;;;;;SAKtB;EACD,IAAI,KAAK,EAAE,EAAE,aAAa,MAAM;EAChC,MAAM,OAAO,OAAO,KAAK,EAAE,EAAE,QAAQ,qBAAqB;EAC1D,OAAO,KACH,0BAA0B,KAAK,4IAC+C,KAAK,gMAED,KAAK,gNAI3F;CACJ,QAAQ,CAER;AACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,wBAClB,KACA,SAC0B;CA+B1B,MAAM,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M,WAAW,yBAAyB;EAC1C,MAAM,OAAO,WACP,IAAI,KAAK,SAAS,SAAS,6EAA6E,SAAS,iBAAiB,UAAU,KAAK,gEACjJ,0BAA0B,KAAK,MAAM,YAAY;EAEvD,SAAS,KACL,kBAAkB,KAAK,QAAQ,MAAM,KAAK,IAAI,EAAE,KAAK,IAAI,SAAS,MACtE;CACJ;CAEA,IAAI,SAAS,SAAS,GAClB,MAAM,IAAI,MACN,mFACI,YAAY,wIAEhB,SAAS,KAAK,MAAM,IAAI,IAC5B;AAER"}
|
|
@@ -79,6 +79,15 @@ export declare const isPgPool: (value: unknown) => value is Pick<Pool, "connect"
|
|
|
79
79
|
* is lifted here per query.
|
|
80
80
|
*/
|
|
81
81
|
export declare const poolIndexBuildSession: (pool: Pick<Pool, "connect">) => OpenIndexBuildSession;
|
|
82
|
+
/**
|
|
83
|
+
* A session on a connection opened for it, from a URL — for a pool behind a
|
|
84
|
+
* transaction-mode pooler, where "the pool's next connection" is not one
|
|
85
|
+
* backend: the pooler hands each statement whatever server connection is
|
|
86
|
+
* free, so a session advisory lock and `SET statement_timeout = 0` would land
|
|
87
|
+
* on one and the `CREATE INDEX` run on another. The URL must name the
|
|
88
|
+
* database itself (`DATABASE_DIRECT_URL`). Ended, not released, when done.
|
|
89
|
+
*/
|
|
90
|
+
export declare const clientIndexBuildSession: (connectionString: string) => OpenIndexBuildSession;
|
|
82
91
|
export interface DeferredIndexOptions extends BootLockOptions {
|
|
83
92
|
/** Progress, one line per index. Failures are also `logger.warn`ed. */
|
|
84
93
|
log?: (message: string) => void;
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
import { createRequire as __createRequire } from "module";
|
|
3
3
|
__createRequire(import.meta.url);
|
|
4
4
|
import { a as buildSearchColumnSpec } from "../search-column-BM-GV6vH.js";
|
|
5
|
-
import { a as diagnoseDbError } from "../cli-errors-
|
|
6
|
-
import { d as
|
|
5
|
+
import { a as diagnoseDbError } from "../cli-errors-D8s4z_3g.js";
|
|
6
|
+
import { d as validatePolicyPgRoles, f as warnOnAnonymousGrants } from "../rls-enforcement-jZTv1yci.js";
|
|
7
7
|
import { n as describeFailure, t as chalk } from "../source-fZb92pN8.js";
|
|
8
|
-
import { n as formatPolicyDrift, r as hasDrift, t as checkPolicyDrift } from "../policy-drift-
|
|
9
|
-
import { n as loadCollections, r as runDoctor } from "../doctor-
|
|
8
|
+
import { n as formatPolicyDrift, r as hasDrift, t as checkPolicyDrift } from "../policy-drift-IjD2AUD-.js";
|
|
9
|
+
import { n as loadCollections, r as runDoctor } from "../doctor-_g2tHRtG.js";
|
|
10
10
|
import { isPostgresCollectionConfig } from "@rebasepro/types";
|
|
11
11
|
import { getTableName, relationalCollections } from "@rebasepro/common";
|
|
12
12
|
import path from "path";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
|
-
import { t as main } from "../generate-drizzle-schema-
|
|
3
|
+
import { t as main } from "../generate-drizzle-schema-taNTu3xv.js";
|
|
4
4
|
//#region src/schema/bin/generate-drizzle-schema.ts
|
|
5
5
|
/**
|
|
6
6
|
* The built entry point for `generate-drizzle-schema`.
|
|
@@ -39,6 +39,7 @@ export interface GenerateFileOptions {
|
|
|
39
39
|
export declare function writeDrizzleSchema(options: GenerateFileOptions): Promise<void>;
|
|
40
40
|
/**
|
|
41
41
|
* `schema.sql` (Atlas's desired state) and, beside it, `policies.sql`,
|
|
42
|
-
* `search.sql`, `vector.sql` and `
|
|
42
|
+
* `search.sql`, `vector.sql`, `triggers.sql` and `views.sql` — the parts Atlas
|
|
43
|
+
* does not own.
|
|
43
44
|
*/
|
|
44
45
|
export declare function writePostgresDdl(options: GenerateFileOptions): Promise<void>;
|
|
@@ -94,6 +94,12 @@ export declare const vectorExcludePatterns: (allCollections: CollectionConfig[])
|
|
|
94
94
|
* `on_update` — the caller writes no file then, and removes a stale one.
|
|
95
95
|
*/
|
|
96
96
|
export declare const generatePostgresTriggersDdl: (allCollections: CollectionConfig[]) => string;
|
|
97
|
+
/**
|
|
98
|
+
* `.rebase/sql/views.sql` — the views of the collections that declare `view`,
|
|
99
|
+
* which Atlas's free tier does not manage. Empty when none does — the caller
|
|
100
|
+
* writes no file then, and removes a stale one.
|
|
101
|
+
*/
|
|
102
|
+
export declare const generatePostgresViewsDdl: (allCollections: CollectionConfig[]) => string;
|
|
97
103
|
/** @see searchExcludePatterns */
|
|
98
104
|
export declare const triggerExcludePatterns: (allCollections: CollectionConfig[]) => string[];
|
|
99
105
|
/** A column a `relation` or `reference` property owns on its own table. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { r as out } from "../source-fZb92pN8.js";
|
|
4
|
-
import { r as writePostgresDdl } from "../generate-files-
|
|
4
|
+
import { r as writePostgresDdl } from "../generate-files-DbwU8Btx.js";
|
|
5
5
|
import path from "path";
|
|
6
6
|
//#region src/schema/generate-postgres-ddl.ts
|
|
7
7
|
/**
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { n as require_arg, o as __toESM, t as promptConfirm } from "../cli-prompt-DXG0yk-h.js";
|
|
4
|
-
import {
|
|
5
|
-
import { a as diagnoseDbError } from "../cli-errors-
|
|
4
|
+
import { u as pinSearchPath } from "../connection-COuS5Fm-.js";
|
|
5
|
+
import { a as diagnoseDbError } from "../cli-errors-D8s4z_3g.js";
|
|
6
6
|
import { a as outWarn, i as outError, r as out, t as chalk } from "../source-fZb92pN8.js";
|
|
7
7
|
import { i as readSchemaMetadata, n as isUsableFileName, r as quoteRelation, t as countRowsUpTo } from "../introspect-db-queries-DevUrzll.js";
|
|
8
8
|
import { a as compositeKeySkipReason, c as generateIndexContent, d as mergeIndexContent, f as safeHostFromUrl, h as lookupCandidates, i as buildTablesMap, m as classifyTables, o as describeRlsOffTables, r as buildEnumMap, s as generateCollectionFile } from "../introspect-db-logic-DgQVzccW.js";
|
|
@@ -45,7 +45,16 @@ export interface Queryable {
|
|
|
45
45
|
* Read tables, columns, enums, primary keys and foreign keys for a schema.
|
|
46
46
|
* Mirrors the queries in introspect-db.ts.
|
|
47
47
|
*/
|
|
48
|
-
export declare function introspectSchema(client: Queryable, pgSchema: string
|
|
48
|
+
export declare function introspectSchema(client: Queryable, pgSchema: string,
|
|
49
|
+
/**
|
|
50
|
+
* Read views and materialized views too, as tables to read from — what
|
|
51
|
+
* the runtime catalogue needs for collections that declare `view`. Off
|
|
52
|
+
* for introspection that turns relations into collections, where a view
|
|
53
|
+
* is not one.
|
|
54
|
+
*/
|
|
55
|
+
options?: {
|
|
56
|
+
views?: boolean;
|
|
57
|
+
}): Promise<IntrospectedSchema>;
|
|
49
58
|
/**
|
|
50
59
|
* Turn an introspected schema into collections.
|
|
51
60
|
*
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
*/
|
|
22
22
|
import { type CollectionConfig, type Property, type SecurityRule } from "@rebasepro/types";
|
|
23
23
|
import { SET_UPDATED_AT_FN } from "./updated-at-trigger.js";
|
|
24
|
-
import type { PgType, PlanOptions, PolicyPlan, SchemaPlan } from "./types.js";
|
|
24
|
+
import type { PgType, PlanOptions, PolicyPlan, SchemaPlan, ViewPlan } from "./types.js";
|
|
25
25
|
type ResolveCollection = (slug: string) => CollectionConfig | undefined;
|
|
26
26
|
/**
|
|
27
27
|
* Single-quote escaping for a SQL string literal (PostgreSQL doubles the
|
|
@@ -96,4 +96,12 @@ export declare const columnPgType: (propName: string, prop: Property, collection
|
|
|
96
96
|
*/
|
|
97
97
|
export declare const compileSecurityRule: (collection: CollectionConfig, rule: SecurityRule, resolveCollection: ResolveCollection, injected: boolean, ruleKey?: string) => PolicyPlan[];
|
|
98
98
|
export declare function planSchema(allCollections: CollectionConfig[], options?: PlanOptions): SchemaPlan;
|
|
99
|
+
/**
|
|
100
|
+
* The view collections' views, each after the views its query names.
|
|
101
|
+
*
|
|
102
|
+
* Which views a query reads is read off its text — a planned view's name as a
|
|
103
|
+
* whole word — which is enough to order them: a name that appears in a string
|
|
104
|
+
* literal only orders two views that did not need it, never the other way.
|
|
105
|
+
*/
|
|
106
|
+
export declare function planViews(collections: CollectionConfig[]): ViewPlan[];
|
|
99
107
|
export { SET_UPDATED_AT_FN };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ColumnPlan, PgType, PolicyPlan, SchemaPlan, TablePlan } from "./types.js";
|
|
1
|
+
import type { ColumnPlan, PgType, PolicyPlan, SchemaPlan, TablePlan, ViewPlan } from "./types.js";
|
|
2
2
|
/** What `schema.sql` may leave out, because another file owns it. */
|
|
3
3
|
export interface DdlRenderOptions {
|
|
4
4
|
/** RLS policies. `false` puts them in `policies.sql` alone. */
|
|
@@ -78,3 +78,27 @@ export declare const vectorExcludePatternsOf: (plan: SchemaPlan) => string[];
|
|
|
78
78
|
export declare function renderTriggersDdl(plan: SchemaPlan): string;
|
|
79
79
|
/** @see searchExcludePatternsOf */
|
|
80
80
|
export declare const triggerExcludePatternsOf: (plan: SchemaPlan) => string[];
|
|
81
|
+
/** The comment a view Rebase created carries: `rebase:view:<hash>`. */
|
|
82
|
+
export declare const viewComment: (view: ViewPlan) => string;
|
|
83
|
+
/**
|
|
84
|
+
* The statements that create one view as planned, comment included, for
|
|
85
|
+
* `EXECUTE`. A plain view runs as the caller (`security_invoker`), so the
|
|
86
|
+
* policies of the tables it reads decide what each caller sees; a
|
|
87
|
+
* materialized view gets a unique index on its id columns, which
|
|
88
|
+
* `REFRESH MATERIALIZED VIEW CONCURRENTLY` needs.
|
|
89
|
+
*/
|
|
90
|
+
export declare function viewCreateStatements(view: ViewPlan): string[];
|
|
91
|
+
/**
|
|
92
|
+
* `views.sql`: the views of the collections that declare one, as the file
|
|
93
|
+
* Rebase applies itself — Atlas manages no views on its free tier.
|
|
94
|
+
*
|
|
95
|
+
* Idempotent, in two passes. The first drops, last first, every view whose
|
|
96
|
+
* comment no longer matches its plan and every view that reads one of those
|
|
97
|
+
* (Postgres will not drop a view another still reads, and will not change a
|
|
98
|
+
* view's columns in place); the second creates, in order, every view that is
|
|
99
|
+
* not there. A view that is up to date is left alone, rows and all. A table or
|
|
100
|
+
* a view Rebase did not create under the same name is refused, never dropped.
|
|
101
|
+
*
|
|
102
|
+
* Empty when no collection declares a view.
|
|
103
|
+
*/
|
|
104
|
+
export declare function renderViewsDdl(plan: SchemaPlan): string;
|
|
@@ -414,6 +414,24 @@ export interface PlanOptions {
|
|
|
414
414
|
*/
|
|
415
415
|
databaseExtensions?: readonly string[];
|
|
416
416
|
}
|
|
417
|
+
/** A collection's SQL view, as `views.sql` creates it. See `PostgresCollectionConfig.view`. */
|
|
418
|
+
export interface ViewPlan {
|
|
419
|
+
schema: string;
|
|
420
|
+
name: string;
|
|
421
|
+
/** `schema.name`, unquoted. */
|
|
422
|
+
qualified: string;
|
|
423
|
+
query: string;
|
|
424
|
+
materialized: boolean;
|
|
425
|
+
/** The `isId` columns: a materialized view gets a unique index on them, which `REFRESH … CONCURRENTLY` needs. */
|
|
426
|
+
idColumns: string[];
|
|
427
|
+
/** The other planned views this one's query names, which must exist first. */
|
|
428
|
+
dependsOn: string[];
|
|
429
|
+
/**
|
|
430
|
+
* A hash of everything above, kept as the view's comment
|
|
431
|
+
* (`rebase:view:<hash>`): a view whose comment differs is recreated.
|
|
432
|
+
*/
|
|
433
|
+
hash: string;
|
|
434
|
+
}
|
|
417
435
|
/**
|
|
418
436
|
* Everything a set of collections asks the database for.
|
|
419
437
|
*
|
|
@@ -437,6 +455,12 @@ export interface SchemaPlan {
|
|
|
437
455
|
declaredSchemas: string[];
|
|
438
456
|
enums: EnumPlan[];
|
|
439
457
|
tables: TablePlan[];
|
|
458
|
+
/**
|
|
459
|
+
* The collections that serve a SQL view (`view`), in creation order: a
|
|
460
|
+
* view whose query names another comes after it. No table, policy or enum
|
|
461
|
+
* is planned for them.
|
|
462
|
+
*/
|
|
463
|
+
views: ViewPlan[];
|
|
440
464
|
relations: RelationPlan[];
|
|
441
465
|
/** `CREATE EXTENSION IF NOT EXISTS …;` statements, deduplicated. */
|
|
442
466
|
extensions: string[];
|
|
@@ -272,6 +272,17 @@ export declare function internalTablesGrantedToUserRole(run: RawSqlRunner, schem
|
|
|
272
272
|
* semantics: it is why `rebase.uid() IS NOT NULL` is true for anonymous requests.
|
|
273
273
|
*/
|
|
274
274
|
export declare function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void>;
|
|
275
|
+
/**
|
|
276
|
+
* {@link applyAuthContext} as one statement and its values, for a transaction
|
|
277
|
+
* that sends it in the same batch as its first query
|
|
278
|
+
* (`pipelined-transaction.ts`). `before` are settings of the transaction's own
|
|
279
|
+
* — what a pooled connection could not carry at connect — set ahead of the
|
|
280
|
+
* caller's, in the same statement.
|
|
281
|
+
*/
|
|
282
|
+
export declare function authContextStatement(auth: AuthContext, userRole?: string, before?: readonly (readonly [string, string])[]): {
|
|
283
|
+
text: string;
|
|
284
|
+
values: string[];
|
|
285
|
+
};
|
|
275
286
|
/**
|
|
276
287
|
* Warn about rules that read as "signed-in users only" but admit anonymous
|
|
277
288
|
* callers — `rebase.uid() IS NOT NULL`, or a comparison against another
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SQL } from "drizzle-orm";
|
|
2
2
|
import { AnyPgColumn, PgTable } from "drizzle-orm/pg-core";
|
|
3
3
|
import { FilterValues, OrderByTuple, LogicalCondition } from "@rebasepro/types";
|
|
4
|
-
import type { IncludeSpec, VectorSearchParams } from "@rebasepro/types";
|
|
4
|
+
import type { DriverAggregate, DriverAggregateGroup, IncludeSpec, VectorSearchParams } from "@rebasepro/types";
|
|
5
5
|
import { RelationService } from "./RelationService.js";
|
|
6
6
|
import { DrizzleClient } from "../interfaces.js";
|
|
7
7
|
import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry.js";
|
|
@@ -30,11 +30,7 @@ import { type ReadCallContextProvider } from "./read-scope.js";
|
|
|
30
30
|
* Exported to be tested: the parsing itself needs a database, this decision
|
|
31
31
|
* does not.
|
|
32
32
|
*/
|
|
33
|
-
export declare function numericAggregateAliases(aggregates: {
|
|
34
|
-
fn: "count" | "sum" | "avg" | "min" | "max";
|
|
35
|
-
field?: string;
|
|
36
|
-
alias: string;
|
|
37
|
-
}[], properties: Record<string, {
|
|
33
|
+
export declare function numericAggregateAliases(aggregates: DriverAggregate[], properties: Record<string, {
|
|
38
34
|
type?: string;
|
|
39
35
|
}>): Set<string>;
|
|
40
36
|
export declare class FetchService {
|
|
@@ -562,12 +558,8 @@ export declare class FetchService {
|
|
|
562
558
|
* has to be zero.
|
|
563
559
|
*/
|
|
564
560
|
aggregate<M extends Record<string, unknown>>(collectionPath: string, options: {
|
|
565
|
-
aggregates:
|
|
566
|
-
|
|
567
|
-
field?: string;
|
|
568
|
-
alias: string;
|
|
569
|
-
}[];
|
|
570
|
-
groupBy?: string[];
|
|
561
|
+
aggregates: DriverAggregate[];
|
|
562
|
+
groupBy?: (string | DriverAggregateGroup)[];
|
|
571
563
|
filter?: FilterValues<Extract<keyof M, string>>;
|
|
572
564
|
logical?: LogicalCondition;
|
|
573
565
|
searchString?: string;
|
|
@@ -582,6 +574,14 @@ export declare class FetchService {
|
|
|
582
574
|
/** See `FetchCollectionProps.withDeleted`. */
|
|
583
575
|
withDeleted?: WithDeleted;
|
|
584
576
|
}): Promise<Record<string, unknown>[]>;
|
|
577
|
+
/**
|
|
578
|
+
* A transformed group (`AggregateGroup`) as SQL. `lower`/`upper` read the
|
|
579
|
+
* column as text; `year`/`month`/`day` truncate a date or timestamp, in UTC
|
|
580
|
+
* when it has a time zone, to `YYYY`, `YYYY-MM` or `YYYY-MM-DD`; `unnest`
|
|
581
|
+
* adds a lateral join over the array's elements to `lateral` and groups by
|
|
582
|
+
* the element.
|
|
583
|
+
*/
|
|
584
|
+
private groupExpression;
|
|
585
585
|
/**
|
|
586
586
|
* The `ORDER BY` of a grouped aggregate: the caller's keys, then every
|
|
587
587
|
* group key they did not name.
|
|
@@ -31,6 +31,18 @@ export interface PersistSaveOptions {
|
|
|
31
31
|
* without being named here.
|
|
32
32
|
*/
|
|
33
33
|
insertOnlyKeys?: readonly string[];
|
|
34
|
+
/**
|
|
35
|
+
* The caller did not read the row this update addresses, so the write is
|
|
36
|
+
* what establishes it is there: an UPDATE that matched nothing is the 404
|
|
37
|
+
* (`explainZeroRowWrite`), and an update that sets no column reads the row
|
|
38
|
+
* instead of assuming it.
|
|
39
|
+
*/
|
|
40
|
+
unreadRow?: boolean;
|
|
41
|
+
}
|
|
42
|
+
/** One row of a {@link PersistService.saveRows} batch: its values and what its INSERT alone may write. */
|
|
43
|
+
export interface PersistBatchRow {
|
|
44
|
+
values: Record<string, unknown>;
|
|
45
|
+
insertOnlyKeys?: readonly string[];
|
|
34
46
|
}
|
|
35
47
|
/**
|
|
36
48
|
* Service for handling all row write operations.
|
|
@@ -137,6 +149,53 @@ export declare class PersistService {
|
|
|
137
149
|
* not have. What they compile to is `field-op-sql.ts`.
|
|
138
150
|
*/
|
|
139
151
|
save<M extends Record<string, unknown>>(collectionPath: string, values: Partial<M>, id?: string | number, databaseId?: string, options?: PersistSaveOptions): Promise<Record<string, unknown>>;
|
|
152
|
+
/**
|
|
153
|
+
* Write a batch of new rows — inserted, or upserted with `options.upsert` —
|
|
154
|
+
* as multi-row statements, and return each row as {@link save} returns it.
|
|
155
|
+
*
|
|
156
|
+
* The statements are the ones {@link save} sends for one row, carrying up
|
|
157
|
+
* to {@link BATCH_MAX_ROWS} rows each: the same columns, defaults, conflict
|
|
158
|
+
* target, conflict-update and scope. A batch of 1,000 rows is one or two
|
|
159
|
+
* statements instead of a thousand.
|
|
160
|
+
*
|
|
161
|
+
* `undefined`, before anything is written, for a batch that needs what
|
|
162
|
+
* only the row-by-row save does: a nested path, a relation or field
|
|
163
|
+
* operation in a row, an upsert row without its whole conflict key, or a
|
|
164
|
+
* collection whose rows cannot be returned by the write itself (a
|
|
165
|
+
* `beforeQuery` or per-field read access). The caller then saves the rows
|
|
166
|
+
* one by one.
|
|
167
|
+
*
|
|
168
|
+
* Run inside the caller's transaction, which a statement the database
|
|
169
|
+
* refuses aborts: the caller undoes the batch and replays its rows one by
|
|
170
|
+
* one to say which row failed.
|
|
171
|
+
*
|
|
172
|
+
* Rows go out in order, in consecutive runs: a run ends where the next
|
|
173
|
+
* row's conflict-update would set other columns, or where an upsert names
|
|
174
|
+
* a key the run already holds (one statement cannot update a row twice),
|
|
175
|
+
* so a key written twice still ends with the later values.
|
|
176
|
+
*/
|
|
177
|
+
saveRows(collectionPath: string, rows: readonly PersistBatchRow[], options?: {
|
|
178
|
+
upsert?: boolean;
|
|
179
|
+
onConflict?: readonly string[];
|
|
180
|
+
}): Promise<Record<string, unknown>[] | undefined>;
|
|
181
|
+
/**
|
|
182
|
+
* Update rows by id, each with its own values, as
|
|
183
|
+
* `UPDATE … FROM (VALUES …) … RETURNING` statements, and return each row as
|
|
184
|
+
* {@link save} returns it — or `undefined`, before anything is written,
|
|
185
|
+
* for updates that need what only the row-by-row update does: a nested
|
|
186
|
+
* path, a relation or field operation in a row, a collection whose rows the
|
|
187
|
+
* write cannot return (`beforeQuery`, per-field read access) or that has a
|
|
188
|
+
* trash. Consecutive updates setting the same columns share a statement;
|
|
189
|
+
* an id named twice starts a new one, so the later values win.
|
|
190
|
+
*
|
|
191
|
+
* An id the statement did not update — not there, or not the caller's to
|
|
192
|
+
* update — fails the call: the caller replays the updates one by one to say
|
|
193
|
+
* which, and why.
|
|
194
|
+
*/
|
|
195
|
+
updateRows(collectionPath: string, updates: readonly {
|
|
196
|
+
id: string | number;
|
|
197
|
+
values: Record<string, unknown>;
|
|
198
|
+
}[]): Promise<Record<string, unknown>[] | undefined>;
|
|
140
199
|
/**
|
|
141
200
|
* The caller's `beforeQuery` scope over this table, as one condition: what
|
|
142
201
|
* a stored row must satisfy for a write that meets it to change it. The
|
|
@@ -240,4 +240,6 @@ export declare function warnOnKeysTheAdminCannotResolve(collections: CollectionC
|
|
|
240
240
|
* callers decide what that means, since "unaddressable" is a different answer
|
|
241
241
|
* in a notification (broadcast a wildcard) than in a save (fail).
|
|
242
242
|
*/
|
|
243
|
-
export declare function deriveRowAddress(row: Record<string, unknown>, collection: CollectionConfig, registry: PostgresCollectionRegistry
|
|
243
|
+
export declare function deriveRowAddress(row: Record<string, unknown>, collection: CollectionConfig, registry: PostgresCollectionRegistry,
|
|
244
|
+
/** The collection's keys, when the caller already has them — a batch derives one address per row. */
|
|
245
|
+
primaryKeys?: PrimaryKeyInfo[]): string;
|