Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/modules/booking/routes/PublicBooking.server.ts
T

197 lines
7.6 KiB
TypeScript

// AK-P16b · public booking flow (M06 Block G) — loader + action shared by the
// canonical `/b/{tenant}/{slug}` route and its `/embed` iframe variant. NO auth, NO
// session CSRF (there is no logged-in user); abuse is bounded by a honeypot + the
// GDPR-acceptance gate + the slot re-check on submit. The tenant is resolved from
// the URL slug; an unknown/inactive tenant or unpublished page is a 404 with the
// same Klartext (never leaks tenant existence, M06 G.4/K.6).
import { type LoaderFunctionArgs, type ActionFunctionArgs, data, redirect } from "react-router";
import { formatInTimeZone } from "date-fns-tz";
import { notFoundResponse } from "./bookingRoutePaths";
import { resolvePublicBookingPage } from "../db/booking.db.server";
import { loadSlotsForDate } from "../services/SlotQueryService.server";
import { pickFirstAvailableProvider } from "../services/slotEngine";
import { submitBooking, BookingValidationError, BookingSlotTakenError } from "../services/BookingSubmitService.server";
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolvePublicBookingPageRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
import { getTranslations } from "~/locale/i18next.server";
const DEFAULT_TZ = "Europe/Berlin";
const BOOKING_SUBMIT_RATE_LIMIT = 10;
const BOOKING_SUBMIT_RATE_WINDOW_MS = 60 * 1000;
export interface PublicBookingSlotVM {
readonly startAtIso: string;
readonly label: string;
}
export interface PublicBookingLoaderData {
readonly tenantSlug: string;
readonly slug: string;
readonly title: string;
readonly description: string | null;
readonly tenantName: string;
readonly durationMinutes: number;
readonly date: string;
readonly timezone: string;
readonly slots: PublicBookingSlotVM[];
readonly isEmbed: boolean;
}
export type PublicBookingActionData =
| { readonly ok: true; readonly titleLabel: string; readonly dateLabel: string; readonly timeLabel: string; readonly icsBase64: string }
| { readonly ok: false; readonly errorKey: string; readonly field?: string };
function resolveTimezone(url: URL): string {
return url.searchParams.get("tz") || DEFAULT_TZ;
}
function resolveDate(url: URL, timezone: string, now: Date): string {
const requested = url.searchParams.get("date");
if (requested && /^\d{4}-\d{2}-\d{2}$/u.test(requested)) {
return requested;
}
return formatInTimeZone(now, timezone, "yyyy-MM-dd");
}
async function buildSlots(
tenantId: string,
providerUserIds: string[],
date: string,
config: Parameters<typeof loadSlotsForDate>[0]["config"],
timezone: string,
now: Date
): Promise<PublicBookingSlotVM[]> {
const slots = await loadSlotsForDate({ tenantId, providerUserIds, date, config, now });
return slots
.filter((slot) => pickFirstAvailableProvider(slot) !== null)
.map((slot) => ({ startAtIso: slot.startAt.toISOString(), label: formatInTimeZone(slot.startAt, timezone, "HH:mm") }));
}
export async function publicBookingLoader({ request, params }: LoaderFunctionArgs) {
const identity = await resolvePublicBookingPageRlsIdentity(params.tenant ?? "", params.slug ?? "");
if (!identity) {
throw notFoundResponse();
}
return runWithRlsContext({ tenantId: identity.tenantId }, async () => {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
throw notFoundResponse();
}
const url = new URL(request.url);
const now = new Date();
const timezone = resolveTimezone(url);
const date = resolveDate(url, timezone, now);
const slots = await buildSlots(page.tenantId, page.providerUserIds, date, page.config, timezone, now);
const payload: PublicBookingLoaderData = {
tenantSlug: page.tenantSlug,
slug: page.slug,
title: page.title,
description: page.description,
tenantName: page.tenantName,
durationMinutes: page.durationMinutes,
date,
timezone,
slots,
isEmbed: url.pathname.endsWith("/embed"),
};
return data(payload);
});
}
export async function publicBookingAction({ request, params }: ActionFunctionArgs) {
const rateLimit = await checkAuthRateLimit({
request,
action: "booking-submit",
identifier: `${params.tenant ?? ""}/${params.slug ?? ""}`,
limit: BOOKING_SUBMIT_RATE_LIMIT,
windowMs: BOOKING_SUBMIT_RATE_WINDOW_MS,
});
if (!rateLimit.allowed) {
return Response.json(
{ ok: false, errorKey: "bookings.error.submitFailed" },
{
status: 429,
headers: {
"Cache-Control": "no-store",
"Retry-After": String(rateLimit.retryAfterSeconds),
},
}
);
}
const identity = await resolvePublicBookingPageRlsIdentity(params.tenant ?? "", params.slug ?? "");
if (!identity) {
throw notFoundResponse();
}
return runWithRlsContext({ tenantId: identity.tenantId }, async () => {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
throw notFoundResponse();
}
const form = await request.formData();
// Honeypot: real users never fill this hidden field (M06 abuse guard).
if ((form.get("company") as string | null)?.trim()) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 400 });
}
const url = new URL(request.url);
const timezone = (form.get("tz") as string | null) || resolveTimezone(url);
const date = (form.get("date") as string | null) ?? "";
const startAtIso = (form.get("startAt") as string | null) ?? "";
const translations = await getTranslations(request);
try {
const result = await submitBooking({
page,
startAtIso,
date,
viewerTimeZone: timezone,
locale: translations.locale,
intake: {
vorname: (form.get("vorname") as string | null) ?? "",
nachname: (form.get("nachname") as string | null) ?? "",
email: (form.get("email") as string | null) ?? "",
telefon: (form.get("telefon") as string | null) ?? undefined,
gdprAccepted: form.get("gdpr") === "on" || form.get("gdpr") === "true",
},
now: new Date(),
});
const redirectUrl = normalizePublicBookingRedirect(result.redirectUrl);
if (redirectUrl) {
return redirect(redirectUrl);
}
return data<PublicBookingActionData>({
ok: true,
titleLabel: page.title,
dateLabel: formatInTimeZone(result.startAt, timezone, "dd.MM.yyyy"),
timeLabel: formatInTimeZone(result.startAt, timezone, "HH:mm"),
icsBase64: result.icsBase64,
});
} catch (error) {
if (error instanceof BookingValidationError) {
return data<PublicBookingActionData>({ ok: false, errorKey: error.code, field: error.field }, { status: 400 });
}
if (error instanceof BookingSlotTakenError) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.slotTaken" }, { status: 409 });
}
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 500 });
}
});
}
export function normalizePublicBookingRedirect(value: string | null | undefined): string | null {
if (!value || value.length > 2_048) return null;
try {
const url = new URL(value);
const localDevelopmentUrl = url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");
if (url.protocol !== "https:" && !localDevelopmentUrl) return null;
return url.toString();
} catch {
return null;
}
}