feat: establish core identity foundation
CI / verify (pull_request) Successful in 25s
CI / infrastructure-smoke (pull_request) Successful in 12s
CI / migration-smoke (pull_request) Successful in 22s

Adds Core-owned identity contracts, a Core-owned Better Auth database schema
(ekklesia_core_user/session/account/verification), a first-class Core-owned
migration source that coexists with module-owned migrations under the exact
existing migration system, and an explicit Better Auth construction boundary.
No authentication endpoint or sign-in UI is exposed yet (ADR 0010).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
This commit is contained in:
ekklesia
2026-07-21 16:39:15 -05:00
co-authored by Claude Sonnet 5
parent df0f20d8af
commit 679a5d225c
43 changed files with 4259 additions and 64 deletions
+184
View File
@@ -0,0 +1,184 @@
export type IdentityEnvironment = "development" | "production";
export type IdentityConfigErrorCode =
| "BASE_URL_INSECURE_IN_PRODUCTION"
| "BASE_URL_INVALID"
| "BASE_URL_LOOPBACK_IN_PRODUCTION"
| "BASE_URL_MISSING"
| "SECRET_LOW_ENTROPY"
| "SECRET_MISSING"
| "SECRET_TOO_SHORT"
| "TRUSTED_ORIGIN_INSECURE_IN_PRODUCTION"
| "TRUSTED_ORIGIN_INVALID"
| "TRUSTED_ORIGIN_LOOPBACK_IN_PRODUCTION"
| "TRUSTED_ORIGIN_WILDCARD_UNSUPPORTED"
| "TRUSTED_ORIGINS_EMPTY"
| "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",
]);
const errorMessages: Readonly<Record<IdentityConfigErrorCode, string>> = Object.freeze({
BASE_URL_INSECURE_IN_PRODUCTION: "The identity base URL must use https in production.",
BASE_URL_INVALID: "The identity base URL must be an absolute http or https URL.",
BASE_URL_LOOPBACK_IN_PRODUCTION:
"The identity base URL must not resolve to a loopback host in production.",
BASE_URL_MISSING: "The identity base URL is required.",
SECRET_LOW_ENTROPY: "The identity secret does not have sufficient entropy.",
SECRET_MISSING: "The identity secret is required.",
SECRET_TOO_SHORT: `The identity secret must be at least ${MIN_SECRET_LENGTH} characters.`,
TRUSTED_ORIGIN_INSECURE_IN_PRODUCTION: "Trusted origins must use https in production.",
TRUSTED_ORIGIN_INVALID:
"Every trusted origin must be an absolute http or https origin with no path, query, or fragment.",
TRUSTED_ORIGIN_LOOPBACK_IN_PRODUCTION:
"Trusted origins must not resolve to a loopback host in production.",
TRUSTED_ORIGIN_WILDCARD_UNSUPPORTED:
"Wildcard trusted origins are not supported in this release.",
TRUSTED_ORIGINS_EMPTY: "At least one trusted origin is required.",
TRUSTED_ORIGINS_MISSING: "Trusted origins are required.",
});
/**
* Never carries the offending secret, URL, origin, hostname, or any other caller-supplied value.
* Only a stable code and a fixed, generic message are ever exposed.
*/
export class IdentityConfigError extends Error {
readonly code: IdentityConfigErrorCode;
constructor(code: IdentityConfigErrorCode) {
super(errorMessages[code]);
this.name = "IdentityConfigError";
this.code = code;
this.stack = `${this.name}: ${this.message}`;
Object.freeze(this);
}
}
export interface IdentityConfig {
readonly baseUrl: string;
readonly secret: string;
readonly trustedOrigins: readonly string[];
}
export interface IdentityConfigInput {
readonly baseUrl?: unknown;
readonly secret?: unknown;
readonly trustedOrigins?: unknown;
}
export interface CreateIdentityConfigOptions {
/** Defaults to "production" so an omitted environment never silently relaxes validation. */
readonly environment?: IdentityEnvironment;
}
function isLoopbackHostname(hostname: string): boolean {
return LOOPBACK_HOSTNAMES.has(hostname.toLowerCase());
}
function parseAbsoluteHttpUrl(value: unknown): URL | undefined {
if (typeof value !== "string" || value.length === 0) {
return undefined;
}
try {
const url = new URL(value);
return url.protocol === "http:" || url.protocol === "https:" ? url : undefined;
} catch {
return undefined;
}
}
function validateSecret(secret: unknown): string {
if (typeof secret !== "string" || secret.length === 0) {
throw new IdentityConfigError("SECRET_MISSING");
}
if (secret.length < MIN_SECRET_LENGTH) {
throw new IdentityConfigError("SECRET_TOO_SHORT");
}
// A narrow, deterministic guard against trivially degenerate secrets (e.g. one repeated
// character). It cannot measure true entropy; operators remain responsible for generating a
// high-entropy value (for example `openssl rand -base64 32`).
if (/^(.)\1*$/u.test(secret)) {
throw new IdentityConfigError("SECRET_LOW_ENTROPY");
}
return secret;
}
function validateBaseUrl(baseUrl: unknown, environment: IdentityEnvironment): string {
if (typeof baseUrl !== "string" || baseUrl.length === 0) {
throw new IdentityConfigError("BASE_URL_MISSING");
}
const url = parseAbsoluteHttpUrl(baseUrl);
if (!url) {
throw new IdentityConfigError("BASE_URL_INVALID");
}
if (environment === "production") {
if (url.protocol !== "https:") {
throw new IdentityConfigError("BASE_URL_INSECURE_IN_PRODUCTION");
}
if (isLoopbackHostname(url.hostname)) {
throw new IdentityConfigError("BASE_URL_LOOPBACK_IN_PRODUCTION");
}
}
return baseUrl;
}
function validateTrustedOrigin(origin: unknown, environment: IdentityEnvironment): string {
if (typeof origin !== "string" || origin.length === 0) {
throw new IdentityConfigError("TRUSTED_ORIGIN_INVALID");
}
// Better Auth itself supports glob-style wildcard trusted origins. Phase 4A deliberately does
// not: cross-subdomain cookies are not enabled yet (see ADR 0010), so a wildcard origin would
// widen the trusted-origin surface without a matching cookie-scope decision. Revisit only
// alongside a future ADR that enables cross-subdomain cookies.
if (origin.includes("*") || origin.includes("?")) {
throw new IdentityConfigError("TRUSTED_ORIGIN_WILDCARD_UNSUPPORTED");
}
const url = parseAbsoluteHttpUrl(origin);
if (!url || url.origin !== origin) {
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)) {
throw new IdentityConfigError("TRUSTED_ORIGIN_LOOPBACK_IN_PRODUCTION");
}
}
return origin;
}
function validateTrustedOrigins(
trustedOrigins: unknown,
environment: IdentityEnvironment,
): readonly string[] {
if (trustedOrigins === undefined || trustedOrigins === null) {
throw new IdentityConfigError("TRUSTED_ORIGINS_MISSING");
}
if (!Array.isArray(trustedOrigins) || trustedOrigins.length === 0) {
throw new IdentityConfigError("TRUSTED_ORIGINS_EMPTY");
}
return Object.freeze(trustedOrigins.map((origin) => validateTrustedOrigin(origin, environment)));
}
/**
* Validates explicit, typed identity configuration. Performs no environment reads, network
* calls, or database access; callers are responsible for sourcing `input` (for example from
* environment variables) before calling this function.
*/
export function createIdentityConfig(
input: IdentityConfigInput,
options: CreateIdentityConfigOptions = {},
): IdentityConfig {
const environment = options.environment ?? "production";
const secret = validateSecret(input.secret);
const baseUrl = validateBaseUrl(input.baseUrl, environment);
const trustedOrigins = validateTrustedOrigins(input.trustedOrigins, environment);
return Object.freeze({ baseUrl, secret, trustedOrigins });
}
+69
View File
@@ -0,0 +1,69 @@
import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
import { Pool, type PoolConfig } from "pg";
import { identityAdapterSchema } from "./schema.js";
export type IdentityDrizzleDatabase = NodePgDatabase<typeof identityAdapterSchema>;
export type IdentityDatabaseErrorCode = "IDENTITY_DATABASE_CONFIGURATION_INVALID";
/** Never carries the offending connection string, host, or underlying driver error. */
export class IdentityDatabaseError extends Error {
readonly code: IdentityDatabaseErrorCode;
constructor(code: IdentityDatabaseErrorCode) {
super("Identity database configuration is invalid.");
this.name = "IdentityDatabaseError";
this.code = code;
this.stack = `${this.name}: ${this.message}`;
Object.freeze(this);
}
}
export interface IdentityDatabaseOptions {
readonly connectionTimeoutMs?: number;
}
export interface IdentityDatabaseHandle {
readonly close: () => Promise<void>;
readonly db: IdentityDrizzleDatabase;
}
function validateConnectionString(connectionString: string): string {
if (connectionString.trim().length === 0) {
throw new IdentityDatabaseError("IDENTITY_DATABASE_CONFIGURATION_INVALID");
}
let protocol: string;
try {
protocol = new URL(connectionString).protocol;
} catch {
throw new IdentityDatabaseError("IDENTITY_DATABASE_CONFIGURATION_INVALID");
}
if (protocol !== "postgres:" && protocol !== "postgresql:") {
throw new IdentityDatabaseError("IDENTITY_DATABASE_CONFIGURATION_INVALID");
}
return connectionString;
}
/**
* Explicitly constructs the Core-owned Drizzle database instance used by the identity factory.
* Building the `pg.Pool` performs no network I/O until a query is issued, and this function is
* only ever invoked by explicit caller code — never during module import.
*/
export function createIdentityDrizzleDatabase(
connectionString: string,
options: IdentityDatabaseOptions = {},
): IdentityDatabaseHandle {
const validatedConnectionString = validateConnectionString(connectionString);
const poolConfig: PoolConfig = { connectionString: validatedConnectionString };
if (options.connectionTimeoutMs !== undefined) {
poolConfig.connectionTimeoutMillis = options.connectionTimeoutMs;
}
const pool = new Pool(poolConfig);
const db = drizzle(pool, { schema: identityAdapterSchema });
return Object.freeze({
close: () => pool.end(),
db,
});
}
+58
View File
@@ -0,0 +1,58 @@
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import type { IdentityConfig } from "./config.js";
import type { IdentityDrizzleDatabase } from "./database.js";
import { identityAdapterSchema } from "./schema.js";
export type IdentityConstructionErrorCode = "IDENTITY_CONSTRUCTION_FAILED";
/** Never carries the underlying Better Auth error, cause, stack, secret, or URL. */
export class IdentityConstructionError extends Error {
readonly code: IdentityConstructionErrorCode;
constructor() {
super("Identity could not be constructed.");
this.name = "IdentityConstructionError";
this.code = "IDENTITY_CONSTRUCTION_FAILED";
this.stack = `${this.name}: ${this.message}`;
Object.freeze(this);
}
}
export interface CreateIdentityAuthOptions {
readonly config: IdentityConfig;
readonly db: IdentityDrizzleDatabase;
}
/**
* Deliberately opaque: Phase 4A never exposes the Better Auth instance, its HTTP handler, the
* injected database, or the Drizzle adapter beyond this module. A later HTTP transport slice
* decides what (if anything) becomes reachable outside core/src/identity.
*/
export interface EkklesiaIdentityInstance {
readonly constructed: true;
}
/**
* Core's Better Auth composition boundary. Constructs Better Auth explicitly from injected,
* already-validated configuration and an injected Drizzle database — it never reads environment
* variables, never resolves a connection string, and enables no provider or plugin beyond the
* four core models required for the identity schema itself.
*/
export function createIdentityAuth(options: CreateIdentityAuthOptions): EkklesiaIdentityInstance {
try {
betterAuth({
baseURL: options.config.baseUrl,
database: drizzleAdapter(options.db, {
provider: "pg",
schema: identityAdapterSchema,
}),
secret: options.config.secret,
trustedOrigins: [...options.config.trustedOrigins],
});
} catch {
throw new IdentityConstructionError();
}
return Object.freeze({ constructed: true });
}
+111
View File
@@ -0,0 +1,111 @@
import { relations } from "drizzle-orm";
import { boolean, index, pgTable, text, timestamp } from "drizzle-orm/pg-core";
/**
* Core-owned Better Auth schema for the four required core models: user, session, account,
* and verification. Table and index names are explicit and namespaced so ownership is
* unambiguous inside the shared public PostgreSQL schema. Columns, types, defaults, uniqueness,
* foreign keys, and delete behavior mirror the pinned [email protected] Drizzle/PostgreSQL
* generator output exactly (see docs/development/identity.md for the regeneration workflow).
*/
export const ekklesiaCoreUser = pgTable("ekklesia_core_user", {
id: text("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
emailVerified: boolean("email_verified").default(false).notNull(),
image: text("image"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.defaultNow()
.$onUpdate(() => new Date())
.notNull(),
});
export const ekklesiaCoreSession = pgTable(
"ekklesia_core_session",
{
id: text("id").primaryKey(),
expiresAt: timestamp("expires_at").notNull(),
token: text("token").notNull().unique(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.$onUpdate(() => new Date())
.notNull(),
ipAddress: text("ip_address"),
userAgent: text("user_agent"),
userId: text("user_id")
.notNull()
.references(() => ekklesiaCoreUser.id, { onDelete: "cascade" }),
},
(table) => [index("ekklesia_core_session_user_id_idx").on(table.userId)],
);
export const ekklesiaCoreAccount = pgTable(
"ekklesia_core_account",
{
id: text("id").primaryKey(),
accountId: text("account_id").notNull(),
providerId: text("provider_id").notNull(),
userId: text("user_id")
.notNull()
.references(() => ekklesiaCoreUser.id, { onDelete: "cascade" }),
accessToken: text("access_token"),
refreshToken: text("refresh_token"),
idToken: text("id_token"),
accessTokenExpiresAt: timestamp("access_token_expires_at"),
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
scope: text("scope"),
password: text("password"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.$onUpdate(() => new Date())
.notNull(),
},
(table) => [index("ekklesia_core_account_user_id_idx").on(table.userId)],
);
export const ekklesiaCoreVerification = pgTable(
"ekklesia_core_verification",
{
id: text("id").primaryKey(),
identifier: text("identifier").notNull(),
value: text("value").notNull(),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.defaultNow()
.$onUpdate(() => new Date())
.notNull(),
},
(table) => [index("ekklesia_core_verification_identifier_idx").on(table.identifier)],
);
export const ekklesiaCoreUserRelations = relations(ekklesiaCoreUser, ({ many }) => ({
accounts: many(ekklesiaCoreAccount),
sessions: many(ekklesiaCoreSession),
}));
export const ekklesiaCoreSessionRelations = relations(ekklesiaCoreSession, ({ one }) => ({
user: one(ekklesiaCoreUser, {
fields: [ekklesiaCoreSession.userId],
references: [ekklesiaCoreUser.id],
}),
}));
export const ekklesiaCoreAccountRelations = relations(ekklesiaCoreAccount, ({ one }) => ({
user: one(ekklesiaCoreUser, {
fields: [ekklesiaCoreAccount.userId],
references: [ekklesiaCoreUser.id],
}),
}));
/**
* Explicit mapping from Better Auth's logical core model names to Ekklesia's physical schema
* objects. Passed directly to the Drizzle adapter so table naming is never inferred by accident.
*/
export const identityAdapterSchema = {
account: ekklesiaCoreAccount,
session: ekklesiaCoreSession,
user: ekklesiaCoreUser,
verification: ekklesiaCoreVerification,
} as const;