@rebasepro/server-postgres 0.23.0 → 0.24.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-DGPL6G_C.js → BranchService-BRt78gfa.js} +35 -18
- package/dist/BranchService-BRt78gfa.js.map +1 -0
- package/dist/PostgresBackendDriver.d.ts +84 -12
- package/dist/auth/services.d.ts +72 -14
- package/dist/{auth-users-columns-D2LBFrMH.js → auth-users-columns-C72EMoDJ.js} +17 -1
- package/dist/{auth-users-columns-D2LBFrMH.js.map → auth-users-columns-C72EMoDJ.js.map} +1 -1
- package/dist/{backup-cli-24v4OlSp.js → backup-cli-DW5p9_zv.js} +2 -2
- package/dist/{backup-cli-24v4OlSp.js.map → backup-cli-DW5p9_zv.js.map} +1 -1
- package/dist/{backup-service-HQ9GC4tN.js → backup-service-EwcDVG-8.js} +7 -9
- package/dist/{backup-service-HQ9GC4tN.js.map → backup-service-EwcDVG-8.js.map} +1 -1
- package/dist/{cli-errors-B8qHg02P.js → cli-errors-DsA-K9uP.js} +96 -1
- package/dist/{cli-errors-B8qHg02P.js.map → cli-errors-DsA-K9uP.js.map} +1 -1
- package/dist/cli-errors.d.ts +42 -0
- package/dist/cli-helpers.d.ts +12 -12
- package/dist/cli.js +91 -37
- package/dist/cli.js.map +1 -1
- package/dist/{column-plan-helpers-DF-8dTVa.js → column-plan-helpers-1-LQD0yI.js} +34 -24
- package/dist/column-plan-helpers-1-LQD0yI.js.map +1 -0
- package/dist/data-transformer.d.ts +0 -8
- package/dist/{doctor-Cb2thZ8s.js → doctor-C-sYWbmt.js} +224 -43
- package/dist/doctor-C-sYWbmt.js.map +1 -0
- package/dist/{ensure-collection-policies-RHUcEp4v.js → ensure-collection-policies-B1ureSIV.js} +73 -18
- package/dist/ensure-collection-policies-B1ureSIV.js.map +1 -0
- package/dist/{ensure-collection-tables-BEEjn5cn.js → ensure-collection-tables-kkkHk8oo.js} +76 -20
- package/dist/ensure-collection-tables-kkkHk8oo.js.map +1 -0
- package/dist/{ensure-tables-Dhn9KM3B.js → ensure-tables-BmI_tRxc.js} +10 -3
- package/dist/ensure-tables-BmI_tRxc.js.map +1 -0
- package/dist/{generate-drizzle-schema-yzY_BLhr.js → generate-drizzle-schema-93M0lUxK.js} +2 -2
- package/dist/{generate-drizzle-schema-yzY_BLhr.js.map → generate-drizzle-schema-93M0lUxK.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-BfzK7UQd.js → generate-drizzle-schema-logic-sSFDp6LR.js} +26 -8
- package/dist/generate-drizzle-schema-logic-sSFDp6LR.js.map +1 -0
- package/dist/generate-postgres-ddl-logic-BJsLaVNX.js +152 -0
- package/dist/generate-postgres-ddl-logic-BJsLaVNX.js.map +1 -0
- package/dist/generated-sql.d.ts +28 -0
- package/dist/index.es.js +3415 -917
- package/dist/index.es.js.map +1 -1
- package/dist/{introspect-db-logic-WMuAfxvw.js → introspect-db-logic-kCETE8TY.js} +523 -349
- package/dist/introspect-db-logic-kCETE8TY.js.map +1 -0
- package/dist/introspect-db-queries-C_Q5VgQw.js +317 -0
- package/dist/introspect-db-queries-C_Q5VgQw.js.map +1 -0
- package/dist/{plan-schema-C0fxM8dY.js → plan-schema-DU9exq6C.js} +139 -504
- package/dist/plan-schema-DU9exq6C.js.map +1 -0
- package/dist/{policy-drift-DljYdrpW.js → policy-drift-B-J2hhm0.js} +3 -3
- package/dist/policy-drift-B-J2hhm0.js.map +1 -0
- package/dist/{generate-postgres-ddl-logic-Bt2d2mRH.js → render-ddl-Ds2t_d9V.js} +11 -149
- package/dist/render-ddl-Ds2t_d9V.js.map +1 -0
- package/dist/{rls-bootstrap-sql-B8EclDyM.js → rls-bootstrap-sql-_KNnjanK.js} +263 -39
- package/dist/rls-bootstrap-sql-_KNnjanK.js.map +1 -0
- package/dist/{rls-enforcement-C6Xk0lA6.js → rls-enforcement-CfXOJJaW.js} +10 -2
- package/dist/rls-enforcement-CfXOJJaW.js.map +1 -0
- package/dist/schema/auth-schema.d.ts +170 -0
- package/dist/schema/classify-change.d.ts +29 -1
- package/dist/schema/column-plan-helpers.d.ts +33 -21
- package/dist/schema/destructive-sql.d.ts +20 -1
- package/dist/schema/doctor-cli.js +4 -4
- package/dist/schema/doctor.d.ts +34 -1
- package/dist/schema/ensure-collection-policies.d.ts +22 -0
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -5
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/generate-schema-commit.d.ts +12 -0
- package/dist/schema/introspect-db-logic.d.ts +31 -0
- package/dist/schema/introspect-db-queries.d.ts +1 -1
- package/dist/schema/introspect-db-search.d.ts +22 -0
- package/dist/schema/introspect-db-storage.d.ts +83 -0
- package/dist/schema/introspect-db.js +15 -3
- package/dist/schema/introspect-db.js.map +1 -1
- package/dist/schema/plan/diff-plan.d.ts +1 -1
- package/dist/schema/plan/plan-schema.d.ts +16 -8
- package/dist/schema/plan/render-ddl.d.ts +6 -0
- package/dist/schema/plan/types.d.ts +37 -11
- package/dist/search-column-BM-GV6vH.js +442 -0
- package/dist/search-column-BM-GV6vH.js.map +1 -0
- package/dist/security/policy-drift.d.ts +1 -1
- package/dist/security/rls-enforcement.d.ts +7 -0
- package/dist/services/BranchService.d.ts +22 -1
- package/dist/services/FetchService.d.ts +5 -4
- package/dist/services/RelationService.d.ts +18 -0
- package/dist/services/cdc/CdcListener.d.ts +9 -4
- package/dist/services/cdc/identity-columns.d.ts +19 -0
- package/dist/services/cdc/trigger-cdc.d.ts +45 -7
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +12 -7
- package/dist/services/channel-history.d.ts +17 -1
- package/dist/services/collection-helpers.d.ts +11 -1
- package/dist/services/pg-notify-listener.d.ts +88 -6
- package/dist/services/realtimeService.d.ts +159 -45
- package/dist/services/socket-liveness.d.ts +45 -0
- package/dist/services/soft-delete.d.ts +12 -0
- package/dist/services/sql-script.d.ts +71 -0
- package/dist/services/write-depth.d.ts +16 -0
- package/dist/services/write-transaction-scope.d.ts +6 -3
- package/dist/utils/drizzle-conditions.d.ts +42 -2
- package/dist/utils/sql-redaction.d.ts +21 -0
- package/dist/websocket.d.ts +50 -18
- package/package.json +7 -7
- package/dist/BranchService-DGPL6G_C.js.map +0 -1
- package/dist/column-plan-helpers-DF-8dTVa.js.map +0 -1
- package/dist/doctor-Cb2thZ8s.js.map +0 -1
- package/dist/ensure-collection-policies-RHUcEp4v.js.map +0 -1
- package/dist/ensure-collection-tables-BEEjn5cn.js.map +0 -1
- package/dist/ensure-tables-Dhn9KM3B.js.map +0 -1
- package/dist/generate-drizzle-schema-logic-BfzK7UQd.js.map +0 -1
- package/dist/generate-postgres-ddl-logic-Bt2d2mRH.js.map +0 -1
- package/dist/introspect-db-logic-WMuAfxvw.js.map +0 -1
- package/dist/plan-schema-C0fxM8dY.js.map +0 -1
- package/dist/policy-drift-DljYdrpW.js.map +0 -1
- package/dist/rls-bootstrap-sql-B8EclDyM.js.map +0 -1
- package/dist/rls-enforcement-C6Xk0lA6.js.map +0 -1
|
@@ -12,6 +12,7 @@ var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
|
|
|
12
12
|
applyAuthContext: () => applyAuthContext,
|
|
13
13
|
detectConnectionPosture: () => detectConnectionPosture,
|
|
14
14
|
ensureAppRole: () => ensureAppRole,
|
|
15
|
+
revokeUserRoleSql: () => revokeUserRoleSql,
|
|
15
16
|
validatePolicyPgRoles: () => validatePolicyPgRoles,
|
|
16
17
|
warnOnAnonymousGrants: () => warnOnAnonymousGrants,
|
|
17
18
|
warnOnLegacyRlsFunctions: () => warnOnLegacyRlsFunctions,
|
|
@@ -21,6 +22,13 @@ var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
|
21
22
|
/** DML the user role holds on managed tables (RLS still filters per row). */
|
|
22
23
|
var USER_TABLE_PRIVILEGES = "SELECT, INSERT, UPDATE, DELETE";
|
|
23
24
|
/**
|
|
25
|
+
* Take every privilege the user role holds on one table back — what a table
|
|
26
|
+
* gets when RLS cannot be switched on for it, so it is unreachable rather than
|
|
27
|
+
* unprotected. Quoted exactly: a mixed-case adopted table (`"User"`) folded to
|
|
28
|
+
* lower case names a table that does not exist.
|
|
29
|
+
*/
|
|
30
|
+
var revokeUserRoleSql = (schema, table) => `REVOKE ALL PRIVILEGES ON ${quoteIdent(schema)}.${quoteIdent(table)} FROM ${quoteIdent(REBASE_USER_ROLE$1)}`;
|
|
31
|
+
/**
|
|
24
32
|
* Warn when the connection role shares its name with an existing schema.
|
|
25
33
|
*
|
|
26
34
|
* Postgres resolves unqualified names through `search_path`, which defaults to
|
|
@@ -338,6 +346,6 @@ async function validatePolicyPgRoles(run, collections, requestRole = REBASE_USER
|
|
|
338
346
|
if (problems.length > 0) throw new Error(`Security rules target PostgreSQL roles this server cannot use. Requests run as "${requestRole}", so these policies would never apply and every row would be filtered out — the collections would look empty rather than error.\n\n` + problems.join("\n\n") + "\n");
|
|
339
347
|
}
|
|
340
348
|
//#endregion
|
|
341
|
-
export {
|
|
349
|
+
export { revokeUserRoleSql as a, warnOnAnonymousGrants as c, ensureAppRole as i, warnOnLegacyRlsFunctions as l, applyAuthContext as n, rls_enforcement_exports as o, detectConnectionPosture as r, validatePolicyPgRoles as s, REBASE_USER_ROLE$1 as t, warnOnRoleSchemaCollision as u };
|
|
342
350
|
|
|
343
|
-
//# sourceMappingURL=rls-enforcement-
|
|
351
|
+
//# sourceMappingURL=rls-enforcement-CfXOJJaW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rls-enforcement-CfXOJJaW.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_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 `SET LOCAL ROLE rebase_user` so\n * RLS binds. Transaction-scoped, so it 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 await run(`CREATE ROLE ${REBASE_USER_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT`);\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. Table owners (the expected non-superuser posture) can\n // always grant on their own objects, so this tier needs no extra privilege.\n const nspRows = await run(\"SELECT nspname FROM pg_namespace\");\n const existing = new Set(nspRows.map((r) => String(r.nspname)));\n for (const schema of uniqueSchemas) {\n if (!existing.has(schema)) continue;\n const s = quoteIdent(schema);\n await run(`GRANT USAGE ON SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n await run(`GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${s} TO ${REBASE_USER_ROLE}`);\n 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 await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${REBASE_USER_ROLE}`);\n await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${REBASE_USER_ROLE}`);\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 await revokeInternalTableAccess(async (text) => { await run(text); }, schema, {\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 logger.debug(`🔐 [rls] User role \"${REBASE_USER_ROLE}\" provisioned (schemas: ${uniqueSchemas.join(\", \")})`);\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 — `SET LOCAL ROLE` so RLS binds every statement in this\n * 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)\n `);\n if (userRole) {\n await tx.execute(drizzleSql.raw(`SET LOCAL ROLE ${quoteIdent(userRole)}`));\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}\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AAC;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"}
|
|
@@ -250,6 +250,74 @@ export declare function createAuthSchema(usersSchemaName?: string): {
|
|
|
250
250
|
identity: undefined;
|
|
251
251
|
generated: undefined;
|
|
252
252
|
}, {}, {}>;
|
|
253
|
+
disabledAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
254
|
+
name: "disabled_at";
|
|
255
|
+
tableName: "users";
|
|
256
|
+
dataType: "date";
|
|
257
|
+
columnType: "PgTimestamp";
|
|
258
|
+
data: Date;
|
|
259
|
+
driverParam: string;
|
|
260
|
+
notNull: false;
|
|
261
|
+
hasDefault: false;
|
|
262
|
+
isPrimaryKey: false;
|
|
263
|
+
isAutoincrement: false;
|
|
264
|
+
hasRuntimeDefault: false;
|
|
265
|
+
enumValues: undefined;
|
|
266
|
+
baseColumn: never;
|
|
267
|
+
identity: undefined;
|
|
268
|
+
generated: undefined;
|
|
269
|
+
}, {}, {}>;
|
|
270
|
+
pendingEmail: import("drizzle-orm/pg-core").PgColumn<{
|
|
271
|
+
name: "pending_email";
|
|
272
|
+
tableName: "users";
|
|
273
|
+
dataType: "string";
|
|
274
|
+
columnType: "PgText";
|
|
275
|
+
data: string;
|
|
276
|
+
driverParam: string;
|
|
277
|
+
notNull: false;
|
|
278
|
+
hasDefault: false;
|
|
279
|
+
isPrimaryKey: false;
|
|
280
|
+
isAutoincrement: false;
|
|
281
|
+
hasRuntimeDefault: false;
|
|
282
|
+
enumValues: [string, ...string[]];
|
|
283
|
+
baseColumn: never;
|
|
284
|
+
identity: undefined;
|
|
285
|
+
generated: undefined;
|
|
286
|
+
}, {}, {}>;
|
|
287
|
+
emailChangeToken: import("drizzle-orm/pg-core").PgColumn<{
|
|
288
|
+
name: "email_change_token";
|
|
289
|
+
tableName: "users";
|
|
290
|
+
dataType: "string";
|
|
291
|
+
columnType: "PgText";
|
|
292
|
+
data: string;
|
|
293
|
+
driverParam: string;
|
|
294
|
+
notNull: false;
|
|
295
|
+
hasDefault: false;
|
|
296
|
+
isPrimaryKey: false;
|
|
297
|
+
isAutoincrement: false;
|
|
298
|
+
hasRuntimeDefault: false;
|
|
299
|
+
enumValues: [string, ...string[]];
|
|
300
|
+
baseColumn: never;
|
|
301
|
+
identity: undefined;
|
|
302
|
+
generated: undefined;
|
|
303
|
+
}, {}, {}>;
|
|
304
|
+
emailChangeSentAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
305
|
+
name: "email_change_sent_at";
|
|
306
|
+
tableName: "users";
|
|
307
|
+
dataType: "date";
|
|
308
|
+
columnType: "PgTimestamp";
|
|
309
|
+
data: Date;
|
|
310
|
+
driverParam: string;
|
|
311
|
+
notNull: false;
|
|
312
|
+
hasDefault: false;
|
|
313
|
+
isPrimaryKey: false;
|
|
314
|
+
isAutoincrement: false;
|
|
315
|
+
hasRuntimeDefault: false;
|
|
316
|
+
enumValues: undefined;
|
|
317
|
+
baseColumn: never;
|
|
318
|
+
identity: undefined;
|
|
319
|
+
generated: undefined;
|
|
320
|
+
}, {}, {}>;
|
|
253
321
|
createdAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
254
322
|
name: "created_at";
|
|
255
323
|
tableName: "users";
|
|
@@ -444,6 +512,23 @@ export declare function createAuthSchema(usersSchemaName?: string): {
|
|
|
444
512
|
identity: undefined;
|
|
445
513
|
generated: undefined;
|
|
446
514
|
}, {}, {}>;
|
|
515
|
+
method: import("drizzle-orm/pg-core").PgColumn<{
|
|
516
|
+
name: "method";
|
|
517
|
+
tableName: "refresh_tokens";
|
|
518
|
+
dataType: "string";
|
|
519
|
+
columnType: "PgText";
|
|
520
|
+
data: string;
|
|
521
|
+
driverParam: string;
|
|
522
|
+
notNull: false;
|
|
523
|
+
hasDefault: false;
|
|
524
|
+
isPrimaryKey: false;
|
|
525
|
+
isAutoincrement: false;
|
|
526
|
+
hasRuntimeDefault: false;
|
|
527
|
+
enumValues: [string, ...string[]];
|
|
528
|
+
baseColumn: never;
|
|
529
|
+
identity: undefined;
|
|
530
|
+
generated: undefined;
|
|
531
|
+
}, {}, {}>;
|
|
447
532
|
userAgent: import("drizzle-orm/pg-core").PgColumn<{
|
|
448
533
|
name: "user_agent";
|
|
449
534
|
tableName: "refresh_tokens";
|
|
@@ -1516,6 +1601,74 @@ export declare const users: import("drizzle-orm/pg-core").PgTableWithColumns<{
|
|
|
1516
1601
|
identity: undefined;
|
|
1517
1602
|
generated: undefined;
|
|
1518
1603
|
}, {}, {}>;
|
|
1604
|
+
disabledAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
1605
|
+
name: "disabled_at";
|
|
1606
|
+
tableName: "users";
|
|
1607
|
+
dataType: "date";
|
|
1608
|
+
columnType: "PgTimestamp";
|
|
1609
|
+
data: Date;
|
|
1610
|
+
driverParam: string;
|
|
1611
|
+
notNull: false;
|
|
1612
|
+
hasDefault: false;
|
|
1613
|
+
isPrimaryKey: false;
|
|
1614
|
+
isAutoincrement: false;
|
|
1615
|
+
hasRuntimeDefault: false;
|
|
1616
|
+
enumValues: undefined;
|
|
1617
|
+
baseColumn: never;
|
|
1618
|
+
identity: undefined;
|
|
1619
|
+
generated: undefined;
|
|
1620
|
+
}, {}, {}>;
|
|
1621
|
+
pendingEmail: import("drizzle-orm/pg-core").PgColumn<{
|
|
1622
|
+
name: "pending_email";
|
|
1623
|
+
tableName: "users";
|
|
1624
|
+
dataType: "string";
|
|
1625
|
+
columnType: "PgText";
|
|
1626
|
+
data: string;
|
|
1627
|
+
driverParam: string;
|
|
1628
|
+
notNull: false;
|
|
1629
|
+
hasDefault: false;
|
|
1630
|
+
isPrimaryKey: false;
|
|
1631
|
+
isAutoincrement: false;
|
|
1632
|
+
hasRuntimeDefault: false;
|
|
1633
|
+
enumValues: [string, ...string[]];
|
|
1634
|
+
baseColumn: never;
|
|
1635
|
+
identity: undefined;
|
|
1636
|
+
generated: undefined;
|
|
1637
|
+
}, {}, {}>;
|
|
1638
|
+
emailChangeToken: import("drizzle-orm/pg-core").PgColumn<{
|
|
1639
|
+
name: "email_change_token";
|
|
1640
|
+
tableName: "users";
|
|
1641
|
+
dataType: "string";
|
|
1642
|
+
columnType: "PgText";
|
|
1643
|
+
data: string;
|
|
1644
|
+
driverParam: string;
|
|
1645
|
+
notNull: false;
|
|
1646
|
+
hasDefault: false;
|
|
1647
|
+
isPrimaryKey: false;
|
|
1648
|
+
isAutoincrement: false;
|
|
1649
|
+
hasRuntimeDefault: false;
|
|
1650
|
+
enumValues: [string, ...string[]];
|
|
1651
|
+
baseColumn: never;
|
|
1652
|
+
identity: undefined;
|
|
1653
|
+
generated: undefined;
|
|
1654
|
+
}, {}, {}>;
|
|
1655
|
+
emailChangeSentAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
1656
|
+
name: "email_change_sent_at";
|
|
1657
|
+
tableName: "users";
|
|
1658
|
+
dataType: "date";
|
|
1659
|
+
columnType: "PgTimestamp";
|
|
1660
|
+
data: Date;
|
|
1661
|
+
driverParam: string;
|
|
1662
|
+
notNull: false;
|
|
1663
|
+
hasDefault: false;
|
|
1664
|
+
isPrimaryKey: false;
|
|
1665
|
+
isAutoincrement: false;
|
|
1666
|
+
hasRuntimeDefault: false;
|
|
1667
|
+
enumValues: undefined;
|
|
1668
|
+
baseColumn: never;
|
|
1669
|
+
identity: undefined;
|
|
1670
|
+
generated: undefined;
|
|
1671
|
+
}, {}, {}>;
|
|
1519
1672
|
createdAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
1520
1673
|
name: "created_at";
|
|
1521
1674
|
tableName: "users";
|
|
@@ -1710,6 +1863,23 @@ export declare const refreshTokens: import("drizzle-orm/pg-core").PgTableWithCol
|
|
|
1710
1863
|
identity: undefined;
|
|
1711
1864
|
generated: undefined;
|
|
1712
1865
|
}, {}, {}>;
|
|
1866
|
+
method: import("drizzle-orm/pg-core").PgColumn<{
|
|
1867
|
+
name: "method";
|
|
1868
|
+
tableName: "refresh_tokens";
|
|
1869
|
+
dataType: "string";
|
|
1870
|
+
columnType: "PgText";
|
|
1871
|
+
data: string;
|
|
1872
|
+
driverParam: string;
|
|
1873
|
+
notNull: false;
|
|
1874
|
+
hasDefault: false;
|
|
1875
|
+
isPrimaryKey: false;
|
|
1876
|
+
isAutoincrement: false;
|
|
1877
|
+
hasRuntimeDefault: false;
|
|
1878
|
+
enumValues: [string, ...string[]];
|
|
1879
|
+
baseColumn: never;
|
|
1880
|
+
identity: undefined;
|
|
1881
|
+
generated: undefined;
|
|
1882
|
+
}, {}, {}>;
|
|
1713
1883
|
userAgent: import("drizzle-orm/pg-core").PgColumn<{
|
|
1714
1884
|
name: "user_agent";
|
|
1715
1885
|
tableName: "refresh_tokens";
|
|
@@ -30,6 +30,23 @@
|
|
|
30
30
|
* `diverges` is the whole point of this module: an editor that reports them as
|
|
31
31
|
* safe is worse than one that refuses them.
|
|
32
32
|
*
|
|
33
|
+
* ## Read from the plan, not from the properties
|
|
34
|
+
*
|
|
35
|
+
* Whether an edit changes the database is decided by comparing what
|
|
36
|
+
* `planSchema` — the one reading of a `Property` every emitter renders — makes
|
|
37
|
+
* of the collections before and after it: each table's columns, their types,
|
|
38
|
+
* nullability, defaults, uniqueness and foreign keys, the junction tables,
|
|
39
|
+
* indexes and triggers. It used to be decided by a hand-picked list of property
|
|
40
|
+
* fields, which knew nothing of `validation.integer`, of a string becoming an
|
|
41
|
+
* enum, of an array's element type or of anything about a relation beyond its
|
|
42
|
+
* name — and every one of those was reported "safe, no change", committed, and
|
|
43
|
+
* never applied. A difference in the plan cannot be missed that way: a new kind
|
|
44
|
+
* of edit either changes the plan, and is classified here from the difference,
|
|
45
|
+
* or it does not change the database.
|
|
46
|
+
*
|
|
47
|
+
* The property-level reading is still here, for the parts only it can name: a
|
|
48
|
+
* property added or removed, a required flag, an enum's values, a key renamed.
|
|
49
|
+
*
|
|
33
50
|
* ## Why refusing is the right default for the rest
|
|
34
51
|
*
|
|
35
52
|
* Dropping a column, narrowing a type, changing a primary key: each is
|
|
@@ -37,7 +54,7 @@
|
|
|
37
54
|
* somebody wrote and read. `needs-migration` says exactly that, and naming the
|
|
38
55
|
* change is more useful than attempting it.
|
|
39
56
|
*/
|
|
40
|
-
import type
|
|
57
|
+
import { type CollectionConfig, type SchemaChange, type SchemaChangeKind, type SchemaChangeVerdict, type ClassifiedSchemaChanges } from "@rebasepro/types";
|
|
41
58
|
/**
|
|
42
59
|
* The vocabulary lives in `@rebasepro/types` so that `@rebasepro/server`, which
|
|
43
60
|
* cannot import this package, can still describe a change. Re-exported here
|
|
@@ -66,6 +83,10 @@ export interface SchemaFacts {
|
|
|
66
83
|
notNullColumns?: Set<string>;
|
|
67
84
|
/** `schema.typename` → the values that type currently holds. */
|
|
68
85
|
enumValues?: Map<string, string[]>;
|
|
86
|
+
/** `schema.table.column` → the type Postgres reports for it (`udt_name`). */
|
|
87
|
+
columnTypes?: Map<string, string>;
|
|
88
|
+
/** `schema.table.column` of every column that has a DEFAULT. */
|
|
89
|
+
columnDefaults?: Set<string>;
|
|
69
90
|
}
|
|
70
91
|
/**
|
|
71
92
|
* Classify the difference between two collection sets.
|
|
@@ -78,5 +99,12 @@ export interface SchemaFacts {
|
|
|
78
99
|
* get the conservative reading.
|
|
79
100
|
*/
|
|
80
101
|
export declare function classifyCollectionChanges(before: CollectionConfig[], after: CollectionConfig[], facts?: SchemaFacts): ClassifiedChanges;
|
|
102
|
+
/**
|
|
103
|
+
* The statements a default change needs that the additive ensure does not
|
|
104
|
+
* plan: it sets a DEFAULT only on a column that has none, and never changes or
|
|
105
|
+
* drops one. Both are metadata-only — a DEFAULT binds future writes and touches
|
|
106
|
+
* no row — so a reviewed change may make them.
|
|
107
|
+
*/
|
|
108
|
+
export declare function defaultChangeStatements(before: CollectionConfig[], after: CollectionConfig[], existingTables: Map<string, Set<string>>): string[];
|
|
81
109
|
/** A one-line summary, for a log or a refusal message. */
|
|
82
110
|
export declare function summarizeChanges(classified: ClassifiedChanges): string;
|
|
@@ -16,9 +16,9 @@
|
|
|
16
16
|
* this is where they belong.
|
|
17
17
|
*
|
|
18
18
|
* Everything here is pure and synchronous, and it throws rather than guesses:
|
|
19
|
-
* an enum with no values, a `cuid` id on Postgres and a
|
|
20
|
-
* configurations that produce a broken database in
|
|
21
|
-
* where every path passes.
|
|
19
|
+
* an enum with no values, a `cuid` id on Postgres and a foreign key into a
|
|
20
|
+
* composite key are all configurations that produce a broken database in
|
|
21
|
+
* silence, so they are refused where every path passes.
|
|
22
22
|
*/
|
|
23
23
|
import type { CollectionConfig, Property } from "@rebasepro/types";
|
|
24
24
|
/**
|
|
@@ -29,21 +29,14 @@ import type { CollectionConfig, Property } from "@rebasepro/types";
|
|
|
29
29
|
*/
|
|
30
30
|
export declare const resolveColumnName: (propName: string, prop?: Property | null) => string;
|
|
31
31
|
/**
|
|
32
|
-
*
|
|
32
|
+
* The properties marked `isId`, in declaration order.
|
|
33
33
|
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
* inline `PRIMARY KEY` clauses in one `CREATE TABLE` (Postgres: "multiple
|
|
39
|
-
* primary keys for table are not allowed"), and boot-ensure created the table
|
|
40
|
-
* with the *first* id column and silently never added the second — so a managed
|
|
41
|
-
* tenant got a table missing a column its own collection reads.
|
|
42
|
-
*
|
|
43
|
-
* None of those is recoverable at runtime, and two of them fail long after the
|
|
44
|
-
* config was written. Refused here instead, where the collection has a name.
|
|
34
|
+
* Several of them are one composite primary key: the table carries a single
|
|
35
|
+
* `PRIMARY KEY (a, b)` constraint over their columns, and a row's address lists
|
|
36
|
+
* the parts in this same order (`buildCompositeId`), which is the order the
|
|
37
|
+
* admin reads them in too.
|
|
45
38
|
*/
|
|
46
|
-
export declare const
|
|
39
|
+
export declare const primaryKeyPropertyNames: (collection: CollectionConfig) => string[];
|
|
47
40
|
/**
|
|
48
41
|
* A collection's primary key, by both of its names.
|
|
49
42
|
*
|
|
@@ -64,11 +57,30 @@ export interface PrimaryKey {
|
|
|
64
57
|
/** The declaring property; absent for the implicit `id TEXT` of a collection that declares none. */
|
|
65
58
|
prop?: Property;
|
|
66
59
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
60
|
+
/**
|
|
61
|
+
* The one column a link into this collection points at.
|
|
62
|
+
*
|
|
63
|
+
* A foreign key column references a single column, and Postgres only accepts
|
|
64
|
+
* that column when it is unique on its own — `REFERENCES t (a)` against a
|
|
65
|
+
* composite key `(a, b)` fails with "there is no unique constraint matching
|
|
66
|
+
* given keys for referenced table". So a link into a collection whose key
|
|
67
|
+
* spans several columns has no column to point at, and it is refused here,
|
|
68
|
+
* naming the link, rather than emitted as a constraint `db push` or boot would
|
|
69
|
+
* then fail to create.
|
|
70
|
+
*
|
|
71
|
+
* @param via the link that needs the column, for the refusal: `relation "posts.author"`.
|
|
72
|
+
*/
|
|
73
|
+
export declare const getPrimaryKeyProp: (collection: CollectionConfig, via: string) => PrimaryKey;
|
|
74
|
+
/**
|
|
75
|
+
* The primary key's property key. What a Drizzle relation's `references`
|
|
76
|
+
* names. Refused on the same terms as {@link getPrimaryKeyProp}.
|
|
77
|
+
*/
|
|
78
|
+
export declare const getPrimaryKeyName: (collection: CollectionConfig, via: string) => string;
|
|
79
|
+
/**
|
|
80
|
+
* The primary key's column. What a foreign key's `REFERENCES` names. Refused
|
|
81
|
+
* on the same terms as {@link getPrimaryKeyProp}.
|
|
82
|
+
*/
|
|
83
|
+
export declare const getPrimaryKeyColumn: (collection: CollectionConfig, via: string) => string;
|
|
72
84
|
export declare const isIdProperty: (propName: string, prop: Property, collection: CollectionConfig) => boolean;
|
|
73
85
|
/**
|
|
74
86
|
* The labels an `enum` declares, in order, whichever form it was written in.
|
|
@@ -9,13 +9,17 @@
|
|
|
9
9
|
* here, and refuse to auto-approve anything destructive without an explicit
|
|
10
10
|
* opt-in.
|
|
11
11
|
*
|
|
12
|
-
* A type change is
|
|
12
|
+
* A type change is a destructive plan that names no DROP. `ALTER COLUMN
|
|
13
13
|
* "price" TYPE integer` rounds every 19.99 to 20, and `TYPE date` throws away
|
|
14
14
|
* every timestamp's time of day, in a statement that reads like a routine
|
|
15
15
|
* alter. So a type change is gated too, unless it is a widening every value
|
|
16
16
|
* survives unchanged — which needs the column's current type, read from the
|
|
17
17
|
* catalogue by the caller.
|
|
18
18
|
*
|
|
19
|
+
* A primary key change names no DROP of data either: `DROP CONSTRAINT
|
|
20
|
+
* "<table>_pkey", ADD PRIMARY KEY ("id", "locale")` keeps every value and
|
|
21
|
+
* gives every row a new address. It is gated like a drop.
|
|
22
|
+
*
|
|
19
23
|
* Everything in this file is side-effect free so it can be unit-tested
|
|
20
24
|
* without Atlas or a database.
|
|
21
25
|
*/
|
|
@@ -26,6 +30,12 @@
|
|
|
26
30
|
* plan, so a naive split is safe and keeps this dependency-free.
|
|
27
31
|
*/
|
|
28
32
|
export declare function splitSqlStatements(sql: string): string[];
|
|
33
|
+
/**
|
|
34
|
+
* The statements of an Atlas plan, each exactly once, without Atlas's
|
|
35
|
+
* rendering and without the trailing `;`. See {@link readPlan} for the shape
|
|
36
|
+
* it reads; `test/fixtures/atlas-dry-run/` holds real captures of it.
|
|
37
|
+
*/
|
|
38
|
+
export declare function extractPlanStatements(plan: string): string[];
|
|
29
39
|
export interface DestructiveStatement {
|
|
30
40
|
/** The offending statement (trimmed, without the trailing `;`). */
|
|
31
41
|
statement: string;
|
|
@@ -62,6 +72,15 @@ export declare const COLUMN_TYPES_SQL = "\n SELECT n.nspname AS \"schema\",\n
|
|
|
62
72
|
* whether the change keeps its values.
|
|
63
73
|
*/
|
|
64
74
|
export declare function detectDestructiveStatements(planSql: string, columnTypes?: readonly ExistingColumnType[]): DestructiveStatement[];
|
|
75
|
+
/**
|
|
76
|
+
* The statement from its `ALTER TABLE` on, wherever on a line that starts.
|
|
77
|
+
*
|
|
78
|
+
* {@link readPlan} hands over clean statements. This is the second line of
|
|
79
|
+
* defence for text it could not clean — a rendering it does not know yet —
|
|
80
|
+
* where a line of prose above the statement must not hide the statement, which
|
|
81
|
+
* is exactly how an anchored match once read Atlas's whole plan as safe.
|
|
82
|
+
*/
|
|
83
|
+
export declare function fromAlterTable(statement: string): string;
|
|
65
84
|
/**
|
|
66
85
|
* Is `ALTER COLUMN … TYPE to` a widening, one that keeps every value exactly
|
|
67
86
|
* as it was?
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __createRequire } from "module";
|
|
3
3
|
__createRequire(import.meta.url);
|
|
4
|
-
import { i as diagnoseDbError } from "../cli-errors-
|
|
5
|
-
import {
|
|
4
|
+
import { i as diagnoseDbError } from "../cli-errors-DsA-K9uP.js";
|
|
5
|
+
import { c as warnOnAnonymousGrants, s as validatePolicyPgRoles } from "../rls-enforcement-CfXOJJaW.js";
|
|
6
6
|
import { t as chalk } from "../source-Br7L7GOI.js";
|
|
7
|
-
import { n as loadCollections, r as runDoctor } from "../doctor-
|
|
8
|
-
import { n as formatPolicyDrift, r as hasDrift, t as checkPolicyDrift } from "../policy-drift-
|
|
7
|
+
import { n as loadCollections, r as runDoctor } from "../doctor-C-sYWbmt.js";
|
|
8
|
+
import { n as formatPolicyDrift, r as hasDrift, t as checkPolicyDrift } from "../policy-drift-B-J2hhm0.js";
|
|
9
9
|
import path from "path";
|
|
10
10
|
//#region src/schema/doctor-policy-checks.ts
|
|
11
11
|
/**
|
package/dist/schema/doctor.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { CollectionConfig, Property } from "@rebasepro/types";
|
|
2
|
+
import type { PgType, TablePlan } from "./plan/types.js";
|
|
2
3
|
export type IssueSeverity = "error" | "warning" | "info";
|
|
3
4
|
export interface DoctorIssue {
|
|
4
5
|
severity: IssueSeverity;
|
|
5
|
-
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale" | "sdk_not_generated" | "sdk_ungeneratable";
|
|
6
|
+
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "primary_key_mismatch" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "orphaned_junction" | "sdk_stale" | "sdk_not_generated" | "sdk_ungeneratable";
|
|
6
7
|
table?: string;
|
|
7
8
|
column?: string;
|
|
8
9
|
expected?: string;
|
|
@@ -84,6 +85,14 @@ export declare function getExpectedColumnType(prop: Property): string | null;
|
|
|
84
85
|
export declare function loadCollections(collectionsPath: string): Promise<CollectionConfig[]>;
|
|
85
86
|
export declare function checkCollectionsVsSchema(collections: CollectionConfig[], schemaFilePath: string): Promise<DoctorPhase>;
|
|
86
87
|
export declare function checkCollectionsVsSdk(collections: CollectionConfig[], sdkFilePath: string): Promise<DoctorPhase>;
|
|
88
|
+
interface DbColumn {
|
|
89
|
+
table_schema: string;
|
|
90
|
+
table_name: string;
|
|
91
|
+
column_name: string;
|
|
92
|
+
data_type: string;
|
|
93
|
+
is_nullable: string;
|
|
94
|
+
udt_name: string;
|
|
95
|
+
}
|
|
87
96
|
/**
|
|
88
97
|
* Extensions the collections need, that the database does not have installed.
|
|
89
98
|
*
|
|
@@ -115,6 +124,29 @@ export declare function schemaStampIssues(pool: {
|
|
|
115
124
|
rows: T[];
|
|
116
125
|
}>;
|
|
117
126
|
}, collections: CollectionConfig[]): Promise<DoctorIssue[]>;
|
|
127
|
+
/**
|
|
128
|
+
* What to do about a column whose type is not the one the collection plans.
|
|
129
|
+
*
|
|
130
|
+
* Both ways out, because the doctor cannot know which side is right: the
|
|
131
|
+
* property moved, or the database did. Putting the property back always clears
|
|
132
|
+
* the finding; converting the column clears it when every value converts.
|
|
133
|
+
*/
|
|
134
|
+
export declare function typeMismatchFix(schema: string, table: string, column: string, actual: string, planned: PgType | undefined): string;
|
|
135
|
+
/**
|
|
136
|
+
* The table's primary key against the one the collection reads it by.
|
|
137
|
+
*
|
|
138
|
+
* Rebase addresses a row by the key the plan names — the `isId` property, or
|
|
139
|
+
* the implicit `id` — so a table keyed on other columns, or on none, serves
|
|
140
|
+
* reads and writes against a key that does not hold. An error, because that is
|
|
141
|
+
* what it is at runtime.
|
|
142
|
+
*/
|
|
143
|
+
export declare function primaryKeyIssues(tablePlan: TablePlan, dbPk: string[], displayName: string): DoctorIssue[];
|
|
144
|
+
/**
|
|
145
|
+
* A junction's two key columns: present, typed like the keys they point at,
|
|
146
|
+
* and the table keyed on the pair. Order is not compared — boot and `db push`
|
|
147
|
+
* have built the key in both orders, and either one serves the same rows.
|
|
148
|
+
*/
|
|
149
|
+
export declare function junctionKeyIssues(junctionPlan: TablePlan, dbColumns: DbColumn[], dbPk: string[], displayName: string): DoctorIssue[];
|
|
118
150
|
export declare function checkCollectionsVsDatabase(collections: CollectionConfig[], databaseUrl: string): Promise<DoctorPhase>;
|
|
119
151
|
export declare function renderReport(report: DoctorReport): void;
|
|
120
152
|
export declare function runDoctor(options: {
|
|
@@ -123,3 +155,4 @@ export declare function runDoctor(options: {
|
|
|
123
155
|
sdkPath: string;
|
|
124
156
|
databaseUrl?: string;
|
|
125
157
|
}): Promise<DoctorReport>;
|
|
158
|
+
export {};
|
|
@@ -81,4 +81,26 @@ export interface PolicyEnsureResult {
|
|
|
81
81
|
*/
|
|
82
82
|
orphansDropped: number;
|
|
83
83
|
}
|
|
84
|
+
export interface TableLockResult {
|
|
85
|
+
/** Tables RLS is now on for. */
|
|
86
|
+
locked: number;
|
|
87
|
+
/** Tables it could not be switched on for. See {@link PolicyEnsureResult.unsecured}. */
|
|
88
|
+
unsecured: PolicyEnsureResult["unsecured"];
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Switch RLS on for every table the collections declare — each collection's
|
|
92
|
+
* and each junction's — and do nothing else.
|
|
93
|
+
*
|
|
94
|
+
* The first thing `rebase db push` does once Atlas has committed. Atlas cannot
|
|
95
|
+
* carry `ENABLE ROW LEVEL SECURITY` (its free tier neither plans nor reads it),
|
|
96
|
+
* so a table it creates arrives with RLS off — while the user role already
|
|
97
|
+
* holds DML on it through the schema's default privileges. Everything push runs
|
|
98
|
+
* after Atlas can refuse: the vector, search and trigger DDL, the policies
|
|
99
|
+
* themselves. Locking first means none of those failures can leave a table
|
|
100
|
+
* open: RLS with no policy denies, which is a state a failed push may leave.
|
|
101
|
+
*
|
|
102
|
+
* A declared table that is not in the database is skipped — nothing can reach
|
|
103
|
+
* a table that does not exist, and the step that creates it locks it.
|
|
104
|
+
*/
|
|
105
|
+
export declare function lockCollectionTables(client: Queryable, collections: CollectionConfig[]): Promise<TableLockResult>;
|
|
84
106
|
export declare function ensureCollectionPolicies(client: Queryable, collections: CollectionConfig[], log?: (message: string) => void): Promise<PolicyEnsureResult>;
|
|
@@ -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-93M0lUxK.js";
|
|
4
4
|
//#region src/schema/bin/generate-drizzle-schema.ts
|
|
5
5
|
/**
|
|
6
6
|
* The built entry point for `generate-drizzle-schema`.
|