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]>
This commit is contained in:
ekklesia
2026-07-26 17:03:52 -05:00
co-authored by Claude Opus 5
parent 7a0f624fc3
commit 6b6b77c105
34 changed files with 2035 additions and 52 deletions
+13
View File
@@ -1,5 +1,9 @@
import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
import { Pool, type PoolConfig } from "pg";
import {
type DatabaseTransportPolicy,
databaseTlsConnectionOptions,
} from "../database/transport.js";
import { authorizationSchema } from "./schema.js";
export type AuthorizationDrizzleDatabase = NodePgDatabase<typeof authorizationSchema>;
@@ -27,6 +31,10 @@ export interface AuthorizationDatabaseOptions {
* `core/src/identity/database.ts`: `connectionTimeoutMs` alone only bounds establishing a
* connection, not a hung query already running on one. */
readonly operationTimeoutMs?: number;
/** The validated transport policy (`core/src/database/transport.js`). Passed explicitly by
* every production executable; omitted by single-domain unit/integration factories that use
* the disposable loopback database, which keeps the pre-existing plaintext behavior. */
readonly transport?: DatabaseTransportPolicy;
}
export interface AuthorizationDatabaseHandle {
@@ -80,8 +88,13 @@ export function createAuthorizationDrizzleDatabase(
const validatedConnectionString = validateConnectionString(connectionString);
const validatedConnectionTimeoutMs = validateTimeout(options.connectionTimeoutMs);
const validatedOperationTimeoutMs = validateTimeout(options.operationTimeoutMs);
const ssl =
options.transport === undefined
? undefined
: databaseTlsConnectionOptions(validatedConnectionString, options.transport);
const poolConfig: PoolConfig = {
connectionString: validatedConnectionString,
...(ssl === undefined ? {} : { ssl }),
...(validatedConnectionTimeoutMs === undefined
? {}
: { connectionTimeoutMillis: validatedConnectionTimeoutMs }),
+9 -1
View File
@@ -1,11 +1,19 @@
import { formatMigrationApplyReport } from "./migration-report.js";
import { discoverRepositoryMigrations } from "./migration-command-support.js";
import { reportMigrationCommandError } from "./migration-command-errors.js";
import { resolveExecutableDatabaseTransport } from "./database-transport-environment.js";
import { applyModuleMigrations, createPostgresMigrationDatabase } from "../migrations/index.js";
async function main(): Promise<void> {
const aggregate = await discoverRepositoryMigrations();
const database = createPostgresMigrationDatabase(process.env.DATABASE_URL);
const databaseUrl = process.env.DATABASE_URL;
// Resolved and asserted before any client exists: an unsafe production transport fails
// here rather than after opening a connection.
const transport =
typeof databaseUrl === "string" ? resolveExecutableDatabaseTransport(databaseUrl) : undefined;
const database = createPostgresMigrationDatabase(databaseUrl, {
...(transport === undefined ? {} : { transport }),
});
const result = await applyModuleMigrations({ aggregate, database });
for (const line of formatMigrationApplyReport(result)) {
+5
View File
@@ -6,6 +6,7 @@ import {
createAuthorizationDrizzleDatabase,
PlatformOwnerBootstrapError,
} from "../authorization/index.js";
import { resolveExecutableDatabaseTransport } from "./database-transport-environment.js";
class BootstrapCliError extends Error {
constructor(message: string) {
@@ -67,9 +68,13 @@ async function main(): Promise<void> {
throw new BootstrapCliError("DATABASE_URL is required.");
}
// Asserted before the connection is constructed, so an unsafe production transport never opens
// a client at all.
const transport = resolveExecutableDatabaseTransport(databaseUrl);
const { close, db } = createAuthorizationDrizzleDatabase(databaseUrl, {
connectionTimeoutMs: 10_000,
operationTimeoutMs: 10_000,
transport,
});
try {
await bootstrapPlatformOwner(db, { userId: parsedUserId.data });
@@ -0,0 +1,46 @@
import {
assertProductionDatabaseTransport,
type DatabaseTransportEnvironment,
type DatabaseTransportPolicy,
createDatabaseTransportPolicy,
} from "../database/transport.js";
/**
* The one place every Core-owned executable reads its database transport policy from the process
* environment, so `pnpm doctor`, `pnpm migrations:plan`, `pnpm migrations:apply`, and
* `pnpm authorization:bootstrap-owner` cannot drift from each other or from `apps/api`.
*
* Environment reading lives here, in the executable layer, deliberately: the reusable Core
* database/migration constructors keep taking explicit typed inputs and never touch `process.env`.
* `NODE_ENV` is interpreted exactly as `apps/api` interprets it — only the literal string
* `"development"` relaxes anything, so an unset or misspelled value validates as production.
*/
export function readDatabaseTransportFromEnvironment(): {
readonly environment: DatabaseTransportEnvironment;
readonly transport: DatabaseTransportPolicy;
} {
const environment: DatabaseTransportEnvironment =
process.env.NODE_ENV === "development" ? "development" : "production";
const transport = createDatabaseTransportPolicy(
{
...(process.env.EKKLESIA_DATABASE_CA === undefined
? {}
: { certificateAuthority: process.env.EKKLESIA_DATABASE_CA }),
...(process.env.EKKLESIA_DATABASE_TLS_MODE === undefined
? {}
: { mode: process.env.EKKLESIA_DATABASE_TLS_MODE }),
},
{ environment },
);
return { environment, transport };
}
/**
* Resolves the policy and asserts it is safe for the given database URL before any client, pool,
* or connection is constructed. Throws the sanitized `DatabaseTransportError` otherwise.
*/
export function resolveExecutableDatabaseTransport(databaseUrl: string): DatabaseTransportPolicy {
const { environment, transport } = readDatabaseTransportFromEnvironment();
assertProductionDatabaseTransport(databaseUrl, transport, environment);
return transport;
}
+11
View File
@@ -81,8 +81,19 @@ export async function runDoctorCommand(repositoryRoot = process.cwd()): Promise<
const rootPackage = rootPackageDocument(rootValue);
const moduleSdkPackage = rootPackageDocument(moduleSdkValue);
const databaseEnvironment =
process.env.NODE_ENV === "development" ? ("development" as const) : ("production" as const);
const report = await diagnoseEkklesia({
clientAddress: readClientAddressFromEnvironment(),
databaseEnvironment,
databaseTransport: {
...(process.env.EKKLESIA_DATABASE_CA === undefined
? {}
: { certificateAuthority: process.env.EKKLESIA_DATABASE_CA }),
...(process.env.EKKLESIA_DATABASE_TLS_MODE === undefined
? {}
: { mode: process.env.EKKLESIA_DATABASE_TLS_MODE }),
},
databaseUrl: process.env.DATABASE_URL,
identityConfiguration: readIdentityConfigurationFromEnvironment(),
moduleDiscovery: {
+9
View File
@@ -1,7 +1,16 @@
import { DatabaseTransportError } from "../database/transport.js";
import { MigrationRunnerError, PostgresMigrationDatabaseError } from "../migrations/index.js";
import { ModuleDiscoveryError, ModuleMigrationDiscoveryError } from "../modules/index.js";
export function reportMigrationCommandError(error: unknown): void {
if (error instanceof DatabaseTransportError) {
// The message is a fixed string chosen by code; it never carries the connection string, host,
// port, credentials, CA material, or the offending mode value, so it is safe to print as-is —
// and an operator who misconfigured TLS needs to know that, not "failed unexpectedly".
console.error(`[${error.code}] ${error.message}`);
return;
}
if (error instanceof ModuleDiscoveryError) {
console.error(error.message);
for (const issue of error.issues) {
+9 -1
View File
@@ -1,11 +1,19 @@
import { formatMigrationPlanReport } from "./migration-report.js";
import { discoverRepositoryMigrations } from "./migration-command-support.js";
import { reportMigrationCommandError } from "./migration-command-errors.js";
import { resolveExecutableDatabaseTransport } from "./database-transport-environment.js";
import { createPostgresMigrationDatabase, planModuleMigrations } from "../migrations/index.js";
async function main(): Promise<void> {
const aggregate = await discoverRepositoryMigrations();
const database = createPostgresMigrationDatabase(process.env.DATABASE_URL);
const databaseUrl = process.env.DATABASE_URL;
// Resolved and asserted before any client exists: an unsafe production transport fails
// here rather than after opening a connection.
const transport =
typeof databaseUrl === "string" ? resolveExecutableDatabaseTransport(databaseUrl) : undefined;
const database = createPostgresMigrationDatabase(databaseUrl, {
...(transport === undefined ? {} : { transport }),
});
const plan = await planModuleMigrations({ aggregate, database });
for (const line of formatMigrationPlanReport(plan)) {
+1
View File
@@ -1 +1,2 @@
export * from "./pool.js";
export * from "./transport.js";
+14
View File
@@ -1,4 +1,5 @@
import { Pool, type PoolConfig } from "pg";
import { type DatabaseTransportPolicy, databaseTlsConnectionOptions } from "./transport.js";
export type PostgresPoolErrorCode = "POSTGRES_POOL_CONFIGURATION_INVALID";
@@ -22,6 +23,11 @@ export interface PostgresPoolOptions {
/** Bounds both `query_timeout` and `statement_timeout`: `connectionTimeoutMs` alone only bounds
* establishing a connection, not a hung query already running on one. */
readonly operationTimeoutMs?: number;
/** The validated transport policy (`./transport.js`). Omitted only by isolated unit-test and
* single-domain factories that connect to a disposable loopback database; every production
* executable passes one explicitly. When omitted, no `ssl` option is set and the connection is
* plaintext — exactly the pre-existing development behavior. */
readonly transport?: DatabaseTransportPolicy;
}
export interface PostgresPoolHandle {
@@ -84,8 +90,16 @@ export function createValidatedPostgresPool(
const validatedConnectionString = validateConnectionString(connectionString);
const validatedConnectionTimeoutMs = validateTimeout(options.connectionTimeoutMs);
const validatedOperationTimeoutMs = validateTimeout(options.operationTimeoutMs);
// `databaseTlsConnectionOptions` also rejects a URL carrying its own TLS parameters, so the
// pinned driver's `Object.assign({}, config, parse(connectionString))` precedence can never
// silently replace the policy's `ssl` object with a weaker one.
const ssl =
options.transport === undefined
? undefined
: databaseTlsConnectionOptions(validatedConnectionString, options.transport);
const poolConfig: PoolConfig = {
connectionString: validatedConnectionString,
...(ssl === undefined ? {} : { ssl }),
...(validatedConnectionTimeoutMs === undefined
? {}
: { connectionTimeoutMillis: validatedConnectionTimeoutMs }),
+252
View File
@@ -0,0 +1,252 @@
import net from "node:net";
import tls from "node:tls";
import type { ConnectionOptions } from "node:tls";
export type DatabaseTransportEnvironment = "development" | "production";
/**
* The two transport modes this release supports, named after the libpq/PostgreSQL vocabulary an
* operator already knows:
*
* - `verify-full` — TLS is required, the server certificate must chain to a trusted CA, **and**
* the certificate identity must match the configured database host. This is the production
* default, and the only mode a production deployment may use.
* - `disable` — no TLS at all. Available only for the disposable loopback PostgreSQL used by local
* development and this repository's integration harness.
*
* There is deliberately no encryption-only mode (`require`/`verify-ca`) and no
* `rejectUnauthorized: false` escape hatch: both authenticate nothing, and an unauthenticated
* encrypted channel to an attacker-controlled endpoint is not a security property worth offering.
*/
export type DatabaseTlsMode = "disable" | "verify-full";
export type DatabaseTransportErrorCode =
| "DATABASE_TLS_CONNECTION_STRING_CONFLICT"
| "DATABASE_TLS_MODE_INVALID"
| "DATABASE_TLS_REQUIRED_IN_PRODUCTION"
| "DATABASE_URL_INVALID";
const errorMessages: Readonly<Record<DatabaseTransportErrorCode, string>> = Object.freeze({
DATABASE_TLS_CONNECTION_STRING_CONFLICT:
"The database URL must not carry TLS parameters; configure the database TLS mode explicitly.",
DATABASE_TLS_MODE_INVALID: 'The database TLS mode must be exactly "verify-full" or "disable".',
DATABASE_TLS_REQUIRED_IN_PRODUCTION:
"A production database connection must use certificate-verified TLS.",
DATABASE_URL_INVALID: "The database URL must be an absolute postgres:// or postgresql:// URL.",
});
/** Never carries the connection string, host, port, database name, credentials, certificate, CA
* material, or the offending mode value. */
export class DatabaseTransportError extends Error {
readonly code: DatabaseTransportErrorCode;
constructor(code: DatabaseTransportErrorCode) {
super(errorMessages[code]);
this.name = "DatabaseTransportError";
this.code = code;
this.stack = `${this.name}: ${this.message}`;
Object.freeze(this);
}
}
export interface DatabaseTransportPolicy {
readonly mode: DatabaseTlsMode;
/** PEM trust material for a private PostgreSQL CA. Optional: when omitted, Node's own trusted CA
* set is used. Never logged, never echoed in an error. */
readonly certificateAuthority?: string;
}
export interface DatabaseTransportPolicyInput {
readonly mode?: unknown;
readonly certificateAuthority?: unknown;
}
export interface CreateDatabaseTransportPolicyOptions {
/** Defaults to production, so an omitted environment never silently relaxes transport security. */
readonly environment?: DatabaseTransportEnvironment;
}
/**
* Every TLS-related parameter `[email protected]` recognizes in a PostgreSQL URL. These
* are rejected outright rather than merged, because the pinned driver resolves them in a way that
* silently defeats an explicit policy: `pg`'s own `ConnectionParameters` does
* `Object.assign({}, config, parse(config.connectionString))`
* (`pg/lib/connection-parameters.js`), so a URL parameter **overwrites** the `ssl` object a caller
* passed alongside it. Verified directly against a live TLS PostgreSQL instance: a
* `?sslmode=disable` URL combined with an explicit certificate-verifying `ssl` object connects in
* plaintext.
*
* The pinned release additionally aliases `prefer`/`require`/`verify-ca` to full verification while
* printing a deprecation warning that they will adopt weaker libpq semantics in `pg@9`, so even
* a URL that looks safe today is not a durable guarantee. One typed policy is the whole contract.
*/
const CONNECTION_STRING_TLS_PARAMETERS = Object.freeze([
"ssl",
"sslcert",
"sslkey",
"sslmode",
"sslnegotiation",
"sslpassword",
"sslrootcert",
"uselibpqcompat",
]);
function parseDatabaseUrl(databaseUrl: string): URL {
let url: URL;
try {
url = new URL(databaseUrl);
} catch {
throw new DatabaseTransportError("DATABASE_URL_INVALID");
}
if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") {
throw new DatabaseTransportError("DATABASE_URL_INVALID");
}
return url;
}
/** The host a certificate's identity must match — the exact host the driver will connect to. */
export function databaseHostFromUrl(databaseUrl: string): string {
const url = parseDatabaseUrl(databaseUrl);
// `URL.hostname` keeps IPv6 literals bracketed; TLS identity checking wants the bare address.
const hostname = url.hostname;
return hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
}
/** Whether the database endpoint is an unambiguous loopback literal. Used only to decide whether
* the development plaintext mode is even permissible; it is never a production allowance. */
function isLoopbackDatabaseHost(host: string): boolean {
const normalized = host.toLowerCase();
if (normalized === "localhost" || normalized.endsWith(".localhost")) {
return true;
}
if (net.isIPv4(normalized)) {
return normalized.startsWith("127.");
}
if (net.isIPv6(normalized)) {
return normalized === "::1" || normalized === "::ffff:127.0.0.1";
}
return false;
}
/**
* Validates the typed transport policy. Parsing is deliberately separate from environment policy,
* matching the convention the public-signup gate already established: a malformed mode is reported
* as malformed in every environment, never relabeled as a production failure.
*/
export function createDatabaseTransportPolicy(
input: DatabaseTransportPolicyInput = {},
options: CreateDatabaseTransportPolicyOptions = {},
): DatabaseTransportPolicy {
const environment = options.environment ?? "production";
let mode: DatabaseTlsMode;
if (input.mode === undefined) {
// Production fails safe to verified TLS; development keeps the plaintext disposable-PostgreSQL
// workflow this repository's harness relies on.
mode = environment === "production" ? "verify-full" : "disable";
} else if (input.mode === "verify-full" || input.mode === "disable") {
mode = input.mode;
} else {
// No coercion of booleans, `1`, `"TRUE"`, `" verify-full "`, or any other loose spelling.
throw new DatabaseTransportError("DATABASE_TLS_MODE_INVALID");
}
if (environment === "production" && mode !== "verify-full") {
throw new DatabaseTransportError("DATABASE_TLS_REQUIRED_IN_PRODUCTION");
}
if (
input.certificateAuthority !== undefined &&
(typeof input.certificateAuthority !== "string" ||
input.certificateAuthority.trim().length === 0)
) {
throw new DatabaseTransportError("DATABASE_TLS_MODE_INVALID");
}
return Object.freeze({
...(typeof input.certificateAuthority === "string"
? { certificateAuthority: input.certificateAuthority }
: {}),
mode,
});
}
/**
* Rejects any database URL carrying its own TLS parameters. Called before a pool or client is ever
* constructed, so a URL can never silently downgrade or contradict the validated policy — there is
* exactly one place transport security is decided.
*/
export function assertNoConnectionStringTlsParameters(databaseUrl: string): void {
const url = parseDatabaseUrl(databaseUrl);
for (const [name] of url.searchParams) {
if (CONNECTION_STRING_TLS_PARAMETERS.includes(name.toLowerCase())) {
throw new DatabaseTransportError("DATABASE_TLS_CONNECTION_STRING_CONFLICT");
}
}
}
/**
* Translates the validated policy into the exact pinned-`pg` options that achieve it, and asserts
* the URL cannot override them.
*
* `verify-full` is **not** simply `ssl: true` or `{ rejectUnauthorized: true }`. Verified directly
* against a live TLS PostgreSQL instance: those verify the certificate *chain*, but `pg` only sets
* `options.servername` for non-IP hosts (`pg/lib/connection.js`), and Node performs no identity
* check at all when `servername` is unset — so a certificate issued for an entirely different name
* is accepted when connecting to an IP address. Supplying an explicit `checkServerIdentity` pinned
* to the configured host closes that gap for DNS and IP hosts alike (proven: a certificate valid
* only for `localhost` is rejected with `ERR_TLS_CERT_ALTNAME_INVALID` when reached via
* `127.0.0.1`).
*/
export function databaseTlsConnectionOptions(
databaseUrl: string,
policy: DatabaseTransportPolicy,
): false | ConnectionOptions {
assertNoConnectionStringTlsParameters(databaseUrl);
if (policy.mode === "disable") {
return false;
}
const host = databaseHostFromUrl(databaseUrl);
return {
...(policy.certificateAuthority === undefined ? {} : { ca: policy.certificateAuthority }),
// Chain verification. There is no configuration that can set this to `false`.
rejectUnauthorized: true,
// Identity verification against the host actually being connected to — never the SNI value pg
// may or may not have set, and never skipped for an IP endpoint.
checkServerIdentity: (_servername: string, certificate: tls.PeerCertificate) =>
tls.checkServerIdentity(host, certificate),
};
}
/**
* The one production guard every executable database path shares: a production deployment must use
* `verify-full`, and its URL must not carry TLS parameters. There is no production plaintext
* exception — not for loopback, not for an RFC1918 address, not for a Docker service name. A
* production process that genuinely runs beside its database still gets certificate-verified TLS,
* which costs nothing and removes an entire class of "it was only internal" misconfiguration.
*/
export function assertProductionDatabaseTransport(
databaseUrl: string,
policy: DatabaseTransportPolicy,
environment: DatabaseTransportEnvironment,
): void {
assertNoConnectionStringTlsParameters(databaseUrl);
if (environment !== "production") {
return;
}
if (policy.mode !== "verify-full") {
throw new DatabaseTransportError("DATABASE_TLS_REQUIRED_IN_PRODUCTION");
}
}
/** A fixed, generic description of the effective transport for diagnostics. Never includes the
* URL, host, port, database name, credentials, certificate, or CA path. */
export function describeDatabaseTransport(policy: DatabaseTransportPolicy): string {
return policy.mode === "verify-full"
? `TLS required with certificate and hostname verification${
policy.certificateAuthority === undefined ? "" : " (explicit private CA supplied)"
}.`
: "TLS disabled (development/test plaintext).";
}
export { isLoopbackDatabaseHost };
+1 -1
View File
@@ -13,7 +13,7 @@ const sections: readonly DoctorSection[] = Object.freeze([
section("Platform", ["platform.runtime"]),
section("Modules", ["modules.discovery", "modules.dependencies", "modules.permissions"]),
section("Data definitions", ["schemas.discovery", "migrations.discovery"]),
section("PostgreSQL", ["postgresql.connection", "postgresql.plan"]),
section("PostgreSQL", ["database.transport", "postgresql.connection", "postgresql.plan"]),
section("Identity", ["identity.configuration", "identity.client-address"]),
section("Object storage", ["object-storage.integration"]),
]);
+61
View File
@@ -7,6 +7,14 @@ import {
} from "@ekklesia/contracts";
import { getTableName } from "drizzle-orm";
import { type PermissionRegistry, PermissionRegistryError } from "../authorization/index.js";
import {
assertProductionDatabaseTransport,
type DatabaseTransportEnvironment,
type DatabaseTransportPolicyInput,
DatabaseTransportError,
createDatabaseTransportPolicy,
describeDatabaseTransport,
} from "../database/transport.js";
import {
type ClientAddressConfigInput,
ClientAddressConfigError,
@@ -41,6 +49,7 @@ import {
} from "../modules/index.js";
export type DoctorCheckId =
| "database.transport"
| "platform.runtime"
| "modules.discovery"
| "modules.dependencies"
@@ -78,6 +87,10 @@ export interface DoctorIdentityConfigurationOptions {
export interface DoctorOptions {
readonly clientAddress?: ClientAddressConfigInput | undefined;
/** The environment the executable resolved, used only for transport policy evaluation; identity
* configuration keeps its own `identityConfiguration.environment` for the same purpose. */
readonly databaseEnvironment?: DatabaseTransportEnvironment | undefined;
readonly databaseTransport?: DatabaseTransportPolicyInput | undefined;
readonly databaseUrl?: string | undefined;
readonly identityConfiguration?: DoctorIdentityConfigurationOptions | undefined;
readonly moduleDiscovery: ModuleDiscoveryOptions;
@@ -417,6 +430,41 @@ function identityConfigurationCheck(
* combination is a `failure`, distinguishing the three states this pass's audit specifically calls
* for: safe direct mode, explicitly configured proxy mode, and an invalid configuration.
*/
/**
* Pure configuration validation only: never opens a connection, and never prints the database URL,
* host, port, database name, credentials, certificate, or CA material. An unsafe production
* transport is a blocking `failure`, not a warning — a production deployment that would reach
* PostgreSQL without certificate-verified TLS is not "ready with warnings".
*/
function databaseTransportCheck(
input: DatabaseTransportPolicyInput | undefined,
databaseUrl: string | undefined,
environment: DatabaseTransportEnvironment | undefined,
): DoctorCheck {
const effectiveEnvironment = environment ?? "production";
try {
const policy = createDatabaseTransportPolicy(input, { environment: effectiveEnvironment });
if (typeof databaseUrl === "string" && databaseUrl.trim() !== "") {
// Also rejects a URL carrying TLS parameters that could override the policy.
assertProductionDatabaseTransport(databaseUrl, policy, effectiveEnvironment);
}
return freezeCheck(
"database.transport",
"pass",
policy.mode === "verify-full"
? "Database TLS verified"
: "Database TLS disabled (development)",
[describeDatabaseTransport(policy)],
);
} catch (error) {
const code =
error instanceof DatabaseTransportError ? error.code : "DATABASE_TRANSPORT_INVALID";
return freezeCheck("database.transport", "failure", "Database transport unsafe", [
`[${code}] The configured database transport is not permitted.`,
]);
}
}
function clientAddressCheck(input: ClientAddressConfigInput | undefined): DoctorCheck {
try {
const config = createClientAddressConfig(input, TRUSTED_CLIENT_ADDRESS_HEADER);
@@ -580,9 +628,16 @@ export async function diagnoseEkklesia(
);
} else {
try {
// Doctor's own read-only connection uses the exact same validated transport policy every
// other executable does, so a Doctor "connection established" can never mean something
// weaker than what `pnpm api:start` or `pnpm migrations:apply` would use.
const doctorTransport = createDatabaseTransportPolicy(options.databaseTransport, {
environment: options.databaseEnvironment ?? "production",
});
const database = dependencies.createMigrationDatabase(databaseUrl, {
connectionTimeoutMs: doctorPostgresTimeoutMs,
operationTimeoutMs: doctorPostgresTimeoutMs,
transport: doctorTransport,
});
const plan = await dependencies.planMigrations({ aggregate: migrations, database });
postgresConnectionCheck = freezeCheck(
@@ -598,6 +653,11 @@ export async function diagnoseEkklesia(
const identityCheck = identityConfigurationCheck(options.identityConfiguration);
const clientAddressDoctorCheck = clientAddressCheck(options.clientAddress);
const transportCheck = databaseTransportCheck(
options.databaseTransport,
options.databaseUrl,
options.databaseEnvironment,
);
const storageCheck = freezeCheck("object-storage.integration", "skipped", "Check unavailable", [
"Core storage integration has not been implemented yet.",
@@ -610,6 +670,7 @@ export async function diagnoseEkklesia(
permissionsCheck,
schemaCheck,
migrationCheck,
transportCheck,
postgresConnectionCheck,
postgresPlanCheck,
identityCheck,
+142 -20
View File
@@ -18,12 +18,108 @@ export type IdentityConfigErrorCode =
| "TRUSTED_ORIGINS_MISSING";
const MIN_SECRET_LENGTH = 32;
const LOOPBACK_HOSTNAMES: ReadonlySet<string> = new Set([
"localhost",
"127.0.0.1",
"::1",
"0.0.0.0",
]);
/**
* Hostnames that are never a legitimate public production origin, matched exactly (after WHATWG
* URL canonicalization, which already folds `127.1`, `2130706433`, and `0x7f000001` into
* `127.0.0.1`, and lowercases every hostname).
*
* This is a purely *syntactic* classifier. It rejects literal and reserved loopback/unspecified
* spellings; it performs no DNS resolution, so it cannot and does not prove that some arbitrary
* public name will never resolve to a loopback address later. Network reachability remains the
* deployment's own firewall/DNS responsibility.
*/
const IPV4_LOOPBACK_BLOCK = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/u;
const UNSPECIFIED_HOSTNAMES: ReadonlySet<string> = new Set(["0.0.0.0", "[::]"]);
const LITERAL_LOOPBACK_HOSTNAMES: ReadonlySet<string> = new Set(["localhost"]);
/** Expands a bracketed IPv6 `URL.hostname` into its 8 canonical 16-bit groups, or `undefined` when
* the value is not a bracketed IPv6 literal. Handles `::` zero-compression and the mixed
* `::ffff:a.b.c.d` notation the WHATWG parser preserves. */
function expandIpv6Hostname(hostname: string): readonly number[] | undefined {
if (!hostname.startsWith("[") || !hostname.endsWith("]")) {
return undefined;
}
let body = hostname.slice(1, -1);
// Mixed notation: translate a trailing dotted-quad into two hex groups.
const dotted = /^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u.exec(body);
if (dotted) {
const octets = [dotted[2], dotted[3], dotted[4], dotted[5]].map((part) => Number(part));
if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {
return undefined;
}
const high = ((octets[0] as number) << 8) | (octets[1] as number);
const low = ((octets[2] as number) << 8) | (octets[3] as number);
body = `${dotted[1]}${high.toString(16)}:${low.toString(16)}`;
}
const [head, tail, ...extra] = body.split("::");
if (extra.length > 0) {
return undefined;
}
const parseGroups = (value: string | undefined): number[] | undefined => {
if (value === undefined || value === "") {
return [];
}
const groups: number[] = [];
for (const part of value.split(":")) {
if (!/^[0-9a-f]{1,4}$/u.test(part)) {
return undefined;
}
groups.push(Number.parseInt(part, 16));
}
return groups;
};
const leading = parseGroups(head);
const trailing = tail === undefined ? [] : parseGroups(tail);
if (!leading || !trailing) {
return undefined;
}
if (tail === undefined) {
return leading.length === 8 ? leading : undefined;
}
const missing = 8 - leading.length - trailing.length;
if (missing < 0) {
return undefined;
}
return [...leading, ...Array.from({ length: missing }, () => 0), ...trailing];
}
/** Whether a canonicalized `URL.hostname` is a loopback or unspecified listen address in any
* spelling this repository accepts — literal name, reserved `.localhost` namespace, the full IPv4
* `127.0.0.0/8` block, IPv6 `::1` compressed or expanded, IPv6 `::` unspecified, and IPv4-mapped
* IPv6 forms of both in mixed (`::ffff:127.0.0.1`) and hexadecimal (`::ffff:7f00:1`) notation. */
function isLoopbackOrUnspecifiedHostname(hostname: string): boolean {
const normalized = hostname.toLowerCase();
if (LITERAL_LOOPBACK_HOSTNAMES.has(normalized) || UNSPECIFIED_HOSTNAMES.has(normalized)) {
return true;
}
// RFC 6761 reserves the entire `.localhost` namespace for loopback.
if (normalized.endsWith(".localhost")) {
return true;
}
if (IPV4_LOOPBACK_BLOCK.test(normalized)) {
return true;
}
const groups = expandIpv6Hostname(normalized);
if (!groups) {
return false;
}
const isAllZero = groups.every((group) => group === 0);
// `::` (unspecified) and `::1` (loopback).
if (isAllZero || (groups.slice(0, 7).every((group) => group === 0) && groups[7] === 1)) {
return true;
}
// IPv4-mapped IPv6 (`::ffff:a.b.c.d`): classify the embedded IPv4 address.
const isMapped = groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff;
if (isMapped) {
const high = groups[6] as number;
const low = groups[7] as number;
const embedded = `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;
return IPV4_LOOPBACK_BLOCK.test(embedded) || embedded === "0.0.0.0";
}
return false;
}
const errorMessages: Readonly<Record<IdentityConfigErrorCode, string>> = Object.freeze({
BASE_URL_INSECURE_IN_PRODUCTION: "The identity base URL must use https in production.",
@@ -90,20 +186,38 @@ export interface CreateIdentityConfigOptions {
readonly environment?: IdentityEnvironment;
}
function isLoopbackHostname(hostname: string): boolean {
return LOOPBACK_HOSTNAMES.has(hostname.toLowerCase());
}
function parseAbsoluteHttpUrl(value: unknown): URL | undefined {
/**
* Parses one value that must be exactly a canonical absolute `http:`/`https:` **origin** — the
* single representation both the identity base URL and every trusted origin use, so no component
* of the platform can reinterpret the same deployment differently.
*
* Canonical means `URL.origin` must equal the configured string byte-for-byte. That one comparison
* structurally rejects every non-origin component at once — credentials, any path (including a
* bare trailing `/`, since `URL.origin` is slashless), a query, a fragment, surrounding
* whitespace, an uppercase hostname, and a redundant default port — because the WHATWG parser
* normalizes or preserves each of those in a way that no longer matches `origin`.
*
* Structural parsing is deliberately separate from environment policy: a caller distinguishes
* "this is not an origin" from "this origin is not allowed in production" and reports the
* structural code first, so an already-malformed URL is never mislabeled as a production-loopback
* failure.
*/
function parseCanonicalHttpOrigin(value: unknown): URL | undefined {
if (typeof value !== "string" || value.length === 0) {
return undefined;
}
let url: URL;
try {
const url = new URL(value);
return url.protocol === "http:" || url.protocol === "https:" ? url : undefined;
url = new URL(value);
} catch {
return undefined;
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
return undefined;
}
// `URL.origin` carries no credentials, path, query, or fragment, and is already lowercased with
// any default port elided — so requiring exact equality is the whole canonical-origin rule.
return url.origin === value ? url : undefined;
}
function validateSecret(secret: unknown): string {
@@ -126,7 +240,11 @@ function validateBaseUrl(baseUrl: unknown, environment: IdentityEnvironment): st
if (typeof baseUrl !== "string" || baseUrl.length === 0) {
throw new IdentityConfigError("BASE_URL_MISSING");
}
const url = parseAbsoluteHttpUrl(baseUrl);
// Structural validity first, in every environment: the base URL is the public origin of the
// already-fixed `/api/auth` transport, and Ekklesia does not support mounting Better Auth
// beneath a configurable URL path. A credentialed, pathed, queried, fragmented, whitespace-
// padded, or otherwise non-canonical spelling is structurally invalid, never a policy failure.
const url = parseCanonicalHttpOrigin(baseUrl);
if (!url) {
throw new IdentityConfigError("BASE_URL_INVALID");
}
@@ -134,11 +252,13 @@ function validateBaseUrl(baseUrl: unknown, environment: IdentityEnvironment): st
if (url.protocol !== "https:") {
throw new IdentityConfigError("BASE_URL_INSECURE_IN_PRODUCTION");
}
if (isLoopbackHostname(url.hostname)) {
if (isLoopbackOrUnspecifiedHostname(url.hostname)) {
throw new IdentityConfigError("BASE_URL_LOOPBACK_IN_PRODUCTION");
}
}
return baseUrl;
// Store the canonical origin — identical to what `validateTrustedOrigin` stores — so CORS,
// Better Auth's own origin checks, and this base URL can never disagree about the same origin.
return url.origin;
}
function validateTrustedOrigin(origin: unknown, environment: IdentityEnvironment): string {
@@ -152,19 +272,21 @@ function validateTrustedOrigin(origin: unknown, environment: IdentityEnvironment
if (origin.includes("*") || origin.includes("?")) {
throw new IdentityConfigError("TRUSTED_ORIGIN_WILDCARD_UNSUPPORTED");
}
const url = parseAbsoluteHttpUrl(origin);
if (!url || url.origin !== origin) {
const url = parseCanonicalHttpOrigin(origin);
if (!url) {
throw new IdentityConfigError("TRUSTED_ORIGIN_INVALID");
}
if (environment === "production") {
if (url.protocol !== "https:") {
throw new IdentityConfigError("TRUSTED_ORIGIN_INSECURE_IN_PRODUCTION");
}
if (isLoopbackHostname(url.hostname)) {
// The identical classifier the base URL uses, so the two can never disagree about whether the
// same host is a production-legal origin.
if (isLoopbackOrUnspecifiedHostname(url.hostname)) {
throw new IdentityConfigError("TRUSTED_ORIGIN_LOOPBACK_IN_PRODUCTION");
}
}
return origin;
return url.origin;
}
/**
+13
View File
@@ -1,5 +1,9 @@
import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
import { Pool, type PoolConfig } from "pg";
import {
type DatabaseTransportPolicy,
databaseTlsConnectionOptions,
} from "../database/transport.js";
import { identityAdapterSchema } from "./schema.js";
export type IdentityDrizzleDatabase = NodePgDatabase<typeof identityAdapterSchema>;
@@ -28,6 +32,10 @@ export interface IdentityDatabaseOptions {
* indefinitely. `connectionTimeoutMs` alone only bounds establishing a connection — it does
* nothing once a query is already running on one. */
readonly operationTimeoutMs?: number;
/** The validated transport policy (`core/src/database/transport.js`). Passed explicitly by
* every production executable; omitted by single-domain unit/integration factories that use
* the disposable loopback database, which keeps the pre-existing plaintext behavior. */
readonly transport?: DatabaseTransportPolicy;
}
export interface IdentityDatabaseHandle {
@@ -81,8 +89,13 @@ export function createIdentityDrizzleDatabase(
const validatedConnectionString = validateConnectionString(connectionString);
const validatedConnectionTimeoutMs = validateTimeout(options.connectionTimeoutMs);
const validatedOperationTimeoutMs = validateTimeout(options.operationTimeoutMs);
const ssl =
options.transport === undefined
? undefined
: databaseTlsConnectionOptions(validatedConnectionString, options.transport);
const poolConfig: PoolConfig = {
connectionString: validatedConnectionString,
...(ssl === undefined ? {} : { ssl }),
...(validatedConnectionTimeoutMs === undefined
? {}
: { connectionTimeoutMillis: validatedConnectionTimeoutMs }),
+16
View File
@@ -1,4 +1,8 @@
import { Client, type ClientConfig, type QueryResultRow } from "pg";
import {
type DatabaseTransportPolicy,
databaseTlsConnectionOptions,
} from "../database/transport.js";
import type {
AppliedMigrationRecord,
MigrationDatabase,
@@ -76,6 +80,10 @@ export class PostgresMigrationDatabaseError extends Error {
export interface PostgresMigrationDatabaseOptions {
readonly connectionTimeoutMs?: number;
readonly operationTimeoutMs?: number;
/** The validated transport policy (`core/src/database/transport.js`). Every production executable
* that plans or applies migrations passes one; omitting it keeps the pre-existing plaintext
* behavior used by the disposable loopback PostgreSQL harness. */
readonly transport?: DatabaseTransportPolicy;
}
interface HistoryExistenceRow extends QueryResultRow {
@@ -178,8 +186,16 @@ function createClientConfig(
"The PostgreSQL operation timeout is invalid.",
);
// Also rejects a URL carrying its own TLS parameters, so `pg`'s connection-string precedence
// can never silently replace this policy with a weaker one.
const ssl =
options?.transport === undefined
? undefined
: databaseTlsConnectionOptions(connectionString, options.transport);
return {
connectionString,
...(ssl === undefined ? {} : { ssl }),
...(validatedConnectionTimeoutMs === undefined
? {}
: { connectionTimeoutMillis: validatedConnectionTimeoutMs }),