feat: expose core identity transport
CI / verify (pull_request) Successful in 27s
CI / infrastructure-smoke (pull_request) Successful in 19s
CI / migration-smoke (pull_request) Successful in 26s

This commit is contained in:
ekklesia
2026-07-21 19:15:14 -05:00
parent 82fe338a8d
commit 91d8f5946f
33 changed files with 2672 additions and 224 deletions
+39
View File
@@ -0,0 +1,39 @@
{
"name": "@ekklesia/api",
"version": "0.1.0",
"private": true,
"type": "module",
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/app.d.ts",
"import": "./dist/app.js"
}
},
"scripts": {
"build": "tsc --project tsconfig.build.json",
"lint": "biome lint .",
"test": "vitest run",
"typecheck": "tsc --noEmit --project tsconfig.json"
},
"dependencies": {
"@ekklesia/contracts": "workspace:*",
"@ekklesia/core": "workspace:*",
"@hono/node-server": "2.0.10",
"hono": "4.12.31"
},
"devDependencies": {
"@biomejs/biome": "2.5.3",
"@ekklesia/typescript-config": "workspace:*",
"@types/node": "24.13.3",
"@types/pg": "8.20.0",
"pg": "8.22.0",
"typescript": "7.0.2",
"vitest": "4.1.10"
},
"ekklesia": {
"layer": "app"
}
}
+72
View File
@@ -0,0 +1,72 @@
import { isAuthenticatedPrincipal } from "@ekklesia/contracts";
import { type EkklesiaIdentityRuntime, IdentityRuntimeError } from "@ekklesia/core/identity";
import { Hono } from "hono";
import type { Context } from "hono";
import { cors } from "hono/cors";
export interface CreateApiAppOptions {
readonly runtime: EkklesiaIdentityRuntime;
/** Exact allowed browser origins. Never a wildcard; combined with `credentials: true`, only an
* exact, reflected match is ever returned in `Access-Control-Allow-Origin`. */
readonly trustedOrigins: readonly string[];
}
function sanitizedErrorResponse(c: Context, error: unknown, status: 500 | 503) {
const code = error instanceof IdentityRuntimeError ? error.code : "INTERNAL_ERROR";
c.header("Cache-Control", "no-store");
return c.json({ code }, status);
}
/**
* Pure Hono application factory: no I/O, no environment reads, no process side effects. Suitable
* for unit and integration tests via `app.fetch` directly, with a fully injected identity runtime
* standing in for real Better Auth/PostgreSQL where appropriate.
*/
export function createApiApp(options: CreateApiAppOptions): Hono {
const { runtime } = options;
const allowedOrigins = new Set(options.trustedOrigins);
const app = new Hono();
const corsMiddleware = cors({
allowHeaders: ["Content-Type"],
allowMethods: ["GET", "POST", "OPTIONS"],
credentials: true,
maxAge: 600,
origin: (origin) => (origin && allowedOrigins.has(origin) ? origin : undefined),
});
app.use("/api/auth/*", corsMiddleware);
app.use("/api/v1/*", corsMiddleware);
app.on(["POST", "GET"], "/api/auth/*", async (c) => {
try {
return await runtime.handleAuthRequest(c.req.raw);
} catch (error) {
return sanitizedErrorResponse(c, error, 500);
}
});
app.get("/api/v1/principal", async (c) => {
c.header("Cache-Control", "no-store");
c.header("Vary", "Origin, Cookie");
try {
const principal = await runtime.resolvePrincipal(c.req.raw.headers);
return c.json(
isAuthenticatedPrincipal(principal)
? { kind: "authenticated" as const, userId: principal.userId }
: { kind: "anonymous" as const },
200,
);
} catch (error) {
return sanitizedErrorResponse(c, error, 503);
}
});
app.notFound((c) => {
c.header("Cache-Control", "no-store");
return c.json({ code: "NOT_FOUND" }, 404);
});
app.onError((_error, c) => sanitizedErrorResponse(c, _error, 500));
return app;
}
+117
View File
@@ -0,0 +1,117 @@
import {
type CreateIdentityConfigOptions,
createIdentityConfig,
type IdentityConfig,
type IdentityConfigInput,
} from "@ekklesia/core/identity";
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 databaseUrl: string;
readonly host: string;
readonly identity: IdentityConfig;
readonly port: number;
}
export interface ApiRuntimeConfigInput {
readonly databaseUrl?: unknown;
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 },
);
return Object.freeze({ databaseUrl, host, identity, port });
}
+168
View File
@@ -0,0 +1,168 @@
import path from "node:path";
import { pathToFileURL } from "node:url";
import {
createIdentityDrizzleDatabase,
createIdentityRuntime,
type IdentityDatabaseHandle,
type IdentityRateLimitOverride,
} from "@ekklesia/core/identity";
import { serve, type ServerType } from "@hono/node-server";
import type { Hono } from "hono";
import { createApiApp } from "./app.js";
import { type ApiRuntimeConfig, createApiRuntimeConfig } from "./config.js";
const connectionTimeoutMs = 10_000;
export interface RunningApi {
readonly app: Hono;
readonly server: ServerType;
shutdown(): Promise<void>;
}
export interface StartApiOptions {
/** Test-only escape hatch: never set by the executable entry point. See
* `IdentityRateLimitOverride` for why production must leave this unset. */
readonly rateLimitOverride?: IdentityRateLimitOverride;
}
async function safeCloseDatabase(handle: IdentityDatabaseHandle): Promise<void> {
try {
await handle.close();
} catch {
// Cleanup failures are swallowed here deliberately: they must never mask a startup failure
// that is already propagating, and there is no raw driver detail safe to surface.
}
}
function bindServer(app: Hono, host: string, port: number): Promise<ServerType> {
return new Promise((resolve, reject) => {
let settled = false;
const server = serve({ fetch: app.fetch, hostname: host, port }, () => {
if (!settled) {
settled = true;
resolve(server);
}
});
server.once("error", () => {
if (!settled) {
settled = true;
reject(new Error("The API server failed to start listening."));
}
});
});
}
/**
* Explicit runtime composition: constructs the PostgreSQL pool and Drizzle database, the Core
* identity runtime, and the Hono application, then starts the Node HTTP server. Returns a handle
* with an idempotent `shutdown()` so both the executable entry point and tests can stop the
* server and close the database pool deterministically. Never applies migrations or generates
* schema — the database must already be migrated through `pnpm migrations:apply`.
*/
export async function startApi(
config: ApiRuntimeConfig,
options: StartApiOptions = {},
): Promise<RunningApi> {
const databaseHandle = createIdentityDrizzleDatabase(config.databaseUrl, {
connectionTimeoutMs,
});
let runtime: ReturnType<typeof createIdentityRuntime>;
try {
runtime = createIdentityRuntime({
config: config.identity,
db: databaseHandle.db,
...(options.rateLimitOverride ? { rateLimitOverride: options.rateLimitOverride } : {}),
});
} catch (error) {
await safeCloseDatabase(databaseHandle);
throw error;
}
const app = createApiApp({ runtime, trustedOrigins: config.identity.trustedOrigins });
let server: ServerType;
try {
server = await bindServer(app, config.host, config.port);
} catch (error) {
await safeCloseDatabase(databaseHandle);
throw error;
}
let shuttingDown = false;
const shutdown = async (): Promise<void> => {
if (shuttingDown) {
return;
}
shuttingDown = true;
await new Promise<void>((resolve) => {
server.close(() => resolve());
});
await safeCloseDatabase(databaseHandle);
};
return Object.freeze({ app, server, shutdown });
}
function readConfigFromEnvironment(): {
readonly input: Parameters<typeof createApiRuntimeConfig>[0];
readonly environment: "development" | "production";
} {
const trustedOriginsValue = process.env.EKKLESIA_IDENTITY_TRUSTED_ORIGINS;
const trustedOrigins = trustedOriginsValue
?.split(",")
.map((origin) => origin.trim())
.filter((origin) => origin.length > 0);
return {
environment: process.env.NODE_ENV === "development" ? "development" : "production",
input: {
databaseUrl: process.env.DATABASE_URL,
host: process.env.EKKLESIA_API_HOST,
identity: {
baseUrl: process.env.EKKLESIA_IDENTITY_BASE_URL,
secret: process.env.EKKLESIA_IDENTITY_SECRET,
trustedOrigins,
},
port: process.env.EKKLESIA_API_PORT,
},
};
}
export async function main(): Promise<void> {
const { environment, input } = readConfigFromEnvironment();
const config = createApiRuntimeConfig(input, { environment });
const running = await startApi(config);
const address = running.server.address();
const boundPort = address && typeof address === "object" ? address.port : config.port;
console.log(`Ekklesia API listening on ${config.host}:${boundPort}`);
let signalReceived = false;
const handleSignal = (): void => {
if (signalReceived) {
return;
}
signalReceived = true;
running
.shutdown()
.then(() => process.exit(0))
.catch(() => process.exit(1));
};
process.on("SIGINT", handleSignal);
process.on("SIGTERM", handleSignal);
}
function isDirectExecution(): boolean {
const entrypoint = process.argv[1];
return (
entrypoint !== undefined && import.meta.url === pathToFileURL(path.resolve(entrypoint)).href
);
}
if (isDirectExecution()) {
main().catch(() => {
console.error("Ekklesia API failed to start.");
process.exitCode = 1;
});
}
+631
View File
@@ -0,0 +1,631 @@
import { randomBytes } from "node:crypto";
import { fileURLToPath } from "node:url";
import path from "node:path";
import {
applyModuleMigrations,
createPostgresMigrationDatabase,
discoverAllMigrations,
} from "@ekklesia/core/migrations";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { Client, type QueryResultRow } from "pg";
import { afterAll, describe, expect, it } from "vitest";
import { createApiRuntimeConfig } from "../src/config.js";
import { startApi, type RunningApi } from "../src/server.js";
const integrationDatabaseUrlEnvironment = "EKKLESIA_MIGRATION_TEST_DATABASE_URL";
const coreMigrationsDirectory = path.join(
path.dirname(fileURLToPath(import.meta.url)),
"..",
"..",
"..",
"core",
"drizzle",
);
const trackedDatabases = new Set<string>();
let databaseCounter = 0;
class IntegrationHarnessError extends Error {
constructor(message: string) {
super(message);
this.name = "IntegrationHarnessError";
this.stack = `${this.name}: ${this.message}`;
}
}
function harnessError(message: string): IntegrationHarnessError {
return new IntegrationHarnessError(message);
}
function baseDatabaseUrl(): string {
const value = process.env[integrationDatabaseUrlEnvironment];
if (typeof value !== "string" || value.trim() === "") {
throw harnessError("The API integration database is not configured.");
}
try {
const parsed = new URL(value);
if (parsed.protocol !== "postgres:" && parsed.protocol !== "postgresql:") {
throw new TypeError("Unsupported protocol.");
}
} catch {
throw harnessError("The API integration database configuration is invalid.");
}
return value;
}
function quoteDatabaseName(databaseName: string): string {
if (!/^[a-z][a-z0-9_]{0,62}$/u.test(databaseName)) {
throw harnessError("The generated integration database name is invalid.");
}
return `"${databaseName}"`;
}
function makeDatabaseName(label: string): string {
const safeLabel = label
.toLowerCase()
.replaceAll(/[^a-z0-9]+/gu, "_")
.replaceAll(/^_+|_+$/gu, "")
.slice(0, 14);
databaseCounter += 1;
return `ekk_api_${process.pid}_${databaseCounter}_${safeLabel || "scenario"}_${randomBytes(4).toString("hex")}`;
}
function databaseUrl(databaseName: string): string {
const parsed = new URL(baseDatabaseUrl());
parsed.pathname = `/${databaseName}`;
parsed.searchParams.delete("application_name");
return parsed.toString();
}
async function openAdministrativeClient(connectionString: string): Promise<Client> {
const client = new Client({ connectionString });
client.on("error", () => undefined);
try {
await client.connect();
return client;
} catch {
try {
await client.end();
} catch {
// The public harness failure remains static when connection cleanup also fails.
}
throw harnessError("The API integration database connection failed.");
}
}
async function safeQuery<Row extends QueryResultRow>(
client: Client,
text: string,
values: unknown[] = [],
): Promise<readonly Row[]> {
try {
const result = await client.query<Row>(text, values);
return result.rows;
} catch {
throw harnessError("An integration database administration operation failed.");
}
}
async function safeEnd(client: Client): Promise<void> {
try {
await client.end();
} catch {
throw harnessError("An integration database connection could not be closed.");
}
}
async function createDatabase(databaseName: string): Promise<void> {
const admin = await openAdministrativeClient(baseDatabaseUrl());
try {
await safeQuery(admin, `CREATE DATABASE ${quoteDatabaseName(databaseName)} TEMPLATE template0`);
} finally {
await safeEnd(admin);
}
}
async function dropDatabase(databaseName: string): Promise<void> {
const admin = await openAdministrativeClient(baseDatabaseUrl());
try {
await safeQuery(
admin,
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()",
[databaseName],
);
await safeQuery(
admin,
`DROP DATABASE IF EXISTS ${quoteDatabaseName(databaseName)} WITH (FORCE)`,
);
trackedDatabases.delete(databaseName);
} finally {
await safeEnd(admin);
}
}
async function activeConnectionCount(databaseName: string): Promise<number> {
const admin = await openAdministrativeClient(baseDatabaseUrl());
try {
const rows = await safeQuery<{ count: string }>(
admin,
"SELECT count(*)::text AS count FROM pg_stat_activity WHERE datname = $1",
[databaseName],
);
return Number(rows[0]?.count ?? "0");
} finally {
await safeEnd(admin);
}
}
async function createDisposableDatabase(label: string): Promise<{ name: string; url: string }> {
const name = makeDatabaseName(label);
await createDatabase(name);
trackedDatabases.add(name);
return { name, url: databaseUrl(name) };
}
async function applyCoreMigrations(url: string): Promise<void> {
const emptyModulesDirectory = await mkdtemp(path.join(tmpdir(), "ekklesia-api-no-modules-"));
try {
const aggregate = await discoverAllMigrations({
coreMigrationsDirectory,
moduleDiscovery: {
moduleSdkVersion: "0.1.0",
modulesDirectory: emptyModulesDirectory,
platformVersion: "0.1.0",
},
});
// Phase 4A's committed migration must not have drifted while building this transport slice.
expect(aggregate.migrations.map((entry) => entry.identity)).toEqual([
"core:0000_identity_core_tables",
]);
expect(aggregate.migrations[0]?.checksum).toBe(
"f8f2086ef06f7a6943e8ffc4350bb010b37aed04c0a72030d2b153c986b1325f",
);
await applyModuleMigrations({ aggregate, database: createPostgresMigrationDatabase(url) });
} finally {
await rm(emptyModulesDirectory, { recursive: true, force: true });
}
}
afterAll(async () => {
for (const databaseName of [...trackedDatabases]) {
await dropDatabase(databaseName).catch(() => undefined);
}
});
const identityBaseUrl = "https://identity.example.test";
const dashboardOrigin = "https://dashboard.example.test";
const untrustedOrigin = "https://evil.example.test";
function apiOrigin(running: RunningApi): string {
const address = running.server.address();
if (!address || typeof address !== "object") {
throw harnessError("The API integration server has no bound address.");
}
return `http://127.0.0.1:${address.port}`;
}
async function startMigratedApi(url: string): Promise<RunningApi> {
const config = createApiRuntimeConfig(
{
databaseUrl: url,
host: "127.0.0.1",
identity: {
baseUrl: identityBaseUrl,
secret: "integration-test-secret-0123456789abcdefgh",
trustedOrigins: [identityBaseUrl, dashboardOrigin],
},
port: 0,
},
{ environment: "production" },
);
// A narrow, explicit test-only override: production composition (server.ts's `main`) never
// sets this. Better Auth's built-in sign-in/sign-up rate limit (3 requests / 10s) would
// otherwise reject this suite's many sequential requests.
return startApi(config, { rateLimitOverride: { max: 1000, window: 1 } });
}
function setCookieValue(response: Response): string | undefined {
return response.headers.get("set-cookie") ?? undefined;
}
function firstCookiePair(setCookieHeader: string): string {
return setCookieHeader.split(",")[0]?.split(";")[0]?.trim() ?? "";
}
interface SignUpResult {
readonly response: Response;
readonly body: { token: string | null; user: { id: string; email: string } };
}
async function signUp(
origin: string,
email: string,
password: string,
headers: Record<string, string> = {},
): Promise<SignUpResult> {
const response = await fetch(`${origin}/api/auth/sign-up/email`, {
body: JSON.stringify({ email, name: "Integration Test User", password }),
headers: { "content-type": "application/json", ...headers },
method: "POST",
});
return { body: (await response.clone().json()) as SignUpResult["body"], response };
}
interface SignInResult {
readonly cookiePair: string | undefined;
readonly response: Response;
}
async function signIn(
origin: string,
email: string,
password: string,
headers: Record<string, string> = {},
): Promise<SignInResult> {
const response = await fetch(`${origin}/api/auth/sign-in/email`, {
body: JSON.stringify({ email, password }),
headers: {
"content-type": "application/json",
origin: dashboardOrigin,
...headers,
},
method: "POST",
});
const setCookie = setCookieValue(response);
return { cookiePair: setCookie ? firstCookiePair(setCookie) : undefined, response };
}
async function fetchPrincipal(
origin: string,
headers: Record<string, string> = {},
): Promise<{ body: unknown; response: Response }> {
const response = await fetch(`${origin}/api/v1/principal`, { headers });
return { body: await response.clone().json(), response };
}
describe.sequential("live API — signup, sign-in, principal, sign-out", () => {
let database: { name: string; url: string };
let running: RunningApi;
let origin: string;
const emailOne = "[email protected]";
const emailTwo = "[email protected]";
const password = "correct horse battery staple";
it("applies migrations and starts the API against a freshly migrated database", async () => {
database = await createDisposableDatabase("signup_flow");
await applyCoreMigrations(database.url);
running = await startMigratedApi(database.url);
origin = apiOrigin(running);
expect(running.server.listening).toBe(true);
});
it("returns the anonymous principal shape before any sign-in", async () => {
const { body, response } = await fetchPrincipal(origin);
expect(response.status).toBe(200);
expect(body).toEqual({ kind: "anonymous" });
});
it("publicly creates the first ordinary identity via sign-up, with no automatic session (autoSignIn: false)", async () => {
const { body, response } = await signUp(origin, emailOne, password);
expect(response.status).toBe(200);
expect(body.token).toBeNull();
expect(body.user.email).toBe(emailOne);
expect(setCookieValue(response)).toBeUndefined();
});
it("does not sign in automatically after sign-up", async () => {
const { body } = await fetchPrincipal(origin);
expect(body).toEqual({ kind: "anonymous" });
});
it("rejects wrong credentials without leaking raw internal information", async () => {
const { response } = await signIn(origin, emailOne, "wrong password entirely");
const text = await response.text();
expect(response.status).toBe(401);
expect(text).not.toContain(database.url);
expect(text).not.toContain("postgres");
expect(text.toLowerCase()).not.toContain("stack");
});
let sessionCookie: string;
it("signs in explicitly and returns a valid, host-only, HttpOnly, SameSite=Lax, secure session cookie", async () => {
const { cookiePair, response } = await signIn(origin, emailOne, password);
const setCookie = setCookieValue(response);
expect(response.status).toBe(200);
expect(setCookie).toBeDefined();
expect(cookiePair).toBeDefined();
sessionCookie = cookiePair as string;
const cookieText = setCookie as string;
expect(cookieText).toContain("HttpOnly");
expect(cookieText).toContain("SameSite=Lax");
expect(cookieText).toContain("Secure");
expect(cookieText).not.toMatch(/domain=/iu);
});
it("resolves the authenticated principal containing only kind and the opaque user id", async () => {
const { body, response } = await fetchPrincipal(origin, { cookie: sessionCookie });
expect(response.status).toBe(200);
expect(body).toMatchObject({ kind: "authenticated" });
const record = body as Record<string, unknown>;
expect(Object.keys(record).sort()).toEqual(["kind", "userId"]);
expect(typeof record.userId).toBe("string");
});
it("resolves a malformed cookie as anonymous rather than failing", async () => {
const { body, response } = await fetchPrincipal(origin, {
cookie: "better-auth.session_token=not-a-real-token",
});
expect(response.status).toBe(200);
expect(body).toEqual({ kind: "anonymous" });
});
it("resolves a nonexistent cookie name as anonymous", async () => {
const { body, response } = await fetchPrincipal(origin, { cookie: "unrelated=value" });
expect(response.status).toBe(200);
expect(body).toEqual({ kind: "anonymous" });
});
it("does not create a second identity on duplicate sign-up, and does not leak unstable internal details", async () => {
const { body, response } = await signUp(origin, emailOne, "a totally different password");
expect(response.status).toBe(200);
expect(body.token).toBeNull();
expect(typeof body.user.id).toBe("string");
});
it("keeps exactly one user row for the duplicated email after the duplicate sign-up attempt", async () => {
const admin = await openAdministrativeClient(database.url);
try {
const rows = await safeQuery<{ count: string }>(
admin,
'select count(*)::text as count from "ekklesia_core_user" where email = $1',
[emailOne],
);
expect(rows[0]?.count).toBe("1");
} finally {
await safeEnd(admin);
}
});
it("signs out and invalidates the session", async () => {
const response = await fetch(`${origin}/api/auth/sign-out`, {
body: "{}",
headers: {
"content-type": "application/json",
cookie: sessionCookie,
origin: dashboardOrigin,
},
method: "POST",
});
expect(response.status).toBe(200);
expect(setCookieValue(response)).toBeDefined();
});
it("resolves the old cookie as anonymous after sign-out", async () => {
const { body, response } = await fetchPrincipal(origin, { cookie: sessionCookie });
expect(response.status).toBe(200);
expect(body).toEqual({ kind: "anonymous" });
});
let secondUserId: string;
it("registers and signs in a second, distinct public account", async () => {
const signUpResult = await signUp(origin, emailTwo, password);
expect(signUpResult.response.status).toBe(200);
const signInResult = await signIn(origin, emailTwo, password);
expect(signInResult.response.status).toBe(200);
expect(signInResult.cookiePair).toBeDefined();
const { body } = await fetchPrincipal(origin, {
cookie: signInResult.cookiePair as string,
});
const record = body as { kind: string; userId: string };
expect(record.kind).toBe("authenticated");
secondUserId = record.userId;
expect(secondUserId).toBeTruthy();
});
it("gives the first and second account identical principal shapes with no elevation", async () => {
const first = await signIn(origin, emailOne, password);
const { body: firstBody } = await fetchPrincipal(origin, {
cookie: first.cookiePair as string,
});
const second = await signIn(origin, emailTwo, password);
const { body: secondBody } = await fetchPrincipal(origin, {
cookie: second.cookiePair as string,
});
expect(Object.keys(firstBody as object).sort()).toEqual(
Object.keys(secondBody as object).sort(),
);
expect((firstBody as { kind: string }).kind).toBe((secondBody as { kind: string }).kind);
});
it("gives neither account owner, role, permission, membership, or volunteer data at the database level", async () => {
const admin = await openAdministrativeClient(database.url);
try {
const columns = await safeQuery<{ column_name: string }>(
admin,
"select column_name from information_schema.columns where table_schema = 'public' and table_name = 'ekklesia_core_user'",
);
const columnNames = columns.map((row) => row.column_name);
for (const forbidden of [
"role",
"is_admin",
"is_owner",
"is_staff",
"is_volunteer",
"is_member",
"permissions",
"grants",
]) {
expect(columnNames).not.toContain(forbidden);
}
} finally {
await safeEnd(admin);
}
});
it("never stores a plaintext password", async () => {
const admin = await openAdministrativeClient(database.url);
try {
const rows = await safeQuery<{ password: string | null }>(
admin,
`select a.password from "ekklesia_core_account" a
inner join "ekklesia_core_user" u on u.id = a.user_id
where u.email = $1`,
[emailOne],
);
const stored = rows[0]?.password;
expect(stored).toBeTruthy();
expect(stored).not.toBe(password);
expect(stored?.length ?? 0).toBeGreaterThan(password.length);
} finally {
await safeEnd(admin);
}
});
it("supports a server-to-server sign-up request that carries no Origin header at all", async () => {
const { response } = await signUp(origin, "[email protected]", password);
expect(response.status).toBe(200);
});
it("allows a trusted browser origin for the principal route with credentials", async () => {
const response = await fetch(`${origin}/api/v1/principal`, {
headers: { cookie: sessionCookie, origin: dashboardOrigin },
});
expect(response.status).toBe(200);
expect(response.headers.get("access-control-allow-origin")).toBe(dashboardOrigin);
expect(response.headers.get("access-control-allow-credentials")).toBe("true");
});
it("never returns Access-Control-Allow-Origin for an untrusted browser origin", async () => {
const principalResponse = await fetch(`${origin}/api/v1/principal`, {
headers: { origin: untrustedOrigin },
});
expect(principalResponse.headers.get("access-control-allow-origin")).toBeNull();
});
it("leaves Better Auth's handler unavailable outside /api/auth/*", async () => {
const response = await fetch(`${origin}/sign-in/email`, { method: "POST" });
expect(response.status).toBe(404);
});
it("shuts down cleanly, closing the HTTP listener and the PostgreSQL pool", async () => {
await running.shutdown();
await expect(fetch(origin, { signal: AbortSignal.timeout(1_000) })).rejects.toBeTruthy();
const remainingConnections = await activeConnectionCount(database.name);
expect(remainingConnections).toBe(0);
await dropDatabase(database.name);
});
});
// Better Auth's own server-side rejection of a cookie-bearing state-changing request from an
// untrusted origin (403 INVALID_ORIGIN) was verified directly and repeatedly against this exact
// pinned release and this exact compiled `apps/api` server — signup, sign-in, then a sign-out
// attempt with the valid session cookie and an untrusted Origin header reliably returns 403, and
// the presented session remains valid afterward — but only when driven by a plain Node script
// against the running server. The identical scenario could not be made to reproduce reliably when
// driven through Vitest specifically (the rejection silently does not fire), even in a single
// isolated test with its own fresh database and API instance, and even with `NODE_ENV` forced to
// `"production"` inside the test process. The cause was not pinned down to a documented,
// reproducible contract inside the time available for this slice, so no automated assertion is
// made for this specific request shape here rather than commit a flaky or misleading test. What
// *is* covered by an automated test above is the layer this repository's own code owns: CORS
// never returns `Access-Control-Allow-Origin` for an untrusted origin, which is the actual
// browser-enforced boundary preventing a malicious page from reading a response. See ADR 0011 for
// the full account, including the exact manual reproduction used.
describe.sequential("live API — startup and migration guarantees", () => {
it("does not create any tables or migration history when started against an unmigrated database", async () => {
const database = await createDisposableDatabase("unmigrated");
try {
const config = createApiRuntimeConfig(
{
databaseUrl: database.url,
host: "127.0.0.1",
identity: {
baseUrl: identityBaseUrl,
secret: "integration-test-secret-0123456789abcdefgh",
trustedOrigins: [identityBaseUrl],
},
port: 0,
},
{ environment: "production" },
);
const running = await startApi(config, { rateLimitOverride: { max: 1000, window: 1 } });
const origin = apiOrigin(running);
try {
// A request that touches the (nonexistent) identity tables fails, but must not repair
// or create anything. The exact failure body is not asserted here (Better Auth's
// internal-error shape for this case is not a stable public contract); only that it is
// not a successful sign-up.
const response = await fetch(`${origin}/api/auth/sign-up/email`, {
body: JSON.stringify({
email: "[email protected]",
name: "Integration Test User",
password: "correct horse battery staple",
}),
headers: { "content-type": "application/json" },
method: "POST",
});
expect(response.status).not.toBe(200);
} finally {
await running.shutdown();
}
const admin = await openAdministrativeClient(database.url);
try {
const rows = await safeQuery<{ count: string }>(
admin,
"select count(*)::text as count from information_schema.tables where table_schema = 'public'",
);
expect(rows[0]?.count).toBe("0");
} finally {
await safeEnd(admin);
}
} finally {
await dropDatabase(database.name);
}
});
});
describe.sequential("live API — principal infrastructure failure is never downgraded to anonymous", () => {
it("returns a sanitized failure, not a false anonymous 200, when the database becomes unreachable mid-session", async () => {
const database = await createDisposableDatabase("infra_failure");
await applyCoreMigrations(database.url);
const running = await startMigratedApi(database.url);
const origin = apiOrigin(running);
await signUp(origin, "[email protected]", "correct horse battery staple");
const { cookiePair } = await signIn(
origin,
"[email protected]",
"correct horse battery staple",
);
expect(cookiePair).toBeDefined();
// Force the database itself unreachable out from under the running API pool.
await dropDatabase(database.name);
const { body, response } = await fetchPrincipal(origin, { cookie: cookiePair as string });
expect(response.status).toBe(503);
expect(body).toEqual({ code: "PRINCIPAL_RESOLUTION_FAILED" });
await running.shutdown().catch(() => undefined);
});
});
+167
View File
@@ -0,0 +1,167 @@
import { ANONYMOUS_PRINCIPAL, createAuthenticatedPrincipal } from "@ekklesia/contracts";
import type { EkklesiaIdentityRuntime } from "@ekklesia/core/identity";
import { IdentityRuntimeError } from "@ekklesia/core/identity";
import { describe, expect, it, vi } from "vitest";
import { createApiApp } from "../src/app.js";
const trustedOrigin = "https://dashboard.example.test";
const untrustedOrigin = "https://evil.example.test";
function fakeRuntime(overrides: Partial<EkklesiaIdentityRuntime> = {}): EkklesiaIdentityRuntime {
return {
handleAuthRequest: vi.fn().mockResolvedValue(new Response("auth-ok", { status: 200 })),
resolvePrincipal: vi.fn().mockResolvedValue(ANONYMOUS_PRINCIPAL),
...overrides,
};
}
describe("Ekklesia API Hono application", () => {
it("mounts Better Auth exactly under /api/auth/*", async () => {
const runtime = fakeRuntime();
const app = createApiApp({ runtime, trustedOrigins: [trustedOrigin] });
const response = await app.request("/api/auth/sign-in/email", { method: "POST" });
expect(response.status).toBe(200);
expect(await response.text()).toBe("auth-ok");
expect(runtime.handleAuthRequest).toHaveBeenCalledTimes(1);
});
it("does not route requests outside /api/auth/* to Better Auth", async () => {
const runtime = fakeRuntime();
const app = createApiApp({ runtime, trustedOrigins: [trustedOrigin] });
const response = await app.request("/sign-in/email", { method: "POST" });
expect(response.status).toBe(404);
expect(runtime.handleAuthRequest).not.toHaveBeenCalled();
});
it("returns the anonymous principal shape with no-store caching", async () => {
const runtime = fakeRuntime({
resolvePrincipal: vi.fn().mockResolvedValue(ANONYMOUS_PRINCIPAL),
});
const app = createApiApp({ runtime, trustedOrigins: [trustedOrigin] });
const response = await app.request("/api/v1/principal");
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ kind: "anonymous" });
expect(response.headers.get("cache-control")).toBe("no-store");
expect(response.headers.get("vary")).toContain("Cookie");
});
it("returns the authenticated principal shape containing only kind and userId", async () => {
const runtime = fakeRuntime({
resolvePrincipal: vi.fn().mockResolvedValue(createAuthenticatedPrincipal("user_123")),
});
const app = createApiApp({ runtime, trustedOrigins: [trustedOrigin] });
const response = await app.request("/api/v1/principal");
const body = (await response.json()) as Record<string, unknown>;
expect(response.status).toBe(200);
expect(body).toEqual({ kind: "authenticated", userId: "user_123" });
expect(Object.keys(body).sort()).toEqual(["kind", "userId"]);
});
it("returns a stable sanitized 503 when principal resolution fails, never a false anonymous 200", async () => {
const runtime = fakeRuntime({
resolvePrincipal: vi
.fn()
.mockRejectedValue(new IdentityRuntimeError("PRINCIPAL_RESOLUTION_FAILED")),
});
const app = createApiApp({ runtime, trustedOrigins: [trustedOrigin] });
const response = await app.request("/api/v1/principal");
expect(response.status).toBe(503);
expect(await response.json()).toEqual({ code: "PRINCIPAL_RESOLUTION_FAILED" });
expect(response.headers.get("cache-control")).toBe("no-store");
});
it("returns a stable sanitized 500 for an unexpected auth-handler failure, never a raw message", async () => {
const runtime = fakeRuntime({
handleAuthRequest: vi.fn().mockRejectedValue(new Error("postgresql://admin:secret@db/x")),
});
const app = createApiApp({ runtime, trustedOrigins: [trustedOrigin] });
const response = await app.request("/api/auth/sign-in/email", { method: "POST" });
const body = await response.json();
expect(response.status).toBe(500);
expect(body).toEqual({ code: "INTERNAL_ERROR" });
expect(JSON.stringify(body)).not.toContain("secret");
expect(JSON.stringify(body)).not.toContain("postgresql://");
});
it("has deterministic 404 behavior for an unknown route", async () => {
const app = createApiApp({ runtime: fakeRuntime(), trustedOrigins: [trustedOrigin] });
const response = await app.request("/does-not-exist");
expect(response.status).toBe(404);
expect(await response.json()).toEqual({ code: "NOT_FOUND" });
});
it("reflects an allowed origin in Access-Control-Allow-Origin with credentials support", async () => {
const app = createApiApp({ runtime: fakeRuntime(), trustedOrigins: [trustedOrigin] });
const response = await app.request("/api/v1/principal", {
headers: { origin: trustedOrigin },
});
expect(response.headers.get("access-control-allow-origin")).toBe(trustedOrigin);
expect(response.headers.get("access-control-allow-credentials")).toBe("true");
});
it("never returns Access-Control-Allow-Origin for a disallowed origin", async () => {
const app = createApiApp({ runtime: fakeRuntime(), trustedOrigins: [trustedOrigin] });
const response = await app.request("/api/v1/principal", {
headers: { origin: untrustedOrigin },
});
expect(response.headers.get("access-control-allow-origin")).toBeNull();
});
it("supports requests with no Origin header at all (native/server clients)", async () => {
const app = createApiApp({ runtime: fakeRuntime(), trustedOrigins: [trustedOrigin] });
const response = await app.request("/api/v1/principal");
expect(response.status).toBe(200);
});
it("handles preflight OPTIONS requests deterministically for an allowed origin", async () => {
const app = createApiApp({ runtime: fakeRuntime(), trustedOrigins: [trustedOrigin] });
const response = await app.request("/api/v1/principal", {
headers: {
"access-control-request-method": "GET",
origin: trustedOrigin,
},
method: "OPTIONS",
});
expect(response.status).toBe(204);
expect(response.headers.get("access-control-allow-origin")).toBe(trustedOrigin);
});
it("never wildcards Access-Control-Allow-Origin", async () => {
const app = createApiApp({ runtime: fakeRuntime(), trustedOrigins: [trustedOrigin] });
const response = await app.request("/api/v1/principal", {
headers: { origin: trustedOrigin },
});
expect(response.headers.get("access-control-allow-origin")).not.toBe("*");
});
// "No generalized session/user object stored in Hono context" is verified by construction
// rather than by a black-box context probe: unlike Better Auth's own documented Hono example
// (which hydrates `c.set("user", session.user)` on every request), createApiApp never calls
// `c.set` at all — the only per-request identity data that ever exists is the narrow
// EkklesiaPrincipal returned directly from the /api/v1/principal handler above, whose exact
// shape (kind + userId only) is already asserted by the principal-shape tests in this file.
});
+151
View File
@@ -0,0 +1,151 @@
import { describe, expect, it } from "vitest";
import { ApiConfigError, createApiRuntimeConfig } from "../src/config.js";
const validSecret = "correct-horse-battery-staple-0123456789";
function validInput() {
return {
databaseUrl: "postgresql://ekklesia:[email protected]:5432/ekklesia",
host: "127.0.0.1",
identity: {
baseUrl: "https://identity.example.test",
secret: validSecret,
trustedOrigins: ["https://identity.example.test"],
},
port: 3000,
};
}
describe("API runtime configuration", () => {
it("accepts valid API and identity configuration", () => {
const config = createApiRuntimeConfig(validInput(), { environment: "production" });
expect(config).toEqual({
databaseUrl: validInput().databaseUrl,
host: "127.0.0.1",
identity: {
baseUrl: "https://identity.example.test",
secret: validSecret,
trustedOrigins: ["https://identity.example.test"],
},
port: 3000,
});
expect(Object.isFrozen(config)).toBe(true);
});
it("defaults host to loopback and port to 3000 when omitted", () => {
const { host: _host, port: _port, ...rest } = validInput();
const config = createApiRuntimeConfig(rest, { environment: "production" });
expect(config.host).toBe("127.0.0.1");
expect(config.port).toBe(3000);
});
it("permits an explicit non-loopback bind address", () => {
const config = createApiRuntimeConfig(
{ ...validInput(), host: "0.0.0.0" },
{ environment: "production" },
);
expect(config.host).toBe("0.0.0.0");
});
it("rejects a missing database URL", () => {
let captured: unknown;
try {
createApiRuntimeConfig({ ...validInput(), databaseUrl: undefined });
} catch (error) {
captured = error;
}
expect(captured).toBeInstanceOf(ApiConfigError);
expect(captured).toMatchObject({ code: "DATABASE_URL_MISSING" });
});
it("rejects an invalid database URL", () => {
for (const databaseUrl of ["", "not-a-url", "mysql://example.test/db", "http://example.test"]) {
let captured: unknown;
try {
createApiRuntimeConfig({ ...validInput(), databaseUrl });
} catch (error) {
captured = error;
}
expect(captured).toBeInstanceOf(ApiConfigError);
}
});
it("rejects an empty listen host", () => {
let captured: unknown;
try {
createApiRuntimeConfig({ ...validInput(), host: "" });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "HOST_INVALID" });
});
it("rejects an invalid listen port", () => {
for (const port of [-1, 1.5, 70_000, Number.NaN, "not-a-port"]) {
let captured: unknown;
try {
createApiRuntimeConfig({ ...validInput(), port });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "PORT_INVALID" });
}
});
it("accepts port 0 as an explicit request for an OS-assigned ephemeral port", () => {
const config = createApiRuntimeConfig({ ...validInput(), port: 0 });
expect(config.port).toBe(0);
});
it("delegates identity validation to Core's createIdentityConfig, rejecting a short secret", () => {
let captured: unknown;
try {
createApiRuntimeConfig({
...validInput(),
identity: { ...validInput().identity, secret: "too-short" },
});
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "SECRET_TOO_SHORT" });
});
it("explicitly allows local development origins only when environment is development", () => {
const config = createApiRuntimeConfig(
{
databaseUrl: validInput().databaseUrl,
host: "127.0.0.1",
identity: {
baseUrl: "http://localhost:3000",
secret: validSecret,
trustedOrigins: ["http://localhost:3000"],
},
port: 3000,
},
{ environment: "development" },
);
expect(config.identity.baseUrl).toBe("http://localhost:3000");
});
it("never leaks the database URL, secret, or trusted origins through a thrown error", () => {
const hostileUrl = "postgresql://admin:[email protected]:5432/ekklesia";
let captured: unknown;
try {
createApiRuntimeConfig({ ...validInput(), databaseUrl: hostileUrl, port: -1 });
} catch (error) {
captured = error;
}
expect(captured).toBeInstanceOf(ApiConfigError);
const publicText = `${String(captured)}\n${
captured instanceof Error ? (captured.stack ?? "") : ""
}\n${JSON.stringify(captured)}`;
expect(publicText).not.toContain(hostileUrl);
expect(publicText).not.toContain("s3cr3t");
expect(publicText).not.toContain("db.internal.example");
});
});
+75
View File
@@ -0,0 +1,75 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const poolConstructor = vi.hoisted(() => vi.fn());
const betterAuthMock = vi.hoisted(() => vi.fn());
const drizzleAdapterMock = vi.hoisted(() => vi.fn());
const serveMock = vi.hoisted(() => vi.fn());
const processOnSpy = vi.hoisted(() => vi.fn());
vi.mock("pg", () => ({ Pool: poolConstructor }));
vi.mock("better-auth", () => ({ betterAuth: betterAuthMock }));
vi.mock("better-auth/adapters/drizzle", () => ({ drizzleAdapter: drizzleAdapterMock }));
vi.mock("@hono/node-server", () => ({ serve: serveMock }));
describe("Ekklesia API import safety", () => {
const originalEnv = { ...process.env };
const originalProcessOn = process.on.bind(process);
beforeEach(() => {
poolConstructor.mockClear();
betterAuthMock.mockClear();
drizzleAdapterMock.mockClear();
serveMock.mockClear();
processOnSpy.mockClear();
for (const key of Object.keys(process.env)) {
if (!(key in originalEnv)) {
delete process.env[key];
}
}
process.env = { ...originalEnv };
process.on = originalProcessOn;
});
it("does not construct a database pool, Better Auth, or an HTTP server merely by importing the app factory", async () => {
await import("../src/app.js");
expect(poolConstructor).not.toHaveBeenCalled();
expect(betterAuthMock).not.toHaveBeenCalled();
expect(serveMock).not.toHaveBeenCalled();
});
it("does not construct a database pool, Better Auth, or an HTTP server merely by importing configuration", async () => {
await import("../src/config.js");
expect(poolConstructor).not.toHaveBeenCalled();
expect(betterAuthMock).not.toHaveBeenCalled();
expect(serveMock).not.toHaveBeenCalled();
});
it("does not read environment variables, connect to PostgreSQL, construct Better Auth, start a server, or install signal handlers merely by importing the executable server module", async () => {
// Deliberately leave every runtime-required environment variable unset. If importing this
// module performed any runtime composition, missing configuration would throw here.
delete process.env.DATABASE_URL;
delete process.env.EKKLESIA_IDENTITY_SECRET;
delete process.env.EKKLESIA_IDENTITY_BASE_URL;
delete process.env.EKKLESIA_IDENTITY_TRUSTED_ORIGINS;
const onSpy = vi.spyOn(process, "on").mockImplementation(processOnSpy);
await expect(import("../src/server.js")).resolves.toBeDefined();
expect(poolConstructor).not.toHaveBeenCalled();
expect(betterAuthMock).not.toHaveBeenCalled();
expect(drizzleAdapterMock).not.toHaveBeenCalled();
expect(serveMock).not.toHaveBeenCalled();
expect(processOnSpy).not.toHaveBeenCalled();
onSpy.mockRestore();
});
it("exposes startApi and main as explicit functions without invoking them at import time", async () => {
const module = await import("../src/server.js");
expect(typeof module.startApi).toBe("function");
expect(typeof module.main).toBe("function");
expect(serveMock).not.toHaveBeenCalled();
});
});
+14
View File
@@ -0,0 +1,14 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"noEmit": false,
"outDir": "dist",
"rootDir": "src",
"sourceMap": true,
"types": ["node"]
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.test.ts", "tests"]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "@ekklesia/typescript-config/node.json",
"compilerOptions": {
"noEmit": true,
"types": ["node", "vitest/globals"]
},
"include": ["src/**/*.ts", "tests/**/*.ts"]
}