Files
Ekklesia/apps/api/src/config.ts
T
ekklesiaandClaude Opus 5 6b6b77c105 fix: enforce production transport policy
Every PostgreSQL connection this repository opened was plaintext, in every
environment: no connection site set `ssl` at all, so credentials, session
tokens, and row data crossed the network in the clear and nothing in
configuration, startup, or `pnpm doctor` said so. The public identity URL
boundary was also looser than it appeared.

`core/src/database/transport.ts` is now the one typed policy. It has exactly two
modes: `verify-full` (TLS required, certificate chain verified, and server
identity verified against the configured host — the production default) and
`disable` (the development/test default, refused outright in production). There
is deliberately no encryption-only `require` mode, no chain-only `verify-ca`,
and no `rejectUnauthorized: false` escape hatch anywhere in the configuration
surface; every loose or aliased spelling is rejected in both environments, so a
typo never quietly becomes a weaker mode. Production has no plaintext exception
at all, not even for a loopback database — a connection string cannot prove the
database is process-local.

Verification is certificate *and* hostname. The policy supplies an explicit
`checkServerIdentity` pinned to the host parsed from DATABASE_URL, because the
pinned driver sets TLS `servername` only for non-IP hosts and Node performs no
identity check when it is unset — so `rejectUnauthorized: true` alone accepts a
certificate from any host the trusted CA ever signed when connecting by IP.
Both halves are proven against a real TLS-enabled PostgreSQL, including that the
same connection without the pinned callback succeeds. Every CA, certificate, and
key is generated at test runtime and deleted afterwards.

A DATABASE_URL may no longer carry its own TLS parameters. The pinned driver
merges parsed connection-string values over explicitly passed options, so a
`?sslmode=disable` in the URL would silently replace the policy's verified `ssl`
object; that now fails with a stable code, reported by both `pnpm doctor` and
the migration CLIs rather than as "failed unexpectedly".

One shared environment reader keeps `process.env` out of Core's reusable
constructors, and every executable that opens a connection resolves the policy
identically: the API (validated before any pool, Better Auth instance, module
runtime, or listener exists), both migration commands, the bootstrap CLI, and
Doctor's own connection. Doctor reports it as a blocking failure, never a
warning, naming only the effective mode.

Separately, the identity base URL and every trusted origin must now be exactly
one canonical origin — the WHATWG origin serialization must equal the supplied
string — so a path, trailing slash, credentials, explicit default port, or
non-canonical case is rejected rather than normalized into something that no
longer matches what a browser sends. Production's loopback rejection now
classifies the address instead of comparing against three literals, covering
`.localhost`, all of 127.0.0.0/8, 0.0.0.0, `::`, expanded and IPv4-mapped
forms. This is a configuration-shape guarantee only: it does not resolve DNS or
prove reachability, and TLS protects the connection, not the exposure.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-07-26 17:03:52 -05:00

154 lines
5.0 KiB
TypeScript

