trails/packages/db/src/migrate-data.ts
Ullrich Schäfer 5a7bb76ff1
fix(journal): fail loud in production when secrets are unset
Adds `requireSecret(name, devFallback)` in lib/config.server.ts and
`getDatabaseUrl()` in @trails-cool/db. Both:
- return the env var when set,
- fall back to the dev default in non-production,
- throw at boot in production if the env var is missing OR matches the
  known dev fallback (which would otherwise silently ship a public
  secret / point at localhost).

Applied to:
- JWT_SECRET (lib/jwt.server.ts) — was `?? "dev-jwt-secret-change-in-production"`
- SESSION_SECRET (lib/auth/session.server.ts) — was `?? "dev-secret-change-in-production"`
- DATABASE_URL (server.ts health + boss; packages/db migrate-data) — was
  `?? "postgres://trails:trails@localhost:5432/trails"`

Why: these strings are in the repo and known to attackers. A
misconfigured prod deploy that forgot to set them would either run with
guessable signing keys (full session/JWT forgery) or connect to a
non-existent localhost DB. Better to refuse to start than to silently
operate insecurely.

Tests:
- packages/db/src/get-database-url.test.ts (5 cases)
- lib/config.server.test.ts gains `requireSecret` cases (4 new)

Full repo: pnpm typecheck, pnpm lint, pnpm test all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 11:37:20 +02:00

37 lines
1.2 KiB
TypeScript

// Runs hand-written SQL data migrations from packages/db/migrations/*.sql in
// lexical order. Each file is expected to be idempotent (safe to re-run);
// there is no migrations table.
//
// Why this exists: we use `drizzle-kit push --force` for schema, which is
// fine for column adds and renames but unsafe when a unique-key change
// requires collapsing existing rows first. The wahoo-route-update change is
// the first such case.
import { readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import postgres from "postgres";
import { getDatabaseUrl } from "./index.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const migrationsDir = path.resolve(__dirname, "..", "migrations");
async function main() {
const sql = postgres(getDatabaseUrl());
try {
const files = readdirSync(migrationsDir)
.filter((f) => f.endsWith(".sql"))
.sort();
for (const f of files) {
const body = readFileSync(path.join(migrationsDir, f), "utf8");
console.log(`[migrate-data] applying ${f}`);
await sql.unsafe(body);
}
} finally {
await sql.end();
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});