@rebasepro/cli 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/{auth-DifFaOyq.js → auth-Bv0rTbQX.js} +3 -3
- package/dist/{auth-DifFaOyq.js.map → auth-Bv0rTbQX.js.map} +1 -1
- package/dist/commands/doctor.d.ts +1 -0
- package/dist/{console-BXB6-8GT.js → console-CdwIYOMV.js} +2 -2
- package/dist/{console-BXB6-8GT.js.map → console-CdwIYOMV.js.map} +1 -1
- package/dist/{db-KzlqddGD.js → db-DBbKpjYX.js} +35 -6
- package/dist/{db-KzlqddGD.js.map → db-DBbKpjYX.js.map} +1 -1
- package/dist/{dev-CzOazEHW.js → dev-C93d4QIv.js} +2 -2
- package/dist/{dev-CzOazEHW.js.map → dev-C93d4QIv.js.map} +1 -1
- package/dist/{doctor-BuqSHNrd.js → doctor-BBPQUO2g.js} +12 -4
- package/dist/{doctor-BuqSHNrd.js.map → doctor-BBPQUO2g.js.map} +1 -1
- package/dist/index.es.js +10 -10
- package/dist/{schema-CApM25cs.js → schema-DtLPsXbT.js} +3 -3
- package/dist/{schema-CApM25cs.js.map → schema-DtLPsXbT.js.map} +1 -1
- package/dist/schema-reconcile-DkArN9jF.js +2 -0
- package/dist/{verify-D7UsV_qe.js → verify-Y3rWSgfA.js} +2 -2
- package/dist/{verify-D7UsV_qe.js.map → verify-Y3rWSgfA.js.map} +1 -1
- package/package.json +8 -8
- package/templates/overlays/baas/ai-instructions.md +1 -1
- package/templates/template/.cursorrules +1 -1
- package/templates/template/.github/copilot-instructions.md +1 -1
- package/templates/template/.windsurfrules +1 -1
- package/templates/template/AGENTS.md +1 -1
- package/templates/template/CLAUDE.md +1 -1
- package/templates/template/ai-instructions.md +1 -1
- package/templates/template/backend/functions/hello.ts +4 -3
- package/dist/schema-reconcile-CX1_6Xqm.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-CApM25cs.js","names":[],"sources":["../src/commands/schema-reconcile.ts","../src/commands/schema.ts"],"sourcesContent":["/**\n * CLI command: rebase schema reconcile\n *\n * The reviewed step for what boot will not do. Boot only ever adds, so a\n * property made optional leaves its column NOT NULL, and a property removed\n * leaves its column behind, with its data, and blocking inserts if it was\n * required. This asks the running backend for the plan that fixes both, prints\n * it, and applies it only once confirmed.\n *\n * Through the backend rather than a database URL, because on Rebase Cloud the\n * backend is the one thing that can reach the database — and because it plans\n * against the collections it actually runs, not the ones in this checkout.\n * Columns are dropped only when named with `--drop`; the confirmation sends\n * the plan's digest, so the server runs exactly the statements printed here.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport readline from \"node:readline/promises\";\nimport { RebaseApiError } from \"@rebasepro/client\";\nimport type { SchemaReconcilePlan } from \"@rebasepro/types\";\nimport { requireProjectRoot, readEnvFile } from \"../utils/project\";\nimport { UsageError } from \"../utils/args\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { describeFailure, requireBackendUrl } from \"./api-keys\";\n\nexport const RECONCILE_USAGE = \"rebase schema reconcile [--drop <collection>.<column>]... [--yes]\";\n\nexport function parseReconcileArgs(rawArgs: string[]): { drop: string[]; yes: boolean } {\n const flags = arg({ \"--drop\": [String], \"--yes\": Boolean, \"-y\": \"--yes\" }, { argv: rawArgs.slice(2) });\n if (flags._.length > 0) throw new UsageError(`Unexpected argument \"${flags._[0]}\". Usage: ${RECONCILE_USAGE}`);\n return { drop: flags[\"--drop\"] ?? [], yes: flags[\"--yes\"] === true };\n}\n\n/** The plan, as a person reviews it. Returned as lines so it can be tested. */\nexport function describeReconcilePlan(plan: SchemaReconcilePlan): string[] {\n const lines: string[] = [];\n for (const r of plan.relaxed) {\n const why = r.undeclared\n ? `no property in \"${r.collection}\" declares it, and every insert fails on it; its data stays`\n : `optional in \"${r.collection}\", NOT NULL in the database`;\n lines.push(` ${chalk.cyan(\"relax\")} ${r.table}.${r.column} ${chalk.gray(why)}`);\n }\n for (const d of plan.dropped) {\n const rows = d.rowsWithValue === undefined ? \"\" : `${d.rowsWithValue.toLocaleString(\"en-US\")} row(s) hold a value`;\n lines.push(` ${chalk.red(\"drop\")} ${d.table}.${d.column} ${chalk.red(rows)}`);\n }\n const kept = plan.undeclared.filter(u =>\n !plan.dropped.some(d => d.table === u.table && d.column === u.column)\n && !plan.relaxed.some(r => r.undeclared && r.table === u.table && r.column === u.column));\n for (const u of kept) {\n const note = u.blocksInserts\n ? chalk.yellow(\"NOT NULL with no default: every insert fails until it is dropped or relaxed\")\n : chalk.gray(\"no property declares it; kept\");\n lines.push(` ${chalk.gray(\"keep\")} ${u.table}.${u.column} ${note}`);\n }\n return lines;\n}\n\ninterface Backend {\n baseUrl: string;\n post<T>(path: string, body: unknown): Promise<T>;\n}\n\n/** The project's backend, holding the service key. */\nfunction connect(): Backend {\n const projectRoot = requireProjectRoot();\n const env = readEnvFile(projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n if (!serviceKey) {\n console.error(chalk.red(\"✗ REBASE_SERVICE_KEY not found in .env — required to change the database's schema.\"));\n process.exit(1);\n }\n const baseUrl = requireBackendUrl(env, projectRoot).replace(/\\/+$/, \"\");\n return {\n baseUrl,\n async post<T>(path: string, body: unknown): Promise<T> {\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/api/admin/schema/reconcile${path}`, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": cliUserAgent()\n },\n body: JSON.stringify(body)\n });\n } catch (error: unknown) {\n throw new RebaseApiError(error instanceof Error ? error.message : String(error), { status: 0, code: \"NETWORK_ERROR\" });\n }\n const answer: unknown = await response.json().catch(() => undefined);\n if (!response.ok) {\n const error = answer && typeof answer === \"object\" && \"error\" in answer && answer.error && typeof answer.error === \"object\"\n ? answer.error as { message?: unknown; code?: unknown; details?: unknown }\n : undefined;\n throw new RebaseApiError(\n typeof error?.message === \"string\" ? error.message : `The server answered ${response.status}.`,\n { status: response.status, code: typeof error?.code === \"string\" ? error.code : undefined, details: error?.details }\n );\n }\n return answer as T;\n }\n };\n}\n\nfunction fail(action: string, error: unknown, baseUrl: string): never {\n for (const line of describeFailure(action, error, baseUrl)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n if (error instanceof RebaseApiError && error.status === 404) {\n console.error(chalk.gray(\" This backend has no reconcile route: it needs a runtime that has `rebase schema reconcile`.\"));\n }\n process.exit(1);\n}\n\nexport async function schemaReconcileCommand(rawArgs: string[]): Promise<void> {\n const { drop, yes } = parseReconcileArgs(rawArgs);\n const backend = connect();\n\n let plan: SchemaReconcilePlan;\n try {\n plan = await backend.post<SchemaReconcilePlan>(\"/plan\", { drop });\n } catch (error) {\n fail(\"Failed to plan the reconcile\", error, backend.baseUrl);\n }\n\n console.log(chalk.bold(`\\nSchema reconcile for ${backend.baseUrl}\\n`));\n const described = describeReconcilePlan(plan);\n if (described.length > 0) console.log(described.join(\"\\n\"));\n\n if (plan.problems.length > 0) {\n console.error(chalk.red(\"\\n✗ This plan cannot be applied:\"));\n for (const problem of plan.problems) console.error(chalk.red(` • ${problem}`));\n process.exit(1);\n }\n if (plan.statements.length === 0) {\n console.log(chalk.green(\"✓ Nothing to do: the database already matches what the collections declare.\"));\n }\n if (plan.undeclared.length > plan.dropped.length) {\n console.log(chalk.gray(\" To drop a column no property declares, name it: --drop <collection>.<column>\"));\n }\n if (plan.statements.length === 0) return;\n\n console.log(chalk.bold(\"\\nStatements\"));\n for (const statement of plan.statements) console.log(` ${statement}`);\n if (plan.dropped.length > 0) {\n console.log(chalk.red(\"\\n Dropping a column destroys its data. Back the database up first if you may want it back.\"));\n }\n\n if (!yes) {\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"\\n✗ Not applied: confirming needs a terminal. Re-run with --yes once you have read the plan.\"));\n process.exit(1);\n }\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const answer = (await rl.question(`\\nApply ${plan.statements.length} statement(s)? Type \"yes\" to continue: `)).trim();\n rl.close();\n if (answer !== \"yes\") {\n console.log(chalk.gray(\"Aborted. Nothing was changed.\"));\n return;\n }\n }\n\n try {\n const result = await backend.post<{ applied: string[] }>(\"/apply\", { drop, confirm: plan.digest });\n console.log(chalk.green(`✓ Applied ${result.applied.length} statement(s).`));\n } catch (error) {\n if (error instanceof RebaseApiError && error.code === \"SCHEMA_RECONCILE_STALE\") {\n console.error(chalk.red(\"✗ Not applied: the database or the collections changed since this plan was made. Run it again to review the new plan.\"));\n process.exit(1);\n }\n fail(\"Failed to apply the reconcile\", error, backend.baseUrl);\n }\n}\n","/**\n * CLI command: rebase schema <action>\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { ensureDockerDatabase, spawnDriverCli } from \"./db\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { recordEvent } from \"../telemetry\";\nimport { wantsHelp } from \"../utils/args\";\nimport { reportSpawnFailure } from \"../utils/spawn-error\";\nimport { argsFromCommand } from \"../utils/command-words\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from \"../dev-db/prepare\";\nimport { absolutizeLocalPathArgs } from \"./db\";\nimport { COLLECTIONS_FLAG_HELP, refuseMissingCollectionsPath } from \"../utils/path-flags\";\nimport { collectionsDirArgs } from \"../utils/collections-dir\";\nimport { RECONCILE_USAGE } from \"./schema-reconcile\";\n\n/**\n * The line handed to the driver, its paths resolved from where the command was\n * run (the driver runs in `backend/`). `--schema` is left alone: on\n * `introspect` it names a Postgres schema, not a file.\n */\nexport function schemaDriverArgs(rawArgs: string[], cwd: string): string[] {\n return absolutizeLocalPathArgs(argsFromCommand(rawArgs, \"schema\"), cwd, [\"--collections\", \"-c\", \"--output\", \"-o\", \"--out\"]);\n}\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here, before `requireProjectRoot` and before the\n // driver is spawned — the same shape `db.ts` already uses, and for the same\n // reason.\n //\n // `cli.ts` rewrites the subcommand to `\"--help\"` only when the user named\n // none, so `rebase schema --help` was covered and `rebase schema generate\n // --help` was not: the flag travelled into `rawArgs.slice(2)` and reached\n // the driver, whose own `schemaCommand` has no `--help` case. It *ran the\n // generator* — overwriting `src/schema.generated.ts` — for a flag whose\n // entire job is to print text. Worse, the first thing it hit outside a\n // project was `requireProjectRoot`, so `rebase schema introspect --help` in\n // an empty directory exited 1 with \"Could not find a Rebase project root\":\n // help you cannot read until you already have a project is help for nobody.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printSchemaHelp(subcommand === \"--help\" ? undefined : subcommand);\n return;\n }\n\n // A typo is answered here, in the same words every other family uses.\n //\n // It used to travel to the driver, which said the bare line `Unknown schema\n // command.` — no list, no pointer, no did-you-mean, for a family with three\n // subcommands. The set comes from the help table, so what a typo is measured\n // against and what `--help` prints cannot drift apart.\n if (!SCHEMA_ACTION_HELP[subcommand]) {\n unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), \"schema\");\n }\n\n const projectRoot = requireProjectRoot();\n\n // Talks to the running backend, not the driver: on Rebase Cloud the\n // backend is the only thing that reaches the database.\n if (subcommand === \"reconcile\") {\n void recordEvent(\"cli.schema\", { subcommand }, { projectRoot });\n const { schemaReconcileCommand } = await import(\"./schema-reconcile\");\n await schemaReconcileCommand(rawArgs);\n return;\n }\n\n // Fire-and-forget, and a no-op unless the developer opted in. Never awaited:\n // the command is what the user is waiting for, and a slow collector must not\n // sit in front of it.\n void recordEvent(\"cli.schema\", { subcommand: subcommand ?? \"none\" }, { projectRoot });\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n exitDependenciesNotInstalled(projectRoot);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n // Which database this project is on, so the driver's closing line does not\n // recommend a command that database refuses. A pure decision — nothing is\n // started, which matters here above all: `schema generate` reads collection\n // files and writes one file, and booting a database to run it would be a\n // side effect nobody asked for.\n env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? \"\";\n\n refuseMissingCollectionsPath(rawArgs, process.cwd(), backendDir);\n\n // `introspect` is the one schema command that reads a database, and it\n // reads the project's — resolved the way every `db` command resolves it,\n // started if that is what it takes. It used to pass `.env` and nothing\n // else, so on the managed database or after `rebase dev --docker` (with\n // the scaffold's DATABASE_URL commented out, on purpose) it said\n // \"DATABASE_URL is not set\", and `--docker` and `--database-url` passed the\n // flag check only to be ignored.\n if (subcommand === \"introspect\") {\n const flags = arg(\n { \"--database-url\": String, \"--docker\": Boolean },\n { argv: rawArgs.slice(2), permissive: true }\n );\n await ensureDockerDatabase(projectRoot, rawArgs);\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n Object.assign(env, prepared.env);\n env[DEV_DATABASE_KIND_ENV] = prepared.database.kind;\n for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));\n }\n\n try {\n // The one spawn, shared with `db`. This file used to carry its own copy\n // of the tsx-or-node decision; three copies of that rule existed and two\n // were fixed while the third went on spawning plain node.\n const driverArgs = schemaDriverArgs(rawArgs, process.cwd());\n await spawnDriverCli(\n { projectRoot, backendDir, pluginCli, env },\n [...driverArgs, ...collectionsDirArgs(projectRoot, driverArgs)]\n );\n } catch (error) {\n // A child that ran and exited non-zero already printed its diagnostics\n // through inherited stdio; a child that never started (ENOENT on tsx,\n // EACCES on the script) printed nothing at all, and this used to exit 1\n // in silence.\n reportSpawnFailure(error);\n process.exit(1);\n }\n}\n\n/** One page per subcommand, so `rebase schema <action> --help` says something. */\nconst SCHEMA_ACTION_HELP: Record<string, { usage: string; summary: string; notes?: string[] }> = {\n generate: {\n usage: \"rebase schema generate [--collections <dir>] [--output <file>] [--watch]\",\n summary: \"Generate the Drizzle schema from the collection definitions.\",\n notes: [\"--watch regenerates on every change to a collection file.\"]\n },\n introspect: {\n usage: \"rebase schema introspect [--collections <dir>] [--output <dir>] [--schema <name>] [--force] [--data-inference | --no-data-inference]\",\n summary: \"Read an existing database and write Rebase collection definitions from it.\",\n notes: [\n \"--force overwrites collection files that are already there.\",\n \"--data-inference samples up to 100 rows per table to detect formats, constraints and UI settings; \"\n + \"--no-data-inference reads the structure only. Without either it asks, and without a terminal \"\n + \"it reads the structure only.\",\n \"Reads this project's database, the one `rebase db url` prints: --database-url <url> names another; \"\n + \"--docker uses the compose one, starting it if needed.\"\n ]\n },\n reconcile: {\n usage: RECONCILE_USAGE,\n summary: \"Relax and drop what boot will not: NOT NULL on properties made optional, and columns no property declares.\",\n notes: [\n \"Plans on the running backend (the one `.env` and the cloud link point at), prints the plan, and applies it once you type yes.\",\n \"A column is dropped only when named: --drop voice_cache.wav. Each drop shows how many rows hold a value.\",\n \"--yes skips the prompt, for a plan already read. Needs REBASE_SERVICE_KEY in .env.\"\n ]\n },\n stale: {\n usage: \"rebase schema stale [--collections <dir>] [--output <file>] [--fix]\",\n summary: \"Report generated schema files that no longer match the collections.\",\n notes: [\"--fix regenerates them instead of only reporting.\"]\n }\n};\n\n/** Every subcommand the family dispatches — the help table's keys. */\nexport const SCHEMA_SUBCOMMANDS = Object.keys(SCHEMA_ACTION_HELP);\n\nfunction printSchemaHelp(action?: string) {\n const entry = action ? SCHEMA_ACTION_HELP[action] : undefined;\n if (entry) {\n console.log(`\n${chalk.bold(`rebase schema ${action}`)}\n\n ${entry.summary}\n\n${chalk.green.bold(\"Usage\")}\n ${chalk.blue(entry.usage)}\n${entry.notes?.length ? `\\n${chalk.green.bold(\"Notes\")}\\n${entry.notes.map(n => ` ${chalk.gray(`• ${n}`)}`).join(\"\\n\")}\\n` : \"\"}\n${chalk.gray(\"Run `rebase schema --help` for every subcommand.\")}\n`);\n return;\n }\n\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate Schema from collection definitions\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database to generate collection definitions\n ${chalk.blue.bold(\"stale\")} Report generated schema files that no longer match the collections\n ${chalk.blue.bold(\"reconcile\")} Relax NOT NULL and drop columns the collections no longer declare, after review\n\n${chalk.green.bold(\"generate Options\")}\n ${chalk.blue(\"--collections, -c\")} ${COLLECTIONS_FLAG_HELP}\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--output, -o\")} Output directory for generated collection files\n ${chalk.blue(\"--schema\")} Postgres schema to read (default: public)\n ${chalk.blue(\"--force, -f\")} Overwrite collection files that already exist\n ${chalk.blue(\"--database-url\")} Read this database instead of the project's own\n ${chalk.blue(\"--docker\")} Read the compose database, starting it if needed\n ${chalk.blue(\"--data-inference\")} Sample rows to detect formats and constraints ${chalk.gray(\"(asked when omitted)\")}\n ${chalk.blue(\"--no-data-inference\")} Read the structure only, without asking\n\n${chalk.green.bold(\"stale Options\")}\n ${chalk.blue(\"--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AK,WAAW,EAAE;;EAExC,MAAM,MAAM,KAAK,UAAU,EAAE;IAC3B,MAAM,KAAK,+DAA+D,EAAE;IAC5E,MAAM,KAAK,KAAK,UAAU,EAAE;IAC5B,MAAM,KAAK,KAAK,YAAY,EAAE;IAC9B,MAAM,KAAK,KAAK,OAAO,EAAE;IACzB,MAAM,KAAK,KAAK,WAAW,EAAE;;EAE/B,MAAM,MAAM,KAAK,kBAAkB,EAAE;IACnC,MAAM,KAAK,mBAAmB,EAAE,IAAI,sBAAsB;IAC1D,MAAM,KAAK,cAAc,EAAE;IAC3B,MAAM,KAAK,aAAa,EAAE;;EAE5B,MAAM,MAAM,KAAK,oBAAoB,EAAE;IACrC,MAAM,KAAK,cAAc,EAAE;IAC3B,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,aAAa,EAAE;IAC1B,MAAM,KAAK,gBAAgB,EAAE;IAC7B,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,kBAAkB,EAAE,mDAAmD,MAAM,KAAK,sBAAsB,EAAE;IACrH,MAAM,KAAK,qBAAqB,EAAE;;EAEpC,MAAM,MAAM,KAAK,eAAe,EAAE;IAChC,MAAM,KAAK,OAAO,EAAE;CACvB;AACD"}
|
|
1
|
+
{"version":3,"file":"schema-DtLPsXbT.js","names":[],"sources":["../src/commands/schema-reconcile.ts","../src/commands/schema.ts"],"sourcesContent":["/**\n * CLI command: rebase schema reconcile\n *\n * The reviewed step for what boot will not do. Boot only ever adds, so a\n * property made optional leaves its column NOT NULL, and a property removed\n * leaves its column behind, with its data, and blocking inserts if it was\n * required. This asks the running backend for the plan that fixes both, prints\n * it, and applies it only once confirmed.\n *\n * Through the backend rather than a database URL, because on Rebase Cloud the\n * backend is the one thing that can reach the database — and because it plans\n * against the collections it actually runs, not the ones in this checkout.\n * Columns are dropped only when named with `--drop`; the confirmation sends\n * the plan's digest, so the server runs exactly the statements printed here.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport readline from \"node:readline/promises\";\nimport { RebaseApiError } from \"@rebasepro/client\";\nimport type { SchemaReconcilePlan } from \"@rebasepro/types\";\nimport { requireProjectRoot, readEnvFile } from \"../utils/project\";\nimport { UsageError } from \"../utils/args\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { describeFailure, requireBackendUrl } from \"./api-keys\";\n\nexport const RECONCILE_USAGE = \"rebase schema reconcile [--drop <collection>.<column>]... [--yes]\";\n\nexport function parseReconcileArgs(rawArgs: string[]): { drop: string[]; yes: boolean } {\n const flags = arg({ \"--drop\": [String], \"--yes\": Boolean, \"-y\": \"--yes\" }, { argv: rawArgs.slice(2) });\n if (flags._.length > 0) throw new UsageError(`Unexpected argument \"${flags._[0]}\". Usage: ${RECONCILE_USAGE}`);\n return { drop: flags[\"--drop\"] ?? [], yes: flags[\"--yes\"] === true };\n}\n\n/** The plan, as a person reviews it. Returned as lines so it can be tested. */\nexport function describeReconcilePlan(plan: SchemaReconcilePlan): string[] {\n const lines: string[] = [];\n for (const r of plan.relaxed) {\n const why = r.undeclared\n ? `no property in \"${r.collection}\" declares it, and every insert fails on it; its data stays`\n : `optional in \"${r.collection}\", NOT NULL in the database`;\n lines.push(` ${chalk.cyan(\"relax\")} ${r.table}.${r.column} ${chalk.gray(why)}`);\n }\n for (const d of plan.dropped) {\n const rows = d.rowsWithValue === undefined ? \"\" : `${d.rowsWithValue.toLocaleString(\"en-US\")} row(s) hold a value`;\n lines.push(` ${chalk.red(\"drop\")} ${d.table}.${d.column} ${chalk.red(rows)}`);\n }\n const kept = plan.undeclared.filter(u =>\n !plan.dropped.some(d => d.table === u.table && d.column === u.column)\n && !plan.relaxed.some(r => r.undeclared && r.table === u.table && r.column === u.column));\n for (const u of kept) {\n const note = u.blocksInserts\n ? chalk.yellow(\"NOT NULL with no default: every insert fails until it is dropped or relaxed\")\n : chalk.gray(\"no property declares it; kept\");\n lines.push(` ${chalk.gray(\"keep\")} ${u.table}.${u.column} ${note}`);\n }\n return lines;\n}\n\ninterface Backend {\n baseUrl: string;\n post<T>(path: string, body: unknown): Promise<T>;\n}\n\n/** The project's backend, holding the service key. */\nfunction connect(): Backend {\n const projectRoot = requireProjectRoot();\n const env = readEnvFile(projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n if (!serviceKey) {\n console.error(chalk.red(\"✗ REBASE_SERVICE_KEY not found in .env — required to change the database's schema.\"));\n process.exit(1);\n }\n const baseUrl = requireBackendUrl(env, projectRoot).replace(/\\/+$/, \"\");\n return {\n baseUrl,\n async post<T>(path: string, body: unknown): Promise<T> {\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/api/admin/schema/reconcile${path}`, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": cliUserAgent()\n },\n body: JSON.stringify(body)\n });\n } catch (error: unknown) {\n throw new RebaseApiError(error instanceof Error ? error.message : String(error), { status: 0, code: \"NETWORK_ERROR\" });\n }\n const answer: unknown = await response.json().catch(() => undefined);\n if (!response.ok) {\n const error = answer && typeof answer === \"object\" && \"error\" in answer && answer.error && typeof answer.error === \"object\"\n ? answer.error as { message?: unknown; code?: unknown; details?: unknown }\n : undefined;\n throw new RebaseApiError(\n typeof error?.message === \"string\" ? error.message : `The server answered ${response.status}.`,\n { status: response.status, code: typeof error?.code === \"string\" ? error.code : undefined, details: error?.details }\n );\n }\n return answer as T;\n }\n };\n}\n\nfunction fail(action: string, error: unknown, baseUrl: string): never {\n for (const line of describeFailure(action, error, baseUrl)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n if (error instanceof RebaseApiError && error.status === 404) {\n console.error(chalk.gray(\" This backend has no reconcile route: it needs a runtime that has `rebase schema reconcile`.\"));\n }\n process.exit(1);\n}\n\nexport async function schemaReconcileCommand(rawArgs: string[]): Promise<void> {\n const { drop, yes } = parseReconcileArgs(rawArgs);\n const backend = connect();\n\n let plan: SchemaReconcilePlan;\n try {\n plan = await backend.post<SchemaReconcilePlan>(\"/plan\", { drop });\n } catch (error) {\n fail(\"Failed to plan the reconcile\", error, backend.baseUrl);\n }\n\n console.log(chalk.bold(`\\nSchema reconcile for ${backend.baseUrl}\\n`));\n const described = describeReconcilePlan(plan);\n if (described.length > 0) console.log(described.join(\"\\n\"));\n\n if (plan.problems.length > 0) {\n console.error(chalk.red(\"\\n✗ This plan cannot be applied:\"));\n for (const problem of plan.problems) console.error(chalk.red(` • ${problem}`));\n process.exit(1);\n }\n if (plan.statements.length === 0) {\n console.log(chalk.green(\"✓ Nothing to do: the database already matches what the collections declare.\"));\n }\n if (plan.undeclared.length > plan.dropped.length) {\n console.log(chalk.gray(\" To drop a column no property declares, name it: --drop <collection>.<column>\"));\n }\n if (plan.statements.length === 0) return;\n\n console.log(chalk.bold(\"\\nStatements\"));\n for (const statement of plan.statements) console.log(` ${statement}`);\n if (plan.dropped.length > 0) {\n console.log(chalk.red(\"\\n Dropping a column destroys its data. Back the database up first if you may want it back.\"));\n }\n\n if (!yes) {\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"\\n✗ Not applied: confirming needs a terminal. Re-run with --yes once you have read the plan.\"));\n process.exit(1);\n }\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const answer = (await rl.question(`\\nApply ${plan.statements.length} statement(s)? Type \"yes\" to continue: `)).trim();\n rl.close();\n if (answer !== \"yes\") {\n console.log(chalk.gray(\"Aborted. Nothing was changed.\"));\n return;\n }\n }\n\n try {\n const result = await backend.post<{ applied: string[] }>(\"/apply\", { drop, confirm: plan.digest });\n console.log(chalk.green(`✓ Applied ${result.applied.length} statement(s).`));\n } catch (error) {\n if (error instanceof RebaseApiError && error.code === \"SCHEMA_RECONCILE_STALE\") {\n console.error(chalk.red(\"✗ Not applied: the database or the collections changed since this plan was made. Run it again to review the new plan.\"));\n process.exit(1);\n }\n fail(\"Failed to apply the reconcile\", error, backend.baseUrl);\n }\n}\n","/**\n * CLI command: rebase schema <action>\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { ensureDockerDatabase, spawnDriverCli } from \"./db\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { recordEvent } from \"../telemetry\";\nimport { wantsHelp } from \"../utils/args\";\nimport { reportSpawnFailure } from \"../utils/spawn-error\";\nimport { argsFromCommand } from \"../utils/command-words\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from \"../dev-db/prepare\";\nimport { absolutizeLocalPathArgs } from \"./db\";\nimport { COLLECTIONS_FLAG_HELP, refuseMissingCollectionsPath } from \"../utils/path-flags\";\nimport { collectionsDirArgs } from \"../utils/collections-dir\";\nimport { RECONCILE_USAGE } from \"./schema-reconcile\";\n\n/**\n * The line handed to the driver, its paths resolved from where the command was\n * run (the driver runs in `backend/`). `--schema` is left alone: on\n * `introspect` it names a Postgres schema, not a file.\n */\nexport function schemaDriverArgs(rawArgs: string[], cwd: string): string[] {\n return absolutizeLocalPathArgs(argsFromCommand(rawArgs, \"schema\"), cwd, [\"--collections\", \"-c\", \"--output\", \"-o\", \"--out\"]);\n}\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here, before `requireProjectRoot` and before the\n // driver is spawned — the same shape `db.ts` already uses, and for the same\n // reason.\n //\n // `cli.ts` rewrites the subcommand to `\"--help\"` only when the user named\n // none, so `rebase schema --help` was covered and `rebase schema generate\n // --help` was not: the flag travelled into `rawArgs.slice(2)` and reached\n // the driver, whose own `schemaCommand` has no `--help` case. It *ran the\n // generator* — overwriting `src/schema.generated.ts` — for a flag whose\n // entire job is to print text. Worse, the first thing it hit outside a\n // project was `requireProjectRoot`, so `rebase schema introspect --help` in\n // an empty directory exited 1 with \"Could not find a Rebase project root\":\n // help you cannot read until you already have a project is help for nobody.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printSchemaHelp(subcommand === \"--help\" ? undefined : subcommand);\n return;\n }\n\n // A typo is answered here, in the same words every other family uses.\n //\n // It used to travel to the driver, which said the bare line `Unknown schema\n // command.` — no list, no pointer, no did-you-mean, for a family with three\n // subcommands. The set comes from the help table, so what a typo is measured\n // against and what `--help` prints cannot drift apart.\n if (!SCHEMA_ACTION_HELP[subcommand]) {\n unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), \"schema\");\n }\n\n const projectRoot = requireProjectRoot();\n\n // Talks to the running backend, not the driver: on Rebase Cloud the\n // backend is the only thing that reaches the database.\n if (subcommand === \"reconcile\") {\n void recordEvent(\"cli.schema\", { subcommand }, { projectRoot });\n const { schemaReconcileCommand } = await import(\"./schema-reconcile\");\n await schemaReconcileCommand(rawArgs);\n return;\n }\n\n // Fire-and-forget, and a no-op unless the developer opted in. Never awaited:\n // the command is what the user is waiting for, and a slow collector must not\n // sit in front of it.\n void recordEvent(\"cli.schema\", { subcommand: subcommand ?? \"none\" }, { projectRoot });\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n exitDependenciesNotInstalled(projectRoot);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n // Which database this project is on, so the driver's closing line does not\n // recommend a command that database refuses. A pure decision — nothing is\n // started, which matters here above all: `schema generate` reads collection\n // files and writes one file, and booting a database to run it would be a\n // side effect nobody asked for.\n env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? \"\";\n\n refuseMissingCollectionsPath(rawArgs, process.cwd(), backendDir);\n\n // `introspect` is the one schema command that reads a database, and it\n // reads the project's — resolved the way every `db` command resolves it,\n // started if that is what it takes. It used to pass `.env` and nothing\n // else, so on the managed database or after `rebase dev --docker` (with\n // the scaffold's DATABASE_URL commented out, on purpose) it said\n // \"DATABASE_URL is not set\", and `--docker` and `--database-url` passed the\n // flag check only to be ignored.\n if (subcommand === \"introspect\") {\n const flags = arg(\n { \"--database-url\": String, \"--docker\": Boolean },\n { argv: rawArgs.slice(2), permissive: true }\n );\n await ensureDockerDatabase(projectRoot, rawArgs);\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n Object.assign(env, prepared.env);\n env[DEV_DATABASE_KIND_ENV] = prepared.database.kind;\n for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));\n }\n\n try {\n // The one spawn, shared with `db`. This file used to carry its own copy\n // of the tsx-or-node decision; three copies of that rule existed and two\n // were fixed while the third went on spawning plain node.\n const driverArgs = schemaDriverArgs(rawArgs, process.cwd());\n await spawnDriverCli(\n { projectRoot, backendDir, pluginCli, env },\n [...driverArgs, ...collectionsDirArgs(projectRoot, driverArgs)]\n );\n } catch (error) {\n // A child that ran and exited non-zero already printed its diagnostics\n // through inherited stdio; a child that never started (ENOENT on tsx,\n // EACCES on the script) printed nothing at all, and this used to exit 1\n // in silence.\n reportSpawnFailure(error);\n process.exit(1);\n }\n}\n\n/** One page per subcommand, so `rebase schema <action> --help` says something. */\nconst SCHEMA_ACTION_HELP: Record<string, { usage: string; summary: string; notes?: string[] }> = {\n generate: {\n usage: \"rebase schema generate [--collections <dir>] [--output <file>] [--watch]\",\n summary: \"Generate the Drizzle schema from the collection definitions.\",\n notes: [\"--watch regenerates on every change to a collection file.\"]\n },\n introspect: {\n usage: \"rebase schema introspect [--collections <dir>] [--output <dir>] [--schema <name>] [--force] [--data-inference | --no-data-inference]\",\n summary: \"Read an existing database and write Rebase collection definitions from it.\",\n notes: [\n \"--force overwrites collection files that are already there.\",\n \"--data-inference samples up to 100 rows per table to detect formats, constraints and UI settings; \"\n + \"--no-data-inference reads the structure only. Without either it asks, and without a terminal \"\n + \"it reads the structure only.\",\n \"Reads this project's database, the one `rebase db url` prints: --database-url <url> names another; \"\n + \"--docker uses the compose one, starting it if needed.\"\n ]\n },\n reconcile: {\n usage: RECONCILE_USAGE,\n summary: \"Relax and drop what boot will not: NOT NULL on properties made optional, and columns no property declares.\",\n notes: [\n \"Plans on the running backend (the one `.env` and the cloud link point at), prints the plan, and applies it once you type yes.\",\n \"A column is dropped only when named: --drop voice_cache.wav. Each drop shows how many rows hold a value.\",\n \"--yes skips the prompt, for a plan already read. Needs REBASE_SERVICE_KEY in .env.\"\n ]\n },\n stale: {\n usage: \"rebase schema stale [--collections <dir>] [--output <file>] [--fix]\",\n summary: \"Report generated schema files that no longer match the collections.\",\n notes: [\"--fix regenerates them instead of only reporting.\"]\n }\n};\n\n/** Every subcommand the family dispatches — the help table's keys. */\nexport const SCHEMA_SUBCOMMANDS = Object.keys(SCHEMA_ACTION_HELP);\n\nfunction printSchemaHelp(action?: string) {\n const entry = action ? SCHEMA_ACTION_HELP[action] : undefined;\n if (entry) {\n console.log(`\n${chalk.bold(`rebase schema ${action}`)}\n\n ${entry.summary}\n\n${chalk.green.bold(\"Usage\")}\n ${chalk.blue(entry.usage)}\n${entry.notes?.length ? `\\n${chalk.green.bold(\"Notes\")}\\n${entry.notes.map(n => ` ${chalk.gray(`• ${n}`)}`).join(\"\\n\")}\\n` : \"\"}\n${chalk.gray(\"Run `rebase schema --help` for every subcommand.\")}\n`);\n return;\n }\n\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate Schema from collection definitions\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database to generate collection definitions\n ${chalk.blue.bold(\"stale\")} Report generated schema files that no longer match the collections\n ${chalk.blue.bold(\"reconcile\")} Relax NOT NULL and drop columns the collections no longer declare, after review\n\n${chalk.green.bold(\"generate Options\")}\n ${chalk.blue(\"--collections, -c\")} ${COLLECTIONS_FLAG_HELP}\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--output, -o\")} Output directory for generated collection files\n ${chalk.blue(\"--schema\")} Postgres schema to read (default: public)\n ${chalk.blue(\"--force, -f\")} Overwrite collection files that already exist\n ${chalk.blue(\"--database-url\")} Read this database instead of the project's own\n ${chalk.blue(\"--docker\")} Read the compose database, starting it if needed\n ${chalk.blue(\"--data-inference\")} Sample rows to detect formats and constraints ${chalk.gray(\"(asked when omitted)\")}\n ${chalk.blue(\"--no-data-inference\")} Read the structure only, without asking\n\n${chalk.green.bold(\"stale Options\")}\n ${chalk.blue(\"--fix\")} Regenerate the stale files instead of only reporting them\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,kBAAkB;AAE/B,SAAgB,mBAAmB,SAAqD;CACpF,MAAM,QAAQ,IAAI;EAAE,UAAU,CAAC,MAAM;EAAG,SAAS;EAAS,MAAM;CAAQ,GAAG,EAAE,MAAM,QAAQ,MAAM,CAAC,EAAE,CAAC;CACrG,IAAI,MAAM,EAAE,SAAS,GAAG,MAAM,IAAI,WAAW,wBAAwB,MAAM,EAAE,GAAG,YAAY,iBAAiB;CAC7G,OAAO;EAAE,MAAM,MAAM,aAAa,CAAC;EAAG,KAAK,MAAM,aAAa;CAAK;A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,MAAM,KAAK,cAAc,EAAE;IAC3B,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,aAAa,EAAE;IAC1B,MAAM,KAAK,gBAAgB,EAAE;IAC7B,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,kBAAkB,EAAE,mDAAmD,MAAM,KAAK,sBAAsB,EAAE;IACrH,MAAM,KAAK,qBAAqB,EAAE;;EAEpC,MAAM,MAAM,KAAK,eAAe,EAAE;IAChC,MAAM,KAAK,OAAO,EAAE;CACvB;AACD"}
|
|
@@ -669,7 +669,7 @@ function authRequiredFrom(environment, envFile) {
|
|
|
669
669
|
*/
|
|
670
670
|
async function resolveLiveDatabase(projectRoot, rawArgs, options) {
|
|
671
671
|
try {
|
|
672
|
-
const { ensureDockerDatabase, databaseUrlOf } = await import("./db-
|
|
672
|
+
const { ensureDockerDatabase, databaseUrlOf } = await import("./db-DBbKpjYX.js");
|
|
673
673
|
await ensureDockerDatabase(projectRoot, rawArgs);
|
|
674
674
|
const { prepareDatabaseEnv } = await import("./prepare-CTw9NEkh.js");
|
|
675
675
|
return { databaseUrl: databaseUrlOf(await prepareDatabaseEnv(projectRoot, {
|
|
@@ -727,4 +727,4 @@ async function verifyCommand(rawArgs) {
|
|
|
727
727
|
//#endregion
|
|
728
728
|
export { verifyCommand };
|
|
729
729
|
|
|
730
|
-
//# sourceMappingURL=verify-
|
|
730
|
+
//# sourceMappingURL=verify-Y3rWSgfA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verify-D7UsV_qe.js","names":[],"sources":["../src/commands/verify.ts"],"sourcesContent":["/**\n * CLI command: rebase verify\n *\n * One command that says whether the collections are safe to ship, fast enough\n * to run after every edit. An agent writing `config/collections/*.ts` gets three\n * things wrong more than anything else — an option that does not exist, a UI\n * widget outside `admin: { … }`, and no `securityRules` — and every one of them\n * used to surface late: at boot, in review, or never. The project's Claude Code\n * hook (`.claude/hooks/post-edit-collection.sh`, written by `rebase init` and\n * `rebase skills --hooks`) runs this after each edit to a collection file, and\n * CI runs it on every push.\n *\n * Four steps, each reported on its own:\n *\n * 1. **Collection config** — every file under `config/collections/` loads and\n * passes `findCollectionConfigProblems` with unknown keys as errors: the same\n * validator the backend runs at boot, at its strictest.\n * 2. **RLS coverage** — a collection that declares no `securityRules` and\n * inherits none, or one with a `user_id` / `owner_id` / `organization_id` /\n * `tenant_id` column that leans on directory defaults instead of its own\n * rules; and a rule that lets a role read every row of such a table.\n * 3. **Migration freshness** — whether `drizzle/migrations` still builds the\n * tables and columns the collections declare (offline), and with `--live`\n * whether the database has applied every migration.\n * 4. **Live RLS audit** — with `--live`, the `@rebasepro/rls-check` catalogue\n * against the project's database, resolved as `db *` resolves it (the\n * managed one unless something names another).\n *\n * `--json` prints one object an agent can act on: every finding carries the\n * file, the dotted path into the config and the fix.\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport {\n parseEnvBoolean,\n isFirebaseCollectionConfig,\n isRelationalCollectionConfig,\n type CollectionConfig,\n type Property,\n type SecurityRule\n} from \"@rebasepro/types\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { failAsJson, findBackendDir, getActiveBackendPlugin, readEnvFile, requireProjectRoot } from \"../utils/project\";\nimport { COLLECTIONS_FLAG_HELP, missingCollectionsPath } from \"../utils/path-flags\";\nimport { isLoadedCollectionFile } from \"../utils/collection-drift\";\nimport { resolveCollectionsDir } from \"../utils/collections-dir\";\n\n/** The flags `rebase verify` takes. */\nexport const VERIFY_FLAGS = {\n \"--collections\": String,\n \"-c\": \"--collections\",\n \"--json\": Boolean,\n \"--quiet\": Boolean,\n \"-q\": \"--quiet\",\n \"--live\": Boolean,\n \"--database-url\": String,\n \"--docker\": Boolean\n} as const;\n\nconst VERIFY_FLAG_HELP: Record<string, string> = {\n \"--collections, -c\": COLLECTIONS_FLAG_HELP,\n \"--json\": \"Print one JSON object: every step, and every finding with its file, path and fix\",\n \"--quiet, -q\": \"Print nothing when everything passes; only the problems when something fails\",\n \"--live\": \"Also connect to the project's database: check migrations are applied and run the rls-check audit\",\n \"--database-url\": \"With --live: audit this database instead of the project's\",\n \"--docker\": \"With --live: use the database from docker compose, starting it if needed\"\n};\n\nexport type VerifyStepId = \"config\" | \"rls\" | \"migrations\" | \"live\";\n\nexport interface VerifyFinding {\n step: VerifyStepId;\n /** Stable, kebab-case: what kind of problem. An agent can branch on it. */\n check: string;\n severity: \"error\" | \"warning\";\n message: string;\n /** What to change, when there is one thing to change. */\n fix?: string;\n /** The collection's slug. */\n collection?: string;\n /** The file to open, relative to the project root. */\n file?: string;\n /** Dotted path into the collection config — `posts.properties.title.widget`. */\n path?: string;\n}\n\nexport interface VerifyStep {\n id: VerifyStepId;\n title: string;\n status: \"passed\" | \"failed\" | \"warnings\" | \"skipped\";\n /** Why a step was skipped, or what it covered. */\n detail?: string;\n}\n\nexport interface VerifyReport {\n ok: boolean;\n /** Relative to the project root. */\n collectionsDir: string;\n steps: VerifyStep[];\n findings: VerifyFinding[];\n summary: { errors: number; warnings: number };\n}\n\nexport interface VerifyOptions {\n projectRoot: string;\n collectionsDir: string;\n /** The backend package, where `drizzle/migrations` lives. Null for a project without one. */\n backendDir: string | null;\n live: boolean;\n databaseUrl?: string;\n /** Why no `databaseUrl` could be resolved for `--live`, when resolving it failed. */\n databaseUnavailable?: string;\n /**\n * Whether the backend refuses a request with no token (`AUTH_REQUIRE`, on\n * unless set to `false`). Decides how a Rebase-compiled public read reads.\n * Defaults to true, the runtime's default.\n */\n authRequired?: boolean;\n}\n\nconst STEP_TITLES: Record<VerifyStepId, string> = {\n config: \"Collection config\",\n rls: \"RLS coverage\",\n migrations: \"Migration freshness\",\n live: \"Live RLS audit\"\n};\n\n/**\n * Columns that say \"this row belongs to someone\". A table carrying one and\n * served without a row filter is the classic multi-tenant leak.\n */\nconst OWNER_COLUMNS: readonly string[] = [\"user_id\", \"owner_id\", \"organization_id\", \"tenant_id\"];\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** What a collection file must default-export to be loaded as one. */\nfunction isCollection(value: unknown): value is CollectionConfig {\n return isRecord(value) && typeof value.slug === \"string\" && isRecord(value.properties);\n}\n\n/** `organizationId` → `organization_id`, as the generator derives a column from a key. */\nfunction snake(key: string): string {\n return key.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").replace(/[\\s-]+/g, \"_\").toLowerCase();\n}\n\n// ─── Loading ──────────────────────────────────────────────────────────────────\n\ninterface LoadedCollections {\n collections: CollectionConfig[];\n /** Parallel to `collections`: the file each one came from, relative to the project root. */\n sources: string[];\n /** Each collection's `securityRules` as its file declares them, before directory defaults. */\n ownRules: (readonly SecurityRule[] | undefined)[];\n /** `defaultSecurityRules` from the directory's `index.ts`. */\n defaults: readonly SecurityRule[] | undefined;\n defaultsFile?: string;\n failures: VerifyFinding[];\n}\n\n/**\n * Load the collections the way the backend finds them: every top-level file\n * the loader reads (`isLoadedCollectionFile`), each default-exporting one\n * collection, plus `defaultSecurityRules` from the directory's `index.ts`.\n *\n * Through jiti, with its caches off: the CLI is plain Node and the files are\n * TypeScript, and a verifier that answered from the previous edit's module\n * would be worse than none. A file that does not load is a finding, not a\n * crash — after an agent's edit it is the most likely problem of all.\n */\nasync function loadCollectionFiles(projectRoot: string, collectionsDir: string): Promise<LoadedCollections> {\n const { createJiti } = await import(\"jiti\");\n const jiti = createJiti(path.join(collectionsDir, \"index.ts\"), {\n interopDefault: true,\n moduleCache: false,\n fsCache: false\n });\n const relative = (file: string) => path.relative(projectRoot, file);\n\n const loaded: LoadedCollections = { collections: [], sources: [], ownRules: [], defaults: undefined, failures: [] };\n\n for (const name of fs.readdirSync(collectionsDir).filter(isLoadedCollectionFile).sort()) {\n const file = path.join(collectionsDir, name);\n try {\n const exported = await jiti.import<unknown>(file, { default: true });\n if (!isCollection(exported)) {\n loaded.failures.push({\n step: \"config\",\n check: \"config-no-collection\",\n severity: \"error\",\n file: relative(file),\n message: `${name} does not default-export a collection (an object with a \\`slug\\` and \\`properties\\`).`,\n fix: \"End the file with `export default defineCollection({ slug, name, properties, … })` — the backend refuses to boot on a collection file that exports anything else.\"\n });\n continue;\n }\n loaded.collections.push(exported);\n loaded.sources.push(relative(file));\n loaded.ownRules.push(exported.securityRules);\n } catch (error) {\n loaded.failures.push({\n step: \"config\",\n check: \"config-load\",\n severity: \"error\",\n file: relative(file),\n message: `${name} does not load: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"Fix the syntax or import error. The backend refuses to boot on the same file.\"\n });\n }\n }\n\n for (const index of [\"index.ts\", \"index.js\"]) {\n const file = path.join(collectionsDir, index);\n if (!fs.existsSync(file)) continue;\n try {\n const mod = await jiti.import<unknown>(file);\n const rules = isRecord(mod) ? mod.defaultSecurityRules : undefined;\n if (Array.isArray(rules)) {\n loaded.defaults = rules;\n loaded.defaultsFile = relative(file);\n }\n } catch (error) {\n loaded.failures.push({\n step: \"config\",\n check: \"config-load\",\n severity: \"error\",\n file: relative(file),\n message: `${index} does not load: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"Fix the file, or delete it if the project declares no `defaultSecurityRules`. The backend refuses to boot without reading it.\"\n });\n }\n break;\n }\n\n return loaded;\n}\n\n// ─── Step 1: collection config ────────────────────────────────────────────────\n\nasync function checkConfig(loaded: LoadedCollections): Promise<VerifyFinding[]> {\n const { findCollectionConfigProblems } = await import(\"@rebasepro/server\");\n const fileBySlug = new Map(loaded.collections.map((c, i) => [c.slug, loaded.sources[i]]));\n const problems = findCollectionConfigProblems(loaded.collections, {\n unknownKeys: \"error\",\n sources: loaded.sources\n });\n return problems.map((problem): VerifyFinding => {\n const slug = problem.path.split(\".\")[0];\n const file = fileBySlug.get(slug);\n return {\n step: \"config\",\n check: problem.kind === \"key\" ? \"config-key\" : \"config-incoherent\",\n severity: problem.severity,\n message: problem.message,\n path: problem.path,\n ...(fileBySlug.has(slug) && { collection: slug }),\n ...(file && { file })\n };\n });\n}\n\n// ─── Step 2: RLS coverage ─────────────────────────────────────────────────────\n\n/** An owner-ish column a collection's table carries, and the property that declares it. */\ninterface OwnerColumn {\n column: string;\n key: string;\n}\n\n/** The owner-ish columns a collection's table carries: plain columns and `belongsTo` keys. */\nfunction ownerColumnsOf(collection: CollectionConfig): OwnerColumn[] {\n const found: OwnerColumn[] = [];\n const consider = (column: string, key: string) => {\n if (OWNER_COLUMNS.includes(column)) found.push({ column, key });\n };\n for (const [key, property] of Object.entries<Property>(collection.properties ?? {})) {\n if (!isRecord(property)) continue;\n if (property.type === \"relation\") {\n const relation = property.relation;\n if (isRecord(relation) && relation.kind === \"belongsTo\") {\n // As the generator names it (`generateForeignKeyName` in\n // `@rebasepro/utils`, which the CLI does not depend on): from\n // the relation's name, which is the property key only when\n // `relationName` is not set.\n const name = typeof relation.relationName === \"string\" && relation.relationName ? relation.relationName : key;\n const singular = /[^s]s$/.test(name) ? name.slice(0, -1) : name;\n consider(typeof relation.localKey === \"string\" ? relation.localKey : `${snake(singular)}_id`, key);\n }\n continue;\n }\n consider(typeof property.columnName === \"string\" ? property.columnName : snake(key), key);\n }\n return found;\n}\n\n/** Whether a rule applies to reads. */\nfunction coversSelect(rule: SecurityRule): boolean {\n const operations = rule.operations ?? [rule.operation ?? \"all\"];\n return operations.includes(\"select\") || operations.includes(\"all\");\n}\n\n/**\n * A permissive read rule with no row filter: every row, to everyone the rule\n * names. `access: \"public\"` is the same thing said on purpose, so it is not\n * this; `roles: [\"admin\"]` restates the default admin read and adds nothing.\n */\nfunction isUnfilteredRead(rule: SecurityRule): boolean {\n if (!coversSelect(rule) || rule.mode === \"restrictive\") return false;\n if (rule.access === \"public\" || rule.ownerField || rule.condition) return false;\n if (rule.using !== undefined && !/^\\s*\\(?\\s*true\\s*\\)?\\s*$/i.test(rule.using)) return false;\n // A write-only check (`withCheck` with no `using`) filters nothing on read,\n // and it is not a read rule either.\n if (rule.using === undefined && rule.withCheck !== undefined) return false;\n const roles = rule.roles ?? [];\n return !(roles.length > 0 && roles.every(role => role === \"admin\"));\n}\n\n/** A read rule that returns every row to someone: an unfiltered one, or `access: \"public\"`. */\nfunction opensEveryRow(rule: SecurityRule): boolean {\n return isUnfilteredRead(rule) || (rule.access === \"public\" && coversSelect(rule) && rule.mode !== \"restrictive\");\n}\n\nfunction describeRuleTarget(rule: Pick<SecurityRule, \"roles\">): string {\n return rule.roles?.length ? `role${rule.roles.length > 1 ? \"s\" : \"\"} ${rule.roles.map(r => `\"${r}\"`).join(\", \")}` : \"every signed-in user\";\n}\n\nfunction checkRls(loaded: LoadedCollections): VerifyFinding[] {\n const findings: VerifyFinding[] = [];\n loaded.collections.forEach((collection, i) => {\n // Firestore does not implement `securityRules` at all — its own rules\n // language governs it, and nothing here can say anything about that.\n if (isFirebaseCollectionConfig(collection)) return;\n\n const slug = collection.slug;\n const file = loaded.sources[i];\n const own = loaded.ownRules[i] ?? [];\n const owners = ownerColumnsOf(collection);\n const tenantScoped = isRelationalCollectionConfig(collection) && isRecord(collection.tenant);\n const ownerField = owners[0]?.column ?? \"user_id\";\n\n if (own.length === 0) {\n // An auth collection gets a self-read policy and an admin-only write\n // gate from the framework; it is never served unfiltered.\n if (collection.auth) return;\n\n if (owners.length > 0 && !tenantScoped) {\n const perUser = ownerField === \"user_id\" || ownerField === \"owner_id\";\n const fix = perUser\n ? `Add \\`securityRules: [{ operation: \"all\", ownerField: \"${ownerField}\" }]\\` so each user reaches only their own rows. ` +\n \"A table meant to be readable by everyone says so: `{ operation: \\\"select\\\", access: \\\"public\\\" }`.\"\n : `Scope it with \\`tenant: { field: \"${owners[0].key}\", from: { claim: \"${ownerField}\" } }\\` (the claim that carries the caller's tenant), ` +\n \"plus the `securityRules` that grant access inside a tenant — e.g. `[{ operation: \\\"select\\\", access: \\\"public\\\" }]`.\";\n const inherited = loaded.defaults ?? [];\n if (inherited.length === 0) {\n findings.push({\n step: \"rls\",\n check: \"rls-missing\",\n severity: \"error\",\n collection: slug,\n file,\n path: `${slug}.securityRules`,\n message: `\"${slug}\" has a \\`${ownerField}\\` column but declares no \\`securityRules\\`, and inherits none: nothing says which rows belong to whom (by default only admins can read or write it).`,\n fix\n });\n } else if (inherited.some(opensEveryRow)) {\n // Directory defaults are written for every table. On a\n // tenant column, inheriting an all-rows read is the\n // cross-tenant leak; on a per-user column it is often a\n // public profile or author list, so it is said, not failed.\n findings.push({\n step: \"rls\",\n check: perUser ? \"rls-inherited-read\" : \"rls-missing\",\n severity: perUser ? \"warning\" : \"error\",\n collection: slug,\n file,\n path: `${slug}.securityRules`,\n message: `\"${slug}\" has a \\`${ownerField}\\` column but declares no \\`securityRules\\` of its own, so it inherits \\`defaultSecurityRules\\` from ${loaded.defaultsFile}, which let ${describeRuleTarget(inherited.find(opensEveryRow) ?? {})} read every row regardless of \\`${ownerField}\\`.`,\n fix\n });\n }\n return;\n }\n\n if (!loaded.defaults?.length) {\n findings.push({\n step: \"rls\",\n check: \"rls-missing\",\n severity: \"error\",\n collection: slug,\n file,\n path: `${slug}.securityRules`,\n message: `\"${slug}\" declares no \\`securityRules\\` and inherits none, so nothing says who may read or write it (by default only admins can).`,\n fix: \"Declare its access: `securityRules: [{ operation: \\\"select\\\", access: \\\"public\\\" }, { operations: [\\\"insert\\\", \\\"update\\\", \\\"delete\\\"], roles: [\\\"admin\\\"] }]` \" +\n \"for a public table, `{ operation: \\\"all\\\", ownerField: \\\"user_id\\\" }` for per-user rows, \" +\n \"or `{ operation: \\\"all\\\", roles: [\\\"admin\\\"] }` to keep it admin-only on purpose.\"\n });\n }\n return;\n }\n\n if (owners.length === 0 || tenantScoped) return;\n own.forEach((rule, index) => {\n if (!isUnfilteredRead(rule)) return;\n findings.push({\n step: \"rls\",\n check: \"rls-unfiltered-read\",\n severity: \"warning\",\n collection: slug,\n file,\n path: `${slug}.securityRules[${index}]`,\n message: `\"${slug}\" has a \\`${ownerField}\\` column, and securityRules[${index}] lets ${describeRuleTarget(rule)} read every row of it with no row filter.`,\n fix: `Filter the rule — \\`ownerField: \"${ownerField}\"\\` or a \\`condition\\` — or, if every row really is meant for ${describeRuleTarget(rule)}, keep it and ignore this warning.`\n });\n });\n });\n return findings;\n}\n\n// ─── Step 3: migration freshness ──────────────────────────────────────────────\n\nconst POSTGRES_PLUGIN = \"@rebasepro/server-postgres\";\n\n/** One row of `rebase.atlas_schema_revisions`, as far as \"applied\" needs it. */\nexport interface AppliedRevision {\n version: string;\n /** Atlas's revision type, a bit set: 1 baseline, 2 executed, 4 resolved (`migrate set`). */\n type: number;\n}\n\n/** Atlas's baseline bit in `atlas_schema_revisions.type`. */\nconst REVISION_TYPE_BASELINE = 1;\n\n/**\n * The migration files the database has not run, as Atlas's own `migrate status`\n * counts them.\n *\n * A file is applied when its version has a row, or when it is at or behind the\n * newest *baseline* row: `migrate apply --baseline V` records V alone, and\n * means \"everything up to V is already here\". `rebase db migrate --baseline` is\n * what the CLI prescribes for a booted database, so set membership alone\n * reported the earlier migrations of every baselined database as not applied —\n * and prescribed `rebase db migrate`, which answers \"No migration files to\n * execute\". That run failed forever.\n */\nexport function pendingMigrations(\n files: readonly string[],\n revisions: readonly AppliedRevision[],\n compare: (a: string, b: string) => number,\n versionOf: (file: string) => string\n): string[] {\n const recorded = new Set(revisions.map(row => row.version));\n const baseline = revisions\n .filter(row => (Number(row.type) & REVISION_TYPE_BASELINE) !== 0)\n .map(row => row.version)\n .reduce<string | null>((newest, version) => (newest === null || compare(version, newest) > 0 ? version : newest), null);\n return files.filter((file) => {\n const version = versionOf(file);\n if (recorded.has(version)) return false;\n return baseline === null || compare(version, baseline) > 0;\n });\n}\n\nasync function checkMigrations(\n options: VerifyOptions,\n loaded: LoadedCollections,\n step: VerifyStep\n): Promise<VerifyFinding[]> {\n const skip = (detail: string): VerifyFinding[] => {\n step.status = \"skipped\";\n step.detail = detail;\n return [];\n };\n if (!options.backendDir) return skip(\"no backend/ directory\");\n const plugin = getActiveBackendPlugin(options.backendDir);\n if (plugin !== POSTGRES_PLUGIN) {\n return skip(`migrations are checked for ${POSTGRES_PLUGIN} projects${plugin ? `; this one uses ${plugin}` : \"\"}`);\n }\n const migrationsDir = path.join(options.backendDir, \"drizzle\", \"migrations\");\n const files = fs.existsSync(migrationsDir)\n ? fs.readdirSync(migrationsDir).filter(f => f.endsWith(\".sql\")).sort()\n : [];\n if (files.length === 0) {\n return skip(\"no migrations yet — the schema is applied with `rebase db push`; `rebase db generate` starts versioned migrations\");\n }\n\n const relativeDir = path.relative(options.projectRoot, migrationsDir);\n const { findUnmigratedSchema } = await import(\"@rebasepro/server-postgres\");\n const findings: VerifyFinding[] = [];\n const fix = \"Run `rebase db generate` to write the migration, then `rebase db migrate` to apply it.\";\n const fileBySlug = new Map(loaded.collections.map((c, i) => [c.slug, loaded.sources[i]]));\n\n let changes: ReturnType<typeof findUnmigratedSchema>;\n try {\n changes = findUnmigratedSchema(\n loaded.collections,\n files.map(f => fs.readFileSync(path.join(migrationsDir, f), \"utf-8\"))\n );\n } catch (error) {\n return [{\n step: \"migrations\",\n check: \"migration-plan\",\n severity: \"error\",\n message: `Could not derive the schema from the collections: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"`rebase schema generate` reports the same problem with more context.\"\n }];\n }\n\n for (const change of changes) {\n const where = change.column ? `${change.table}.${change.column}` : change.table;\n const message = change.kind === \"missing-table\"\n ? `Table ${where} is declared by the collections but no migration in ${relativeDir} creates it.`\n : change.kind === \"missing-column\"\n ? `Column ${where} is declared by the collections but no migration in ${relativeDir} adds it.`\n : `Column ${where} is no longer declared by the collections, but the migrations in ${relativeDir} still create it.`;\n const file = change.slug ? fileBySlug.get(change.slug) : undefined;\n findings.push({\n step: \"migrations\",\n check: change.kind === \"removed-column\" ? \"migration-stale-column\" : \"migration-missing\",\n severity: \"error\",\n message,\n fix,\n ...(change.slug && { collection: change.slug }),\n ...(file && { file })\n });\n }\n\n step.detail = `${files.length} migration${files.length === 1 ? \"\" : \"s\"} in ${relativeDir}`;\n\n if (options.live && options.databaseUrl) {\n findings.push(...await checkAppliedMigrations(options.databaseUrl, files));\n }\n return findings;\n}\n\n/** Which migration files the database has not run, from Atlas's revision table. */\nasync function checkAppliedMigrations(databaseUrl: string, files: string[]): Promise<VerifyFinding[]> {\n const pg = await import(\"pg\");\n const client = new pg.default.Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5_000 });\n try {\n await client.connect();\n const present = await client.query<{ present: boolean }>(\n \"SELECT to_regclass('rebase.atlas_schema_revisions') IS NOT NULL AS present\"\n );\n if (!present.rows[0]?.present) {\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"warning\",\n message: \"The database has no migration history (rebase.atlas_schema_revisions) — it was provisioned with `rebase db push`, or never migrated.\",\n fix: \"`rebase db migrate --baseline <version>` adopts an existing database; `rebase db migrate` applies the migrations to a new one.\"\n }];\n }\n const applied = await client.query<{ version: string; type: string | number }>(\n \"SELECT version, type FROM rebase.atlas_schema_revisions WHERE error IS NULL OR error = ''\"\n );\n const { compareMigrationVersions, migrationVersionOf } = await import(\"@rebasepro/server-postgres\");\n const pending = pendingMigrations(\n files,\n applied.rows.map(row => ({ version: row.version, type: Number(row.type) })),\n compareMigrationVersions,\n migrationVersionOf\n );\n if (pending.length === 0) return [];\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"error\",\n message: `${pending.length} migration${pending.length === 1 ? \" has\" : \"s have\"} not been applied to the database: ${pending.join(\", \")}.`,\n fix: \"Run `rebase db migrate`.\"\n }];\n } catch (error) {\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"warning\",\n message: `Could not read the database's migration history: ${error instanceof Error ? error.message : String(error)}`\n }];\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n// ─── Step 4: live RLS audit ───────────────────────────────────────────────────\n\n/** rls-check's severities, folded onto this command's two. `info` is not reported. */\nfunction liveSeverity(severity: string): VerifyFinding[\"severity\"] | null {\n if (severity === \"critical\" || severity === \"high\") return \"error\";\n if (severity === \"medium\" || severity === \"low\") return \"warning\";\n return null;\n}\n\n/**\n * Why the database `--live` was pointed at cannot be opened, or `null` when it\n * can. Asked once, before the live steps, so an unreachable database is one\n * error rather than a skipped audit and a migration warning: under `--live`\n * the audit was asked for, and a CI run in which it never ran is not green.\n */\nasync function databaseUnreachable(databaseUrl: string): Promise<string | null> {\n const pg = await import(\"pg\");\n const client = new pg.default.Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5_000 });\n try {\n await client.connect();\n return null;\n } catch (error) {\n return error instanceof Error ? error.message : String(error);\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * A `USING (true)` read policy Rebase compiled from an `access: \"public\"`\n * select rule, on a backend that refuses a request with no token.\n *\n * rls-check reads the policy alone, and for the role every signed-in request\n * runs as it is \"every row to everyone\": critical. But the API answers 401\n * before RLS is consulted unless `AUTH_REQUIRE=false`, so what it grants is\n * every row to every *signed-in* user — exactly what step 2 accepts as a rule\n * said on purpose, and what boot reports as an info line. A fresh blog\n * scaffold failed its own `verify --live` with three such errors. It is a\n * warning here, as an unfiltered read is in step 2; with `AUTH_REQUIRE=false`\n * the rows really are public and it stays an error.\n */\nfunction isTokenGatedPublicRead(\n finding: { id: string; target: { table?: string; policy?: string } },\n authRequired: boolean,\n isGeneratedPolicyName: (name: string, table: string) => boolean\n): boolean {\n if (!authRequired || finding.id !== \"policy-always-true\") return false;\n const { table, policy } = finding.target;\n if (!table || !policy) return false;\n return isGeneratedPolicyName(policy, table) && policy.startsWith(`${table}_select_`);\n}\n\nasync function checkLive(databaseUrl: string, step: VerifyStep, authRequired: boolean): Promise<VerifyFinding[]> {\n const { scan, CHECKS } = await import(\"@rebasepro/rls-check\");\n const { isGeneratedPolicyName } = await import(\"@rebasepro/server-postgres\");\n let result: Awaited<ReturnType<typeof scan>>;\n try {\n result = await scan({ connectionString: databaseUrl, statementTimeoutMs: 10_000 });\n } catch (error) {\n step.detail = \"the audit did not run\";\n return [{\n step: \"live\",\n check: \"live-scan-failed\",\n severity: \"error\",\n message: `The live RLS audit failed: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"`npx @rebasepro/rls-check <database-url>` runs the same audit on its own and reports the failure in full.\"\n }];\n }\n step.detail = `${CHECKS.length} rls-check checks against ${result.database.host}/${result.database.name}`;\n\n const findings: VerifyFinding[] = [];\n for (const finding of result.findings) {\n const severity = liveSeverity(finding.severity);\n if (!severity) continue;\n const tokenGated = severity === \"error\" && isTokenGatedPublicRead(finding, authRequired, isGeneratedPolicyName);\n findings.push({\n step: \"live\",\n check: finding.id,\n severity: tokenGated ? \"warning\" : severity,\n message: tokenGated\n ? `${finding.title} — compiled from an \\`access: \"public\"\\` read rule: every signed-in user reads every row. ` +\n \"A request with no token is refused by the API (AUTH_REQUIRE is on), so it is not an anonymous read.\"\n : finding.title,\n ...(finding.fix && { fix: finding.fix }),\n path: finding.target.table ? `${finding.target.schema}.${finding.target.table}` : finding.target.schema\n });\n }\n for (const degraded of result.diagnostics.degraded) {\n findings.push({\n step: \"live\",\n check: \"rls-check-degraded\",\n severity: \"warning\",\n message: `The audit could not read ${degraded.what}: ${degraded.error}. A clean result does not cover it.`\n });\n }\n return findings;\n}\n\n// ─── The run ──────────────────────────────────────────────────────────────────\n\nfunction settle(step: VerifyStep, findings: VerifyFinding[]): VerifyStep {\n if (step.status === \"skipped\") return step;\n const mine = findings.filter(f => f.step === step.id);\n step.status = mine.some(f => f.severity === \"error\") ? \"failed\" : mine.length > 0 ? \"warnings\" : \"passed\";\n return step;\n}\n\n/**\n * Run every step and return the report. Prints nothing and never exits, so a\n * caller — the command, a test — decides what to do with it.\n */\nexport async function runVerify(options: VerifyOptions): Promise<VerifyReport> {\n const findings: VerifyFinding[] = [];\n const steps: VerifyStep[] = ([\"config\", \"rls\", \"migrations\", \"live\"] as const).map(id => ({\n id,\n title: STEP_TITLES[id],\n status: \"passed\"\n }));\n const [configStep, rlsStep, migrationsStep, liveStep] = steps;\n const collectionsDir = path.relative(options.projectRoot, options.collectionsDir) || \".\";\n\n if (!fs.existsSync(options.collectionsDir) || !fs.statSync(options.collectionsDir).isDirectory()) {\n for (const step of steps) {\n step.status = \"skipped\";\n step.detail = `no collections directory at ${collectionsDir}`;\n }\n return { ok: true, collectionsDir, steps, findings, summary: { errors: 0, warnings: 0 } };\n }\n\n const loaded = await loadCollectionFiles(options.projectRoot, options.collectionsDir);\n findings.push(...loaded.failures);\n\n if (loaded.collections.length > 0) {\n findings.push(...await checkConfig(loaded));\n }\n const counted = `${loaded.collections.length} collection${loaded.collections.length === 1 ? \"\" : \"s\"}`;\n configStep.detail = `${counted}, unknown keys are errors`;\n rlsStep.detail = counted;\n\n // Directory defaults reach a collection the way the loader applies them, so\n // the migration step plans the same policies the backend would.\n if (loaded.defaults?.length) {\n const { applyCollectionDefaults } = await import(\"@rebasepro/server\");\n applyCollectionDefaults(loaded.collections, { defaultSecurityRules: [...loaded.defaults] });\n }\n\n findings.push(...checkRls(loaded));\n\n // The database the live steps read, once it is known to answer. Under\n // `--live` a database that is missing or does not answer is an error: the\n // audit was asked for, and exit 0 without it is a green CI run over nothing.\n let liveUrl: string | undefined;\n if (options.live) {\n if (!options.databaseUrl) {\n liveStep.detail = \"no database to audit\";\n findings.push({\n step: \"live\",\n check: \"live-no-database\",\n severity: \"error\",\n message: options.databaseUnavailable\n ? `--live was asked for, and the database could not be prepared: ${options.databaseUnavailable}`\n : \"--live was asked for, and no database is configured to audit.\",\n fix: \"Pass --database-url <url> (or set DATABASE_URL), or run without --live for the offline checks.\"\n });\n } else {\n const unreachable = await databaseUnreachable(options.databaseUrl);\n if (unreachable) {\n liveStep.detail = \"the database did not answer\";\n findings.push({\n step: \"live\",\n check: \"live-unreachable\",\n severity: \"error\",\n message: `--live was asked for, and the database could not be reached: ${unreachable}. Neither the migration check nor the RLS audit ran.`,\n fix: \"Check the database is running and the URL is right (`rebase db url` prints the one this project resolves), or run without --live for the offline checks.\"\n });\n } else {\n liveUrl = options.databaseUrl;\n }\n }\n }\n\n if (findings.some(f => f.step === \"config\" && f.severity === \"error\")) {\n migrationsStep.status = \"skipped\";\n migrationsStep.detail = \"fix the collection config errors first\";\n } else {\n findings.push(...await checkMigrations({ ...options, databaseUrl: liveUrl }, loaded, migrationsStep));\n }\n\n if (!options.live) {\n liveStep.status = \"skipped\";\n liveStep.detail = \"pass --live to audit the database\";\n } else if (liveUrl) {\n findings.push(...await checkLive(liveUrl, liveStep, options.authRequired ?? true));\n }\n\n steps.forEach(step => settle(step, findings));\n const errors = findings.filter(f => f.severity === \"error\").length;\n return {\n ok: errors === 0,\n collectionsDir,\n steps,\n findings,\n summary: { errors, warnings: findings.length - errors }\n };\n}\n\n// ─── Output ───────────────────────────────────────────────────────────────────\n\nfunction printFinding(finding: VerifyFinding): void {\n const mark = finding.severity === \"error\" ? chalk.red(\"✗\") : chalk.yellow(\"!\");\n const where = [finding.file, finding.path].filter(Boolean).join(\" → \");\n console.log(` ${mark} ${where ? `${chalk.bold(where)} ` : \"\"}${finding.message}`);\n if (finding.fix) console.log(chalk.gray(` fix: ${finding.fix}`));\n}\n\nfunction summaryLine(report: VerifyReport): string {\n const { errors, warnings } = report.summary;\n return `${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"}`;\n}\n\nexport function printReport(report: VerifyReport, quiet: boolean): void {\n if (quiet) {\n if (report.findings.length === 0) return;\n if (!report.ok) console.log(chalk.red(`rebase verify: ${summaryLine(report)}`));\n for (const finding of report.findings) printFinding(finding);\n return;\n }\n\n console.log(\"\");\n console.log(` ${chalk.bold(\"rebase verify\")} ${chalk.gray(report.collectionsDir)}`);\n console.log(\"\");\n for (const step of report.steps) {\n const mark = step.status === \"passed\" ? chalk.green(\"✓\")\n : step.status === \"failed\" ? chalk.red(\"✗\")\n : step.status === \"warnings\" ? chalk.yellow(\"!\")\n : chalk.gray(\"–\");\n const detail = step.detail ? chalk.gray(step.status === \"skipped\" ? `skipped: ${step.detail}` : step.detail) : \"\";\n console.log(` ${mark} ${step.title.padEnd(22)} ${detail}`);\n }\n if (report.findings.length > 0) {\n console.log(\"\");\n for (const finding of report.findings) printFinding(finding);\n }\n console.log(\"\");\n console.log(report.ok ? chalk.green(` ✓ ${summaryLine(report)}`) : chalk.red(` ✗ ${summaryLine(report)}`));\n console.log(\"\");\n}\n\nfunction printVerifyHelp(): void {\n console.log(`\n${chalk.bold(\"rebase verify\")} — Check the collections are safe to ship\n\n${chalk.green.bold(\"Usage\")}\n rebase verify [options]\n\n${chalk.green.bold(\"Options\")}\n${Object.entries(VERIFY_FLAG_HELP).map(([flag, help]) => ` ${chalk.blue(flag.padEnd(20))} ${help}`).join(\"\\n\")}\n\n${chalk.green.bold(\"Steps\")}\n 1. Collection config every file loads and passes the boot validator, unknown keys as errors\n 2. RLS coverage securityRules are declared, and owner/tenant columns are filtered on\n 3. Migration freshness drizzle/migrations builds every declared table and column\n 4. Live RLS audit with --live: the rls-check catalogue against the project's database\n\nExits 1 when any step reports an error; warnings do not fail. Under --live, a\ndatabase that is missing or does not answer is an error. Fast and offline\nwithout --live: for CI, and for the Claude Code hook that ${chalk.cyan(\"rebase skills --hooks\")} installs.\n`);\n}\n\n/**\n * Whether the backend refuses a request with no token: `AUTH_REQUIRE` from the\n * environment, else `.env`, read as every boolean env var is read\n * (`parseEnvBoolean`: `false`/`0`/`no`/`off` turn it off). On unless one of\n * those says otherwise — the runtime's default. Compared raw, `AUTH_REQUIRE=0`\n * read as \"on\", and a compiled public read was reported as token-gated on a\n * backend that serves it to anyone.\n */\nexport function authRequiredFrom(\n environment: Record<string, string | undefined>,\n envFile: Record<string, string | undefined>\n): boolean {\n return parseEnvBoolean(environment.AUTH_REQUIRE ?? envFile.AUTH_REQUIRE) !== false;\n}\n\n/**\n * The database `--live` audits, resolved as every other database door resolves\n * it (`db *`, `console`, `doctor`): `--database-url`, `DATABASE_URL`, `.env`,\n * `--docker` or the last `rebase dev --docker`, and otherwise the managed\n * development database — started if it is not running. Reading only\n * `DATABASE_URL` meant the audit never ran on a fresh scaffold, whose database\n * is the managed one.\n *\n * Progress goes to stderr, so `--json` keeps stdout to the report.\n */\nasync function resolveLiveDatabase(\n projectRoot: string,\n rawArgs: readonly string[],\n options: { flagUrl: string | null; flagDocker: boolean; quiet: boolean }\n): Promise<Pick<VerifyOptions, \"databaseUrl\" | \"databaseUnavailable\">> {\n try {\n const { ensureDockerDatabase, databaseUrlOf } = await import(\"./db\");\n await ensureDockerDatabase(projectRoot, rawArgs);\n const { prepareDatabaseEnv } = await import(\"../dev-db/prepare\");\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: options.flagUrl,\n flagDocker: options.flagDocker,\n quiet: options.quiet,\n onProgress: options.quiet ? undefined : (line) => console.error(chalk.gray(` ${line}`))\n });\n return { databaseUrl: databaseUrlOf(prepared, readEnvFile(projectRoot)) };\n } catch (error) {\n return { databaseUnavailable: error instanceof Error ? error.message : String(error) };\n }\n}\n\nexport async function verifyCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printVerifyHelp();\n return;\n }\n const { flags } = parseCommandArgs({\n spec: VERIFY_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"verify\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n const backendDir = findBackendDir(projectRoot);\n if (flags[\"--collections\"]) {\n // A mistyped `-c` used to skip every step and print \"0 errors\" with\n // exit 0 — a green CI run over nothing. Refused as `doctor` and\n // `schema` refuse it. Without the flag, a project with no collections\n // directory (a headless one) is still a skip, not a failure.\n const refusal = missingCollectionsPath(rawArgs, process.cwd(), backendDir ?? projectRoot, \"verify\");\n if (refusal) {\n if (flags[\"--json\"]) {\n failAsJson(\n `Collections path not found: \"${flags[\"--collections\"]}\" (resolved to ${path.resolve(process.cwd(), flags[\"--collections\"])}).`,\n \"collections_not_found\",\n \"Leave --collections out (config/collections is the default), or pass a directory that exists; relative paths are resolved from where you run the command.\"\n );\n }\n console.error(\"\");\n for (const line of refusal) console.error(line);\n console.error(\"\");\n process.exit(1);\n }\n }\n const collectionsDir = flags[\"--collections\"]\n ? path.resolve(process.cwd(), flags[\"--collections\"])\n : resolveCollectionsDir(projectRoot);\n const live = flags[\"--live\"] === true;\n const database = live\n ? await resolveLiveDatabase(projectRoot, rawArgs, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n quiet: flags[\"--quiet\"] === true\n })\n : {};\n\n const report = await runVerify({\n projectRoot,\n collectionsDir,\n backendDir,\n live,\n ...database,\n authRequired: authRequiredFrom(process.env, readEnvFile(projectRoot))\n });\n\n if (flags[\"--json\"]) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n printReport(report, flags[\"--quiet\"] === true);\n }\n if (!report.ok) process.exitCode = 1;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,eAAe;CACxB,iBAAiB;CACjB,MAAM;CACN,UAAU;CACV,WAAW;CACX,MAAM;CACN,UAAU;CACV,kBAAkB;CAClB,YAAY;AAChB;AAEA,IAAM,mBAA2C;CAC7C,qBAAqB;CACrB,UAAU;CACV,eAAe;CACf,UAAU;CACV,kBAAkB;CAClB,YAAY;AAChB;AAsDA,IAAM,cAA4C;CAC9C,QAAQ;CACR,KAAK;CACL,YAAY;CACZ,MAAM;AACV;;;;;AAMA,IAAM,gBAAmC;CAAC;CAAW;CAAY;CAAmB;AAAW;AAE/F,IAAM,YAAY,UACd,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;AAGvE,SAAS,aAAa,OAA2C;CAC7D,OAAO,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,YAAY,SAAS,MAAM,UAAU;AACzF;;AAGA,SAAS,MAAM,KAAqB;CAChC,OAAO,IAAI,QAAQ,sBAAsB,OAAO,CAAC,CAAC,QAAQ,WAAW,GAAG,CAAC,CAAC,YAAY;AAC1F;;;;;;;;;;;AA0BA,eAAe,oBAAoB,aAAqB,gBAAoD;CACxG,MAAM,EAAE,eAAe,MAAM,OA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Q,MAAM,IAAI;GAC9C,QAAQ,MAAM,EAAE;GAChB,QAAQ,KAAK,CAAC;EAClB;CACJ;CACA,MAAM,iBAAiB,MAAM,mBACvB,KAAK,QAAQ,QAAQ,IAAI,GAAG,MAAM,gBAAgB,IAClD,sBAAsB,WAAW;CACvC,MAAM,OAAO,MAAM,cAAc;CASjC,MAAM,SAAS,MAAM,UAAU;EAC3B;EACA;EACA;EACA;EACA,GAba,OACX,MAAM,oBAAoB,aAAa,SAAS;GAC9C,SAAS,MAAM,qBAAqB;GACpC,YAAY,MAAM,gBAAgB;GAClC,OAAO,MAAM,eAAe;EAChC,CAAC,IACC,CAAC;EAQH,cAAc,iBAAiB,QAAQ,KAAK,YAAY,WAAW,CAAC;CACxE,CAAC;CAED,IAAI,MAAM,WACN,QAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;MAE3C,YAAY,QAAQ,MAAM,eAAe,IAAI;CAEjD,IAAI,CAAC,OAAO,IAAI,QAAQ,WAAW;AACvC"}
|
|
1
|
+
{"version":3,"file":"verify-Y3rWSgfA.js","names":[],"sources":["../src/commands/verify.ts"],"sourcesContent":["/**\n * CLI command: rebase verify\n *\n * One command that says whether the collections are safe to ship, fast enough\n * to run after every edit. An agent writing `config/collections/*.ts` gets three\n * things wrong more than anything else — an option that does not exist, a UI\n * widget outside `admin: { … }`, and no `securityRules` — and every one of them\n * used to surface late: at boot, in review, or never. The project's Claude Code\n * hook (`.claude/hooks/post-edit-collection.sh`, written by `rebase init` and\n * `rebase skills --hooks`) runs this after each edit to a collection file, and\n * CI runs it on every push.\n *\n * Four steps, each reported on its own:\n *\n * 1. **Collection config** — every file under `config/collections/` loads and\n * passes `findCollectionConfigProblems` with unknown keys as errors: the same\n * validator the backend runs at boot, at its strictest.\n * 2. **RLS coverage** — a collection that declares no `securityRules` and\n * inherits none, or one with a `user_id` / `owner_id` / `organization_id` /\n * `tenant_id` column that leans on directory defaults instead of its own\n * rules; and a rule that lets a role read every row of such a table.\n * 3. **Migration freshness** — whether `drizzle/migrations` still builds the\n * tables and columns the collections declare (offline), and with `--live`\n * whether the database has applied every migration.\n * 4. **Live RLS audit** — with `--live`, the `@rebasepro/rls-check` catalogue\n * against the project's database, resolved as `db *` resolves it (the\n * managed one unless something names another).\n *\n * `--json` prints one object an agent can act on: every finding carries the\n * file, the dotted path into the config and the fix.\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport {\n parseEnvBoolean,\n isFirebaseCollectionConfig,\n isRelationalCollectionConfig,\n type CollectionConfig,\n type Property,\n type SecurityRule\n} from \"@rebasepro/types\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { failAsJson, findBackendDir, getActiveBackendPlugin, readEnvFile, requireProjectRoot } from \"../utils/project\";\nimport { COLLECTIONS_FLAG_HELP, missingCollectionsPath } from \"../utils/path-flags\";\nimport { isLoadedCollectionFile } from \"../utils/collection-drift\";\nimport { resolveCollectionsDir } from \"../utils/collections-dir\";\n\n/** The flags `rebase verify` takes. */\nexport const VERIFY_FLAGS = {\n \"--collections\": String,\n \"-c\": \"--collections\",\n \"--json\": Boolean,\n \"--quiet\": Boolean,\n \"-q\": \"--quiet\",\n \"--live\": Boolean,\n \"--database-url\": String,\n \"--docker\": Boolean\n} as const;\n\nconst VERIFY_FLAG_HELP: Record<string, string> = {\n \"--collections, -c\": COLLECTIONS_FLAG_HELP,\n \"--json\": \"Print one JSON object: every step, and every finding with its file, path and fix\",\n \"--quiet, -q\": \"Print nothing when everything passes; only the problems when something fails\",\n \"--live\": \"Also connect to the project's database: check migrations are applied and run the rls-check audit\",\n \"--database-url\": \"With --live: audit this database instead of the project's\",\n \"--docker\": \"With --live: use the database from docker compose, starting it if needed\"\n};\n\nexport type VerifyStepId = \"config\" | \"rls\" | \"migrations\" | \"live\";\n\nexport interface VerifyFinding {\n step: VerifyStepId;\n /** Stable, kebab-case: what kind of problem. An agent can branch on it. */\n check: string;\n severity: \"error\" | \"warning\";\n message: string;\n /** What to change, when there is one thing to change. */\n fix?: string;\n /** The collection's slug. */\n collection?: string;\n /** The file to open, relative to the project root. */\n file?: string;\n /** Dotted path into the collection config — `posts.properties.title.widget`. */\n path?: string;\n}\n\nexport interface VerifyStep {\n id: VerifyStepId;\n title: string;\n status: \"passed\" | \"failed\" | \"warnings\" | \"skipped\";\n /** Why a step was skipped, or what it covered. */\n detail?: string;\n}\n\nexport interface VerifyReport {\n ok: boolean;\n /** Relative to the project root. */\n collectionsDir: string;\n steps: VerifyStep[];\n findings: VerifyFinding[];\n summary: { errors: number; warnings: number };\n}\n\nexport interface VerifyOptions {\n projectRoot: string;\n collectionsDir: string;\n /** The backend package, where `drizzle/migrations` lives. Null for a project without one. */\n backendDir: string | null;\n live: boolean;\n databaseUrl?: string;\n /** Why no `databaseUrl` could be resolved for `--live`, when resolving it failed. */\n databaseUnavailable?: string;\n /**\n * Whether the backend refuses a request with no token (`AUTH_REQUIRE`, on\n * unless set to `false`). Decides how a Rebase-compiled public read reads.\n * Defaults to true, the runtime's default.\n */\n authRequired?: boolean;\n}\n\nconst STEP_TITLES: Record<VerifyStepId, string> = {\n config: \"Collection config\",\n rls: \"RLS coverage\",\n migrations: \"Migration freshness\",\n live: \"Live RLS audit\"\n};\n\n/**\n * Columns that say \"this row belongs to someone\". A table carrying one and\n * served without a row filter is the classic multi-tenant leak.\n */\nconst OWNER_COLUMNS: readonly string[] = [\"user_id\", \"owner_id\", \"organization_id\", \"tenant_id\"];\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** What a collection file must default-export to be loaded as one. */\nfunction isCollection(value: unknown): value is CollectionConfig {\n return isRecord(value) && typeof value.slug === \"string\" && isRecord(value.properties);\n}\n\n/** `organizationId` → `organization_id`, as the generator derives a column from a key. */\nfunction snake(key: string): string {\n return key.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").replace(/[\\s-]+/g, \"_\").toLowerCase();\n}\n\n// ─── Loading ──────────────────────────────────────────────────────────────────\n\ninterface LoadedCollections {\n collections: CollectionConfig[];\n /** Parallel to `collections`: the file each one came from, relative to the project root. */\n sources: string[];\n /** Each collection's `securityRules` as its file declares them, before directory defaults. */\n ownRules: (readonly SecurityRule[] | undefined)[];\n /** `defaultSecurityRules` from the directory's `index.ts`. */\n defaults: readonly SecurityRule[] | undefined;\n defaultsFile?: string;\n failures: VerifyFinding[];\n}\n\n/**\n * Load the collections the way the backend finds them: every top-level file\n * the loader reads (`isLoadedCollectionFile`), each default-exporting one\n * collection, plus `defaultSecurityRules` from the directory's `index.ts`.\n *\n * Through jiti, with its caches off: the CLI is plain Node and the files are\n * TypeScript, and a verifier that answered from the previous edit's module\n * would be worse than none. A file that does not load is a finding, not a\n * crash — after an agent's edit it is the most likely problem of all.\n */\nasync function loadCollectionFiles(projectRoot: string, collectionsDir: string): Promise<LoadedCollections> {\n const { createJiti } = await import(\"jiti\");\n const jiti = createJiti(path.join(collectionsDir, \"index.ts\"), {\n interopDefault: true,\n moduleCache: false,\n fsCache: false\n });\n const relative = (file: string) => path.relative(projectRoot, file);\n\n const loaded: LoadedCollections = { collections: [], sources: [], ownRules: [], defaults: undefined, failures: [] };\n\n for (const name of fs.readdirSync(collectionsDir).filter(isLoadedCollectionFile).sort()) {\n const file = path.join(collectionsDir, name);\n try {\n const exported = await jiti.import<unknown>(file, { default: true });\n if (!isCollection(exported)) {\n loaded.failures.push({\n step: \"config\",\n check: \"config-no-collection\",\n severity: \"error\",\n file: relative(file),\n message: `${name} does not default-export a collection (an object with a \\`slug\\` and \\`properties\\`).`,\n fix: \"End the file with `export default defineCollection({ slug, name, properties, … })` — the backend refuses to boot on a collection file that exports anything else.\"\n });\n continue;\n }\n loaded.collections.push(exported);\n loaded.sources.push(relative(file));\n loaded.ownRules.push(exported.securityRules);\n } catch (error) {\n loaded.failures.push({\n step: \"config\",\n check: \"config-load\",\n severity: \"error\",\n file: relative(file),\n message: `${name} does not load: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"Fix the syntax or import error. The backend refuses to boot on the same file.\"\n });\n }\n }\n\n for (const index of [\"index.ts\", \"index.js\"]) {\n const file = path.join(collectionsDir, index);\n if (!fs.existsSync(file)) continue;\n try {\n const mod = await jiti.import<unknown>(file);\n const rules = isRecord(mod) ? mod.defaultSecurityRules : undefined;\n if (Array.isArray(rules)) {\n loaded.defaults = rules;\n loaded.defaultsFile = relative(file);\n }\n } catch (error) {\n loaded.failures.push({\n step: \"config\",\n check: \"config-load\",\n severity: \"error\",\n file: relative(file),\n message: `${index} does not load: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"Fix the file, or delete it if the project declares no `defaultSecurityRules`. The backend refuses to boot without reading it.\"\n });\n }\n break;\n }\n\n return loaded;\n}\n\n// ─── Step 1: collection config ────────────────────────────────────────────────\n\nasync function checkConfig(loaded: LoadedCollections): Promise<VerifyFinding[]> {\n const { findCollectionConfigProblems } = await import(\"@rebasepro/server\");\n const fileBySlug = new Map(loaded.collections.map((c, i) => [c.slug, loaded.sources[i]]));\n const problems = findCollectionConfigProblems(loaded.collections, {\n unknownKeys: \"error\",\n sources: loaded.sources\n });\n return problems.map((problem): VerifyFinding => {\n const slug = problem.path.split(\".\")[0];\n const file = fileBySlug.get(slug);\n return {\n step: \"config\",\n check: problem.kind === \"key\" ? \"config-key\" : \"config-incoherent\",\n severity: problem.severity,\n message: problem.message,\n path: problem.path,\n ...(fileBySlug.has(slug) && { collection: slug }),\n ...(file && { file })\n };\n });\n}\n\n// ─── Step 2: RLS coverage ─────────────────────────────────────────────────────\n\n/** An owner-ish column a collection's table carries, and the property that declares it. */\ninterface OwnerColumn {\n column: string;\n key: string;\n}\n\n/** The owner-ish columns a collection's table carries: plain columns and `belongsTo` keys. */\nfunction ownerColumnsOf(collection: CollectionConfig): OwnerColumn[] {\n const found: OwnerColumn[] = [];\n const consider = (column: string, key: string) => {\n if (OWNER_COLUMNS.includes(column)) found.push({ column, key });\n };\n for (const [key, property] of Object.entries<Property>(collection.properties ?? {})) {\n if (!isRecord(property)) continue;\n if (property.type === \"relation\") {\n const relation = property.relation;\n if (isRecord(relation) && relation.kind === \"belongsTo\") {\n // As the generator names it (`generateForeignKeyName` in\n // `@rebasepro/utils`, which the CLI does not depend on): from\n // the relation's name, which is the property key only when\n // `relationName` is not set.\n const name = typeof relation.relationName === \"string\" && relation.relationName ? relation.relationName : key;\n const singular = /[^s]s$/.test(name) ? name.slice(0, -1) : name;\n consider(typeof relation.localKey === \"string\" ? relation.localKey : `${snake(singular)}_id`, key);\n }\n continue;\n }\n consider(typeof property.columnName === \"string\" ? property.columnName : snake(key), key);\n }\n return found;\n}\n\n/** Whether a rule applies to reads. */\nfunction coversSelect(rule: SecurityRule): boolean {\n const operations = rule.operations ?? [rule.operation ?? \"all\"];\n return operations.includes(\"select\") || operations.includes(\"all\");\n}\n\n/**\n * A permissive read rule with no row filter: every row, to everyone the rule\n * names. `access: \"public\"` is the same thing said on purpose, so it is not\n * this; `roles: [\"admin\"]` restates the default admin read and adds nothing.\n */\nfunction isUnfilteredRead(rule: SecurityRule): boolean {\n if (!coversSelect(rule) || rule.mode === \"restrictive\") return false;\n if (rule.access === \"public\" || rule.ownerField || rule.condition) return false;\n if (rule.using !== undefined && !/^\\s*\\(?\\s*true\\s*\\)?\\s*$/i.test(rule.using)) return false;\n // A write-only check (`withCheck` with no `using`) filters nothing on read,\n // and it is not a read rule either.\n if (rule.using === undefined && rule.withCheck !== undefined) return false;\n const roles = rule.roles ?? [];\n return !(roles.length > 0 && roles.every(role => role === \"admin\"));\n}\n\n/** A read rule that returns every row to someone: an unfiltered one, or `access: \"public\"`. */\nfunction opensEveryRow(rule: SecurityRule): boolean {\n return isUnfilteredRead(rule) || (rule.access === \"public\" && coversSelect(rule) && rule.mode !== \"restrictive\");\n}\n\nfunction describeRuleTarget(rule: Pick<SecurityRule, \"roles\">): string {\n return rule.roles?.length ? `role${rule.roles.length > 1 ? \"s\" : \"\"} ${rule.roles.map(r => `\"${r}\"`).join(\", \")}` : \"every signed-in user\";\n}\n\nfunction checkRls(loaded: LoadedCollections): VerifyFinding[] {\n const findings: VerifyFinding[] = [];\n loaded.collections.forEach((collection, i) => {\n // Firestore does not implement `securityRules` at all — its own rules\n // language governs it, and nothing here can say anything about that.\n if (isFirebaseCollectionConfig(collection)) return;\n\n const slug = collection.slug;\n const file = loaded.sources[i];\n const own = loaded.ownRules[i] ?? [];\n const owners = ownerColumnsOf(collection);\n const tenantScoped = isRelationalCollectionConfig(collection) && isRecord(collection.tenant);\n const ownerField = owners[0]?.column ?? \"user_id\";\n\n if (own.length === 0) {\n // An auth collection gets a self-read policy and an admin-only write\n // gate from the framework; it is never served unfiltered.\n if (collection.auth) return;\n\n if (owners.length > 0 && !tenantScoped) {\n const perUser = ownerField === \"user_id\" || ownerField === \"owner_id\";\n const fix = perUser\n ? `Add \\`securityRules: [{ operation: \"all\", ownerField: \"${ownerField}\" }]\\` so each user reaches only their own rows. ` +\n \"A table meant to be readable by everyone says so: `{ operation: \\\"select\\\", access: \\\"public\\\" }`.\"\n : `Scope it with \\`tenant: { field: \"${owners[0].key}\", from: { claim: \"${ownerField}\" } }\\` (the claim that carries the caller's tenant), ` +\n \"plus the `securityRules` that grant access inside a tenant — e.g. `[{ operation: \\\"select\\\", access: \\\"public\\\" }]`.\";\n const inherited = loaded.defaults ?? [];\n if (inherited.length === 0) {\n findings.push({\n step: \"rls\",\n check: \"rls-missing\",\n severity: \"error\",\n collection: slug,\n file,\n path: `${slug}.securityRules`,\n message: `\"${slug}\" has a \\`${ownerField}\\` column but declares no \\`securityRules\\`, and inherits none: nothing says which rows belong to whom (by default only admins can read or write it).`,\n fix\n });\n } else if (inherited.some(opensEveryRow)) {\n // Directory defaults are written for every table. On a\n // tenant column, inheriting an all-rows read is the\n // cross-tenant leak; on a per-user column it is often a\n // public profile or author list, so it is said, not failed.\n findings.push({\n step: \"rls\",\n check: perUser ? \"rls-inherited-read\" : \"rls-missing\",\n severity: perUser ? \"warning\" : \"error\",\n collection: slug,\n file,\n path: `${slug}.securityRules`,\n message: `\"${slug}\" has a \\`${ownerField}\\` column but declares no \\`securityRules\\` of its own, so it inherits \\`defaultSecurityRules\\` from ${loaded.defaultsFile}, which let ${describeRuleTarget(inherited.find(opensEveryRow) ?? {})} read every row regardless of \\`${ownerField}\\`.`,\n fix\n });\n }\n return;\n }\n\n if (!loaded.defaults?.length) {\n findings.push({\n step: \"rls\",\n check: \"rls-missing\",\n severity: \"error\",\n collection: slug,\n file,\n path: `${slug}.securityRules`,\n message: `\"${slug}\" declares no \\`securityRules\\` and inherits none, so nothing says who may read or write it (by default only admins can).`,\n fix: \"Declare its access: `securityRules: [{ operation: \\\"select\\\", access: \\\"public\\\" }, { operations: [\\\"insert\\\", \\\"update\\\", \\\"delete\\\"], roles: [\\\"admin\\\"] }]` \" +\n \"for a public table, `{ operation: \\\"all\\\", ownerField: \\\"user_id\\\" }` for per-user rows, \" +\n \"or `{ operation: \\\"all\\\", roles: [\\\"admin\\\"] }` to keep it admin-only on purpose.\"\n });\n }\n return;\n }\n\n if (owners.length === 0 || tenantScoped) return;\n own.forEach((rule, index) => {\n if (!isUnfilteredRead(rule)) return;\n findings.push({\n step: \"rls\",\n check: \"rls-unfiltered-read\",\n severity: \"warning\",\n collection: slug,\n file,\n path: `${slug}.securityRules[${index}]`,\n message: `\"${slug}\" has a \\`${ownerField}\\` column, and securityRules[${index}] lets ${describeRuleTarget(rule)} read every row of it with no row filter.`,\n fix: `Filter the rule — \\`ownerField: \"${ownerField}\"\\` or a \\`condition\\` — or, if every row really is meant for ${describeRuleTarget(rule)}, keep it and ignore this warning.`\n });\n });\n });\n return findings;\n}\n\n// ─── Step 3: migration freshness ──────────────────────────────────────────────\n\nconst POSTGRES_PLUGIN = \"@rebasepro/server-postgres\";\n\n/** One row of `rebase.atlas_schema_revisions`, as far as \"applied\" needs it. */\nexport interface AppliedRevision {\n version: string;\n /** Atlas's revision type, a bit set: 1 baseline, 2 executed, 4 resolved (`migrate set`). */\n type: number;\n}\n\n/** Atlas's baseline bit in `atlas_schema_revisions.type`. */\nconst REVISION_TYPE_BASELINE = 1;\n\n/**\n * The migration files the database has not run, as Atlas's own `migrate status`\n * counts them.\n *\n * A file is applied when its version has a row, or when it is at or behind the\n * newest *baseline* row: `migrate apply --baseline V` records V alone, and\n * means \"everything up to V is already here\". `rebase db migrate --baseline` is\n * what the CLI prescribes for a booted database, so set membership alone\n * reported the earlier migrations of every baselined database as not applied —\n * and prescribed `rebase db migrate`, which answers \"No migration files to\n * execute\". That run failed forever.\n */\nexport function pendingMigrations(\n files: readonly string[],\n revisions: readonly AppliedRevision[],\n compare: (a: string, b: string) => number,\n versionOf: (file: string) => string\n): string[] {\n const recorded = new Set(revisions.map(row => row.version));\n const baseline = revisions\n .filter(row => (Number(row.type) & REVISION_TYPE_BASELINE) !== 0)\n .map(row => row.version)\n .reduce<string | null>((newest, version) => (newest === null || compare(version, newest) > 0 ? version : newest), null);\n return files.filter((file) => {\n const version = versionOf(file);\n if (recorded.has(version)) return false;\n return baseline === null || compare(version, baseline) > 0;\n });\n}\n\nasync function checkMigrations(\n options: VerifyOptions,\n loaded: LoadedCollections,\n step: VerifyStep\n): Promise<VerifyFinding[]> {\n const skip = (detail: string): VerifyFinding[] => {\n step.status = \"skipped\";\n step.detail = detail;\n return [];\n };\n if (!options.backendDir) return skip(\"no backend/ directory\");\n const plugin = getActiveBackendPlugin(options.backendDir);\n if (plugin !== POSTGRES_PLUGIN) {\n return skip(`migrations are checked for ${POSTGRES_PLUGIN} projects${plugin ? `; this one uses ${plugin}` : \"\"}`);\n }\n const migrationsDir = path.join(options.backendDir, \"drizzle\", \"migrations\");\n const files = fs.existsSync(migrationsDir)\n ? fs.readdirSync(migrationsDir).filter(f => f.endsWith(\".sql\")).sort()\n : [];\n if (files.length === 0) {\n return skip(\"no migrations yet — the schema is applied with `rebase db push`; `rebase db generate` starts versioned migrations\");\n }\n\n const relativeDir = path.relative(options.projectRoot, migrationsDir);\n const { findUnmigratedSchema } = await import(\"@rebasepro/server-postgres\");\n const findings: VerifyFinding[] = [];\n const fix = \"Run `rebase db generate` to write the migration, then `rebase db migrate` to apply it.\";\n const fileBySlug = new Map(loaded.collections.map((c, i) => [c.slug, loaded.sources[i]]));\n\n let changes: ReturnType<typeof findUnmigratedSchema>;\n try {\n changes = findUnmigratedSchema(\n loaded.collections,\n files.map(f => fs.readFileSync(path.join(migrationsDir, f), \"utf-8\"))\n );\n } catch (error) {\n return [{\n step: \"migrations\",\n check: \"migration-plan\",\n severity: \"error\",\n message: `Could not derive the schema from the collections: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"`rebase schema generate` reports the same problem with more context.\"\n }];\n }\n\n for (const change of changes) {\n const where = change.column ? `${change.table}.${change.column}` : change.table;\n const message = change.kind === \"missing-table\"\n ? `Table ${where} is declared by the collections but no migration in ${relativeDir} creates it.`\n : change.kind === \"missing-column\"\n ? `Column ${where} is declared by the collections but no migration in ${relativeDir} adds it.`\n : `Column ${where} is no longer declared by the collections, but the migrations in ${relativeDir} still create it.`;\n const file = change.slug ? fileBySlug.get(change.slug) : undefined;\n findings.push({\n step: \"migrations\",\n check: change.kind === \"removed-column\" ? \"migration-stale-column\" : \"migration-missing\",\n severity: \"error\",\n message,\n fix,\n ...(change.slug && { collection: change.slug }),\n ...(file && { file })\n });\n }\n\n step.detail = `${files.length} migration${files.length === 1 ? \"\" : \"s\"} in ${relativeDir}`;\n\n if (options.live && options.databaseUrl) {\n findings.push(...await checkAppliedMigrations(options.databaseUrl, files));\n }\n return findings;\n}\n\n/** Which migration files the database has not run, from Atlas's revision table. */\nasync function checkAppliedMigrations(databaseUrl: string, files: string[]): Promise<VerifyFinding[]> {\n const pg = await import(\"pg\");\n const client = new pg.default.Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5_000 });\n try {\n await client.connect();\n const present = await client.query<{ present: boolean }>(\n \"SELECT to_regclass('rebase.atlas_schema_revisions') IS NOT NULL AS present\"\n );\n if (!present.rows[0]?.present) {\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"warning\",\n message: \"The database has no migration history (rebase.atlas_schema_revisions) — it was provisioned with `rebase db push`, or never migrated.\",\n fix: \"`rebase db migrate --baseline <version>` adopts an existing database; `rebase db migrate` applies the migrations to a new one.\"\n }];\n }\n const applied = await client.query<{ version: string; type: string | number }>(\n \"SELECT version, type FROM rebase.atlas_schema_revisions WHERE error IS NULL OR error = ''\"\n );\n const { compareMigrationVersions, migrationVersionOf } = await import(\"@rebasepro/server-postgres\");\n const pending = pendingMigrations(\n files,\n applied.rows.map(row => ({ version: row.version, type: Number(row.type) })),\n compareMigrationVersions,\n migrationVersionOf\n );\n if (pending.length === 0) return [];\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"error\",\n message: `${pending.length} migration${pending.length === 1 ? \" has\" : \"s have\"} not been applied to the database: ${pending.join(\", \")}.`,\n fix: \"Run `rebase db migrate`.\"\n }];\n } catch (error) {\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"warning\",\n message: `Could not read the database's migration history: ${error instanceof Error ? error.message : String(error)}`\n }];\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n// ─── Step 4: live RLS audit ───────────────────────────────────────────────────\n\n/** rls-check's severities, folded onto this command's two. `info` is not reported. */\nfunction liveSeverity(severity: string): VerifyFinding[\"severity\"] | null {\n if (severity === \"critical\" || severity === \"high\") return \"error\";\n if (severity === \"medium\" || severity === \"low\") return \"warning\";\n return null;\n}\n\n/**\n * Why the database `--live` was pointed at cannot be opened, or `null` when it\n * can. Asked once, before the live steps, so an unreachable database is one\n * error rather than a skipped audit and a migration warning: under `--live`\n * the audit was asked for, and a CI run in which it never ran is not green.\n */\nasync function databaseUnreachable(databaseUrl: string): Promise<string | null> {\n const pg = await import(\"pg\");\n const client = new pg.default.Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5_000 });\n try {\n await client.connect();\n return null;\n } catch (error) {\n return error instanceof Error ? error.message : String(error);\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * A `USING (true)` read policy Rebase compiled from an `access: \"public\"`\n * select rule, on a backend that refuses a request with no token.\n *\n * rls-check reads the policy alone, and for the role every signed-in request\n * runs as it is \"every row to everyone\": critical. But the API answers 401\n * before RLS is consulted unless `AUTH_REQUIRE=false`, so what it grants is\n * every row to every *signed-in* user — exactly what step 2 accepts as a rule\n * said on purpose, and what boot reports as an info line. A fresh blog\n * scaffold failed its own `verify --live` with three such errors. It is a\n * warning here, as an unfiltered read is in step 2; with `AUTH_REQUIRE=false`\n * the rows really are public and it stays an error.\n */\nfunction isTokenGatedPublicRead(\n finding: { id: string; target: { table?: string; policy?: string } },\n authRequired: boolean,\n isGeneratedPolicyName: (name: string, table: string) => boolean\n): boolean {\n if (!authRequired || finding.id !== \"policy-always-true\") return false;\n const { table, policy } = finding.target;\n if (!table || !policy) return false;\n return isGeneratedPolicyName(policy, table) && policy.startsWith(`${table}_select_`);\n}\n\nasync function checkLive(databaseUrl: string, step: VerifyStep, authRequired: boolean): Promise<VerifyFinding[]> {\n const { scan, CHECKS } = await import(\"@rebasepro/rls-check\");\n const { isGeneratedPolicyName } = await import(\"@rebasepro/server-postgres\");\n let result: Awaited<ReturnType<typeof scan>>;\n try {\n result = await scan({ connectionString: databaseUrl, statementTimeoutMs: 10_000 });\n } catch (error) {\n step.detail = \"the audit did not run\";\n return [{\n step: \"live\",\n check: \"live-scan-failed\",\n severity: \"error\",\n message: `The live RLS audit failed: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"`npx @rebasepro/rls-check <database-url>` runs the same audit on its own and reports the failure in full.\"\n }];\n }\n step.detail = `${CHECKS.length} rls-check checks against ${result.database.host}/${result.database.name}`;\n\n const findings: VerifyFinding[] = [];\n for (const finding of result.findings) {\n const severity = liveSeverity(finding.severity);\n if (!severity) continue;\n const tokenGated = severity === \"error\" && isTokenGatedPublicRead(finding, authRequired, isGeneratedPolicyName);\n findings.push({\n step: \"live\",\n check: finding.id,\n severity: tokenGated ? \"warning\" : severity,\n message: tokenGated\n ? `${finding.title} — compiled from an \\`access: \"public\"\\` read rule: every signed-in user reads every row. ` +\n \"A request with no token is refused by the API (AUTH_REQUIRE is on), so it is not an anonymous read.\"\n : finding.title,\n ...(finding.fix && { fix: finding.fix }),\n path: finding.target.table ? `${finding.target.schema}.${finding.target.table}` : finding.target.schema\n });\n }\n for (const degraded of result.diagnostics.degraded) {\n findings.push({\n step: \"live\",\n check: \"rls-check-degraded\",\n severity: \"warning\",\n message: `The audit could not read ${degraded.what}: ${degraded.error}. A clean result does not cover it.`\n });\n }\n return findings;\n}\n\n// ─── The run ──────────────────────────────────────────────────────────────────\n\nfunction settle(step: VerifyStep, findings: VerifyFinding[]): VerifyStep {\n if (step.status === \"skipped\") return step;\n const mine = findings.filter(f => f.step === step.id);\n step.status = mine.some(f => f.severity === \"error\") ? \"failed\" : mine.length > 0 ? \"warnings\" : \"passed\";\n return step;\n}\n\n/**\n * Run every step and return the report. Prints nothing and never exits, so a\n * caller — the command, a test — decides what to do with it.\n */\nexport async function runVerify(options: VerifyOptions): Promise<VerifyReport> {\n const findings: VerifyFinding[] = [];\n const steps: VerifyStep[] = ([\"config\", \"rls\", \"migrations\", \"live\"] as const).map(id => ({\n id,\n title: STEP_TITLES[id],\n status: \"passed\"\n }));\n const [configStep, rlsStep, migrationsStep, liveStep] = steps;\n const collectionsDir = path.relative(options.projectRoot, options.collectionsDir) || \".\";\n\n if (!fs.existsSync(options.collectionsDir) || !fs.statSync(options.collectionsDir).isDirectory()) {\n for (const step of steps) {\n step.status = \"skipped\";\n step.detail = `no collections directory at ${collectionsDir}`;\n }\n return { ok: true, collectionsDir, steps, findings, summary: { errors: 0, warnings: 0 } };\n }\n\n const loaded = await loadCollectionFiles(options.projectRoot, options.collectionsDir);\n findings.push(...loaded.failures);\n\n if (loaded.collections.length > 0) {\n findings.push(...await checkConfig(loaded));\n }\n const counted = `${loaded.collections.length} collection${loaded.collections.length === 1 ? \"\" : \"s\"}`;\n configStep.detail = `${counted}, unknown keys are errors`;\n rlsStep.detail = counted;\n\n // Directory defaults reach a collection the way the loader applies them, so\n // the migration step plans the same policies the backend would.\n if (loaded.defaults?.length) {\n const { applyCollectionDefaults } = await import(\"@rebasepro/server\");\n applyCollectionDefaults(loaded.collections, { defaultSecurityRules: [...loaded.defaults] });\n }\n\n findings.push(...checkRls(loaded));\n\n // The database the live steps read, once it is known to answer. Under\n // `--live` a database that is missing or does not answer is an error: the\n // audit was asked for, and exit 0 without it is a green CI run over nothing.\n let liveUrl: string | undefined;\n if (options.live) {\n if (!options.databaseUrl) {\n liveStep.detail = \"no database to audit\";\n findings.push({\n step: \"live\",\n check: \"live-no-database\",\n severity: \"error\",\n message: options.databaseUnavailable\n ? `--live was asked for, and the database could not be prepared: ${options.databaseUnavailable}`\n : \"--live was asked for, and no database is configured to audit.\",\n fix: \"Pass --database-url <url> (or set DATABASE_URL), or run without --live for the offline checks.\"\n });\n } else {\n const unreachable = await databaseUnreachable(options.databaseUrl);\n if (unreachable) {\n liveStep.detail = \"the database did not answer\";\n findings.push({\n step: \"live\",\n check: \"live-unreachable\",\n severity: \"error\",\n message: `--live was asked for, and the database could not be reached: ${unreachable}. Neither the migration check nor the RLS audit ran.`,\n fix: \"Check the database is running and the URL is right (`rebase db url` prints the one this project resolves), or run without --live for the offline checks.\"\n });\n } else {\n liveUrl = options.databaseUrl;\n }\n }\n }\n\n if (findings.some(f => f.step === \"config\" && f.severity === \"error\")) {\n migrationsStep.status = \"skipped\";\n migrationsStep.detail = \"fix the collection config errors first\";\n } else {\n findings.push(...await checkMigrations({ ...options, databaseUrl: liveUrl }, loaded, migrationsStep));\n }\n\n if (!options.live) {\n liveStep.status = \"skipped\";\n liveStep.detail = \"pass --live to audit the database\";\n } else if (liveUrl) {\n findings.push(...await checkLive(liveUrl, liveStep, options.authRequired ?? true));\n }\n\n steps.forEach(step => settle(step, findings));\n const errors = findings.filter(f => f.severity === \"error\").length;\n return {\n ok: errors === 0,\n collectionsDir,\n steps,\n findings,\n summary: { errors, warnings: findings.length - errors }\n };\n}\n\n// ─── Output ───────────────────────────────────────────────────────────────────\n\nfunction printFinding(finding: VerifyFinding): void {\n const mark = finding.severity === \"error\" ? chalk.red(\"✗\") : chalk.yellow(\"!\");\n const where = [finding.file, finding.path].filter(Boolean).join(\" → \");\n console.log(` ${mark} ${where ? `${chalk.bold(where)} ` : \"\"}${finding.message}`);\n if (finding.fix) console.log(chalk.gray(` fix: ${finding.fix}`));\n}\n\nfunction summaryLine(report: VerifyReport): string {\n const { errors, warnings } = report.summary;\n return `${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"}`;\n}\n\nexport function printReport(report: VerifyReport, quiet: boolean): void {\n if (quiet) {\n if (report.findings.length === 0) return;\n if (!report.ok) console.log(chalk.red(`rebase verify: ${summaryLine(report)}`));\n for (const finding of report.findings) printFinding(finding);\n return;\n }\n\n console.log(\"\");\n console.log(` ${chalk.bold(\"rebase verify\")} ${chalk.gray(report.collectionsDir)}`);\n console.log(\"\");\n for (const step of report.steps) {\n const mark = step.status === \"passed\" ? chalk.green(\"✓\")\n : step.status === \"failed\" ? chalk.red(\"✗\")\n : step.status === \"warnings\" ? chalk.yellow(\"!\")\n : chalk.gray(\"–\");\n const detail = step.detail ? chalk.gray(step.status === \"skipped\" ? `skipped: ${step.detail}` : step.detail) : \"\";\n console.log(` ${mark} ${step.title.padEnd(22)} ${detail}`);\n }\n if (report.findings.length > 0) {\n console.log(\"\");\n for (const finding of report.findings) printFinding(finding);\n }\n console.log(\"\");\n console.log(report.ok ? chalk.green(` ✓ ${summaryLine(report)}`) : chalk.red(` ✗ ${summaryLine(report)}`));\n console.log(\"\");\n}\n\nfunction printVerifyHelp(): void {\n console.log(`\n${chalk.bold(\"rebase verify\")} — Check the collections are safe to ship\n\n${chalk.green.bold(\"Usage\")}\n rebase verify [options]\n\n${chalk.green.bold(\"Options\")}\n${Object.entries(VERIFY_FLAG_HELP).map(([flag, help]) => ` ${chalk.blue(flag.padEnd(20))} ${help}`).join(\"\\n\")}\n\n${chalk.green.bold(\"Steps\")}\n 1. Collection config every file loads and passes the boot validator, unknown keys as errors\n 2. RLS coverage securityRules are declared, and owner/tenant columns are filtered on\n 3. Migration freshness drizzle/migrations builds every declared table and column\n 4. Live RLS audit with --live: the rls-check catalogue against the project's database\n\nExits 1 when any step reports an error; warnings do not fail. Under --live, a\ndatabase that is missing or does not answer is an error. Fast and offline\nwithout --live: for CI, and for the Claude Code hook that ${chalk.cyan(\"rebase skills --hooks\")} installs.\n`);\n}\n\n/**\n * Whether the backend refuses a request with no token: `AUTH_REQUIRE` from the\n * environment, else `.env`, read as every boolean env var is read\n * (`parseEnvBoolean`: `false`/`0`/`no`/`off` turn it off). On unless one of\n * those says otherwise — the runtime's default. Compared raw, `AUTH_REQUIRE=0`\n * read as \"on\", and a compiled public read was reported as token-gated on a\n * backend that serves it to anyone.\n */\nexport function authRequiredFrom(\n environment: Record<string, string | undefined>,\n envFile: Record<string, string | undefined>\n): boolean {\n return parseEnvBoolean(environment.AUTH_REQUIRE ?? envFile.AUTH_REQUIRE) !== false;\n}\n\n/**\n * The database `--live` audits, resolved as every other database door resolves\n * it (`db *`, `console`, `doctor`): `--database-url`, `DATABASE_URL`, `.env`,\n * `--docker` or the last `rebase dev --docker`, and otherwise the managed\n * development database — started if it is not running. Reading only\n * `DATABASE_URL` meant the audit never ran on a fresh scaffold, whose database\n * is the managed one.\n *\n * Progress goes to stderr, so `--json` keeps stdout to the report.\n */\nasync function resolveLiveDatabase(\n projectRoot: string,\n rawArgs: readonly string[],\n options: { flagUrl: string | null; flagDocker: boolean; quiet: boolean }\n): Promise<Pick<VerifyOptions, \"databaseUrl\" | \"databaseUnavailable\">> {\n try {\n const { ensureDockerDatabase, databaseUrlOf } = await import(\"./db\");\n await ensureDockerDatabase(projectRoot, rawArgs);\n const { prepareDatabaseEnv } = await import(\"../dev-db/prepare\");\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: options.flagUrl,\n flagDocker: options.flagDocker,\n quiet: options.quiet,\n onProgress: options.quiet ? undefined : (line) => console.error(chalk.gray(` ${line}`))\n });\n return { databaseUrl: databaseUrlOf(prepared, readEnvFile(projectRoot)) };\n } catch (error) {\n return { databaseUnavailable: error instanceof Error ? error.message : String(error) };\n }\n}\n\nexport async function verifyCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printVerifyHelp();\n return;\n }\n const { flags } = parseCommandArgs({\n spec: VERIFY_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"verify\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n const backendDir = findBackendDir(projectRoot);\n if (flags[\"--collections\"]) {\n // A mistyped `-c` used to skip every step and print \"0 errors\" with\n // exit 0 — a green CI run over nothing. Refused as `doctor` and\n // `schema` refuse it. Without the flag, a project with no collections\n // directory (a headless one) is still a skip, not a failure.\n const refusal = missingCollectionsPath(rawArgs, process.cwd(), backendDir ?? projectRoot, \"verify\");\n if (refusal) {\n if (flags[\"--json\"]) {\n failAsJson(\n `Collections path not found: \"${flags[\"--collections\"]}\" (resolved to ${path.resolve(process.cwd(), flags[\"--collections\"])}).`,\n \"collections_not_found\",\n \"Leave --collections out (config/collections is the default), or pass a directory that exists; relative paths are resolved from where you run the command.\"\n );\n }\n console.error(\"\");\n for (const line of refusal) console.error(line);\n console.error(\"\");\n process.exit(1);\n }\n }\n const collectionsDir = flags[\"--collections\"]\n ? path.resolve(process.cwd(), flags[\"--collections\"])\n : resolveCollectionsDir(projectRoot);\n const live = flags[\"--live\"] === true;\n const database = live\n ? await resolveLiveDatabase(projectRoot, rawArgs, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n quiet: flags[\"--quiet\"] === true\n })\n : {};\n\n const report = await runVerify({\n projectRoot,\n collectionsDir,\n backendDir,\n live,\n ...database,\n authRequired: authRequiredFrom(process.env, readEnvFile(projectRoot))\n });\n\n if (flags[\"--json\"]) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n printReport(report, flags[\"--quiet\"] === true);\n }\n if (!report.ok) process.exitCode = 1;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,eAAe;CACxB,iBAAiB;CACjB,MAAM;CACN,UAAU;CACV,WAAW;CACX,MAAM;CACN,UAAU;CACV,kBAAkB;CAClB,YAAY;AAChB;AAEA,IAAM,mBAA2C;CAC7C,qBAAqB;CACrB,UAAU;CACV,eAAe;CACf,UAAU;CACV,kBAAkB;CAClB,YAAY;AAChB;AAsDA,IAAM,cAA4C;CAC9C,QAAQ;CACR,KAAK;CACL,YAAY;CACZ,MAAM;AACV;;;;;AAMA,IAAM,gBAAmC;CAAC;CAAW;CAAY;CAAmB;AAAW;AAE/F,IAAM,YAAY,UACd,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;AAGvE,SAAS,aAAa,OAA2C;CAC7D,OAAO,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,YAAY,SAAS,MAAM,UAAU;AACzF;;AAGA,SAAS,MAAM,KAAqB;CAChC,OAAO,IAAI,QAAQ,sBAAsB,OAAO,CAAC,CAAC,QAAQ,WAAW,GAAG,CAAC,CAAC,YAAY;AAC1F;;;;;;;;;;;AA0BA,eAAe,oBAAoB,aAAqB,gBAAoD;CACxG,MAAM,EAAE,eAAe,MAAM,OAAO;CACpC,MAAM,OAAO,WAAW,KAAK,KAAK,gBAAgB,UAAU,GAAG;EAC3D,gBAAgB;EAChB,aAAa;EACb,SAAS;CACb,CAAC;CACD,MAAM,YAAY,SAAiB,KAAK,SAAS,aAAa,IAAI;CAElE,MAAM,SAA4B;EAAE,aAAa,CAAC;EAAG,SAAS,CAAC;EAAG,UAAU,CAAC;EAAG,UAAU,KAAA;EAAW,UAAU,CAAC;CAAE;CAElH,KAAK,MAAM,QA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a,SAAS;GAC9C,SAAS,MAAM,qBAAqB;GACpC,YAAY,MAAM,gBAAgB;GAClC,OAAO,MAAM,eAAe;EAChC,CAAC,IACC,CAAC;EAQH,cAAc,iBAAiB,QAAQ,KAAK,YAAY,WAAW,CAAC;CACxE,CAAC;CAED,IAAI,MAAM,WACN,QAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;MAE3C,YAAY,QAAQ,MAAM,eAAe,IAAI;CAEjD,IAAI,CAAC,OAAO,IAAI,QAAQ,WAAW;AACvC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/cli",
|
|
3
|
-
"version": "0.29.
|
|
3
|
+
"version": "0.29.1",
|
|
4
4
|
"description": "Developer tools for Rebase projects",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -44,13 +44,13 @@
|
|
|
44
44
|
"inquirer": "14.0.2",
|
|
45
45
|
"jiti": "^2.7.0",
|
|
46
46
|
"pg": "^8.22.0",
|
|
47
|
-
"@rebasepro/
|
|
48
|
-
"@rebasepro/
|
|
49
|
-
"@rebasepro/
|
|
50
|
-
"@rebasepro/server": "0.29.
|
|
51
|
-
"@rebasepro/
|
|
52
|
-
"@rebasepro/
|
|
53
|
-
"@rebasepro/
|
|
47
|
+
"@rebasepro/codegen": "0.29.1",
|
|
48
|
+
"@rebasepro/agent-skills": "0.29.1",
|
|
49
|
+
"@rebasepro/server": "0.29.1",
|
|
50
|
+
"@rebasepro/server-postgres": "0.29.1",
|
|
51
|
+
"@rebasepro/types": "0.29.1",
|
|
52
|
+
"@rebasepro/client": "0.29.1",
|
|
53
|
+
"@rebasepro/rls-check": "0.29.1"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@types/node": "^26.1.2",
|
|
@@ -26,7 +26,7 @@ This is a **headless** Rebase project: a REST API, auth, storage and realtime ov
|
|
|
26
26
|
- **Never edit `.env`.** It holds generated secrets and the connection string. Add a variable by asking, and document it in `.env.example`.
|
|
27
27
|
- **Never edit `rebase.resources.json`.** It is generated from `config/resources.ts` — declare there, then `rebase resources --write`.
|
|
28
28
|
- **Never pass `--allow-destructive`** to anything pointed at a database that is not the local development one. It drops columns and tables.
|
|
29
|
-
- **Never read or write application rows
|
|
29
|
+
- **Never read or write application rows as the database owner from code.** The schema is SQL here; owner-level data access (`rebase.sql()`, a Drizzle client) is not, because it skips row-level security, validation and hooks. Analytics have an SDK form — `aggregate()` with `countDistinct`, `mode`, `percentile`, `distinct`, groups by `lower(…)`, `day(…)` or `unnest(tags)`, and `fingerprint()` to know whether a table changed — and bulk writes are `createMany` / `updateMany`, one statement per batch. When those do not fit, `getSql(c)` in a function runs one statement as the caller, under the same policies as the API: read-only unless `{ write: true }`, the query text yours and every value in `params`.
|
|
30
30
|
|
|
31
31
|
## Core rules
|
|
32
32
|
|
|
@@ -6,7 +6,7 @@ The Rebase skills for this assistant live in `.cursor/rules/`. If they are not t
|
|
|
6
6
|
|
|
7
7
|
These hold before you have opened ai-instructions.md, and in every session:
|
|
8
8
|
|
|
9
|
-
- **A table is a collection.** Declare it in `config/collections/<name>.ts` with `defineCollection`, and `pnpm dev` creates it. Never `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` in code, and never
|
|
9
|
+
- **A table is a collection.** Declare it in `config/collections/<name>.ts` with `defineCollection`, and `pnpm dev` creates it. Never `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` in code, and never SQL as the database owner against an application table: `rebase.sql()` skips row-level security, validation and callbacks, so keep it for server work that needs every row and for reading a column marked `excludeFromApi`. When the SDK cannot express a query, run it as the caller with `getSql(c)` — the same row-level security as the SDK, read-only unless `{ write: true }`, every value in `params`. A table that already exists gets its collection from `pnpm schema:introspect`.
|
|
10
10
|
- **Data goes through the SDK:** `rebase.dataAsAdmin.<slug>` in functions and crons, `getDriver(c)` to act as the caller.
|
|
11
11
|
- **A route in `backend/functions/` is public until you guard it** with `requireAuth` or `requireAdmin` from `@rebasepro/server/functions`.
|
|
12
12
|
- **Never deploy, never edit `.env`, never edit generated files** (`backend/src/schema.generated.ts`, `rebase.resources.json`).
|
|
@@ -6,7 +6,7 @@ The Rebase skills for this assistant live in `.github/instructions/`. If they ar
|
|
|
6
6
|
|
|
7
7
|
These hold before you have opened ai-instructions.md, and in every session:
|
|
8
8
|
|
|
9
|
-
- **A table is a collection.** Declare it in `config/collections/<name>.ts` with `defineCollection`, and `pnpm dev` creates it. Never `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` in code, and never
|
|
9
|
+
- **A table is a collection.** Declare it in `config/collections/<name>.ts` with `defineCollection`, and `pnpm dev` creates it. Never `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` in code, and never SQL as the database owner against an application table: `rebase.sql()` skips row-level security, validation and callbacks, so keep it for server work that needs every row and for reading a column marked `excludeFromApi`. When the SDK cannot express a query, run it as the caller with `getSql(c)` — the same row-level security as the SDK, read-only unless `{ write: true }`, every value in `params`. A table that already exists gets its collection from `pnpm schema:introspect`.
|
|
10
10
|
- **Data goes through the SDK:** `rebase.dataAsAdmin.<slug>` in functions and crons, `getDriver(c)` to act as the caller.
|
|
11
11
|
- **A route in `backend/functions/` is public until you guard it** with `requireAuth` or `requireAdmin` from `@rebasepro/server/functions`.
|
|
12
12
|
- **Never deploy, never edit `.env`, never edit generated files** (`backend/src/schema.generated.ts`, `rebase.resources.json`).
|
|
@@ -6,7 +6,7 @@ The Rebase skills for this assistant live in `.windsurf/rules/`. If they are not
|
|
|
6
6
|
|
|
7
7
|
These hold before you have opened ai-instructions.md, and in every session:
|
|
8
8
|
|
|
9
|
-
- **A table is a collection.** Declare it in `config/collections/<name>.ts` with `defineCollection`, and `pnpm dev` creates it. Never `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` in code, and never
|
|
9
|
+
- **A table is a collection.** Declare it in `config/collections/<name>.ts` with `defineCollection`, and `pnpm dev` creates it. Never `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` in code, and never SQL as the database owner against an application table: `rebase.sql()` skips row-level security, validation and callbacks, so keep it for server work that needs every row and for reading a column marked `excludeFromApi`. When the SDK cannot express a query, run it as the caller with `getSql(c)` — the same row-level security as the SDK, read-only unless `{ write: true }`, every value in `params`. A table that already exists gets its collection from `pnpm schema:introspect`.
|
|
10
10
|
- **Data goes through the SDK:** `rebase.dataAsAdmin.<slug>` in functions and crons, `getDriver(c)` to act as the caller.
|
|
11
11
|
- **A route in `backend/functions/` is public until you guard it** with `requireAuth` or `requireAdmin` from `@rebasepro/server/functions`.
|
|
12
12
|
- **Never deploy, never edit `.env`, never edit generated files** (`backend/src/schema.generated.ts`, `rebase.resources.json`).
|
|
@@ -6,7 +6,7 @@ The Rebase skills for this assistant live in `.agents/skills/`. If they are not
|
|
|
6
6
|
|
|
7
7
|
These hold before you have opened ai-instructions.md, and in every session:
|
|
8
8
|
|
|
9
|
-
- **A table is a collection.** Declare it in `config/collections/<name>.ts` with `defineCollection`, and `pnpm dev` creates it. Never `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` in code, and never
|
|
9
|
+
- **A table is a collection.** Declare it in `config/collections/<name>.ts` with `defineCollection`, and `pnpm dev` creates it. Never `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` in code, and never SQL as the database owner against an application table: `rebase.sql()` skips row-level security, validation and callbacks, so keep it for server work that needs every row and for reading a column marked `excludeFromApi`. When the SDK cannot express a query, run it as the caller with `getSql(c)` — the same row-level security as the SDK, read-only unless `{ write: true }`, every value in `params`. A table that already exists gets its collection from `pnpm schema:introspect`.
|
|
10
10
|
- **Data goes through the SDK:** `rebase.dataAsAdmin.<slug>` in functions and crons, `getDriver(c)` to act as the caller.
|
|
11
11
|
- **A route in `backend/functions/` is public until you guard it** with `requireAuth` or `requireAdmin` from `@rebasepro/server/functions`.
|
|
12
12
|
- **Never deploy, never edit `.env`, never edit generated files** (`backend/src/schema.generated.ts`, `rebase.resources.json`).
|
|
@@ -6,7 +6,7 @@ The Rebase skills for this assistant live in `.claude/skills/`. If they are not
|
|
|
6
6
|
|
|
7
7
|
These hold before you have opened ai-instructions.md, and in every session:
|
|
8
8
|
|
|
9
|
-
- **A table is a collection.** Declare it in `config/collections/<name>.ts` with `defineCollection`, and `pnpm dev` creates it. Never `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` in code, and never
|
|
9
|
+
- **A table is a collection.** Declare it in `config/collections/<name>.ts` with `defineCollection`, and `pnpm dev` creates it. Never `CREATE TABLE`, `ALTER TABLE` or `CREATE INDEX` in code, and never SQL as the database owner against an application table: `rebase.sql()` skips row-level security, validation and callbacks, so keep it for server work that needs every row and for reading a column marked `excludeFromApi`. When the SDK cannot express a query, run it as the caller with `getSql(c)` — the same row-level security as the SDK, read-only unless `{ write: true }`, every value in `params`. A table that already exists gets its collection from `pnpm schema:introspect`.
|
|
10
10
|
- **Data goes through the SDK:** `rebase.dataAsAdmin.<slug>` in functions and crons, `getDriver(c)` to act as the caller.
|
|
11
11
|
- **A route in `backend/functions/` is public until you guard it** with `requireAuth` or `requireAdmin` from `@rebasepro/server/functions`.
|
|
12
12
|
- **Never deploy, never edit `.env`, never edit generated files** (`backend/src/schema.generated.ts`, `rebase.resources.json`).
|