import {
assertProductionDatabaseTransport,
type DatabaseTransportPolicy,
type DatabaseTransportPolicyInput,
createDatabaseTransportPolicy,
} from "@ekklesia/core/database";
import {
type CreateIdentityConfigOptions,
createIdentityConfig,
type IdentityConfig,
type IdentityConfigInput,
} from "@ekklesia/core/identity";
import {
type ClientAddressConfig,
type ClientAddressConfigInput,
createClientAddressConfig,
} from "./client-address.js";
export type ApiConfigErrorCode =
| "DATABASE_URL_INVALID"
| "DATABASE_URL_MISSING"
| "HOST_INVALID"
| "PORT_INVALID";
/** Never carries the offending database URL, host, port, or any other caller-supplied value. */
export class ApiConfigError extends Error {
readonly code: ApiConfigErrorCode;
constructor(code: ApiConfigErrorCode) {
super(apiConfigErrorMessages[code]);
this.name = "ApiConfigError";
this.code = code;
this.stack = `${this.name}: ${this.message}`;
Object.freeze(this);
}
}
const apiConfigErrorMessages: Readonly<Record<ApiConfigErrorCode, string>> = Object.freeze({
DATABASE_URL_INVALID:
"The API database URL must be an absolute postgres:// or postgresql:// URL.",
DATABASE_URL_MISSING: "The API database URL is required.",
HOST_INVALID: "The API listen address must be a non-empty host.",
PORT_INVALID:
"The API listen port must be an integer between 0 and 65535 (0 requests an OS-assigned port).",
});
const defaultHost = "127.0.0.1";
const defaultPort = 3000;
export interface ApiRuntimeConfig {
readonly clientAddress: ClientAddressConfig;
readonly databaseUrl: string;
/** The one validated PostgreSQL transport policy this runtime's single pool uses. */
readonly databaseTransport: DatabaseTransportPolicy;
readonly host: string;
readonly identity: IdentityConfig;
readonly port: number;
}
export interface ApiRuntimeConfigInput {
/** Optional. Defaults to direct mode (trusts only the actual immediate socket peer) — no proxy
* trust unless explicitly configured. See `./client-address.js`. */
readonly clientAddress?: ClientAddressConfigInput;
readonly databaseUrl?: unknown;
/** Optional. Defaults to certificate-verified TLS in production and plaintext in development;
* production can never select plaintext. See `@ekklesia/core/database`'s transport policy. */
readonly databaseTransport?: DatabaseTransportPolicyInput;
readonly host?: unknown;
readonly identity: IdentityConfigInput;
readonly port?: unknown;
}
export interface CreateApiRuntimeConfigOptions {
readonly environment?: CreateIdentityConfigOptions["environment"];
}
function validateDatabaseUrl(databaseUrl: unknown): string {
if (typeof databaseUrl !== "string" || databaseUrl.trim().length === 0) {
throw new ApiConfigError("DATABASE_URL_MISSING");
}
let protocol: string;
try {
protocol = new URL(databaseUrl).protocol;
} catch {
throw new ApiConfigError("DATABASE_URL_INVALID");
}
if (protocol !== "postgres:" && protocol !== "postgresql:") {
throw new ApiConfigError("DATABASE_URL_INVALID");
}
return databaseUrl;
}
function validateHost(host: unknown): string {
if (host === undefined) {
return defaultHost;
}
if (typeof host !== "string" || host.trim().length === 0) {
throw new ApiConfigError("HOST_INVALID");
}
return host;
}
function validatePort(port: unknown): number {
if (port === undefined) {
return defaultPort;
}
const numericPort = typeof port === "string" ? Number(port) : port;
if (
typeof numericPort !== "number" ||
!Number.isInteger(numericPort) ||
numericPort < 0 ||
numericPort > 65_535
) {
throw new ApiConfigError("PORT_INVALID");
}
return numericPort;
}
/**
* Validates explicit, typed API runtime configuration, delegating identity fields to Core's
* existing `createIdentityConfig` rather than defining a competing identity configuration
* contract. Performs no environment reads, network calls, or database access.
*/
export function createApiRuntimeConfig(
input: ApiRuntimeConfigInput,
options: CreateApiRuntimeConfigOptions = {},
): ApiRuntimeConfig {
const databaseUrl = validateDatabaseUrl(input.databaseUrl);
const host = validateHost(input.host);
const port = validatePort(input.port);
const identity = createIdentityConfig(
input.identity,
options.environment === undefined ? {} : { environment: options.environment },
);
const clientAddress = createClientAddressConfig(input.clientAddress);
const environment = options.environment ?? "production";
const databaseTransport = createDatabaseTransportPolicy(input.databaseTransport, {
environment,
});
// Fails here — before `startApi` constructs a pool, Better Auth, the module runtime, or a
// listener — if a production deployment would connect without certificate-verified TLS, or if
// the URL carries TLS parameters that could override the policy.
assertProductionDatabaseTransport(databaseUrl, databaseTransport, environment);
return Object.freeze({
clientAddress,
databaseTransport,
databaseUrl,
host,
identity,
port,
});
}