Integrate LiveKit SFU and harden booking workflow

This commit is contained in:
2026-09-16 19:38:28 +02:00
parent f1cd07b3ad
commit d0864e2911
55 changed files with 1648 additions and 1234 deletions
+3 -1
View File
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { getCurrentCustomer } from "@/lib/auth/customer";
import { getCustomerBookings } from "@/lib/booking/queries";
import { PersonalCalendar } from "@/components/booking/PersonalCalendar";
import { getMeetingSettingsGlobal } from "@/lib/payload/globals";
export const metadata: Metadata = { title: "Mein Kalender" };
@@ -10,12 +11,13 @@ export default async function KontoKalenderPage() {
if (!customer) return null;
const bookings = await getCustomerBookings(customer.id);
const meetingSettings = await getMeetingSettingsGlobal();
return (
<div>
<h2 className="font-serif text-xl font-medium text-anouma-plum">Mein Kalender</h2>
<div className="mt-6">
<PersonalCalendar bookings={bookings} />
<PersonalCalendar bookings={bookings} meetingSettings={meetingSettings} />
</div>
</div>
);
+4 -1
View File
@@ -3,6 +3,8 @@ import { getCurrentCustomer } from "@/lib/auth/customer";
import { getCustomerBookings } from "@/lib/booking/queries";
import { BookingCard } from "@/components/booking/BookingCard";
import { ArrowLink } from "@/components/ArrowLink";
import { getMeetingSettingsGlobal } from "@/lib/payload/globals";
import { getBookingMeetingStatus } from "@/lib/booking/meetingAccess";
export const metadata: Metadata = { title: "Mein Konto" };
@@ -11,6 +13,7 @@ export default async function KontoOverviewPage() {
if (!customer) return null; // Layout already redirects; keeps TS happy.
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");
@@ -53,7 +56,7 @@ export default async function KontoOverviewPage() {
) : (
<div className="mt-4 grid gap-4 sm:grid-cols-2">
{confirmed.map((b) => (
<BookingCard key={b.id} booking={b} />
<BookingCard key={b.id} booking={b} meetingStatus={getBookingMeetingStatus(b, meetingSettings)} />
))}
</div>
)}
+4 -1
View File
@@ -2,6 +2,8 @@ import type { Metadata } from "next";
import { getCurrentCustomer } from "@/lib/auth/customer";
import { getCustomerBookings } from "@/lib/booking/queries";
import { BookingCard } from "@/components/booking/BookingCard";
import { getMeetingSettingsGlobal } from "@/lib/payload/globals";
import { getBookingMeetingStatus } from "@/lib/booking/meetingAccess";
export const metadata: Metadata = { title: "Meine Termine" };
@@ -10,6 +12,7 @@ export default async function KontoTerminePage() {
if (!customer) return null;
const bookings = await getCustomerBookings(customer.id);
const meetingSettings = await getMeetingSettingsGlobal();
return (
<div>
@@ -21,7 +24,7 @@ export default async function KontoTerminePage() {
) : (
<div className="mt-4 grid gap-4 sm:grid-cols-2">
{bookings.map((b) => (
<BookingCard key={b.id} booking={b} />
<BookingCard key={b.id} booking={b} meetingStatus={getBookingMeetingStatus(b, meetingSettings)} />
))}
</div>
)}
@@ -5,6 +5,7 @@ import { JoinForm } from "@/components/meeting/JoinForm";
import { OrganicBlob } from "@/components/OrganicBlob";
import { getEventForJoin } from "@/lib/payload/content";
import { combineDateAndTime } from "@/lib/meeting/status";
import { formatBerlinDate, formatBerlinTime } from "@/lib/calendar/timezone";
export const dynamic = "force-dynamic";
@@ -21,8 +22,8 @@ export default async function BeitretenPage({ params }: Args) {
if (!event || !event.isOnline) notFound();
const start = combineDateAndTime(event.date, event.startTime);
const dateLabel = start.toLocaleDateString("de-DE", { day: "2-digit", month: "long" });
const timeLabel = start.toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });
const dateLabel = formatBerlinDate(start, { day: "2-digit", month: "long" });
const timeLabel = formatBerlinTime(start, { hour: "2-digit", minute: "2-digit" });
return (
<section className="relative flex min-h-[80vh] items-center overflow-hidden py-20">
+1 -1
View File
@@ -76,7 +76,7 @@ export default async function EventDetailPage({ params }: Args) {
const { user } = await payload.auth({ headers: await headers() });
// Must check the collection, not just presence — a logged-in customer
// (collection "customers") must never be treated as host.
const isHost = user?.collection === "users";
const isHost = user?.collection === "users" && user.role === "admin";
const settings = await payload.findGlobal({ slug: "meeting-settings" });
const start = combineDateAndTime(event.date, event.startTime);
const end = event.endTime
+3 -1
View File
@@ -21,7 +21,9 @@ export default async function TerminePage() {
const events = await getAllEvents();
const today = new Date();
today.setHours(0, 0, 0, 0);
const upcoming = events.filter((e) => new Date(e.date) >= today).reverse();
const upcoming = events
.filter((e) => new Date(e.date) >= today)
.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
const past = events.filter((e) => new Date(e.date) < today);
const siteUrl = await getSiteUrl();
@@ -0,0 +1,56 @@
import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { createMeetingToken } from "@/lib/meeting/token";
export const dynamic = "force-dynamic";
type Body = { eventSlug?: unknown };
/** Creates a host session for an online event from the authenticated CRM. */
export async function POST(request: Request) {
let body: Body;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400 });
}
const eventSlug = typeof body.eventSlug === "string" ? body.eventSlug.trim() : "";
if (!eventSlug) return NextResponse.json({ error: "Online-Termin fehlt." }, { status: 400 });
try {
const payload = await getPayload({ config });
const { user } = await payload.auth({ headers: request.headers });
if (!user || user.collection !== "users" || user.role !== "admin") {
return NextResponse.json({ error: "Nicht autorisiert." }, { status: 401 });
}
const { docs } = await payload.find({
collection: "events",
where: { slug: { equals: eventSlug } },
limit: 1,
});
const event = docs[0];
if (!event || !event.isOnline) {
return NextResponse.json({ error: "Dieser Termin ist kein Online-Termin." }, { status: 404 });
}
const { token } = createMeetingToken({
eventSlug,
name: typeof user.name === "string" && user.name.trim() ? user.name.trim() : "Host",
role: "host",
});
// Keep the token in the URL fragment: browsers do not send fragments to
// the server, so the temporary host credential does not enter request or
// reverse-proxy logs. The CRM copies this test link without navigating.
const baseUrl = process.env.NEXT_PUBLIC_SERVER_URL || new URL(request.url).origin;
const testUrl = `${baseUrl.replace(/\/$/, "")}/termine/${encodeURIComponent(eventSlug)}/call#token=${encodeURIComponent(token)}`;
return NextResponse.json({ testUrl });
} catch (error) {
console.error("admin meeting start failed", error);
return NextResponse.json({ error: "Der Video-Call konnte nicht gestartet werden." }, { status: 500 });
}
}
+5 -7
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 } from "@/lib/calendar/timezone";
export const dynamic = "force-dynamic";
@@ -59,16 +60,13 @@ export async function POST(request: Request) {
// Re-validate the slot is actually free right now (defense against a
// stale slot list) — the hard, race-safe check still runs again when
// Anna confirms (see collections/BookingRequests.ts).
const dayStart = new Date(start);
dayStart.setHours(0, 0, 0, 0);
const dayEnd = new Date(start);
dayEnd.setHours(23, 59, 59, 999);
const dayBounds = berlinDayBounds(start);
const slotsByDay = await getAvailableSlots(payload, {
durationMinutes: offer.durationMinutes,
from: dayStart,
to: dayEnd,
from: dayBounds.start,
to: dayBounds.end,
});
const key = dayStart.toISOString().slice(0, 10);
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 });
+12 -2
View File
@@ -29,11 +29,21 @@ export async function GET(request: Request) {
return NextResponse.json({ error: "Dieses Angebot ist nicht buchbar." }, { status: 404 });
}
const from = fromParam ? new Date(fromParam) : new Date();
const from = fromParam ? new Date(`${fromParam}T00:00:00`) : new Date();
if (Number.isNaN(from.getTime())) {
return NextResponse.json({ error: "Ungültiges Startdatum." }, { status: 400 });
}
from.setHours(0, 0, 0, 0);
const to = toParam ? new Date(toParam) : new Date(from.getTime() + 21 * 24 * 60 * 60 * 1000);
const to = toParam ? new Date(`${toParam}T00:00:00`) : new Date(from.getTime() + 21 * 24 * 60 * 60 * 1000);
if (Number.isNaN(to.getTime())) {
return NextResponse.json({ error: "Ungültiges Enddatum." }, { status: 400 });
}
to.setHours(23, 59, 59, 999);
if (to < from) {
return NextResponse.json({ error: "Das Enddatum muss nach dem Startdatum liegen." }, { status: 400 });
}
// Cap the range so this can't be abused to run an expensive scan.
const maxRangeMs = 62 * 24 * 60 * 60 * 1000;
if (to.getTime() - from.getTime() > maxRangeMs) {
@@ -0,0 +1,42 @@
import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { createLiveKitToken, getLiveKitClientUrl } from "@/lib/meeting/livekit";
import { isMeetingParticipantKicked } from "@/lib/meeting/kicks";
import { verifyMeetingToken } from "@/lib/meeting/token";
export const dynamic = "force-dynamic";
type Args = { params: Promise<{ slug: string }> };
/** Exchanges the app's short-lived meeting credential for a LiveKit token. */
export async function POST(request: Request, { params }: Args) {
const { slug } = await params;
const authorization = request.headers.get("authorization") ?? "";
const appToken = authorization.startsWith("Bearer ") ? authorization.slice(7) : "";
const meetingToken = verifyMeetingToken(appToken);
if (!meetingToken || meetingToken.eventSlug !== slug) {
return NextResponse.json({ error: "Die Meeting-Sitzung ist ungültig." }, { status: 401 });
}
if (isMeetingParticipantKicked(slug, meetingToken.participantId, meetingToken.clientId)) {
return NextResponse.json({ error: "Du wurdest aus diesem Meeting entfernt." }, { status: 403 });
}
try {
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 participantToken = await createLiveKitToken({
eventSlug: slug,
participantId: meetingToken.participantId,
name: meetingToken.name,
role: meetingToken.role,
clientId: meetingToken.clientId,
});
return NextResponse.json({ serverUrl: getLiveKitClientUrl(), participantToken });
} catch (error) {
console.error("meeting LiveKit connect failed", error);
return NextResponse.json({ error: "Der Video-Server ist gerade nicht erreichbar." }, { status: 503 });
}
}
@@ -4,7 +4,8 @@ import { getPayload } from "payload";
import config from "@payload-config";
import { createMeetingToken } from "@/lib/meeting/token";
import { canJoinMeeting, combineDateAndTime, getMeetingStatus } from "@/lib/meeting/status";
import { getIceServers } from "@/lib/meeting/iceServers";
import { createLiveKitToken, getLiveKitClientUrl } from "@/lib/meeting/livekit";
import { isMeetingParticipantKicked } from "@/lib/meeting/kicks";
export const dynamic = "force-dynamic";
@@ -30,9 +31,12 @@ export async function POST(request: Request, { params }: Args) {
const name = typeof body.name === "string" ? body.name.trim() : "";
const password = typeof body.password === "string" ? body.password.trim() : "";
const clientId = typeof body.clientId === "string" ? body.clientId.trim() : undefined;
if (!name) {
if (!name || name.length > 120) {
return NextResponse.json({ error: "Bitte gib deinen Namen ein." }, { status: 400 });
}
if (password.length > 200) {
return NextResponse.json({ error: "Das Meeting-Passwort ist ungültig." }, { status: 400 });
}
try {
const payload = await getPayload({ config });
@@ -50,7 +54,7 @@ export async function POST(request: Request, { params }: Args) {
const { user } = await payload.auth({ headers: request.headers });
// Must check the collection, not just presence — a logged-in customer
// (collection "customers") must never be treated as host.
const isHost = user?.collection === "users";
const isHost = user?.collection === "users" && user.role === "admin";
if (!isHost) {
if (!password) {
@@ -88,7 +92,18 @@ export async function POST(request: Request, { params }: Args) {
role: isHost ? "host" : "participant",
// 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, see signalingServer.ts).
// hosts can't be kicked in the first place.
clientId: isHost ? undefined : clientId,
});
if (!isHost && isMeetingParticipantKicked(slug, participantId, clientId)) {
return NextResponse.json({ error: "Du wurdest aus diesem Meeting entfernt." }, { status: 403 });
}
const participantToken = await createLiveKitToken({
eventSlug: slug,
participantId,
name,
role: isHost ? "host" : "participant",
clientId: isHost ? undefined : clientId,
});
@@ -97,7 +112,8 @@ export async function POST(request: Request, { params }: Args) {
participantId,
role: isHost ? "host" : "participant",
eventTitle: event.title,
iceServers: getIceServers(),
participantToken,
serverUrl: getLiveKitClientUrl(),
});
} catch (error) {
console.error("meeting join failed", error);
@@ -0,0 +1,50 @@
import { NextResponse } from "next/server";
import { getLiveKitRoomName, getLiveKitRoomService } from "@/lib/meeting/livekit";
import { markMeetingParticipantKicked } from "@/lib/meeting/kicks";
import { verifyMeetingToken } from "@/lib/meeting/token";
export const dynamic = "force-dynamic";
type Args = { params: Promise<{ slug: string }> };
export async function POST(request: Request, { params }: Args) {
const { slug } = await params;
const authorization = request.headers.get("authorization") ?? "";
const appToken = authorization.startsWith("Bearer ") ? authorization.slice(7) : "";
const host = verifyMeetingToken(appToken);
if (!host || host.eventSlug !== slug || host.role !== "host") {
return NextResponse.json({ error: "Nur der Host darf Teilnehmer entfernen." }, { status: 403 });
}
let body: { participantId?: unknown };
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400 });
}
const participantId = typeof body.participantId === "string" ? body.participantId.trim() : "";
if (!participantId || participantId.length > 100 || participantId === host.participantId) {
return NextResponse.json({ error: "Ungültiger Teilnehmer." }, { status: 400 });
}
try {
const roomService = getLiveKitRoomService();
const room = getLiveKitRoomName(slug);
const participant = (await roomService.listParticipants(room)).find((item) => item.identity === participantId);
if (!participant) return NextResponse.json({ error: "Teilnehmer nicht gefunden." }, { status: 404 });
let clientId: string | undefined;
try {
const metadata = JSON.parse(participant.metadata || "{}") as { clientId?: unknown };
if (typeof metadata.clientId === "string" && metadata.clientId.length <= 100) clientId = metadata.clientId;
} catch {
// Metadata is optional; the participant identity is still revoked below.
}
markMeetingParticipantKicked(slug, participantId, clientId);
await roomService.removeParticipant(room, participantId);
return NextResponse.json({ ok: true });
} catch (error) {
console.error("meeting participant kick failed", error);
return NextResponse.json({ error: "Der Teilnehmer konnte nicht entfernt werden." }, { status: 503 });
}
}
@@ -1,14 +1,40 @@
import { NextResponse } from "next/server";
import { getPayload } from "payload";
import config from "@payload-config";
import { checkRateLimit, getClientIp } from "@/lib/auth/rateLimit";
export const dynamic = "force-dynamic";
// Registration capacity is checked before the insert. Serialize registrations
// for the same event so two simultaneous requests cannot both observe the
// same free seat in this single-process deployment.
const registrationLocks = new Map<string, Promise<void>>();
async function withEventRegistrationLock<T>(eventId: string, action: () => Promise<T>): Promise<T> {
const previous = registrationLocks.get(eventId) ?? Promise.resolve();
let release!: () => void;
const current = new Promise<void>((resolve) => {
release = resolve;
});
registrationLocks.set(eventId, current);
await previous;
try {
return await action();
} finally {
release();
if (registrationLocks.get(eventId) === current) registrationLocks.delete(eventId);
}
}
type Args = { params: Promise<{ slug: string }> };
export async function POST(request: Request, { params }: Args) {
const { slug } = await params;
if (!checkRateLimit(`event-registration:ip:${getClientIp(request)}`, { max: 20, windowMs: 60 * 60 * 1000 })) {
return NextResponse.json({ error: "Zu viele Anmeldungen. Bitte versuche es später erneut." }, { status: 429 });
}
let body: { name?: unknown; email?: unknown };
try {
body = await request.json();
@@ -17,8 +43,8 @@ export async function POST(request: Request, { params }: Args) {
}
const name = typeof body.name === "string" ? body.name.trim() : "";
const email = typeof body.email === "string" ? body.email.trim() : "";
if (!name || !email || !email.includes("@")) {
const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
if (!name || name.length > 120 || !email || email.length > 254 || !email.includes("@")) {
return NextResponse.json({ error: "Bitte gib deinen Namen und eine gültige E-Mail-Adresse an." }, { status: 400 });
}
@@ -31,41 +57,46 @@ export async function POST(request: Request, { params }: Args) {
limit: 1,
});
const event = docs[0];
if (!event) {
if (!event || event._status !== "published" || !event.registrationRequired) {
return NextResponse.json({ error: "Dieser Termin wurde nicht gefunden." }, { status: 404 });
}
const { docs: existingForEmail } = await payload.find({
collection: "event-registrations",
where: {
and: [
{ event: { equals: event.id } },
{ email: { equals: email } },
{ status: { equals: "registered" } },
],
},
limit: 1,
});
if (existingForEmail[0]) {
return NextResponse.json({ ok: true, alreadyRegistered: true });
if (!checkRateLimit(`event-registration:email:${event.id}:${email}`, { max: 3, windowMs: 60 * 60 * 1000 })) {
return NextResponse.json({ error: "Zu viele Anmeldeversuche für diese Adresse. Bitte versuche es später erneut." }, { status: 429 });
}
if (event.maxParticipants) {
const { totalDocs } = await payload.count({
return await withEventRegistrationLock(String(event.id), async () => {
const { docs: existingForEmail } = await payload.find({
collection: "event-registrations",
where: { and: [{ event: { equals: event.id } }, { status: { equals: "registered" } }] },
where: {
and: [
{ event: { equals: event.id } },
{ email: { equals: email } },
{ status: { equals: "registered" } },
],
},
limit: 1,
});
if (totalDocs >= event.maxParticipants) {
return NextResponse.json({ error: "Dieser Termin ist bereits ausgebucht." }, { status: 409 });
if (existingForEmail[0]) {
return NextResponse.json({ ok: true, alreadyRegistered: true });
}
}
await payload.create({
collection: "event-registrations",
data: { event: event.id, name, email, status: "registered" },
if (event.maxParticipants) {
const { totalDocs } = await payload.count({
collection: "event-registrations",
where: { and: [{ event: { equals: event.id } }, { status: { equals: "registered" } }] },
});
if (totalDocs >= event.maxParticipants) {
return NextResponse.json({ error: "Dieser Termin ist bereits ausgebucht." }, { status: 409 });
}
}
await payload.create({
collection: "event-registrations",
data: { event: event.id, name, email, status: "registered" },
});
return NextResponse.json({ ok: true });
});
return NextResponse.json({ ok: true });
} catch (error) {
console.error("event registration failed", error);
return NextResponse.json({ error: "Die Anmeldung ist gerade nicht möglich. Bitte versuche es später erneut." }, { status: 500 });