@rebasepro/server-postgres 0.29.0 → 0.29.1
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-JiYJ_n9E.js → BranchService-BIIBF5ZL.js} +3 -3
- package/dist/{BranchService-JiYJ_n9E.js.map → BranchService-BIIBF5ZL.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +27 -9
- package/dist/PostgresBootstrapper.d.ts +14 -0
- package/dist/{backup-cli-D_aKXPyX.js → backup-cli-QcOpmRpQ.js} +3 -3
- package/dist/{backup-cli-D_aKXPyX.js.map → backup-cli-QcOpmRpQ.js.map} +1 -1
- package/dist/{boot-ddl-D4W9o9xE.js → boot-ddl-BSNpEUOS.js} +2 -2
- package/dist/{boot-ddl-D4W9o9xE.js.map → boot-ddl-BSNpEUOS.js.map} +1 -1
- package/dist/{cli-console-DPdZCWTi.js → cli-console-DTsm96lW.js} +5 -5
- package/dist/{cli-console-DPdZCWTi.js.map → cli-console-DTsm96lW.js.map} +1 -1
- package/dist/{cli-errors-D8s4z_3g.js → cli-errors-DwqFRIWz.js} +49 -6
- package/dist/{cli-errors-D8s4z_3g.js.map → cli-errors-DwqFRIWz.js.map} +1 -1
- package/dist/cli.js +81 -41
- package/dist/cli.js.map +1 -1
- package/dist/database-preflight-D5JtPt8i.js +151 -0
- package/dist/database-preflight-D5JtPt8i.js.map +1 -0
- package/dist/db-subcommands.d.ts +1 -1
- package/dist/{deferred-index-build-F2GWu009.js → deferred-index-build-B8feKnUj.js} +12 -8
- package/dist/deferred-index-build-B8feKnUj.js.map +1 -0
- package/dist/{doctor-_g2tHRtG.js → doctor-BaR11xUe.js} +6 -6
- package/dist/{doctor-_g2tHRtG.js.map → doctor-BaR11xUe.js.map} +1 -1
- package/dist/{ensure-collection-policies-DUpWJb5D.js → ensure-collection-policies-85HiG-k1.js} +8 -8
- package/dist/{ensure-collection-policies-DUpWJb5D.js.map → ensure-collection-policies-85HiG-k1.js.map} +1 -1
- package/dist/{ensure-collection-tables-BK--gDo6.js → ensure-collection-tables-DR_WcxLA.js} +15 -10
- package/dist/ensure-collection-tables-DR_WcxLA.js.map +1 -0
- package/dist/{ensure-tables-Bx1DYarz.js → ensure-tables-Dh5UP_Zs.js} +4 -4
- package/dist/{ensure-tables-Bx1DYarz.js.map → ensure-tables-Dh5UP_Zs.js.map} +1 -1
- package/dist/{enum-labels-kept-DyFE4Gaq.js → enum-labels-kept-DSU8lAnd.js} +3 -3
- package/dist/{enum-labels-kept-DyFE4Gaq.js.map → enum-labels-kept-DSU8lAnd.js.map} +1 -1
- package/dist/{generate-drizzle-schema-taNTu3xv.js → generate-drizzle-schema-5spbTyQ6.js} +2 -2
- package/dist/{generate-drizzle-schema-taNTu3xv.js.map → generate-drizzle-schema-5spbTyQ6.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js → generate-drizzle-schema-logic-C5FB7Fpo.js} +2 -2
- package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js.map → generate-drizzle-schema-logic-C5FB7Fpo.js.map} +1 -1
- package/dist/{generate-files-DbwU8Btx.js → generate-files-Bl3_D_oP.js} +3 -3
- package/dist/{generate-files-DbwU8Btx.js.map → generate-files-Bl3_D_oP.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-ISVgsP34.js → generate-postgres-ddl-logic-BC3JA93M.js} +3 -3
- package/dist/{generate-postgres-ddl-logic-ISVgsP34.js.map → generate-postgres-ddl-logic-BC3JA93M.js.map} +1 -1
- package/dist/{generated-schema-diff-4lOC0g1_.js → generated-schema-diff-Jm93vyJB.js} +12 -4
- package/dist/generated-schema-diff-Jm93vyJB.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.es.js +20 -12
- package/dist/index.es.js.map +1 -1
- package/dist/{migrate-baseline-BeepEphh.js → migrate-baseline-BfHmq3vN.js} +49 -4
- package/dist/{migrate-baseline-BeepEphh.js.map → migrate-baseline-BfHmq3vN.js.map} +1 -1
- package/dist/{migrate-policy-stamps-cYMJ_9Ha.js → migrate-policy-stamps-B4k1ggma.js} +6 -6
- package/dist/{migrate-policy-stamps-cYMJ_9Ha.js.map → migrate-policy-stamps-B4k1ggma.js.map} +1 -1
- package/dist/{open-rebase-CTNBmmH8.js → open-rebase-CiO_sjMT.js} +465 -80
- package/dist/open-rebase-CiO_sjMT.js.map +1 -0
- package/dist/open-rebase.d.ts +6 -1
- package/dist/{pg-error-utils-BLOVXK67.js → pg-error-utils-D1Nc0UML.js} +2 -2
- package/dist/{pg-error-utils-BLOVXK67.js.map → pg-error-utils-D1Nc0UML.js.map} +1 -1
- package/dist/{plan-schema-CMNWvqIa.js → plan-schema-BYxOzflz.js} +89 -9
- package/dist/plan-schema-BYxOzflz.js.map +1 -0
- package/dist/{policy-drift-IjD2AUD-.js → policy-drift-DKuTJHfc.js} +2 -2
- package/dist/{policy-drift-IjD2AUD-.js.map → policy-drift-DKuTJHfc.js.map} +1 -1
- package/dist/{push-index-prebuild-CIvajIrL.js → push-index-prebuild-bqXimSZz.js} +4 -4
- package/dist/{push-index-prebuild-CIvajIrL.js.map → push-index-prebuild-bqXimSZz.js.map} +1 -1
- package/dist/{push-kept-defaults-CLbsuSmo.js → push-kept-defaults-CN9R8cHf.js} +2 -2
- package/dist/{push-kept-defaults-CLbsuSmo.js.map → push-kept-defaults-CN9R8cHf.js.map} +1 -1
- package/dist/{push-legacy-renames-DeW_HTLJ.js → push-legacy-renames-CU_UYPbz.js} +4 -4
- package/dist/{push-legacy-renames-DeW_HTLJ.js.map → push-legacy-renames-CU_UYPbz.js.map} +1 -1
- package/dist/{push-policy-plan--oRXOj4X.js → push-policy-plan-JcyK94bc.js} +4 -4
- package/dist/{push-policy-plan--oRXOj4X.js.map → push-policy-plan-JcyK94bc.js.map} +1 -1
- package/dist/{render-ddl-CzVcbbR1.js → render-ddl-DCdVP-pQ.js} +27 -10
- package/dist/render-ddl-DCdVP-pQ.js.map +1 -0
- package/dist/request-role-cli-DSdRtvgH.js +260 -0
- package/dist/request-role-cli-DSdRtvgH.js.map +1 -0
- package/dist/request-role-cli.d.ts +86 -0
- package/dist/request-role-migration-D9BZ5Uba.js +150 -0
- package/dist/request-role-migration-D9BZ5Uba.js.map +1 -0
- package/dist/rls-enforcement-BO618rnr.js +992 -0
- package/dist/rls-enforcement-BO618rnr.js.map +1 -0
- package/dist/rls-settings-De5NoHHy.js +211 -0
- package/dist/rls-settings-De5NoHHy.js.map +1 -0
- package/dist/schema/doctor-cli.js +144 -6
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/doctor-database.d.ts +27 -0
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/introspect-db.js +1 -1
- package/dist/schema/plan/diff-plan.d.ts +6 -1
- package/dist/schema/plan/render-ddl.d.ts +10 -3
- package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
- package/dist/schema/plan/types.d.ts +15 -0
- package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
- package/dist/schema/plan/view-names.d.ts +6 -0
- package/dist/schema/rls-bootstrap-sql.d.ts +23 -0
- package/dist/security/caller-sql-columns.d.ts +60 -0
- package/dist/security/caller-sql.d.ts +8 -0
- package/dist/security/database-preflight.d.ts +24 -0
- package/dist/security/request-role-migration.d.ts +36 -0
- package/dist/security/rls-enforcement.d.ts +191 -21
- package/dist/security/rls-settings.d.ts +177 -0
- package/dist/services/dataService.d.ts +2 -0
- package/dist/services/realtimeService.d.ts +3 -0
- package/dist/services/view-access.d.ts +2 -2
- package/dist/view-names-Dscp6--B.js +24 -0
- package/dist/view-names-Dscp6--B.js.map +1 -0
- package/dist/{websocket-D2y88dOa.js → websocket-B33YjKhs.js} +3 -3
- package/dist/{websocket-D2y88dOa.js.map → websocket-B33YjKhs.js.map} +1 -1
- package/package.json +7 -7
- package/dist/deferred-index-build-F2GWu009.js.map +0 -1
- package/dist/ensure-collection-tables-BK--gDo6.js.map +0 -1
- package/dist/generated-schema-diff-4lOC0g1_.js.map +0 -1
- package/dist/open-rebase-CTNBmmH8.js.map +0 -1
- package/dist/plan-schema-CMNWvqIa.js.map +0 -1
- package/dist/render-ddl-CzVcbbR1.js.map +0 -1
- package/dist/rls-enforcement-jZTv1yci.js +0 -534
- package/dist/rls-enforcement-jZTv1yci.js.map +0 -1
|
@@ -2,13 +2,13 @@
|
|
|
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 {
|
|
5
|
+
import { a as diagnoseDbError } from "../cli-errors-DwqFRIWz.js";
|
|
6
|
+
import { b as validatePolicyPgRoles, x as warnOnAnonymousGrants } from "../rls-enforcement-BO618rnr.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-DKuTJHfc.js";
|
|
9
|
+
import { n as loadCollections, r as runDoctor } from "../doctor-BaR11xUe.js";
|
|
10
10
|
import { isPostgresCollectionConfig } from "@rebasepro/types";
|
|
11
|
-
import { getTableName, relationalCollections } from "@rebasepro/common";
|
|
11
|
+
import { getTableName, relationalCollections, resolveJunctionSpecs } from "@rebasepro/common";
|
|
12
12
|
import path from "path";
|
|
13
13
|
//#region src/schema/doctor-policy-checks.ts
|
|
14
14
|
/**
|
|
@@ -183,6 +183,140 @@ async function runSearchScaleCheck(collectionsPath, databaseUrl) {
|
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
185
|
//#endregion
|
|
186
|
+
//#region src/schema/doctor-database.ts
|
|
187
|
+
/**
|
|
188
|
+
* `rebase doctor --database`: whether this database can host Rebase's request
|
|
189
|
+
* role(s) under the project's `rls` settings, read from the catalogue without
|
|
190
|
+
* changing anything.
|
|
191
|
+
*
|
|
192
|
+
* Lives beside `doctor-cli.ts` rather than inside it because that file runs
|
|
193
|
+
* `main()` on import; the rendering and the table list are tested here.
|
|
194
|
+
*/
|
|
195
|
+
/**
|
|
196
|
+
* The tables Rebase serves, as the server would list them: every relational
|
|
197
|
+
* collection's table in its schema (`public` by default), and every junction
|
|
198
|
+
* table a many-to-many declares.
|
|
199
|
+
*/
|
|
200
|
+
function managedTablesOf(collections) {
|
|
201
|
+
const relational = relationalCollections(collections);
|
|
202
|
+
const tables = /* @__PURE__ */ new Map();
|
|
203
|
+
const add = (schema, table) => tables.set(`${schema}.${table}`, {
|
|
204
|
+
schema,
|
|
205
|
+
table
|
|
206
|
+
});
|
|
207
|
+
for (const collection of relational) add(isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public", getTableName(collection));
|
|
208
|
+
for (const spec of resolveJunctionSpecs(relational).values()) add(spec.schema, spec.table);
|
|
209
|
+
return [...tables.values()];
|
|
210
|
+
}
|
|
211
|
+
/** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */
|
|
212
|
+
function preflightSchemasOf(collections) {
|
|
213
|
+
return Array.from(/* @__PURE__ */ new Set([
|
|
214
|
+
"public",
|
|
215
|
+
"rebase",
|
|
216
|
+
...relationalCollections(collections).filter(isPostgresCollectionConfig).map((c) => c.schema).filter((s) => !!s)
|
|
217
|
+
]));
|
|
218
|
+
}
|
|
219
|
+
var LEVEL_ORDER = [
|
|
220
|
+
"fail",
|
|
221
|
+
"warn",
|
|
222
|
+
"ok"
|
|
223
|
+
];
|
|
224
|
+
var LEVEL_TITLE = {
|
|
225
|
+
fail: "Needs fixing before Rebase can serve requests here",
|
|
226
|
+
warn: "Worth a look",
|
|
227
|
+
ok: "Fine"
|
|
228
|
+
};
|
|
229
|
+
var LEVEL_MARK = {
|
|
230
|
+
fail: chalk.red("✗"),
|
|
231
|
+
warn: chalk.yellow("⚠"),
|
|
232
|
+
ok: chalk.green("✓")
|
|
233
|
+
};
|
|
234
|
+
/**
|
|
235
|
+
* The report, grouped by level, failures first. Each finding that is not fine
|
|
236
|
+
* shows the SQL to run as an administrator in gray, and the `rls` setting that
|
|
237
|
+
* would fit Rebase to the database instead.
|
|
238
|
+
*/
|
|
239
|
+
function renderPreflightFindings(findings, settings) {
|
|
240
|
+
const lines = [];
|
|
241
|
+
lines.push(chalk.bold(" Database preflight"));
|
|
242
|
+
lines.push(chalk.gray(` Request role(s): ${settings.roles.join(", ")}. ` + (settings.nonDefaults.length > 0 ? `Non-default settings: ${settings.nonDefaults.join(", ")}.` : "The other rls settings are at their defaults.")));
|
|
243
|
+
for (const level of LEVEL_ORDER) {
|
|
244
|
+
const group = findings.filter((f) => f.level === level);
|
|
245
|
+
if (group.length === 0) continue;
|
|
246
|
+
lines.push("");
|
|
247
|
+
lines.push(` ${LEVEL_TITLE[level]}`);
|
|
248
|
+
for (const finding of group) {
|
|
249
|
+
lines.push(` ${LEVEL_MARK[level]} ${finding.check}: ${finding.detail}`);
|
|
250
|
+
if (finding.sql) for (const sqlLine of finding.sql.split("\n")) lines.push(chalk.gray(` ${sqlLine}`));
|
|
251
|
+
if (finding.setting) lines.push(chalk.cyan(` ${finding.sql ? "or set" : "set"}: ${finding.setting}`));
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return lines;
|
|
255
|
+
}
|
|
256
|
+
/** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */
|
|
257
|
+
function preflightStatus(findings) {
|
|
258
|
+
return findings.some((f) => f.level === "fail") ? "problems" : "ok";
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Every table in `schemas` but `rebase`: what a project with no declared
|
|
262
|
+
* collections serves, since its API is introspected from the database.
|
|
263
|
+
*/
|
|
264
|
+
async function everyTableIn(run, schemas) {
|
|
265
|
+
const names = schemas.filter((s) => s !== "rebase").map((s) => `'${s.replace(/'/g, "''")}'`);
|
|
266
|
+
if (names.length === 0) return [];
|
|
267
|
+
return (await run(`
|
|
268
|
+
SELECT n.nspname AS schema, c.relname AS name
|
|
269
|
+
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
270
|
+
WHERE n.nspname IN (${names.join(", ")}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
|
271
|
+
ORDER BY 1, 2
|
|
272
|
+
`)).map((r) => ({
|
|
273
|
+
schema: String(r.schema),
|
|
274
|
+
table: String(r.name)
|
|
275
|
+
}));
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Run the preflight against `databaseUrl` with the settings a command outside
|
|
279
|
+
* the server sees (`REBASE_RLS_*`, else the roles recorded in the database),
|
|
280
|
+
* and print it. Never reports `ok` for a check it could not run.
|
|
281
|
+
*/
|
|
282
|
+
async function runDatabasePreflight(collectionsPath, databaseUrl) {
|
|
283
|
+
if (!databaseUrl) {
|
|
284
|
+
console.error(chalk.yellow(" ⚠ No DATABASE_URL — the database preflight did NOT run"));
|
|
285
|
+
return "unchecked";
|
|
286
|
+
}
|
|
287
|
+
const { loadCollections } = await import("../doctor-BaR11xUe.js").then((n) => n.t);
|
|
288
|
+
const { preflightDatabase } = await import("../database-preflight-D5JtPt8i.js");
|
|
289
|
+
const { readRecordedRequestRoles } = await import("../rls-enforcement-BO618rnr.js").then((n) => n.v);
|
|
290
|
+
const { cliRlsSettings } = await import("../rls-settings-De5NoHHy.js").then((n) => n.a);
|
|
291
|
+
const { Pool } = await import("pg");
|
|
292
|
+
const pool = new Pool({ connectionString: databaseUrl });
|
|
293
|
+
try {
|
|
294
|
+
const run = async (text) => (await pool.query(text)).rows;
|
|
295
|
+
const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
|
|
296
|
+
const existing = new Set((await run("SELECT nspname FROM pg_namespace")).map((row) => String(row.nspname)));
|
|
297
|
+
const schemas = preflightSchemasOf(collections).filter((schema) => existing.has(schema));
|
|
298
|
+
const settings = cliRlsSettings(await readRecordedRequestRoles(run));
|
|
299
|
+
let managedTables = managedTablesOf(collections);
|
|
300
|
+
console.log("");
|
|
301
|
+
if (managedTables.length === 0) {
|
|
302
|
+
managedTables = await everyTableIn(run, schemas);
|
|
303
|
+
console.log(chalk.gray(" No declared collections: every table in public is treated as served, as an introspected project serves them."));
|
|
304
|
+
}
|
|
305
|
+
const findings = await preflightDatabase(run, settings, {
|
|
306
|
+
schemas,
|
|
307
|
+
managedTables
|
|
308
|
+
});
|
|
309
|
+
for (const line of renderPreflightFindings(findings, settings)) console.log(line);
|
|
310
|
+
console.log("");
|
|
311
|
+
return preflightStatus(findings);
|
|
312
|
+
} catch (err) {
|
|
313
|
+
console.error(chalk.red(" ✗ Could not run the database preflight:"), err instanceof Error ? err.message : String(err));
|
|
314
|
+
return "unchecked";
|
|
315
|
+
} finally {
|
|
316
|
+
await pool.end();
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
//#endregion
|
|
186
320
|
//#region src/schema/doctor-cli.ts
|
|
187
321
|
/**
|
|
188
322
|
* CLI entry point for `rebase doctor`.
|
|
@@ -193,6 +327,7 @@ async function main() {
|
|
|
193
327
|
const schemaArg = process.argv.find((a) => a.startsWith("--schema="));
|
|
194
328
|
const sdkArg = process.argv.find((a) => a.startsWith("--sdk="));
|
|
195
329
|
const policiesOnly = process.argv.includes("--policies");
|
|
330
|
+
const databaseOnly = process.argv.includes("--database");
|
|
196
331
|
const collectionsPath = collectionsArg?.split("=")[1] ?? path.join("..", "config", "collections");
|
|
197
332
|
const schemaPath = schemaArg?.split("=")[1] ?? path.join("src", "schema.generated.ts");
|
|
198
333
|
const sdkPath = sdkArg?.split("=")[1] ?? path.join("..", "generated", "sdk", "database.types.ts");
|
|
@@ -206,7 +341,10 @@ async function main() {
|
|
|
206
341
|
else dotenv.config({ quiet: true });
|
|
207
342
|
} catch {}
|
|
208
343
|
const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;
|
|
209
|
-
if (policiesOnly
|
|
344
|
+
if (policiesOnly || databaseOnly) {
|
|
345
|
+
const statuses = [...databaseOnly ? [await runDatabasePreflight(collectionsPath, databaseUrl)] : [], ...policiesOnly ? [await runPolicyChecks(collectionsPath, databaseUrl)] : []];
|
|
346
|
+
process.exit(statuses.some((status) => exitCodeForPolicyGate(status) !== 0) ? 1 : 0);
|
|
347
|
+
}
|
|
210
348
|
const report = await runDoctor({
|
|
211
349
|
collectionsPath: path.resolve(process.cwd(), collectionsPath),
|
|
212
350
|
schemaPath: path.resolve(process.cwd(), schemaPath),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"doctor-cli.js","names":[],"sources":["../../src/schema/doctor-policy-checks.ts","../../src/schema/doctor-search-scale.ts","../../src/schema/doctor-cli.ts"],"sourcesContent":["/**\n * The RLS half of `rebase doctor`, and the exit code `--policies` gates CI on.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import: a gate whose failure modes cannot be unit-tested is how\n * this one shipped reporting success for work it never did.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { checkPolicyDrift, formatPolicyDrift, hasDrift } from \"../security/policy-drift\";\nimport { validatePolicyPgRoles, warnOnAnonymousGrants } from \"../security/rls-enforcement\";\n\n/**\n * What the RLS checks concluded.\n *\n * `unchecked` exists because \"we could not look\" and \"we looked and it is fine\"\n * used to be reported identically: a collections path that did not resolve made\n * the loader return `[]` (it warns, it does not throw), `checkPolicyDrift`\n * early-returned an empty diff, and the gate printed\n * `✓ RLS policies match your collections` having compared zero policies against\n * zero collections. Any exception at all — a collection file that throws on\n * import, a `pg_policies` read the CI role is not granted, a connection reset —\n * did the same thing through a `warn`, and exited 0.\n */\nexport type PolicyCheckStatus = \"ok\" | \"problems\" | \"unchecked\";\n\n/**\n * The exit code for `rebase doctor --policies`.\n *\n * A gate that could not run has not passed. Only a completed, clean check\n * exits 0 — anything else, including \"we never opened a connection\", is a\n * failure, or the flag certifies a database nobody looked at.\n */\nexport function exitCodeForPolicyGate(status: PolicyCheckStatus): 0 | 1 {\n return status === \"ok\" ? 0 : 1;\n}\n\n/**\n * Policies actually deployed vs the ones the collections describe, plus policy\n * roles this server could never satisfy.\n *\n * Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.\n */\nexport async function runPolicyChecks(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — RLS policies were NOT checked\"));\n return \"unchecked\";\n }\n\n const resolvedPath = path.resolve(process.cwd(), collectionsPath);\n let problems = false;\n const { Pool } = await import(\"pg\");\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const collections: CollectionConfig[] = await loadCollections(resolvedPath);\n\n // Zero collections is not \"no drift\", it is nothing to compare. The\n // loader returns `[]` for a path that does not exist, so the commonest\n // way to get here is a `--collections` path resolved against the wrong\n // directory — which used to render as a green tick.\n if (collections.length === 0) {\n console.error(chalk.red(` ✗ No collections found in ${resolvedPath}`));\n console.error(chalk.gray(\" RLS policies were NOT checked. Pass --collections=<dir> if your collections live elsewhere.\"));\n return \"unchecked\";\n }\n\n const runSql = async (text: string) => (await pool.query(text)).rows as Record<string, unknown>[];\n\n // Prove the connection before anything is ticked.\n //\n // `validatePolicyPgRoles` returns without a query when no collection\n // names a `pgRoles` — which is most projects — so it \"passed\" against a\n // database that was never reached, and the tick printed above an\n // ECONNREFUSED that only surfaced two checks later. Ten lines up, this\n // file says that reporting success for work it never did is the reason\n // it exists. This is the same shape, one function along.\n try {\n await runSql(\"SELECT 1\");\n } catch (err) {\n console.error(chalk.gray(\" ⏭ Policy roles: not checked\"));\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n }\n\n // A policy naming a role the server never runs as filters every row, so\n // the collection reads as empty. Report it without booting a server.\n try {\n await validatePolicyPgRoles(runSql, collections as never);\n console.log(chalk.green(\" ✓ Policy roles are usable by this server\"));\n } catch (err) {\n problems = true;\n console.log(\"\");\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n }\n\n // A rule that reads as a lockdown but is true for every caller compiles\n // to a grant. Report it without booting a server.\n warnOnAnonymousGrants(collections as never);\n\n const drift = await checkPolicyDrift(pool as never, collections);\n console.log(\"\");\n if (hasDrift(drift)) {\n problems = true;\n console.log(chalk.yellow(\" RLS policies: database does not match your collections\"));\n console.log(formatPolicyDrift(drift));\n } else {\n console.log(chalk.green(` ✓ RLS policies match your collections (${collections.length} collection(s) checked)`));\n }\n } catch (err) {\n // Fail closed. This catch covers every query and every collection import\n // above, so returning the pre-catch verdict made the documented CI gate\n // green on exactly the runs it exists to catch.\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n return problems ? \"problems\" : \"ok\";\n}\n","/**\n * `rebase doctor`: collections searched by a full scan of a large table.\n *\n * Without a `search` block, a search — the admin's search box, `?searchString=`,\n * `.search()` — is `ILIKE '%term%'` over every text column. A leading `%`\n * defeats a B-tree, so each one reads the whole table: on 100k posts a search\n * took 326 ms, half for the page and half for its count. Nothing reports it;\n * the box just gets slower as the table grows. This names the collections\n * where that has started to matter, and points at the block that fixes it.\n *\n * A hint, not a failure: it never changes doctor's exit code, and the database\n * is not changed — Rebase does not add a search index on its own.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { getTableName, relationalCollections } from \"@rebasepro/common\";\nimport { isPostgresCollectionConfig, type CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { buildSearchColumnSpec } from \"./search-column\";\n\n/** Above this many rows an unindexed search is worth a word. */\nexport const UNINDEXED_SEARCH_ROWS = 10_000;\n\n/** A collection whose search would be `ILIKE` over these fields. */\nexport interface IlikeSearchedCollection {\n slug: string;\n schema: string;\n table: string;\n /** The string properties the search reads. */\n fields: string[];\n}\n\n/**\n * The collections a search reaches without an index: no `search` block (or\n * one that does not build), and at least one property the default search\n * reads — a `string`, not an enum, not a uuid key (the rule in\n * `DrizzleConditionBuilder.buildSearchConditions`).\n */\nexport function ilikeSearchedCollections(collections: CollectionConfig[]): IlikeSearchedCollection[] {\n const found: IlikeSearchedCollection[] = [];\n for (const collection of relationalCollections(collections)) {\n if (!isPostgresCollectionConfig(collection)) continue;\n let indexed: boolean;\n try {\n indexed = buildSearchColumnSpec(collection) !== undefined;\n } catch {\n // A block that does not build is reported by the boot; the search\n // falls back to ILIKE meanwhile, so it counts as none here.\n indexed = false;\n }\n if (indexed) continue;\n const fields = Object.entries(collection.properties ?? {})\n .filter(([, property]) => property.type === \"string\" && !property.enum && property.isId !== \"uuid\")\n .map(([key]) => key);\n const table = getTableName(collection);\n if (fields.length === 0 || !table) continue;\n found.push({ slug: collection.slug, schema: collection.schema ?? \"public\", table, fields });\n }\n return found;\n}\n\n/** Those of `candidates` whose table holds more than `threshold` rows, by estimate. */\nexport function unindexedSearchFindings(\n candidates: IlikeSearchedCollection[],\n rowEstimates: ReadonlyMap<string, number>,\n threshold: number = UNINDEXED_SEARCH_ROWS\n): (IlikeSearchedCollection & { rows: number })[] {\n return candidates\n .map(candidate => ({ ...candidate, rows: rowEstimates.get(`${candidate.schema}.${candidate.table}`) ?? 0 }))\n .filter(candidate => candidate.rows > threshold);\n}\n\n/**\n * Row counts by `schema.table`, estimated — `pg_class.reltuples`, or the\n * statistics collector's live-tuple count when the table was never analysed.\n * Nothing is scanned: counting the tables this is about would be the cost it\n * warns of.\n */\nexport async function estimateRowCounts(\n query: (text: string, values: unknown[]) => Promise<{ rows: { schema: string; table: string; rows: string | number }[] }>,\n schemas: string[]\n): Promise<Map<string, number>> {\n const { rows } = await query(\n `SELECT n.nspname AS schema, c.relname AS table,\n GREATEST(c.reltuples, COALESCE(s.n_live_tup, 0), 0)::bigint AS rows\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid\n WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1)`,\n [schemas]\n );\n return new Map(rows.map(row => [`${row.schema}.${row.table}`, Number(row.rows)]));\n}\n\n/** The report, one warning per collection. */\nexport function formatUnindexedSearches(findings: (IlikeSearchedCollection & { rows: number })[]): string[] {\n if (findings.length === 0) return [];\n const lines = [\"\", chalk.yellow(` ⚠ ${findings.length} collection(s) searched by reading the whole table:`)];\n for (const finding of findings) {\n lines.push(chalk.yellow(\n ` • ${finding.slug} — about ${finding.rows.toLocaleString(\"en-US\")} rows, no \\`search\\` block: a search is ` +\n `ILIKE '%term%' over ${finding.fields.join(\", \")}`\n ));\n }\n lines.push(chalk.gray(\n \" Each search reads every row, and its count reads them again. A `search` block indexes it\\n\" +\n \" (full-text, or `mode: \\\"hybrid\\\"` for substrings too): https://rebase.pro/docs/backend/search\"\n ));\n return lines;\n}\n\n/**\n * Print the warning for the project at `collectionsPath`, against\n * `databaseUrl`. Never throws and never fails the run: it is a hint, and a\n * check that could not run says so in one grey line.\n */\nexport async function runSearchScaleCheck(collectionsPath: string, databaseUrl?: string): Promise<void> {\n if (!databaseUrl) return;\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: databaseUrl });\n try {\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n const candidates = ilikeSearchedCollections(collections);\n if (candidates.length === 0) return;\n await client.connect();\n const estimates = await estimateRowCounts(\n (text, values) => client.query(text, values),\n [...new Set(candidates.map(candidate => candidate.schema))]\n );\n for (const line of formatUnindexedSearches(unindexedSearchFindings(candidates, estimates))) console.log(line);\n } catch (err) {\n console.log(chalk.gray(` ⏭ Search on large tables: not checked (${err instanceof Error ? err.message : String(err)})`));\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n","#!/usr/bin/env node\n/**\n * CLI entry point for `rebase doctor`.\n * Invoked via tsx by the server-postgres CLI plugin.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { runDoctor } from \"./doctor\";\nimport { exitCodeForPolicyGate, runPolicyChecks } from \"./doctor-policy-checks\";\nimport { runSearchScaleCheck } from \"./doctor-search-scale\";\nimport { diagnoseDbError } from \"../cli-errors\";\nimport { describeFailure } from \"../cli-output\";\n\nasync function main() {\n const collectionsArg = process.argv.find((a) => a.startsWith(\"--collections=\"));\n const schemaArg = process.argv.find((a) => a.startsWith(\"--schema=\"));\n const sdkArg = process.argv.find((a) => a.startsWith(\"--sdk=\"));\n // --policies runs only the RLS checks: no schema diff, no SDK types. Useful\n // as a CI gate against a deployed database, where the collection files and\n // generated schema are not what you are asking about.\n const policiesOnly = process.argv.includes(\"--policies\");\n\n const collectionsPath = collectionsArg?.split(\"=\")[1] ?? path.join(\"..\", \"config\", \"collections\");\n const schemaPath = schemaArg?.split(\"=\")[1] ?? path.join(\"src\", \"schema.generated.ts\");\n const sdkPath = sdkArg?.split(\"=\")[1] ?? path.join(\"..\", \"generated\", \"sdk\", \"database.types.ts\");\n\n // Load .env\n try {\n const dotenv = await import(\"dotenv\");\n const envPath = process.env.DOTENV_CONFIG_PATH;\n if (envPath) {\n dotenv.config({ path: envPath, quiet: true });\n } else {\n dotenv.config({ quiet: true });\n }\n } catch {\n // dotenv may not be installed\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n\n if (policiesOnly) {\n // Non-zero so this can gate CI — the whole point of the flag, and a\n // check that could not run has not passed. See exitCodeForPolicyGate.\n process.exit(exitCodeForPolicyGate(await runPolicyChecks(collectionsPath, databaseUrl)));\n }\n\n const report = await runDoctor({\n collectionsPath: path.resolve(process.cwd(), collectionsPath),\n schemaPath: path.resolve(process.cwd(), schemaPath),\n sdkPath: path.resolve(process.cwd(), sdkPath),\n databaseUrl: databaseUrl ?? undefined\n });\n\n const policyStatus = await runPolicyChecks(collectionsPath, databaseUrl);\n\n // A hint about speed, not drift: it never changes the exit code.\n await runSearchScaleCheck(collectionsPath, databaseUrl);\n\n // Exit non-zero if there are errors. A policy run that could not happen is\n // reported loudly above but does not fail the interactive command — the\n // same treatment the *chosen* skip of the database phase gets. `--policies`\n // is the gate, and that one fails closed.\n //\n // A phase that was skipped by a fault is different, and `blocked` is what\n // separates the two: \"no DATABASE_URL\" is a local situation somebody may be\n // content with, while \"the DATABASE_URL you set refuses connections\" would\n // otherwise let `rebase doctor` go green in CI against a database it never\n // reached.\n const blocked = [report.collectionsToSchema, report.schemaToDatabase, report.collectionsToSdk]\n .some(phase => phase.blocked);\n if (report.summary.errors > 0 || policyStatus === \"problems\" || blocked) {\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n // A known database failure has a diagnosis; a stack trace through pg and\n // drizzle internals is not it. This is the last resort — `runDoctor`\n // already catches the connection failure it can name — so it exists for\n // everything reached after the report, the policy checks in particular.\n const banner = diagnoseDbError(err, process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING);\n if (banner) {\n console.error(banner);\n } else {\n console.error(chalk.red(` ✗ Doctor failed: ${describeFailure(err)}`));\n }\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,sBAAsB,QAAkC;CACpE,OAAO,WAAW,OAAO,IAAI;AACjC;;;;;;;AAQA,eAAsB,gBAAgB,iBAAyB,aAAkD;CAC7G,IAAI,CAAC,aAAa;EACd,QAAQ,MAAM,MAAM,OAAO,qDAAqD,CAAC;EACjF,OAAO;CACX;CAEA,MAAM,eAAe,KAAK,QAAQ,QAAQ,IAAI,GAAG,eAAe;CAChE,IAAI,WAAW;CACf,MAAM,EAAE,SAAS,MAAM,OAAO;CAC9B,MAAM,OAAO,IAAI,KAAK,EAAE,kBAAkB,YAAY,CAAC;CACvD,IAAI;EACA,MAAM,cAAkC,MAAM,gBAAgB,YAAY;EAM1E,IAAI,YAAY,WAAW,GAA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,KAAK,CAAC;AAClB,CAAC"}
|
|
1
|
+
{"version":3,"file":"doctor-cli.js","names":[],"sources":["../../src/schema/doctor-policy-checks.ts","../../src/schema/doctor-search-scale.ts","../../src/schema/doctor-database.ts","../../src/schema/doctor-cli.ts"],"sourcesContent":["/**\n * The RLS half of `rebase doctor`, and the exit code `--policies` gates CI on.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import: a gate whose failure modes cannot be unit-tested is how\n * this one shipped reporting success for work it never did.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { checkPolicyDrift, formatPolicyDrift, hasDrift } from \"../security/policy-drift\";\nimport { validatePolicyPgRoles, warnOnAnonymousGrants } from \"../security/rls-enforcement\";\n\n/**\n * What the RLS checks concluded.\n *\n * `unchecked` exists because \"we could not look\" and \"we looked and it is fine\"\n * used to be reported identically: a collections path that did not resolve made\n * the loader return `[]` (it warns, it does not throw), `checkPolicyDrift`\n * early-returned an empty diff, and the gate printed\n * `✓ RLS policies match your collections` having compared zero policies against\n * zero collections. Any exception at all — a collection file that throws on\n * import, a `pg_policies` read the CI role is not granted, a connection reset —\n * did the same thing through a `warn`, and exited 0.\n */\nexport type PolicyCheckStatus = \"ok\" | \"problems\" | \"unchecked\";\n\n/**\n * The exit code for `rebase doctor --policies`.\n *\n * A gate that could not run has not passed. Only a completed, clean check\n * exits 0 — anything else, including \"we never opened a connection\", is a\n * failure, or the flag certifies a database nobody looked at.\n */\nexport function exitCodeForPolicyGate(status: PolicyCheckStatus): 0 | 1 {\n return status === \"ok\" ? 0 : 1;\n}\n\n/**\n * Policies actually deployed vs the ones the collections describe, plus policy\n * roles this server could never satisfy.\n *\n * Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.\n */\nexport async function runPolicyChecks(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — RLS policies were NOT checked\"));\n return \"unchecked\";\n }\n\n const resolvedPath = path.resolve(process.cwd(), collectionsPath);\n let problems = false;\n const { Pool } = await import(\"pg\");\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const collections: CollectionConfig[] = await loadCollections(resolvedPath);\n\n // Zero collections is not \"no drift\", it is nothing to compare. The\n // loader returns `[]` for a path that does not exist, so the commonest\n // way to get here is a `--collections` path resolved against the wrong\n // directory — which used to render as a green tick.\n if (collections.length === 0) {\n console.error(chalk.red(` ✗ No collections found in ${resolvedPath}`));\n console.error(chalk.gray(\" RLS policies were NOT checked. Pass --collections=<dir> if your collections live elsewhere.\"));\n return \"unchecked\";\n }\n\n const runSql = async (text: string) => (await pool.query(text)).rows as Record<string, unknown>[];\n\n // Prove the connection before anything is ticked.\n //\n // `validatePolicyPgRoles` returns without a query when no collection\n // names a `pgRoles` — which is most projects — so it \"passed\" against a\n // database that was never reached, and the tick printed above an\n // ECONNREFUSED that only surfaced two checks later. Ten lines up, this\n // file says that reporting success for work it never did is the reason\n // it exists. This is the same shape, one function along.\n try {\n await runSql(\"SELECT 1\");\n } catch (err) {\n console.error(chalk.gray(\" ⏭ Policy roles: not checked\"));\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n }\n\n // A policy naming a role the server never runs as filters every row, so\n // the collection reads as empty. Report it without booting a server.\n try {\n await validatePolicyPgRoles(runSql, collections as never);\n console.log(chalk.green(\" ✓ Policy roles are usable by this server\"));\n } catch (err) {\n problems = true;\n console.log(\"\");\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n }\n\n // A rule that reads as a lockdown but is true for every caller compiles\n // to a grant. Report it without booting a server.\n warnOnAnonymousGrants(collections as never);\n\n const drift = await checkPolicyDrift(pool as never, collections);\n console.log(\"\");\n if (hasDrift(drift)) {\n problems = true;\n console.log(chalk.yellow(\" RLS policies: database does not match your collections\"));\n console.log(formatPolicyDrift(drift));\n } else {\n console.log(chalk.green(` ✓ RLS policies match your collections (${collections.length} collection(s) checked)`));\n }\n } catch (err) {\n // Fail closed. This catch covers every query and every collection import\n // above, so returning the pre-catch verdict made the documented CI gate\n // green on exactly the runs it exists to catch.\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n return problems ? \"problems\" : \"ok\";\n}\n","/**\n * `rebase doctor`: collections searched by a full scan of a large table.\n *\n * Without a `search` block, a search — the admin's search box, `?searchString=`,\n * `.search()` — is `ILIKE '%term%'` over every text column. A leading `%`\n * defeats a B-tree, so each one reads the whole table: on 100k posts a search\n * took 326 ms, half for the page and half for its count. Nothing reports it;\n * the box just gets slower as the table grows. This names the collections\n * where that has started to matter, and points at the block that fixes it.\n *\n * A hint, not a failure: it never changes doctor's exit code, and the database\n * is not changed — Rebase does not add a search index on its own.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { getTableName, relationalCollections } from \"@rebasepro/common\";\nimport { isPostgresCollectionConfig, type CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { buildSearchColumnSpec } from \"./search-column\";\n\n/** Above this many rows an unindexed search is worth a word. */\nexport const UNINDEXED_SEARCH_ROWS = 10_000;\n\n/** A collection whose search would be `ILIKE` over these fields. */\nexport interface IlikeSearchedCollection {\n slug: string;\n schema: string;\n table: string;\n /** The string properties the search reads. */\n fields: string[];\n}\n\n/**\n * The collections a search reaches without an index: no `search` block (or\n * one that does not build), and at least one property the default search\n * reads — a `string`, not an enum, not a uuid key (the rule in\n * `DrizzleConditionBuilder.buildSearchConditions`).\n */\nexport function ilikeSearchedCollections(collections: CollectionConfig[]): IlikeSearchedCollection[] {\n const found: IlikeSearchedCollection[] = [];\n for (const collection of relationalCollections(collections)) {\n if (!isPostgresCollectionConfig(collection)) continue;\n let indexed: boolean;\n try {\n indexed = buildSearchColumnSpec(collection) !== undefined;\n } catch {\n // A block that does not build is reported by the boot; the search\n // falls back to ILIKE meanwhile, so it counts as none here.\n indexed = false;\n }\n if (indexed) continue;\n const fields = Object.entries(collection.properties ?? {})\n .filter(([, property]) => property.type === \"string\" && !property.enum && property.isId !== \"uuid\")\n .map(([key]) => key);\n const table = getTableName(collection);\n if (fields.length === 0 || !table) continue;\n found.push({ slug: collection.slug, schema: collection.schema ?? \"public\", table, fields });\n }\n return found;\n}\n\n/** Those of `candidates` whose table holds more than `threshold` rows, by estimate. */\nexport function unindexedSearchFindings(\n candidates: IlikeSearchedCollection[],\n rowEstimates: ReadonlyMap<string, number>,\n threshold: number = UNINDEXED_SEARCH_ROWS\n): (IlikeSearchedCollection & { rows: number })[] {\n return candidates\n .map(candidate => ({ ...candidate, rows: rowEstimates.get(`${candidate.schema}.${candidate.table}`) ?? 0 }))\n .filter(candidate => candidate.rows > threshold);\n}\n\n/**\n * Row counts by `schema.table`, estimated — `pg_class.reltuples`, or the\n * statistics collector's live-tuple count when the table was never analysed.\n * Nothing is scanned: counting the tables this is about would be the cost it\n * warns of.\n */\nexport async function estimateRowCounts(\n query: (text: string, values: unknown[]) => Promise<{ rows: { schema: string; table: string; rows: string | number }[] }>,\n schemas: string[]\n): Promise<Map<string, number>> {\n const { rows } = await query(\n `SELECT n.nspname AS schema, c.relname AS table,\n GREATEST(c.reltuples, COALESCE(s.n_live_tup, 0), 0)::bigint AS rows\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid\n WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1)`,\n [schemas]\n );\n return new Map(rows.map(row => [`${row.schema}.${row.table}`, Number(row.rows)]));\n}\n\n/** The report, one warning per collection. */\nexport function formatUnindexedSearches(findings: (IlikeSearchedCollection & { rows: number })[]): string[] {\n if (findings.length === 0) return [];\n const lines = [\"\", chalk.yellow(` ⚠ ${findings.length} collection(s) searched by reading the whole table:`)];\n for (const finding of findings) {\n lines.push(chalk.yellow(\n ` • ${finding.slug} — about ${finding.rows.toLocaleString(\"en-US\")} rows, no \\`search\\` block: a search is ` +\n `ILIKE '%term%' over ${finding.fields.join(\", \")}`\n ));\n }\n lines.push(chalk.gray(\n \" Each search reads every row, and its count reads them again. A `search` block indexes it\\n\" +\n \" (full-text, or `mode: \\\"hybrid\\\"` for substrings too): https://rebase.pro/docs/backend/search\"\n ));\n return lines;\n}\n\n/**\n * Print the warning for the project at `collectionsPath`, against\n * `databaseUrl`. Never throws and never fails the run: it is a hint, and a\n * check that could not run says so in one grey line.\n */\nexport async function runSearchScaleCheck(collectionsPath: string, databaseUrl?: string): Promise<void> {\n if (!databaseUrl) return;\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: databaseUrl });\n try {\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n const candidates = ilikeSearchedCollections(collections);\n if (candidates.length === 0) return;\n await client.connect();\n const estimates = await estimateRowCounts(\n (text, values) => client.query(text, values),\n [...new Set(candidates.map(candidate => candidate.schema))]\n );\n for (const line of formatUnindexedSearches(unindexedSearchFindings(candidates, estimates))) console.log(line);\n } catch (err) {\n console.log(chalk.gray(` ⏭ Search on large tables: not checked (${err instanceof Error ? err.message : String(err)})`));\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n","/**\n * `rebase doctor --database`: whether this database can host Rebase's request\n * role(s) under the project's `rls` settings, read from the catalogue without\n * changing anything.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import; the rendering and the table list are tested here.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport { isPostgresCollectionConfig } from \"@rebasepro/types\";\nimport { getTableName, relationalCollections, resolveJunctionSpecs } from \"@rebasepro/common\";\nimport type { PreflightFinding } from \"../security/database-preflight\";\nimport type { ManagedTable, RawSqlRunner } from \"../security/rls-enforcement\";\nimport type { RlsSettings } from \"../security/rls-settings\";\nimport type { PolicyCheckStatus } from \"./doctor-policy-checks\";\n\n/**\n * The tables Rebase serves, as the server would list them: every relational\n * collection's table in its schema (`public` by default), and every junction\n * table a many-to-many declares.\n */\nexport function managedTablesOf(collections: CollectionConfig[]): ManagedTable[] {\n const relational = relationalCollections(collections);\n const tables = new Map<string, ManagedTable>();\n const add = (schema: string, table: string) => tables.set(`${schema}.${table}`, { schema, table });\n for (const collection of relational) {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n add(schema, getTableName(collection));\n }\n for (const spec of resolveJunctionSpecs(relational).values()) add(spec.schema, spec.table);\n return [...tables.values()];\n}\n\n/** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */\nexport function preflightSchemasOf(collections: CollectionConfig[]): string[] {\n return Array.from(new Set([\n \"public\",\n \"rebase\",\n ...relationalCollections(collections)\n .filter(isPostgresCollectionConfig)\n .map((c) => c.schema)\n .filter((s): s is string => !!s)\n ]));\n}\n\nconst LEVEL_ORDER: PreflightFinding[\"level\"][] = [\"fail\", \"warn\", \"ok\"];\nconst LEVEL_TITLE: Record<PreflightFinding[\"level\"], string> = {\n fail: \"Needs fixing before Rebase can serve requests here\",\n warn: \"Worth a look\",\n ok: \"Fine\"\n};\nconst LEVEL_MARK: Record<PreflightFinding[\"level\"], string> = {\n fail: chalk.red(\"✗\"),\n warn: chalk.yellow(\"⚠\"),\n ok: chalk.green(\"✓\")\n};\n\n/**\n * The report, grouped by level, failures first. Each finding that is not fine\n * shows the SQL to run as an administrator in gray, and the `rls` setting that\n * would fit Rebase to the database instead.\n */\nexport function renderPreflightFindings(\n findings: readonly PreflightFinding[],\n settings: Pick<RlsSettings, \"roles\" | \"nonDefaults\">\n): string[] {\n const lines: string[] = [];\n lines.push(chalk.bold(\" Database preflight\"));\n lines.push(chalk.gray(\n ` Request role(s): ${settings.roles.join(\", \")}. ` +\n (settings.nonDefaults.length > 0 ? `Non-default settings: ${settings.nonDefaults.join(\", \")}.` : \"The other rls settings are at their defaults.\")\n ));\n for (const level of LEVEL_ORDER) {\n const group = findings.filter((f) => f.level === level);\n if (group.length === 0) continue;\n lines.push(\"\");\n lines.push(` ${LEVEL_TITLE[level]}`);\n for (const finding of group) {\n lines.push(` ${LEVEL_MARK[level]} ${finding.check}: ${finding.detail}`);\n if (finding.sql) {\n for (const sqlLine of finding.sql.split(\"\\n\")) lines.push(chalk.gray(` ${sqlLine}`));\n }\n if (finding.setting) lines.push(chalk.cyan(` ${finding.sql ? \"or set\" : \"set\"}: ${finding.setting}`));\n }\n }\n return lines;\n}\n\n/** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */\nexport function preflightStatus(findings: readonly PreflightFinding[]): PolicyCheckStatus {\n return findings.some((f) => f.level === \"fail\") ? \"problems\" : \"ok\";\n}\n\n/**\n * Every table in `schemas` but `rebase`: what a project with no declared\n * collections serves, since its API is introspected from the database.\n */\nasync function everyTableIn(run: RawSqlRunner, schemas: readonly string[]): Promise<ManagedTable[]> {\n const names = schemas.filter((s) => s !== \"rebase\").map((s) => `'${s.replace(/'/g, \"''\")}'`);\n if (names.length === 0) return [];\n const rows = await run(`\n SELECT n.nspname AS schema, c.relname AS name\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname IN (${names.join(\", \")}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f')\n ORDER BY 1, 2\n `);\n return rows.map((r) => ({ schema: String(r.schema), table: String(r.name) }));\n}\n\n/**\n * Run the preflight against `databaseUrl` with the settings a command outside\n * the server sees (`REBASE_RLS_*`, else the roles recorded in the database),\n * and print it. Never reports `ok` for a check it could not run.\n */\nexport async function runDatabasePreflight(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — the database preflight did NOT run\"));\n return \"unchecked\";\n }\n\n const { loadCollections } = await import(\"./doctor\");\n const { preflightDatabase } = await import(\"../security/database-preflight\");\n const { readRecordedRequestRoles } = await import(\"../security/rls-enforcement\");\n const { cliRlsSettings } = await import(\"../security/rls-settings\");\n const { Pool } = await import(\"pg\");\n\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const run: RawSqlRunner = async (text) => (await pool.query(text)).rows as Record<string, unknown>[];\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n // Only the schemas that exist: the SQL a finding carries grants on each\n // one, and a GRANT on a missing schema fails the whole script. A boot\n // grants on the ones it creates itself.\n const existing = new Set((await run(\"SELECT nspname FROM pg_namespace\")).map((row) => String(row.nspname)));\n const schemas = preflightSchemasOf(collections).filter((schema) => existing.has(schema));\n const settings = cliRlsSettings(await readRecordedRequestRoles(run));\n\n let managedTables = managedTablesOf(collections);\n console.log(\"\");\n if (managedTables.length === 0) {\n managedTables = await everyTableIn(run, schemas);\n console.log(chalk.gray(\" No declared collections: every table in public is treated as served, as an introspected project serves them.\"));\n }\n\n const findings = await preflightDatabase(run, settings, { schemas, managedTables });\n for (const line of renderPreflightFindings(findings, settings)) console.log(line);\n console.log(\"\");\n return preflightStatus(findings);\n } catch (err) {\n console.error(chalk.red(\" ✗ Could not run the database preflight:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n}\n","#!/usr/bin/env node\n/**\n * CLI entry point for `rebase doctor`.\n * Invoked via tsx by the server-postgres CLI plugin.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { runDoctor } from \"./doctor\";\nimport { exitCodeForPolicyGate, runPolicyChecks } from \"./doctor-policy-checks\";\nimport { runSearchScaleCheck } from \"./doctor-search-scale\";\nimport { runDatabasePreflight } from \"./doctor-database\";\nimport { diagnoseDbError } from \"../cli-errors\";\nimport { describeFailure } from \"../cli-output\";\n\nasync function main() {\n const collectionsArg = process.argv.find((a) => a.startsWith(\"--collections=\"));\n const schemaArg = process.argv.find((a) => a.startsWith(\"--schema=\"));\n const sdkArg = process.argv.find((a) => a.startsWith(\"--sdk=\"));\n // --policies runs only the RLS checks: no schema diff, no SDK types. Useful\n // as a CI gate against a deployed database, where the collection files and\n // generated schema are not what you are asking about.\n const policiesOnly = process.argv.includes(\"--policies\");\n // --database runs only the preflight of the database itself: whether the\n // request role(s) can be set up and used here under the project's `rls`\n // settings. Read-only, and a gate like --policies.\n const databaseOnly = process.argv.includes(\"--database\");\n\n const collectionsPath = collectionsArg?.split(\"=\")[1] ?? path.join(\"..\", \"config\", \"collections\");\n const schemaPath = schemaArg?.split(\"=\")[1] ?? path.join(\"src\", \"schema.generated.ts\");\n const sdkPath = sdkArg?.split(\"=\")[1] ?? path.join(\"..\", \"generated\", \"sdk\", \"database.types.ts\");\n\n // Load .env\n try {\n const dotenv = await import(\"dotenv\");\n const envPath = process.env.DOTENV_CONFIG_PATH;\n if (envPath) {\n dotenv.config({ path: envPath, quiet: true });\n } else {\n dotenv.config({ quiet: true });\n }\n } catch {\n // dotenv may not be installed\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n\n if (policiesOnly || databaseOnly) {\n // Non-zero so this can gate CI — the whole point of the flags, and a\n // check that could not run has not passed. See exitCodeForPolicyGate.\n const statuses = [\n ...(databaseOnly ? [await runDatabasePreflight(collectionsPath, databaseUrl)] : []),\n ...(policiesOnly ? [await runPolicyChecks(collectionsPath, databaseUrl)] : [])\n ];\n process.exit(statuses.some(status => exitCodeForPolicyGate(status) !== 0) ? 1 : 0);\n }\n\n const report = await runDoctor({\n collectionsPath: path.resolve(process.cwd(), collectionsPath),\n schemaPath: path.resolve(process.cwd(), schemaPath),\n sdkPath: path.resolve(process.cwd(), sdkPath),\n databaseUrl: databaseUrl ?? undefined\n });\n\n const policyStatus = await runPolicyChecks(collectionsPath, databaseUrl);\n\n // A hint about speed, not drift: it never changes the exit code.\n await runSearchScaleCheck(collectionsPath, databaseUrl);\n\n // Exit non-zero if there are errors. A policy run that could not happen is\n // reported loudly above but does not fail the interactive command — the\n // same treatment the *chosen* skip of the database phase gets. `--policies`\n // is the gate, and that one fails closed.\n //\n // A phase that was skipped by a fault is different, and `blocked` is what\n // separates the two: \"no DATABASE_URL\" is a local situation somebody may be\n // content with, while \"the DATABASE_URL you set refuses connections\" would\n // otherwise let `rebase doctor` go green in CI against a database it never\n // reached.\n const blocked = [report.collectionsToSchema, report.schemaToDatabase, report.collectionsToSdk]\n .some(phase => phase.blocked);\n if (report.summary.errors > 0 || policyStatus === \"problems\" || blocked) {\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n // A known database failure has a diagnosis; a stack trace through pg and\n // drizzle internals is not it. This is the last resort — `runDoctor`\n // already catches the connection failure it can name — so it exists for\n // everything reached after the report, the policy checks in particular.\n const banner = diagnoseDbError(err, process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING);\n if (banner) {\n console.error(banner);\n } else {\n console.error(chalk.red(` ✗ Doctor failed: ${describeFailure(err)}`));\n }\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,sBAAsB,QAAkC;CACpE,OAAO,WAAW,OAAO,IAAI;AACjC;;;;;;;AAQA,eAAsB,gBAAgB,iBAAyB,aAAkD;CAC7G,IAAI,CAAC,aAAa;EACd,QAAQ,MAAM,MAAM,OAAO,qDAAqD,CAAC;EACjF,OAAO;CACX;CAEA,MAAM,eAAe,KAAK,QAAQ,QAAQ,IAAI,GAAG,eAAe;CAChE,IAAI,WAAW;CACf,MAAM,EAAE,SAAS,MAAM,OAAO;CAC9B,MAAM,OAAO,IAAI,KAAK,EAAE,kBAAkB,YAAY,CAAC;CACvD,IAAI;EACA,MAAM,cAAkC,MAAM,gBAAgB,YAAY;EAM1E,IAAI,YAAY,WAAW,GAAG;GAC1B,QAAQ,MAAM,MAAM,IAAI,+BAA+B,cAAc,CAAC;GACtE,QAAQ,MAAM,MAAM,KAAK,iGAAiG,CAAC;GAC3H,OAAO;EACX;EAEA,MAAM,SA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AEzE,QAAQ,KAAK,CAAC;AAClB,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { CollectionConfig } from "@rebasepro/types";
|
|
2
|
+
import type { PreflightFinding } from "../security/database-preflight.js";
|
|
3
|
+
import type { ManagedTable } from "../security/rls-enforcement.js";
|
|
4
|
+
import type { RlsSettings } from "../security/rls-settings.js";
|
|
5
|
+
import type { PolicyCheckStatus } from "./doctor-policy-checks.js";
|
|
6
|
+
/**
|
|
7
|
+
* The tables Rebase serves, as the server would list them: every relational
|
|
8
|
+
* collection's table in its schema (`public` by default), and every junction
|
|
9
|
+
* table a many-to-many declares.
|
|
10
|
+
*/
|
|
11
|
+
export declare function managedTablesOf(collections: CollectionConfig[]): ManagedTable[];
|
|
12
|
+
/** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */
|
|
13
|
+
export declare function preflightSchemasOf(collections: CollectionConfig[]): string[];
|
|
14
|
+
/**
|
|
15
|
+
* The report, grouped by level, failures first. Each finding that is not fine
|
|
16
|
+
* shows the SQL to run as an administrator in gray, and the `rls` setting that
|
|
17
|
+
* would fit Rebase to the database instead.
|
|
18
|
+
*/
|
|
19
|
+
export declare function renderPreflightFindings(findings: readonly PreflightFinding[], settings: Pick<RlsSettings, "roles" | "nonDefaults">): string[];
|
|
20
|
+
/** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */
|
|
21
|
+
export declare function preflightStatus(findings: readonly PreflightFinding[]): PolicyCheckStatus;
|
|
22
|
+
/**
|
|
23
|
+
* Run the preflight against `databaseUrl` with the settings a command outside
|
|
24
|
+
* the server sees (`REBASE_RLS_*`, else the roles recorded in the database),
|
|
25
|
+
* and print it. Never reports `ok` for a check it could not run.
|
|
26
|
+
*/
|
|
27
|
+
export declare function runDatabasePreflight(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus>;
|
|
@@ -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-5spbTyQ6.js";
|
|
4
4
|
//#region src/schema/bin/generate-drizzle-schema.ts
|
|
5
5
|
/**
|
|
6
6
|
* The built entry point for `generate-drizzle-schema`.
|
|
@@ -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-Bl3_D_oP.js";
|
|
5
5
|
import path from "path";
|
|
6
6
|
//#region src/schema/generate-postgres-ddl.ts
|
|
7
7
|
/**
|
|
@@ -2,7 +2,7 @@ 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
4
|
import { u as pinSearchPath } from "../connection-COuS5Fm-.js";
|
|
5
|
-
import { a as diagnoseDbError } from "../cli-errors-
|
|
5
|
+
import { a as diagnoseDbError } from "../cli-errors-DwqFRIWz.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";
|
|
@@ -79,7 +79,10 @@ export interface ExistingSchema {
|
|
|
79
79
|
* `numeric(10,2)`).
|
|
80
80
|
*/
|
|
81
81
|
columnTypes?: Map<string, string>;
|
|
82
|
-
/**
|
|
82
|
+
/**
|
|
83
|
+
* `schema.table.trigger` of every trigger that already exists, and the
|
|
84
|
+
* same with its arguments — {@link triggerArgumentsKey}.
|
|
85
|
+
*/
|
|
83
86
|
triggers?: Set<string>;
|
|
84
87
|
/**
|
|
85
88
|
* `schema.name` of every index (any relation of kind `i`/`I`) that already
|
|
@@ -116,6 +119,8 @@ export interface ExistingSchema {
|
|
|
116
119
|
* which is what all of them were before.
|
|
117
120
|
*/
|
|
118
121
|
export declare const HELPER_FUNCTIONS: readonly string[];
|
|
122
|
+
/** A trigger's catalogue key with the arguments it is bound with. */
|
|
123
|
+
export declare const triggerArgumentsKey: (key: string, args: readonly string[]) => string;
|
|
119
124
|
/**
|
|
120
125
|
* Everything `CREATE OR REPLACE FUNCTION` sets on a function, as one string.
|
|
121
126
|
*
|
|
@@ -83,9 +83,16 @@ export declare const viewComment: (view: ViewPlan) => string;
|
|
|
83
83
|
/**
|
|
84
84
|
* The statements that create one view as planned, comment included, for
|
|
85
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
|
|
87
|
-
*
|
|
88
|
-
*
|
|
86
|
+
* policies of the tables it reads decide what each caller sees.
|
|
87
|
+
*
|
|
88
|
+
* A materialized view is two objects (see `view-names.ts`): its rows, stored
|
|
89
|
+
* under {@link viewRowsName} with a unique index on the id columns (which
|
|
90
|
+
* `REFRESH … CONCURRENTLY` needs), and the gate under the collection's name —
|
|
91
|
+
* a `security_barrier` view that reads them with the owner's rights and serves
|
|
92
|
+
* them to the collection's roles and to the server (no uid). It reads the
|
|
93
|
+
* settings directly rather than through `rebase.roles()`, which a first boot
|
|
94
|
+
* creates after the views. It carries each row's `xmin`, for `fingerprint()`;
|
|
95
|
+
* the catalogue reader leaves that column out of the collection.
|
|
89
96
|
*/
|
|
90
97
|
export declare function viewCreateStatements(view: ViewPlan): string[];
|
|
91
98
|
/**
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { TriggerPlan } from "./types.js";
|
|
2
|
+
/** The one trigger function, qualified. A frozen derived name. */
|
|
3
|
+
export declare const KEEP_TENANT_FN = "rebase.keep_tenant";
|
|
4
|
+
/** The trigger's name on `table`. A frozen derived name. */
|
|
5
|
+
export declare const keepTenantTriggerName: (table: string) => string;
|
|
6
|
+
export declare const keepTenantFunction: () => string;
|
|
7
|
+
/** The arguments the binding passes: the column, then each bypass role. */
|
|
8
|
+
export declare const keepTenantArguments: (plan: TriggerPlan) => string[];
|
|
9
|
+
export declare const createKeepTenantStatement: (plan: TriggerPlan) => string;
|
|
@@ -297,6 +297,14 @@ export interface TriggerPlan {
|
|
|
297
297
|
column: string;
|
|
298
298
|
/** Frozen derived name — see `contracts/derived-names.txt`. */
|
|
299
299
|
name: string;
|
|
300
|
+
/**
|
|
301
|
+
* What the trigger does: `touch` stamps `column` with `now()` on every
|
|
302
|
+
* update (`autoValue: "on_update"`, the default); `keep-tenant` refuses an
|
|
303
|
+
* update that changes the tenant `column` (see `tenant-keep-trigger.ts`).
|
|
304
|
+
*/
|
|
305
|
+
kind?: "touch" | "keep-tenant";
|
|
306
|
+
/** `keep-tenant` only: the roles that may move a row between tenants. */
|
|
307
|
+
bypassRoles?: string[];
|
|
300
308
|
}
|
|
301
309
|
/** A Postgres enum type one or more columns reference. */
|
|
302
310
|
export interface EnumPlan {
|
|
@@ -422,8 +430,15 @@ export interface ViewPlan {
|
|
|
422
430
|
qualified: string;
|
|
423
431
|
query: string;
|
|
424
432
|
materialized: boolean;
|
|
433
|
+
/**
|
|
434
|
+
* Materialized only: the roles its gate serves (`view.roles`, default
|
|
435
|
+
* `["admin"]`). See `viewRowsName`.
|
|
436
|
+
*/
|
|
437
|
+
roles: string[];
|
|
425
438
|
/** The `isId` columns: a materialized view gets a unique index on them, which `REFRESH … CONCURRENTLY` needs. */
|
|
426
439
|
idColumns: string[];
|
|
440
|
+
/** Materialized only: the `CREATE INDEX` of each declared index, on the stored rows. */
|
|
441
|
+
indexes: string[];
|
|
427
442
|
/** The other planned views this one's query names, which must exist first. */
|
|
428
443
|
dependsOn: string[];
|
|
429
444
|
/**
|
|
@@ -18,5 +18,5 @@ export declare const setUpdatedAtFunction: () => string;
|
|
|
18
18
|
*/
|
|
19
19
|
export declare const dropTriggerStatement: (plan: TriggerPlan) => string;
|
|
20
20
|
export declare const createTriggerStatement: (plan: TriggerPlan) => string;
|
|
21
|
-
/** Both statements, in the order they must run. */
|
|
21
|
+
/** Both statements, in the order they must run — for either kind of trigger. */
|
|
22
22
|
export declare const triggerStatements: (plan: TriggerPlan) => string[];
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** The roles a materialized view is served to when it names none. */
|
|
2
|
+
export declare const DEFAULT_VIEW_ROLES: readonly string[];
|
|
3
|
+
/** Where a materialized view's rows are stored. A frozen derived name. */
|
|
4
|
+
export declare const viewRowsName: (name: string) => string;
|
|
5
|
+
/** The comment the stored rows carry, beside the gate's `rebase:view:<hash>`. */
|
|
6
|
+
export declare const VIEW_ROWS_COMMENT_PREFIX = "rebase:view-rows:";
|
|
@@ -185,3 +185,26 @@ export declare function dropLegacyAuthSchema(run: (sql: string) => Promise<Recor
|
|
|
185
185
|
info: (m: string) => void;
|
|
186
186
|
warn: (m: string) => void;
|
|
187
187
|
}): Promise<void>;
|
|
188
|
+
/**
|
|
189
|
+
* `rebase.is_request_role(role)` — is `role` one of the roles this database's
|
|
190
|
+
* requests run as? The predicate `rls.policyTarget: "requestRole"` ANDs into
|
|
191
|
+
* every permissive policy (`RLS_IS_REQUEST_ROLE_SQL`), called with
|
|
192
|
+
* `current_user`.
|
|
193
|
+
*
|
|
194
|
+
* SECURITY DEFINER because the recorded roles live in `rebase.schema_meta`,
|
|
195
|
+
* which the request roles cannot read. That is also why the caller's role is
|
|
196
|
+
* an argument: inside the function `current_user` is its owner. The body is
|
|
197
|
+
* dynamic SQL so the function can be created before the table exists — in
|
|
198
|
+
* Atlas's replay of the migrations, for one. With nothing recorded the answer
|
|
199
|
+
* is `rebase_user`, as everywhere else.
|
|
200
|
+
*
|
|
201
|
+
* Created only for a project that asks for `policyTarget: "requestRole"`, so
|
|
202
|
+
* every other project's migrations and boot are exactly what they were.
|
|
203
|
+
*/
|
|
204
|
+
export declare const REQUEST_ROLE_FUNCTION_SQL = "CREATE OR REPLACE FUNCTION rebase.is_request_role(role_name text) RETURNS boolean AS $$\nDECLARE\n request_roles text[];\nBEGIN\n IF to_regclass('\"rebase\".\"schema_meta\"') IS NOT NULL THEN\n EXECUTE 'SELECT string_to_array(value, '','') FROM \"rebase\".\"schema_meta\" WHERE key = ''request_roles'''\n INTO request_roles;\n END IF;\n RETURN role_name = ANY(COALESCE(request_roles, ARRAY['rebase_user']));\nEND\n$$ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog";
|
|
205
|
+
/**
|
|
206
|
+
* Create {@link REQUEST_ROLE_FUNCTION_SQL} when it is missing or its body
|
|
207
|
+
* differs — replacing an unchanged function would still invalidate every
|
|
208
|
+
* cached plan of every policy that calls it.
|
|
209
|
+
*/
|
|
210
|
+
export declare function ensureRequestRoleFunction(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<void>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The columns a caller may not read, taken out of what their SQL returned.
|
|
3
|
+
*
|
|
4
|
+
* Per-field read rules (`access.read`, and `excludeFromApi`, which is
|
|
5
|
+
* `read: []`) are not something Postgres can hold for one request role shared
|
|
6
|
+
* by every user, so the SDK applies them to each row it serves
|
|
7
|
+
* (`stripUnreadable`). SQL run as the caller (`DataDriver.sql`) returns rows
|
|
8
|
+
* the SDK never walked — and `SELECT *` from a users table would hand over the
|
|
9
|
+
* password hash.
|
|
10
|
+
*
|
|
11
|
+
* Postgres says where each result column came from: the row description
|
|
12
|
+
* carries the table's oid and the column's number for every column that is a
|
|
13
|
+
* plain reference to one, aliased or not, `RETURNING` included. A column whose
|
|
14
|
+
* origin is a collection property this caller cannot read is dropped from
|
|
15
|
+
* every row, the way the API drops it.
|
|
16
|
+
*
|
|
17
|
+
* What it cannot see is a value computed from such a column — `md5(hash)`,
|
|
18
|
+
* `hash || ''` — whose origin Postgres reports as none. That is the query
|
|
19
|
+
* text's business, and the query text is the application's (see
|
|
20
|
+
* `caller-sql.ts`).
|
|
21
|
+
*
|
|
22
|
+
* A driver that reports no origins at all (PGlite) has its result columns
|
|
23
|
+
* matched by name instead, against every restricted column of every
|
|
24
|
+
* collection: it may drop a column of the same name from another table, never
|
|
25
|
+
* keep one it should drop.
|
|
26
|
+
*/
|
|
27
|
+
import { type FieldViewer } from "@rebasepro/common";
|
|
28
|
+
import { type CollectionConfig } from "@rebasepro/types";
|
|
29
|
+
/** A result column as the driver describes it. */
|
|
30
|
+
export interface ResultField {
|
|
31
|
+
name: string;
|
|
32
|
+
/** The originating table's oid; 0 for a computed column. Absent when the driver does not say (PGlite). */
|
|
33
|
+
tableID?: number;
|
|
34
|
+
/** The originating column's number within it. */
|
|
35
|
+
columnID?: number;
|
|
36
|
+
}
|
|
37
|
+
/** The columns of a result, from a pg `QueryResult` (or the last of several). */
|
|
38
|
+
export declare function fieldsOfResult(result: unknown): ResultField[];
|
|
39
|
+
type CatalogueRunner = (text: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
|
|
40
|
+
interface Relation {
|
|
41
|
+
schema: string;
|
|
42
|
+
name: string;
|
|
43
|
+
/** `attnum` → `attname`. */
|
|
44
|
+
columns: Map<number, string>;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The relations result columns came from, by oid, read from the catalogue the
|
|
48
|
+
* first time an oid is seen. An oid never changes meaning: a table that is
|
|
49
|
+
* dropped and created again gets a new one, which is read when it appears.
|
|
50
|
+
*/
|
|
51
|
+
export declare class ColumnOrigins {
|
|
52
|
+
private readonly relations;
|
|
53
|
+
describe(oids: number[], run: CatalogueRunner): Promise<Map<number, Relation | null>>;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* `rows` without the columns `viewer` may not read, by the origins `fields`
|
|
57
|
+
* describe. The rows are changed in place and returned.
|
|
58
|
+
*/
|
|
59
|
+
export declare function withoutUnreadableColumns(rows: Record<string, unknown>[], fields: ResultField[], viewer: FieldViewer, collections: CollectionConfig[], origins: ColumnOrigins, run: CatalogueRunner): Promise<Record<string, unknown>[]>;
|
|
60
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The query with every string literal, dollar-quoted body and comment
|
|
3
|
+
* replaced by a space. Quoted identifiers are kept, quotes and all, so a name
|
|
4
|
+
* written `"set_config"` still reads as one.
|
|
5
|
+
*/
|
|
6
|
+
export declare function maskSqlLiterals(text: string): string;
|
|
7
|
+
/** Throw `SQL_NOT_ALLOWED` unless `text` may run as the caller (see the module docs). */
|
|
8
|
+
export declare function assertCallerSql(text: string): void;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type ManagedTable, type RawSqlRunner } from "./rls-enforcement.js";
|
|
2
|
+
import type { RlsSettings } from "./rls-settings.js";
|
|
3
|
+
/**
|
|
4
|
+
* What `rebase doctor --database` checks: whether this database can host
|
|
5
|
+
* Rebase's request role(s) under the project's `rls` settings, read from the
|
|
6
|
+
* catalogue without changing anything.
|
|
7
|
+
*
|
|
8
|
+
* Every finding that is not "ok" carries the SQL to run as an administrator, the
|
|
9
|
+
* `rls` setting that would adapt Rebase to the database instead, or both — the
|
|
10
|
+
* two ways out of any of them.
|
|
11
|
+
*/
|
|
12
|
+
export interface PreflightFinding {
|
|
13
|
+
level: "ok" | "warn" | "fail";
|
|
14
|
+
check: string;
|
|
15
|
+
detail: string;
|
|
16
|
+
/** SQL that fixes it, run as a database administrator. */
|
|
17
|
+
sql?: string;
|
|
18
|
+
/** The `rls` setting that would fit Rebase to the database as it is. */
|
|
19
|
+
setting?: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function preflightDatabase(run: RawSqlRunner, settings: RlsSettings, options: {
|
|
22
|
+
schemas: readonly string[];
|
|
23
|
+
managedTables: readonly ManagedTable[];
|
|
24
|
+
}): Promise<PreflightFinding[]>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type RawSqlRunner } from "./rls-enforcement.js";
|
|
2
|
+
/**
|
|
3
|
+
* Move a database from one set of request roles to another — what
|
|
4
|
+
* `rebase db request-role migrate --to …` runs.
|
|
5
|
+
*
|
|
6
|
+
* A role belongs to the cluster, so renaming one (`ALTER ROLE … RENAME`) moves
|
|
7
|
+
* every database's grants at once, including another project's that shares
|
|
8
|
+
* it. This instead creates the new role(s) and re-issues, in THIS database
|
|
9
|
+
* only, every grant the old ones hold here: tables and views, columns,
|
|
10
|
+
* sequences, schemas, functions, the default privileges this connection set,
|
|
11
|
+
* and the memberships that carry other roles' policies (`rls.inheritRoles`).
|
|
12
|
+
* Policies that name an old role in their `TO` list are re-pointed. The old
|
|
13
|
+
* roles are left as they are — another database may still use them — and the
|
|
14
|
+
* statements to take their grants back here are returned for the operator.
|
|
15
|
+
*/
|
|
16
|
+
export interface RequestRoleMigrationPlan {
|
|
17
|
+
/** What to run, in order, to give the new roles what the old ones hold here. */
|
|
18
|
+
statements: string[];
|
|
19
|
+
/** What would take the old roles' grants back in this database, for the operator to run once satisfied. */
|
|
20
|
+
revokeOld: string[];
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Read the catalogue and plan the move. Writes nothing; {@link migrateRequestRoles}
|
|
24
|
+
* runs the plan.
|
|
25
|
+
*/
|
|
26
|
+
export declare function planRequestRoleMigration(run: RawSqlRunner, from: readonly string[], to: readonly string[]): Promise<RequestRoleMigrationPlan>;
|
|
27
|
+
/**
|
|
28
|
+
* Provision the new role(s), run the plan, and record the new roles — in one
|
|
29
|
+
* transaction where the runner has one, so a failure leaves the database on
|
|
30
|
+
* its old roles. Returns the plan that ran.
|
|
31
|
+
*/
|
|
32
|
+
export declare function migrateRequestRoles(run: RawSqlRunner, options: {
|
|
33
|
+
from: readonly string[];
|
|
34
|
+
to: readonly string[];
|
|
35
|
+
schemas: readonly string[];
|
|
36
|
+
}): Promise<RequestRoleMigrationPlan>;
|