fix: harden editorial registration flow

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 21:04:50 +02:00
1 parent 9b22752ef2
commit a8d4e54ffb
8 files changed
+398 -62

No files matched your search

+5 -2
View File
@@ -3,7 +3,10 @@ import { redirect } from "next/navigation";
import { env } from "@/config/env";
import { registerEditorial } from "@/modules/auth/auth";
import { RegistrationValidationError } from "@/modules/auth/registration";
import {
CURRENT_TERMS_VERSION,
RegistrationValidationError,
} from "@/modules/auth/registration";
import {
RegistrationForm,
type RegistrationFormState,
@@ -57,7 +60,7 @@ async function registerAction(
countryCode: text(formData, "countryCode"),
},
actsForBusiness: formData.has("actsForBusiness"),
termsVersion: formData.has("termsAccepted") ? text(formData, "termsVersion") : "",
termsVersion: formData.has("termsAccepted") ? CURRENT_TERMS_VERSION : "",
privacyAcknowledged: formData.has("privacyAcknowledged"),
});
} catch (error) {
+20 -1
View File
@@ -1,5 +1,24 @@
import { toNextJsHandler } from "better-auth/next-js";
import { NextResponse } from "next/server";
import { auth } from "@/modules/auth/auth";
export const { GET, POST } = toNextJsHandler(auth);
const handlers = toNextJsHandler(auth);
export const GET = handlers.GET;
export async function POST(
request: Request,
{ params }: { params: Promise<{ all: string[] }> },
): Promise<Response> {
const { all } = await params;
if (all.join("/") === "sign-up/email") {
return NextResponse.json(
{ message: "Bitte verwenden Sie die Registrierung des Redaktionsportals." },
{ status: 403 },
);
}
return handlers.POST(request);
}
+46 -4
View File
@@ -1,9 +1,50 @@
import { expect, test } from "vitest";
import { memoryAdapter } from "better-auth/adapters/memory";
import { expect, test, vi } from "vitest";
import { auth } from "./auth";
import { POST } from "@/app/api/auth/[...all]/route";
test("rejects direct Better Auth sign-up requests that bypass B2B registration", async () => {
const response = await auth.handler(
import { createPortalAuth } from "./auth";
import { CURRENT_TERMS_VERSION } from "./registration";
test("allows the trusted registration service ingress while rejecting public direct sign-up", async () => {
const registrationRepository = {
createEditorial: vi.fn(),
markPendingApproval: vi.fn(),
removeUnverifiedAuthIdentity: vi.fn(),
recordRegistrationCompensationFailure: vi.fn(),
recordVerificationInconsistency: vi.fn(),
canCreateSession: vi.fn().mockResolvedValue(false),
};
const { registrationService } = createPortalAuth({
database: memoryAdapter({ user: [], account: [], session: [], verification: [] }),
mailerService: {
sendPasswordReset: vi.fn(),
sendVerification: vi.fn(),
},
registrationRepository,
});
await expect(
registrationService.register({
companyName: "Registration GmbH",
contactName: "Registration Service",
email: "registration@example.com",
password: "sicheres-passwort-123",
billingAddress: {
addressLine1: "Presseweg 1",
postalCode: "10115",
city: "Berlin",
countryCode: "DE",
},
actsForBusiness: true,
termsVersion: CURRENT_TERMS_VERSION,
privacyAcknowledged: true,
}),
).resolves.toEqual({ status: "pending_email" });
expect(registrationRepository.createEditorial).toHaveBeenCalledTimes(1);
const response = await POST(
new Request("http://localhost:3000/api/auth/sign-up/email", {
method: "POST",
headers: { "content-type": "application/json" },
@@ -13,6 +54,7 @@ test("rejects direct Better Auth sign-up requests that bypass B2B registration",
password: "sicheres-passwort-123",
}),
}),
{ params: Promise.resolve({ all: ["sign-up", "email"] }) },
);
expect(response.status).toBe(403);
+41 -26
View File
@@ -1,8 +1,7 @@
import "server-only";
import { drizzleAdapter } from "@better-auth/drizzle-adapter";
import { betterAuth } from "better-auth";
import { APIError, createAuthMiddleware } from "better-auth/api";
import { betterAuth, type BetterAuthOptions } from "better-auth";
import { env } from "@/config/env";
import { db } from "@/db/client";
@@ -15,29 +14,21 @@ import {
type RegistrationInput,
} from "./registration";
const registrationRepository = createEditorialRegistrationRepository(db);
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;
export const auth = betterAuth({
const auth = betterAuth({
baseURL: env.BETTER_AUTH_URL,
secret: env.BETTER_AUTH_SECRET,
database: drizzleAdapter(db, {
provider: "pg",
schema: {
user: users,
account: accounts,
session: sessions,
verification: verifications,
},
}),
hooks: {
before: createAuthMiddleware(async (context) => {
if (context.path === "/sign-up/email") {
throw new APIError("FORBIDDEN", {
message: "Bitte verwenden Sie die Registrierung des Redaktionsportals.",
});
}
}),
},
database,
emailAndPassword: {
enabled: true,
requireEmailVerification: true,
@@ -45,7 +36,7 @@ export const auth = betterAuth({
resetPasswordTokenExpiresIn: 60 * 60,
revokeSessionsOnPasswordReset: true,
async sendResetPassword({ user, url }) {
await mailer.sendPasswordReset({ to: user.email, resetUrl: url });
await mailerService.sendPasswordReset({ to: user.email, resetUrl: url });
},
},
emailVerification: {
@@ -53,9 +44,12 @@ export const auth = betterAuth({
autoSignInAfterVerification: false,
expiresIn: 60 * 60,
async sendVerificationEmail({ user, url }) {
await mailer.sendVerification({ to: user.email, verificationUrl: 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);
},
},
@@ -68,9 +62,9 @@ export const auth = betterAuth({
},
},
},
});
});
export const registrationService = createRegistrationService({
registrationService = createRegistrationService({
auth: {
async signUpEmail({ email, name, password }) {
return auth.api.signUpEmail({ body: { email, name, password } });
@@ -83,8 +77,29 @@ export const registrationService = createRegistrationService({
},
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 registerEditorial(input: RegistrationInput): Promise<{ status: "pending_email" }> {
return registrationService.register(input);
}
+1
View File
@@ -38,4 +38,5 @@ test("registration presents separate B2B, terms, and privacy acknowledgements",
"href",
"https://example.com/datenschutz",
);
expect(document.querySelector('input[name="termsVersion"]')).toBeNull();
});
+22 -2
View File
@@ -6,7 +6,20 @@ import { authClient } from "./client";
export type RegistrationFormState = {
errors?: Partial<
Record<"actsForBusiness" | "termsVersion" | "privacyAcknowledged", string>
Record<
| "companyName"
| "contactName"
| "email"
| "password"
| "addressLine1"
| "postalCode"
| "city"
| "countryCode"
| "actsForBusiness"
| "termsVersion"
| "privacyAcknowledged",
string
>
>;
};
@@ -34,28 +47,32 @@ export function RegistrationForm({
return (
<form action={formAction} className="account-form">
<input name="termsVersion" type="hidden" value="2026-08" />
<div className="form-grid">
<label>
Redaktion oder Unternehmen
<input autoComplete="organization" name="companyName" required />
</label>
<FieldError message={state.errors?.companyName} />
<label>
Ansprechpartner:in
<input autoComplete="name" name="contactName" required />
</label>
<FieldError message={state.errors?.contactName} />
<label>
E-Mail-Adresse
<input autoComplete="email" name="email" required type="email" />
</label>
<FieldError message={state.errors?.email} />
<label>
Passwort
<input autoComplete="new-password" minLength={8} name="password" required type="password" />
</label>
<FieldError message={state.errors?.password} />
<label>
Straße und Hausnummer
<input autoComplete="address-line1" name="addressLine1" required />
</label>
<FieldError message={state.errors?.addressLine1} />
<label>
Adresszusatz
<input autoComplete="address-line2" name="addressLine2" />
@@ -64,10 +81,12 @@ export function RegistrationForm({
Postleitzahl
<input autoComplete="postal-code" name="postalCode" required />
</label>
<FieldError message={state.errors?.postalCode} />
<label>
Ort
<input autoComplete="address-level2" name="city" required />
</label>
<FieldError message={state.errors?.city} />
<label>
Land (ISO-Code)
<input
@@ -78,6 +97,7 @@ export function RegistrationForm({
required
/>
</label>
<FieldError message={state.errors?.countryCode} />
</div>
<fieldset className="acknowledgements">
+91 -3
View File
@@ -1,6 +1,7 @@
import { describe, expect, test, vi } from "vitest";
import {
CURRENT_TERMS_VERSION,
RegistrationValidationError,
createRegistrationService,
type RegistrationInput,
@@ -20,10 +21,14 @@ const validRegistration: RegistrationInput = {
countryCode: "DE",
},
actsForBusiness: true,
termsVersion: "2026-08",
termsVersion: CURRENT_TERMS_VERSION,
privacyAcknowledged: true,
};
type RegistrationChange = Partial<Omit<RegistrationInput, "billingAddress">> & {
billingAddress?: RegistrationInput["billingAddress"];
};
function createService() {
const auth = {
signUpEmail: vi.fn().mockResolvedValue({ user: { id: "user-1" } }),
@@ -32,8 +37,10 @@ function createService() {
const repo = {
createEditorial: vi.fn().mockResolvedValue(undefined),
markPendingApproval: vi.fn().mockResolvedValue(true),
removeUnverifiedAuthIdentity: vi.fn().mockResolvedValue(true),
};
const audit = {
recordRegistrationCompensationFailure: vi.fn().mockResolvedValue(undefined),
recordVerificationInconsistency: vi.fn().mockResolvedValue(undefined),
};
const now = new Date("2026-08-09T10:00:00.000Z");
@@ -63,7 +70,7 @@ describe("editorial registration", () => {
contactName: "Mara Muster",
loginEmail: "mara.muster@example.com",
status: "pending_email",
acceptedTermsVersion: "2026-08",
acceptedTermsVersion: CURRENT_TERMS_VERSION,
acceptedTermsAt: new Date("2026-08-09T10:00:00.000Z"),
privacyAcknowledgedAt: new Date("2026-08-09T10:00:00.000Z"),
billingAddress: {
@@ -105,7 +112,7 @@ describe("editorial registration", () => {
).rejects.toEqual(
new RegistrationValidationError(
"termsVersion",
"Bitte akzeptieren Sie die Nutzungs- und Lizenzbedingungen.",
"Bitte akzeptieren Sie die aktuell gültigen Nutzungs- und Lizenzbedingungen.",
),
);
await expect(
@@ -118,6 +125,87 @@ describe("editorial registration", () => {
);
});
test.each<[string, RegistrationChange, string]>([
["companyName", { companyName: " " }, "Bitte geben Sie den Namen der Redaktion oder des Unternehmens an."],
["contactName", { contactName: " " }, "Bitte geben Sie eine Ansprechperson an."],
["email", { email: "keine-adresse" }, "Bitte geben Sie eine gültige E-Mail-Adresse an."],
["password", { password: "" }, "Bitte geben Sie ein Passwort an."],
[
"addressLine1",
{ billingAddress: { ...validRegistration.billingAddress, addressLine1: " " } },
"Bitte geben Sie Straße und Hausnummer an.",
],
[
"postalCode",
{ billingAddress: { ...validRegistration.billingAddress, postalCode: " " } },
"Bitte geben Sie die Postleitzahl an.",
],
[
"city",
{ billingAddress: { ...validRegistration.billingAddress, city: " " } },
"Bitte geben Sie den Ort an.",
],
[
"countryCode",
{ billingAddress: { ...validRegistration.billingAddress, countryCode: "Deutschland" } },
"Bitte geben Sie einen zweistelligen ISO-Ländercode an.",
],
])("rejects missing or malformed required %s data on the server", async (field, change, message) => {
const { auth, repo, service } = createService();
const input = {
...validRegistration,
...change,
billingAddress: change.billingAddress ?? validRegistration.billingAddress,
};
await expect(service.register(input)).rejects.toEqual(
new RegistrationValidationError(field as RegistrationValidationError["field"], message),
);
expect(auth.signUpEmail).not.toHaveBeenCalled();
expect(repo.createEditorial).not.toHaveBeenCalled();
});
test("pins the accepted terms to the server-owned current version", async () => {
const { auth, service } = createService();
await expect(
service.register({ ...validRegistration, termsVersion: "arbitrary-browser-value" }),
).rejects.toEqual(
new RegistrationValidationError(
"termsVersion",
"Bitte akzeptieren Sie die aktuell gültigen Nutzungs- und Lizenzbedingungen.",
),
);
expect(auth.signUpEmail).not.toHaveBeenCalled();
});
test("compensates a failed editorial transaction by removing the new unverified auth identity", async () => {
const { audit, repo, service } = createService();
const persistenceError = new Error("editorial persistence failed");
repo.createEditorial.mockRejectedValue(persistenceError);
await expect(service.register(validRegistration)).rejects.toBe(persistenceError);
expect(repo.removeUnverifiedAuthIdentity).toHaveBeenCalledWith({
email: "mara.muster@example.com",
userId: "user-1",
});
expect(audit.recordRegistrationCompensationFailure).not.toHaveBeenCalled();
});
test("keeps the original persistence failure and audits a failed compensation without request data", async () => {
const { audit, repo, service } = createService();
const persistenceError = new Error("editorial persistence failed");
repo.createEditorial.mockRejectedValue(persistenceError);
repo.removeUnverifiedAuthIdentity.mockRejectedValue(new Error("cleanup failed"));
await expect(service.register(validRegistration)).rejects.toBe(persistenceError);
expect(audit.recordRegistrationCompensationFailure).toHaveBeenCalledWith({ userId: "user-1" });
});
test("moves a verified account from pending email to pending approval", async () => {
const { audit, repo, service } = createService();
+172 -24
View File
@@ -2,10 +2,34 @@ import "server-only";
import { and, eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { z } from "zod";
import { auditEvents, billingAddressVersions, editorialAccounts, users } from "@/db/schema";
import {
accounts,
auditEvents,
billingAddressVersions,
editorialAccounts,
sessions,
users,
verifications,
} from "@/db/schema";
import type * as schema from "@/db/schema";
export const CURRENT_TERMS_VERSION = "2026-08";
export type RegistrationField =
| "companyName"
| "contactName"
| "email"
| "password"
| "addressLine1"
| "postalCode"
| "city"
| "countryCode"
| "actsForBusiness"
| "termsVersion"
| "privacyAcknowledged";
export type BillingAddressInput = {
addressLine1: string;
addressLine2?: string;
@@ -45,19 +69,18 @@ export type RegistrationAuth = {
export type EditorialRegistrationRepository = {
createEditorial(input: PendingEditorial): Promise<void>;
markPendingApproval(userId: string): Promise<boolean>;
removeUnverifiedAuthIdentity(input: { userId: string; email: string }): Promise<boolean>;
};
export type RegistrationAudit = {
recordVerificationInconsistency(input: { userId: string }): Promise<void>;
recordRegistrationCompensationFailure(input: { userId: string }): Promise<void>;
};
export class RegistrationValidationError extends Error {
readonly name = "RegistrationValidationError";
constructor(
readonly field: "actsForBusiness" | "termsVersion" | "privacyAcknowledged",
message: string,
) {
constructor(readonly field: RegistrationField, message: string) {
super(message);
}
}
@@ -83,13 +106,14 @@ export function createRegistrationService({
});
const acceptedAt = now();
try {
await repo.createEditorial({
userId: result.user.id,
name: registration.companyName,
contactName: registration.contactName,
loginEmail: registration.loginEmail,
status: "pending_email",
acceptedTermsVersion: registration.termsVersion,
acceptedTermsVersion: CURRENT_TERMS_VERSION,
acceptedTermsAt: acceptedAt,
privacyAcknowledgedAt: acceptedAt,
billingAddress: {
@@ -98,6 +122,21 @@ export function createRegistrationService({
...registration.billingAddress,
},
});
} catch (error) {
try {
await repo.removeUnverifiedAuthIdentity({
userId: result.user.id,
email: registration.loginEmail,
});
} catch {
try {
await audit.recordRegistrationCompensationFailure({ userId: result.user.id });
} catch {
// Preserve the original editorial persistence error.
}
}
throw error;
}
await auth.sendVerificationEmail({ email: registration.loginEmail });
return { status: "pending_email" };
@@ -112,12 +151,12 @@ export function createRegistrationService({
};
}
export function createEditorialRegistrationRepository(database: NodePgDatabase<typeof schema>): {
createEditorial(input: PendingEditorial): Promise<void>;
markPendingApproval(userId: string): Promise<boolean>;
recordVerificationInconsistency(input: { userId: string }): Promise<void>;
export function createEditorialRegistrationRepository(
database: NodePgDatabase<typeof schema>,
): EditorialRegistrationRepository &
RegistrationAudit & {
canCreateSession(userId: string): Promise<boolean>;
} {
} {
return {
async createEditorial(input) {
await database.transaction(async (transaction) => {
@@ -219,6 +258,58 @@ export function createEditorialRegistrationRepository(database: NodePgDatabase<t
});
},
async recordRegistrationCompensationFailure({ userId }) {
await database.insert(auditEvents).values({
eventType: "registration_auth_compensation_failed",
actorUserId: userId,
actorType: "system",
entityType: "user",
entityId: userId,
newValues: { reason: "editorial_persistence_failed" },
});
},
async removeUnverifiedAuthIdentity({ userId, email }) {
return database.transaction(async (transaction) => {
const [user] = await transaction
.select({ id: users.id, emailVerified: users.emailVerified, role: users.role })
.from(users)
.where(eq(users.id, userId))
.limit(1);
if (!user || user.emailVerified || user.role !== "EDITORIAL") {
return false;
}
const [existingEditorial] = await transaction
.select({ id: editorialAccounts.id })
.from(editorialAccounts)
.where(eq(editorialAccounts.userId, userId))
.limit(1);
if (existingEditorial) {
return false;
}
await transaction.delete(sessions).where(eq(sessions.userId, userId));
await transaction.delete(accounts).where(eq(accounts.userId, userId));
await transaction.delete(verifications).where(eq(verifications.identifier, email));
const [deletedUser] = await transaction
.delete(users)
.where(
and(
eq(users.id, userId),
eq(users.emailVerified, false),
eq(users.role, "EDITORIAL"),
),
)
.returning({ id: users.id });
return Boolean(deletedUser);
});
},
async canCreateSession(userId) {
const [principal] = await database
.select({ role: users.role, status: editorialAccounts.status })
@@ -237,7 +328,6 @@ function validateRegistration(input: RegistrationInput): {
contactName: string;
loginEmail: string;
password: string;
termsVersion: string;
billingAddress: BillingAddressInput;
} {
if (!input.actsForBusiness) {
@@ -246,10 +336,10 @@ function validateRegistration(input: RegistrationInput): {
"Bitte bestätigen Sie, dass Sie im Namen eines Unternehmens oder einer Redaktion handeln.",
);
}
if (!input.termsVersion.trim()) {
if (trim(input.termsVersion) !== CURRENT_TERMS_VERSION) {
throw new RegistrationValidationError(
"termsVersion",
"Bitte akzeptieren Sie die Nutzungs- und Lizenzbedingungen.",
"Bitte akzeptieren Sie die aktuell gültigen Nutzungs- und Lizenzbedingungen.",
);
}
if (!input.privacyAcknowledged) {
@@ -259,18 +349,76 @@ function validateRegistration(input: RegistrationInput): {
);
}
const companyName = trim(input.companyName);
if (!companyName) {
throw new RegistrationValidationError(
"companyName",
"Bitte geben Sie den Namen der Redaktion oder des Unternehmens an.",
);
}
const contactName = trim(input.contactName);
if (!contactName) {
throw new RegistrationValidationError("contactName", "Bitte geben Sie eine Ansprechperson an.");
}
const loginEmail = trim(input.email).toLowerCase();
if (!z.email().safeParse(loginEmail).success) {
throw new RegistrationValidationError("email", "Bitte geben Sie eine gültige E-Mail-Adresse an.");
}
const password = typeof input.password === "string" ? input.password : "";
if (!password) {
throw new RegistrationValidationError("password", "Bitte geben Sie ein Passwort an.");
}
if (password.length < 8) {
throw new RegistrationValidationError(
"password",
"Bitte verwenden Sie ein Passwort mit mindestens acht Zeichen.",
);
}
const addressLine1 = trim(input.billingAddress?.addressLine1);
if (!addressLine1) {
throw new RegistrationValidationError(
"addressLine1",
"Bitte geben Sie Straße und Hausnummer an.",
);
}
const postalCode = trim(input.billingAddress?.postalCode);
if (!postalCode) {
throw new RegistrationValidationError("postalCode", "Bitte geben Sie die Postleitzahl an.");
}
const city = trim(input.billingAddress?.city);
if (!city) {
throw new RegistrationValidationError("city", "Bitte geben Sie den Ort an.");
}
const countryCode = trim(input.billingAddress?.countryCode).toUpperCase();
if (!/^[A-Z]{2}$/.test(countryCode)) {
throw new RegistrationValidationError(
"countryCode",
"Bitte geben Sie einen zweistelligen ISO-Ländercode an.",
);
}
return {
companyName: input.companyName.trim(),
contactName: input.contactName.trim(),
loginEmail: input.email.trim().toLowerCase(),
password: input.password,
termsVersion: input.termsVersion.trim(),
companyName,
contactName,
loginEmail,
password,
billingAddress: {
addressLine1: input.billingAddress.addressLine1.trim(),
addressLine2: input.billingAddress.addressLine2?.trim() || undefined,
postalCode: input.billingAddress.postalCode.trim(),
city: input.billingAddress.city.trim(),
countryCode: input.billingAddress.countryCode.trim().toUpperCase(),
addressLine1,
addressLine2: trim(input.billingAddress?.addressLine2) || undefined,
postalCode,
city,
countryCode,
},
};
}
function trim(value: unknown): string {
return typeof value === "string" ? value.trim() : "";
}