fix: harden booking and meeting flows

This commit is contained in:
2026-09-17 02:42:27 +02:00
parent cb30ecade9
commit 66710fc65c
42 changed files with 683 additions and 608 deletions
+2 -2
View File
@@ -15,8 +15,8 @@ export default async function KontoOverviewPage() {
const bookings = await getCustomerBookings(customer.id);
const meetingSettings = await getMeetingSettingsGlobal();
const pending = bookings.filter((b) => b.status === "pending");
const confirmed = bookings.filter((b) => b.status === "confirmed" && new Date(b.date) >= new Date());
const past = bookings.filter((b) => new Date(b.date) < new Date() || b.status === "rejected" || b.status === "cancelled");
const confirmed = bookings.filter((b) => b.status === "confirmed" && new Date(b.endTime) >= new Date());
const past = bookings.filter((b) => new Date(b.endTime) < new Date() || b.status === "rejected" || b.status === "cancelled");
return (
<div className="space-y-10">
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { createMeetingToken } from "@/lib/meeting/token";
import { authorizeMeeting } from "@/lib/meeting/access";
export const dynamic = "force-dynamic";
@@ -12,6 +13,7 @@ export async function POST(request: Request) {
let body: Body;
try {
body = await request.json();
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid body");
} catch {
return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400 });
}
@@ -36,10 +38,14 @@ export async function POST(request: Request) {
return NextResponse.json({ error: "Dieser Termin ist kein Online-Termin." }, { status: 404 });
}
const access = await authorizeMeeting(payload, event, "host");
if (!access) return NextResponse.json({ error: "Dieser Termin ist nicht offen oder wurde storniert." }, { status: 403 });
const { token } = createMeetingToken({
eventSlug,
name: typeof user.name === "string" && user.name.trim() ? user.name.trim() : "Host",
role: "host",
accessVersion: access.accessVersion,
ttlMs: Math.min(6 * 3600000, access.expiresAt - Date.now()),
});
// Keep the token in the URL fragment: browsers do not send fragments to
@@ -20,6 +20,7 @@ export async function POST(request: Request) {
eventSlug,
name: typeof user.name === "string" && user.name.trim() ? user.name.trim() : "Host",
role: "host",
testRoom: true,
ttlMs: 60 * 60 * 1000,
});
const baseUrl = process.env.NEXT_PUBLIC_SERVER_URL || new URL(request.url).origin;
@@ -53,6 +53,7 @@ export async function POST(request: Request) {
try {
const raw = await request.text();
body = JSON.parse(raw);
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid body");
} catch {
return new NextResponse(null, { status: 204 });
}
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { checkRateLimit, getClientIp } from "@/lib/auth/rateLimit";
import { allowVerificationEmail } from "@/lib/auth/verificationRateLimit";
import { EMAIL_VERIFICATION_TTL_MS, generateVerificationToken, hashVerificationToken, verificationExpiryISO } from "@/lib/auth/verification";
import { verificationEmail } from "@/lib/email/authTemplates";
import { sendEmail } from "@/lib/email/sendBookingEmails";
@@ -57,11 +58,12 @@ export async function POST(request: Request) {
let body: { email?: unknown } = {};
try {
body = await request.json();
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid body");
} catch {
// no body — handled below as a missing email
}
const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
if (!email) {
const email = typeof body?.email === "string" ? body.email.trim().toLowerCase() : "";
if (!email || email.length > 254) {
return NextResponse.json({ error: "E-Mail-Adresse erforderlich." }, { status: 400 });
}
if (!checkRateLimit(`resend-verification:email:${email}`, { max: 3, windowMs: 60 * 60 * 1000 })) {
@@ -77,8 +79,8 @@ export async function POST(request: Request) {
}
if (customer && !customer.emailVerified) {
if (!checkRateLimit(`resend-verification:customer:${customer.id}`, { max: 3, windowMs: 60 * 60 * 1000 })) {
return NextResponse.json({ error: "Zu viele Anfragen. Bitte versuche es später erneut." }, { status: 429 });
if (!allowVerificationEmail(request, customer.email, customer.id)) {
return NextResponse.json(GENERIC_RESPONSE);
}
await issueAndSend(payload, customer);
}
@@ -1,6 +1,8 @@
import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { combineDateAndTime } from "@/lib/meeting/status";
import { withBookingTransaction } from "@/lib/booking/transaction";
export const dynamic = "force-dynamic";
@@ -19,31 +21,40 @@ export async function POST(request: Request, { params }: Args) {
return NextResponse.json({ error: "Bitte bestätige zuerst deine E-Mail-Adresse.", code: "EMAIL_NOT_VERIFIED" }, { status: 403 });
}
const booking = await payload.findByID({ collection: "booking-requests", id, depth: 0 }).catch(() => null);
if (!booking || Number(booking.user) !== Number(user.id)) {
return NextResponse.json({ error: "Buchung nicht gefunden." }, { status: 404 });
}
const alternative = booking.proposedAlternative;
if (booking.status !== "pending" || !alternative?.date || !alternative.startTime || !alternative.endTime) {
return NextResponse.json({ error: "Für diese Buchung liegt kein alternativer Termin vor." }, { status: 409 });
}
return await withBookingTransaction(payload, `booking:${id}`, async (req) => {
const { docs } = await payload.find({ collection: "booking-requests", where: { id: { equals: id } }, depth: 0, limit: 1, req });
const booking = docs[0];
if (!booking || Number(booking.user) !== Number(user.id)) {
return NextResponse.json({ error: "Buchung nicht gefunden." }, { status: 404 });
}
const alternative = booking.proposedAlternative;
if (booking.status !== "pending" || !alternative?.date || !alternative.startTime || !alternative.endTime) {
return NextResponse.json({ error: "Für diese Buchung liegt kein alternativer Termin vor." }, { status: 409 });
}
// The beforeChange hook on booking-requests re-checks for conflicts
// (with an advisory lock) before allowing this to become "confirmed" —
// the alternative slot may have been taken by someone else since it was
// proposed.
await payload.update({
collection: "booking-requests",
id,
data: {
status: "confirmed",
date: alternative.date,
startTime: alternative.startTime,
endTime: alternative.endTime,
},
const alternativeStart = combineDateAndTime(alternative.date, alternative.startTime);
if (!Number.isFinite(alternativeStart.getTime()) || alternativeStart <= new Date()) {
return NextResponse.json({ error: "Dieser Terminvorschlag liegt bereits in der Vergangenheit." }, { status: 409 });
}
// The beforeChange hook on booking-requests re-checks for conflicts
// (with an advisory lock) before allowing this to become "confirmed" —
// the alternative slot may have been taken by someone else since it was
// proposed.
await payload.update({
collection: "booking-requests",
id,
req,
data: {
status: "confirmed",
date: alternative.date,
startTime: alternative.startTime,
endTime: alternative.endTime,
},
});
return NextResponse.json({ ok: true });
});
return NextResponse.json({ ok: true });
} catch (error) {
if (error instanceof Error && "status" in error && (error as { status: number }).status === 409) {
return NextResponse.json({ error: error.message }, { status: 409 });
+13 -9
View File
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { withBookingTransaction } from "@/lib/booking/transaction";
export const dynamic = "force-dynamic";
@@ -18,16 +19,19 @@ export async function POST(request: Request, { params }: Args) {
// Cancelling is deliberately allowed regardless of verification status —
// only creating/confirming a booking is a gated "protected" action.
const booking = await payload.findByID({ collection: "booking-requests", id, depth: 0 }).catch(() => null);
if (!booking || Number(booking.user) !== Number(user.id)) {
return NextResponse.json({ error: "Buchung nicht gefunden." }, { status: 404 });
}
if (booking.status === "cancelled") {
return NextResponse.json({ ok: true });
}
return await withBookingTransaction(payload, `booking:${id}`, async (req) => {
const { docs } = await payload.find({ collection: "booking-requests", where: { id: { equals: id } }, depth: 0, limit: 1, req });
const booking = docs[0];
if (!booking || Number(booking.user) !== Number(user.id)) {
return NextResponse.json({ error: "Buchung nicht gefunden." }, { status: 404 });
}
if (booking.status === "cancelled") {
return NextResponse.json({ ok: true });
}
await payload.update({ collection: "booking-requests", id, data: { status: "cancelled" } });
return NextResponse.json({ ok: true });
await payload.update({ collection: "booking-requests", id, req, data: { status: "cancelled" } });
return NextResponse.json({ ok: true });
});
} catch (error) {
console.error("booking cancel failed", error);
return NextResponse.json({ error: "Der Termin konnte nicht storniert werden." }, { status: 500 });
+46 -25
View File
@@ -2,6 +2,8 @@ import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { getAvailableSlots } from "@/lib/booking/slots";
import { withBookingTransaction } from "@/lib/booking/transaction";
import { checkRateLimit, getClientIp } from "@/lib/auth/rateLimit";
import { berlinDayBounds } from "@/lib/calendar/timezone";
export const dynamic = "force-dynamic";
@@ -17,13 +19,15 @@ export async function POST(request: Request) {
let body: Body;
try {
body = await request.json();
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid body");
} catch {
return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400 });
}
const offerSlug = typeof body.offerSlug === "string" ? body.offerSlug : "";
const startISO = typeof body.start === "string" ? body.start : "";
const appointmentType = body.appointmentType === "online" ? "online" : "onsite";
const appointmentType = body.appointmentType;
if (appointmentType !== "online" && appointmentType !== "onsite") return NextResponse.json({ error: "Ungültige Terminart." }, { status: 400 });
const message = typeof body.message === "string" ? body.message.trim().slice(0, 2000) : "";
if (!offerSlug || !startISO) {
@@ -40,6 +44,11 @@ export async function POST(request: Request) {
return NextResponse.json({ error: "Bitte bestätige zuerst deine E-Mail-Adresse.", code: "EMAIL_NOT_VERIFIED" }, { status: 403 });
}
if (!checkRateLimit(`booking:ip:${getClientIp(request)}`, { max: 30, windowMs: 3600000 }) ||
!checkRateLimit(`booking:customer:${user.id}`, { max: 10, windowMs: 3600000 })) {
return NextResponse.json({ error: "Zu viele Terminanfragen. Bitte versuche es später erneut." }, { status: 429 });
}
const { docs } = await payload.find({
collection: "offers",
where: { slug: { equals: offerSlug } },
@@ -61,32 +70,44 @@ export async function POST(request: Request) {
// stale slot list) — the hard, race-safe check still runs again when
// Anna confirms (see collections/BookingRequests.ts).
const dayBounds = berlinDayBounds(start);
const slotsByDay = await getAvailableSlots(payload, {
durationMinutes: offer.durationMinutes,
from: dayBounds.start,
to: dayBounds.end,
});
const key = dayBounds.key;
const isStillFree = (slotsByDay.get(key) ?? []).some((s) => s.start.getTime() === start.getTime());
if (!isStillFree) {
return NextResponse.json({ error: "Dieser Termin ist leider nicht mehr verfügbar." }, { status: 409 });
}
return await withBookingTransaction(payload, dayBounds.key, async (req) => {
const { docs: existing } = await payload.find({ collection: "booking-requests", req, depth: 0, limit: 1,
where: { and: [
{ user: { equals: user.id } }, { offer: { equals: offer.id } },
{ startTime: { equals: start.toISOString() } }, { appointmentType: { equals: appointmentType } },
{ status: { in: ["pending", "confirmed"] } },
] },
});
if (existing[0]) return NextResponse.json({ ok: true });
const slotsByDay = await getAvailableSlots(payload, {
durationMinutes: offer.durationMinutes!,
req,
from: dayBounds.start,
to: dayBounds.end,
});
const key = dayBounds.key;
const isStillFree = (slotsByDay.get(key) ?? []).some((s) => s.start.getTime() === start.getTime());
if (!isStillFree) {
return NextResponse.json({ error: "Dieser Termin ist leider nicht mehr verfügbar." }, { status: 409 });
}
await payload.create({
collection: "booking-requests",
data: {
user: user.id,
offer: offer.id,
date: start.toISOString(),
startTime: start.toISOString(),
endTime: end.toISOString(),
appointmentType,
status: "pending",
userMessage: message || undefined,
},
});
await payload.create({
collection: "booking-requests",
req,
data: {
user: user.id,
offer: offer.id,
date: start.toISOString(),
startTime: start.toISOString(),
endTime: end.toISOString(),
appointmentType,
status: "pending",
userMessage: message || undefined,
},
});
return NextResponse.json({ ok: true });
return NextResponse.json({ ok: true });
});
} catch (error) {
console.error("booking request failed", error);
return NextResponse.json({ error: "Die Anfrage konnte nicht gesendet werden. Bitte versuche es später erneut." }, { status: 500 });
+6 -6
View File
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { getAvailableSlots } from "@/lib/booking/slots";
import { berlinDayBounds, parseBerlinDate } from "@/lib/calendar/timezone";
export const dynamic = "force-dynamic";
@@ -29,16 +30,15 @@ export async function GET(request: Request) {
return NextResponse.json({ error: "Dieses Angebot ist nicht buchbar." }, { status: 404 });
}
const from = fromParam ? new Date(`${fromParam}T00:00:00`) : new Date();
if (Number.isNaN(from.getTime())) {
const from = fromParam ? parseBerlinDate(fromParam) : berlinDayBounds(new Date()).start;
if (!from) {
return NextResponse.json({ error: "Ungültiges Startdatum." }, { status: 400 });
}
from.setHours(0, 0, 0, 0);
const to = toParam ? new Date(`${toParam}T00:00:00`) : new Date(from.getTime() + 21 * 24 * 60 * 60 * 1000);
if (Number.isNaN(to.getTime())) {
const toDate = toParam ? parseBerlinDate(toParam) : new Date(from.getTime() + 21 * 24 * 60 * 60 * 1000);
if (!toDate) {
return NextResponse.json({ error: "Ungültiges Enddatum." }, { status: 400 });
}
to.setHours(23, 59, 59, 999);
const to = berlinDayBounds(toDate).end;
if (to < from) {
return NextResponse.json({ error: "Das Enddatum muss nach dem Startdatum liegen." }, { status: 400 });
@@ -4,6 +4,7 @@ import config from "@payload-config";
import { createLiveKitToken, getLiveKitClientUrl } from "@/lib/meeting/livekit";
import { isMeetingParticipantKicked } from "@/lib/meeting/kicks";
import { verifyMeetingToken } from "@/lib/meeting/token";
import { authorizeMeeting } from "@/lib/meeting/access";
export const dynamic = "force-dynamic";
@@ -23,11 +24,17 @@ export async function POST(request: Request, { params }: Args) {
}
try {
const isAdminTestRoom = meetingToken.role === "host" && slug.startsWith("test-");
let expiresAt = meetingToken.exp;
const isAdminTestRoom = meetingToken.role === "host" && meetingToken.testRoom === true && slug.startsWith("test-");
if (!isAdminTestRoom) {
const payload = await getPayload({ config });
const { docs } = await payload.find({ collection: "events", where: { slug: { equals: slug } }, limit: 1 });
if (!docs[0]?.isOnline) return NextResponse.json({ error: "Dieser Online-Termin wurde nicht gefunden." }, { status: 404 });
const access = await authorizeMeeting(payload, docs[0], meetingToken.role);
if (!access || access.accessVersion !== meetingToken.accessVersion) {
return NextResponse.json({ error: "Dieser Meeting-Zugang ist nicht mehr gültig. Bitte tritt erneut bei." }, { status: 403 });
}
expiresAt = Math.min(expiresAt, access.expiresAt);
}
const participantToken = await createLiveKitToken({
@@ -36,6 +43,8 @@ export async function POST(request: Request, { params }: Args) {
name: meetingToken.name,
role: meetingToken.role,
clientId: meetingToken.clientId,
accessVersion: meetingToken.accessVersion,
expiresAt,
});
return NextResponse.json({ serverUrl: getLiveKitClientUrl(), participantToken });
} catch (error) {
+13 -20
View File
@@ -3,7 +3,8 @@ import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { createMeetingToken } from "@/lib/meeting/token";
import { canJoinMeeting, combineDateAndTime, getMeetingStatus } from "@/lib/meeting/status";
import { authorizeMeeting } from "@/lib/meeting/access";
import { checkRateLimit, getClientIp } from "@/lib/auth/rateLimit";
import { createLiveKitToken, getLiveKitClientUrl } from "@/lib/meeting/livekit";
import { isMeetingParticipantKicked } from "@/lib/meeting/kicks";
@@ -20,10 +21,14 @@ type Args = { params: Promise<{ slug: string }> };
export async function POST(request: Request, { params }: Args) {
const { slug } = await params;
if (!checkRateLimit(`meeting-join:${getClientIp(request)}`, { max: 30, windowMs: 60000 })) {
return NextResponse.json({ error: "Zu viele Beitrittsversuche." }, { status: 429 });
}
let body: { name?: unknown; password?: unknown; clientId?: unknown };
try {
body = await request.json();
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid body");
} catch {
return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400 });
}
@@ -65,31 +70,17 @@ export async function POST(request: Request, { params }: Args) {
}
}
const settings = await payload.findGlobal({ slug: "meeting-settings" });
const start = combineDateAndTime(event.date, event.startTime);
const end = event.endTime
? combineDateAndTime(event.date, event.endTime)
: new Date(start.getTime() + 60 * 60_000);
const status = getMeetingStatus({
start,
end,
joinWindowMinutes: isHost ? settings.hostJoinWindowMinutes : settings.participantJoinWindowMinutes,
closeAfterMinutes: settings.meetingCloseAfterMinutes,
});
if (!canJoinMeeting(status)) {
const message =
status === "scheduled"
? "Dieser Termin ist noch nicht offen. Bitte versuche es näher am Beginn erneut."
: "Dieser Termin ist bereits beendet.";
return NextResponse.json({ error: message }, { status: 403 });
const access = await authorizeMeeting(payload, event, isHost ? "host" : "participant");
if (!access) {
return NextResponse.json({ error: "Dieser Termin ist nicht offen oder wurde storniert." }, { status: 403 });
}
const { token, participantId } = createMeetingToken({
eventSlug: slug,
name,
role: isHost ? "host" : "participant",
accessVersion: access.accessVersion,
ttlMs: Math.min(6 * 3600000, access.expiresAt - Date.now()),
// Only meaningful for participants — a host authenticates via a real
// session already, so there's no need to anchor a kick to it (and
// hosts can't be kicked in the first place.
@@ -101,6 +92,8 @@ export async function POST(request: Request, { params }: Args) {
}
const participantToken = await createLiveKitToken({
eventSlug: slug,
accessVersion: access.accessVersion,
expiresAt: access.expiresAt,
participantId,
name,
role: isHost ? "host" : "participant",
@@ -19,6 +19,7 @@ export async function POST(request: Request, { params }: Args) {
let body: { participantId?: unknown };
try {
body = await request.json();
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid body");
} catch {
return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400 });
}
@@ -29,7 +30,7 @@ export async function POST(request: Request, { params }: Args) {
try {
const roomService = getLiveKitRoomService();
const room = getLiveKitRoomName(slug);
const room = getLiveKitRoomName(slug, host.accessVersion);
const participant = (await roomService.listParticipants(room)).find((item) => item.identity === participantId);
if (!participant) return NextResponse.json({ error: "Teilnehmer nicht gefunden." }, { status: 404 });
@@ -38,6 +38,7 @@ export async function POST(request: Request, { params }: Args) {
let body: { name?: unknown; email?: unknown };
try {
body = await request.json();
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid body");
} catch {
return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400 });
}