import "server-only"; import { APIError } from "better-auth"; import { createAuthMiddleware, getSessionFromCtx } from "better-auth/api"; import { drizzleAdapter } from "@better-auth/drizzle-adapter"; import { betterAuth, type BetterAuthOptions } from "better-auth"; import { twoFactor } from "better-auth/plugins"; import { env } from "@/config/env"; import { db } from "@/db/client"; import { accounts, sessions, twoFactors, users, verifications } from "@/db/schema"; import { mailer } from "@/modules/mail/mailer"; import { validatePasswordPolicy, MIN_PASSWORD_LENGTH, } from "@/modules/security/password-policy"; import { consumeRateLimit, registrationPolicy } from "@/modules/security/rate-limit"; import { enforceRateLimit, hashedRequestIdentity, type ConsumeRateLimit, } from "@/modules/security/rate-limit-guard"; import { createEditorialRegistrationRepository, createRegistrationService, type RegistrationInput, } from "./registration"; export const MFA_SESSION_TOKEN_PREFIX = "mfa-"; const mfaVerificationPaths = new Set([ "/two-factor/verify-totp", "/two-factor/verify-backup-code", ]); export const portalAuthRateLimitOptions = { enabled: true, storage: "memory", window: 60, max: 100, customRules: { "/sign-in/email": { window: 15 * 60, max: 5 }, "/request-password-reset": { window: 60 * 60, max: 5 }, "/reset-password": { window: 60 * 60, max: 5 }, "/send-verification-email": { window: 60 * 60, max: 5 }, }, } satisfies NonNullable; export function createPortalAuth({ database, mailerService, registrationRepository, }: { database: NonNullable; mailerService: Pick; registrationRepository: ReturnType; }) { let registrationService: ReturnType | undefined; const auth = betterAuth({ baseURL: env.BETTER_AUTH_URL, secret: env.BETTER_AUTH_SECRET, database, rateLimit: portalAuthRateLimitOptions, // All id columns are typed `uuid`; Better Auth's default id generator emits // a nanoid-style string that Postgres rejects with "invalid input syntax // for type uuid". Generate real UUIDs so inserts (signUp, sessions, // verifications) match the schema. advanced: { database: { generateId: () => crypto.randomUUID() }, // The reverse proxy must overwrite this header; see docs/operations.md. ipAddress: { ipAddressHeaders: ["x-forwarded-for", "x-real-ip"] }, }, // `role` is a custom column on `users` (portalRole enum: ADMIN | EDITORIAL). // Better Auth's parseUserOutput filters the session user to declared fields // only, so without this the drizzle adapter selects `role` but it is then // stripped from session.user — requireAdmin and the root redirect saw // role === undefined and misrouted/blocked every admin. Declaring it makes // Better Auth return it; input:false keeps it unsettable on signUp (the DB // default / admin seed owns it), defaultValue matches the column default so // inserts never send null into the NOT NULL enum column. user: { additionalFields: { role: { type: "string", required: false, defaultValue: "EDITORIAL", input: false, }, twoFactorEnabled: { type: "boolean", required: false, defaultValue: false, input: false, }, }, }, plugins: [ twoFactor({ // TOTP + backup codes only. Expire new trust-device records immediately. trustDeviceMaxAge: 0, }), ], hooks: { before: createAuthSecurityHook(), after: createAuthMiddleware(async (ctx) => { if (ctx.path !== "/two-factor/disable" || !ctx.context.newSession) return; const { session, user } = ctx.context.newSession; const sessions = await ctx.context.internalAdapter.listSessions(user.id); const otherTokens = sessions.filter(({ token }) => token !== session.token).map(({ token }) => token); if (otherTokens.length > 0) await ctx.context.internalAdapter.deleteSessions(otherTokens); }), }, emailAndPassword: { enabled: true, requireEmailVerification: true, autoSignIn: false, minPasswordLength: MIN_PASSWORD_LENGTH, resetPasswordTokenExpiresIn: 60 * 60, revokeSessionsOnPasswordReset: true, async sendResetPassword({ user, url }) { await mailerService.sendPasswordReset({ to: user.email, resetUrl: url }); }, }, emailVerification: { sendOnSignUp: false, autoSignInAfterVerification: false, expiresIn: 60 * 60, async sendVerificationEmail({ user, url }) { await mailerService.sendVerification({ to: user.email, verificationUrl: url }); }, async afterEmailVerification(user) { if (!registrationService) { throw new Error("Registration service is unavailable."); } await registrationService.onEmailVerified(user.id); }, }, databaseHooks: { session: { create: { async before(session, ctx) { if (!(await registrationRepository.canCreateSession(session.userId))) return false; // These endpoints issue a new session only after verifying the factor. if (ctx?.path && mfaVerificationPaths.has(ctx.path)) { return { data: { ...session, token: MFA_SESSION_TOKEN_PREFIX + session.token } }; } }, }, }, }, }); registrationService = createRegistrationService({ auth: { async signUpEmail({ email, name, password }) { return auth.api.signUpEmail({ body: { email, name, password } }); }, async sendVerificationEmail({ email }) { await auth.api.sendVerificationEmail({ body: { email, callbackURL: "/registrieren/bestaetigt?schritt=freigabe" }, }); }, }, repo: registrationRepository, audit: registrationRepository, }); return { auth, registrationService }; } function createAuthSecurityHook() { // Applies the shared policy to password-reset and change-password flows, // which bypass the registration validation. Registration is covered by // validateRegistration(); sign-up additionally enforces Better Auth's // minPasswordLength. return createAuthMiddleware(async (ctx) => { if (ctx.path?.startsWith("/two-factor/") && !mfaVerificationPaths.has(ctx.path)) { const current = await getSessionFromCtx(ctx); if ((current?.user as { twoFactorEnabled?: boolean } | undefined)?.twoFactorEnabled && !current?.session.token.startsWith(MFA_SESSION_TOKEN_PREFIX)) { throw new APIError("UNAUTHORIZED"); } } if (ctx.path !== "/reset-password" && ctx.path !== "/change-password") { return; } const body = (ctx.body ?? {}) as { newPassword?: unknown; password?: unknown }; const candidate = typeof body.newPassword === "string" ? body.newPassword : typeof body.password === "string" ? body.password : undefined; if (candidate === undefined) { return; } const result = validatePasswordPolicy(candidate); if (!result.ok) { throw new APIError("BAD_REQUEST", { message: result.reason }); } }); } const registrationRepository = createEditorialRegistrationRepository(db); const portalAuth = createPortalAuth({ database: drizzleAdapter(db, { provider: "pg", schema: { user: users, account: accounts, session: sessions, verification: verifications, twoFactor: twoFactors, }, }), mailerService: mailer, registrationRepository, }); export const auth = portalAuth.auth; export const registrationService = portalAuth.registrationService; export function createRegistrationIngress({ register, consumeRateLimit: consume, }: { register(input: RegistrationInput): Promise<{ status: "pending_email" }>; consumeRateLimit: ConsumeRateLimit; }) { return async function registrationIngress(input: RegistrationInput, headers = new Headers()) { await enforceRateLimit( consume, hashedRequestIdentity("registration", input.email, headers), registrationPolicy, ); return register(input); }; } export const registerEditorial = createRegistrationIngress({ register: (input) => registrationService.register(input), consumeRateLimit, });