trails/packages/db/src/index.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

63 lines
2.2 KiB
TypeScript

import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as plannerSchema from "./schema/planner.ts";
import * as journalSchema from "./schema/journal.ts";
const DEV_DB_URL = "postgres://trails:trails@localhost:5432/trails";
/**
* Resolve the database URL with fail-loud semantics in production.
* In dev/test we silently fall back to the local Compose URL so the
* loop keeps working; in prod we refuse to start rather than
* silently pointing at localhost (which either won't resolve, or
* worse, will connect to an unintended database on the host).
*/
export function getDatabaseUrl(override?: string): string {
if (override) return override;
const url = process.env.DATABASE_URL;
if (process.env.NODE_ENV === "production") {
if (!url || url === DEV_DB_URL) {
throw new Error(
"Refusing to start: DATABASE_URL is unset or matches the dev default. " +
"Set DATABASE_URL to the production connection string.",
);
}
return url;
}
return url ?? DEV_DB_URL;
}
export function createDb(connectionString?: string) {
const client = postgres(getDatabaseUrl(connectionString));
return drizzle(client, {
schema: { ...plannerSchema, ...journalSchema },
});
}
export type Database = ReturnType<typeof createDb>;
/**
* Wraps a route handler (loader/action) to catch database errors
* and return a 503 Service Unavailable instead of crashing.
*/
export function withDb<T>(handler: () => Promise<T>): Promise<T> {
return handler().catch((error) => {
// Re-throw React Router responses and data() throws:
// - Response instances (redirects, manual responses)
// - DataWithResponseInit from data() throws (type + data + init)
if (
error instanceof Response ||
(error != null && typeof error === "object" && error.type === "DataWithResponseInit")
) {
throw error;
}
// Database error — throw as a 503 that the error boundary will catch
const message = error instanceof Error ? error.message : String(error);
console.error("[withDb] Database error:", message);
throw new Response("Database unavailable", { status: 503, statusText: "Service Unavailable" });
});
}
export { plannerSchema, journalSchema };