171 lines
5.5 KiB
TypeScript
171 lines
5.5 KiB
TypeScript
import "server-only";
|
|
|
|
import { drizzleAdapter } from "@better-auth/drizzle-adapter";
|
|
import { betterAuth, type BetterAuthOptions } from "better-auth";
|
|
|
|
import { env } from "@/config/env";
|
|
import { db } from "@/db/client";
|
|
import { accounts, sessions, users, verifications } from "@/db/schema";
|
|
import { mailer } from "@/modules/mail/mailer";
|
|
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 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<BetterAuthOptions["rateLimit"]>;
|
|
|
|
export function createPortalAuth({
|
|
database,
|
|
mailerService,
|
|
registrationRepository,
|
|
}: {
|
|
database: NonNullable<BetterAuthOptions["database"]>;
|
|
mailerService: Pick<typeof mailer, "sendPasswordReset" | "sendVerification">;
|
|
registrationRepository: ReturnType<typeof createEditorialRegistrationRepository>;
|
|
}) {
|
|
let registrationService: ReturnType<typeof createRegistrationService> | 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,
|
|
},
|
|
},
|
|
},
|
|
emailAndPassword: {
|
|
enabled: true,
|
|
requireEmailVerification: true,
|
|
autoSignIn: false,
|
|
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) {
|
|
return registrationRepository.canCreateSession(session.userId);
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
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" },
|
|
});
|
|
},
|
|
},
|
|
repo: registrationRepository,
|
|
audit: registrationRepository,
|
|
});
|
|
|
|
return { auth, registrationService };
|
|
}
|
|
|
|
const registrationRepository = createEditorialRegistrationRepository(db);
|
|
const portalAuth = createPortalAuth({
|
|
database: drizzleAdapter(db, {
|
|
provider: "pg",
|
|
schema: {
|
|
user: users,
|
|
account: accounts,
|
|
session: sessions,
|
|
verification: verifications,
|
|
},
|
|
}),
|
|
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,
|
|
});
|