Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,101 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadBookingContext: vi.fn(),
requireBookingPermission: vi.fn(),
validateCSRFToken: vi.fn(),
getBookingPageForEdit: vi.fn(),
createBookingPage: vi.fn(),
updateBookingPage: vi.fn(),
isSlugTaken: vi.fn(),
getTenantUsers: vi.fn(),
listIntakeFormOptions: vi.fn(),
getTranslations: vi.fn(),
}));
vi.mock("./bookingAccess.server", () => ({
BOOKING_PERMISSIONS: { admin: "bookings.admin" },
loadBookingContext: mocks.loadBookingContext,
requireBookingPermission: mocks.requireBookingPermission,
}));
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRFToken }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: mocks.getTranslations }));
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenantUsers: mocks.getTenantUsers }));
vi.mock("../db/booking.db.server", () => ({
getBookingPageForEdit: mocks.getBookingPageForEdit,
createBookingPage: mocks.createBookingPage,
updateBookingPage: mocks.updateBookingPage,
isSlugTaken: mocks.isSlugTaken,
listIntakeFormOptions: mocks.listIntakeFormOptions,
}));
import { bookingPageEditorAction, bookingPageEditorLoader } from "./BookingPageEditor.server";
function actionRequest(): Request {
const form = new URLSearchParams();
form.set("slug", "beratung");
form.set("title", "Beratung");
form.set("providers", "provider-a");
form.set("durationMinutes", "30");
return new Request("http://app.localhost/acme/bookings/pages/page-a", { method: "POST", body: form });
}
describe("booking page editor action tenant boundary", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.loadBookingContext.mockResolvedValue({
tenantId: "tenant-a",
userId: "admin-a",
permissions: ["bookings.admin"],
hasModule: true,
});
mocks.getBookingPageForEdit.mockResolvedValue({ id: "page-a" });
mocks.isSlugTaken.mockResolvedValue(false);
mocks.updateBookingPage.mockResolvedValue(true);
mocks.getTenantUsers.mockResolvedValue([]);
mocks.listIntakeFormOptions.mockResolvedValue([]);
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
});
it("returns 404 for a foreign edit target before parsing or writing", async () => {
mocks.getBookingPageForEdit.mockResolvedValueOnce(null);
await expect(bookingPageEditorAction({ request: actionRequest(), params: { tenant: "acme", id: "page-from-tenant-b" } } as never)).rejects.toMatchObject({
status: 404,
});
expect(mocks.getBookingPageForEdit).toHaveBeenCalledWith("tenant-a", "page-from-tenant-b");
expect(mocks.isSlugTaken).not.toHaveBeenCalled();
expect(mocks.updateBookingPage).not.toHaveBeenCalled();
});
it("returns 404 when the transaction loses the tenant-owned target", async () => {
mocks.updateBookingPage.mockResolvedValueOnce(false);
await expect(bookingPageEditorAction({ request: actionRequest(), params: { tenant: "acme", id: "page-a" } } as never)).rejects.toMatchObject({
status: 404,
});
expect(mocks.updateBookingPage).toHaveBeenCalledWith("page-a", expect.objectContaining({ tenantId: "tenant-a" }));
});
it("exposes a translated title for the new-page breadcrumb", async () => {
const result = await bookingPageEditorLoader({
request: new Request("http://app.localhost/acme/bookings/pages/new"),
params: { tenant: "acme" },
} as never);
expect(result).toMatchObject({ data: { title: `bookings.pages.new | ${process.env.APP_NAME}` } });
});
it("uses the booking page name for an edit breadcrumb", async () => {
mocks.getBookingPageForEdit.mockResolvedValueOnce({ id: "page-a", slug: "beratung", title: "Erstberatung" });
const result = await bookingPageEditorLoader({
request: new Request("http://app.localhost/acme/bookings/pages/page-a"),
params: { tenant: "acme", id: "page-a" },
} as never);
expect(result).toMatchObject({ data: { title: `Erstberatung | ${process.env.APP_NAME}` } });
});
});
@@ -5,16 +5,30 @@
import { type LoaderFunctionArgs, type ActionFunctionArgs, data, redirect } from "react-router";
import { validateCSRFToken } from "~/utils/session.server";
import { getTranslations } from "~/locale/i18next.server";
import { getTenantUsers } from "~/utils/db/tenants.db.server";
import { loadBookingContext, requireBookingPermission, BOOKING_PERMISSIONS } from "./bookingAccess.server";
import { RESERVED_BOOKING_SLUGS, bookingPagesListPath, publicBookingPath, publicBookingEmbedPath, notFoundResponse } from "./bookingRoutePaths";
import { getBookingPageForEdit, createBookingPage, updateBookingPage, isSlugTaken, type BookingPageEdit } from "../db/booking.db.server";
import { getBookingPageForEdit, createBookingPage, updateBookingPage, isSlugTaken, listIntakeFormOptions, type BookingPageEdit, type IntakeFormOption } from "../db/booking.db.server";
export interface BookingPageProviderOption {
readonly id: string;
readonly label: string;
}
export interface BookingPageEditorLoaderData {
readonly title: string;
readonly mode: "new" | "edit";
readonly tenantSlug: string;
readonly page: BookingPageEdit | null;
readonly publicUrl: string | null;
readonly embedCode: string | null;
readonly providerOptions: readonly BookingPageProviderOption[];
readonly intakeFormOptions: readonly IntakeFormOption[];
/** Booking-pages list this editor sits under — back link target. */
readonly listHref: string;
/** Breadcrumb ancestor for the shell: the booking-pages list this editor sits under. */
readonly breadcrumbAncestors: readonly { readonly label: string; readonly href: string }[];
}
export type BookingPageEditorActionData = { readonly ok: false; readonly errorKey: string; readonly field?: string };
@@ -24,6 +38,7 @@ function embedSnippet(url: string): string {
}
export async function bookingPageEditorLoader({ request, params }: LoaderFunctionArgs) {
const { t } = await getTranslations(request);
const ctx = await loadBookingContext({ request, params, requireModule: true });
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
const tenantSlug = params.tenant ?? "";
@@ -36,7 +51,29 @@ export async function bookingPageEditorLoader({ request, params }: LoaderFunctio
const publicUrl = page ? `${origin}${publicBookingPath(tenantSlug, page.slug)}` : null;
const embedCode = page ? embedSnippet(`${origin}${publicBookingEmbedPath(tenantSlug, page.slug)}`) : null;
return data<BookingPageEditorLoaderData>({ mode: params.id ? "edit" : "new", tenantSlug, page, publicUrl, embedCode });
const [members, intakeFormOptions] = await Promise.all([getTenantUsers(ctx.tenantId), listIntakeFormOptions(ctx.tenantId)]);
const providerOptions: BookingPageProviderOption[] = members.map((member) => ({
id: member.userId,
label: [member.user.firstName, member.user.lastName].filter(Boolean).join(" ") || member.user.email,
}));
const pageTitle = page?.title ?? t(params.id ? "bookings.pages.editor.title" : "bookings.pages.new");
return data<BookingPageEditorLoaderData>({
title: `${pageTitle} | ${process.env.APP_NAME}`,
mode: params.id ? "edit" : "new",
tenantSlug,
page,
publicUrl,
embedCode,
providerOptions,
intakeFormOptions,
listHref: bookingPagesListPath(tenantSlug),
// Names the booking-pages list this editor was reached through, so the shell
// breadcrumb reads tenant > Termine > Booking-Seiten > <page> instead of
// jumping straight from the module crumb to the page.
breadcrumbAncestors: [{ label: t("bookings.pages.title"), href: bookingPagesListPath(tenantSlug) }],
});
}
export async function bookingPageEditorAction({ request, params }: ActionFunctionArgs) {
@@ -44,6 +81,10 @@ export async function bookingPageEditorAction({ request, params }: ActionFunctio
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
await validateCSRFToken(request);
if (params.id && !(await getBookingPageForEdit(ctx.tenantId, params.id))) {
throw notFoundResponse();
}
const form = await request.formData();
const slug = ((form.get("slug") as string | null) ?? "").trim().toLowerCase();
const title = ((form.get("title") as string | null) ?? "").trim();
@@ -77,12 +118,14 @@ export async function bookingPageEditorAction({ request, params }: ActionFunctio
confirmationEmailBody: ((form.get("confirmationEmailBody") as string | null) ?? "").trim() || "Dein Termin ist bestätigt.",
isPublished: form.get("isPublished") === "on" || form.get("isPublished") === "true",
providerUserIds,
// AK-P16c link: the selected intake form drives the real FormSubmission on booking.
intakeFormId: ((form.get("intakeFormId") as string | null) ?? "").trim() || null,
};
if (params.id) {
await updateBookingPage(params.id, input);
} else {
await createBookingPage(input);
const writeResult = params.id ? await updateBookingPage(params.id, input) : await createBookingPage(input);
if (!writeResult) {
throw notFoundResponse();
}
return redirect(bookingPagesListPath(params.tenant ?? ""));
const messageKey = params.id ? "bookings.pages.toast.saved" : "bookings.pages.toast.created";
return redirect(`${bookingPagesListPath(params.tenant ?? "")}?toast=${encodeURIComponent(messageKey)}`);
}
@@ -0,0 +1,21 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
import { normalizePublicBookingRedirect } from "./PublicBooking.server";
describe("public booking completion redirect", () => {
test("allows HTTPS completion URLs and local HTTP development targets", () => {
expect(normalizePublicBookingRedirect("https://customer.example/thanks?booking=1")).toBe(
"https://customer.example/thanks?booking=1",
);
expect(normalizePublicBookingRedirect("http://localhost:3000/thanks")).toBe("http://localhost:3000/thanks");
});
test("rejects scriptable, relative, malformed and oversized redirect values", () => {
expect(normalizePublicBookingRedirect("javascript:alert(document.cookie)")).toBeNull();
expect(normalizePublicBookingRedirect("data:text/html,<script>alert(1)</script>")).toBeNull();
expect(normalizePublicBookingRedirect("//attacker.example/phish")).toBeNull();
expect(normalizePublicBookingRedirect("/relative-path")).toBeNull();
expect(normalizePublicBookingRedirect("http://customer.example/phish")).toBeNull();
expect(normalizePublicBookingRedirect("x".repeat(2_049))).toBeNull();
});
});
@@ -0,0 +1,77 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActionFunctionArgs } from "react-router";
const mocks = vi.hoisted(() => ({
checkAuthRateLimit: vi.fn(),
resolvePublicBookingPageRlsIdentity: vi.fn(),
resolvePublicBookingPage: vi.fn(),
submitBooking: vi.fn(),
}));
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: mocks.checkAuthRateLimit }));
vi.mock("@hivegrid/db/rls-resolvers.server", () => ({
resolvePublicBookingPageRlsIdentity: mocks.resolvePublicBookingPageRlsIdentity,
}));
vi.mock("../db/booking.db.server", () => ({ resolvePublicBookingPage: mocks.resolvePublicBookingPage }));
vi.mock("../services/SlotQueryService.server", () => ({ loadSlotsForDate: vi.fn() }));
vi.mock("../services/slotEngine", () => ({ pickFirstAvailableProvider: vi.fn() }));
vi.mock("../services/BookingSubmitService.server", () => ({
BookingSlotTakenError: class BookingSlotTakenError extends Error {},
BookingValidationError: class BookingValidationError extends Error {},
submitBooking: mocks.submitBooking,
}));
const { publicBookingAction } = await import("./PublicBooking.server");
beforeEach(() => {
vi.clearAllMocks();
mocks.checkAuthRateLimit.mockResolvedValue({ allowed: true });
mocks.resolvePublicBookingPageRlsIdentity.mockResolvedValue({ tenantId: "tenant_1", resourceId: "page_1" });
});
describe("public booking abuse protection", () => {
it("rate-limits before page lookup, form parsing, or booking writes", async () => {
mocks.checkAuthRateLimit.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 45 });
const request = new Request("https://app.example.test/b/acme/consulting", {
method: "POST",
body: "attacker-controlled-body",
});
const response = await publicBookingAction({
request,
params: { tenant: "acme", slug: "consulting" },
context: {},
unstable_pattern: "b.$tenant.$slug",
} as ActionFunctionArgs);
expect(response.status).toBe(429);
expect(response.headers.get("Retry-After")).toBe("45");
expect(response.headers.get("Cache-Control")).toBe("no-store");
expect(mocks.checkAuthRateLimit).toHaveBeenCalledWith(expect.objectContaining({ action: "booking-submit", identifier: "acme/consulting", limit: 10 }));
expect(mocks.resolvePublicBookingPage).not.toHaveBeenCalled();
expect(mocks.submitBooking).not.toHaveBeenCalled();
});
it("enters the resolved tenant context before reading the protected booking page", async () => {
const { getRlsExecutionContext } = await import("@hivegrid/db/rls-context.server");
mocks.resolvePublicBookingPage.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1" });
return null;
});
const request = new Request("https://app.example.test/b/acme/consulting", {
method: "POST",
body: new URLSearchParams(),
});
await expect(
publicBookingAction({
request,
params: { tenant: "acme", slug: "consulting" },
context: {},
unstable_pattern: "b.$tenant.$slug",
} as ActionFunctionArgs)
).rejects.toMatchObject({ status: 404 });
expect(mocks.resolvePublicBookingPageRlsIdentity).toHaveBeenCalledWith("acme", "consulting");
});
});
@@ -12,8 +12,14 @@ 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;
@@ -49,7 +55,14 @@ function resolveDate(url: URL, timezone: string, now: Date): string {
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[]> {
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)
@@ -57,80 +70,127 @@ async function buildSlots(tenantId: string, providerUserIds: string[], date: str
}
export async function publicBookingLoader({ request, params }: LoaderFunctionArgs) {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
const identity = await resolvePublicBookingPageRlsIdentity(params.tenant ?? "", params.slug ?? "");
if (!identity) {
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);
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);
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 page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
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();
}
const form = await request.formData();
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 });
}
// 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 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 result = await submitBooking({
page,
startAtIso,
date,
viewerTimeZone: timezone,
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(),
});
if (result.redirectUrl) {
return redirect(result.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 });
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;
}
}
@@ -39,6 +39,21 @@ describe("booking route authorization boundary", () => {
expect(source).toContain('intent === "reassign"');
});
test("availability action guards permission + CSRF before parsing the form", () => {
const source = fs.readFileSync(path.join(appRoot, "routes/app.$tenant/availability.tsx"), "utf8");
const formDataAt = source.indexOf("await request.formData()");
expect(formDataAt).toBeGreaterThanOrEqual(0);
const permissionAt = source.indexOf("requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn)", source.indexOf("export const action"));
const csrfAt = source.indexOf("await validateCSRFToken(request)");
expect(permissionAt).toBeGreaterThanOrEqual(0);
expect(csrfAt).toBeGreaterThanOrEqual(0);
expect(permissionAt).toBeLessThan(formDataAt);
expect(csrfAt).toBeLessThan(formDataAt);
// The action only ever writes the CALLER's availability (own scope).
expect(source).toContain("providerUserId: ctx.userId");
});
test("booking-page editor action guards admin permission + CSRF before parsing the form", () => {
const source = fs.readFileSync(path.join(appRoot, "modules/booking/routes/BookingPageEditor.server.ts"), "utf8");
const formDataAt = source.indexOf("await request.formData()");