Add email verification, personal calendar feed, and full SEO implementation
- Customer accounts now require email verification (hashed, single-use, time-limited tokens) before they can request/confirm bookings, with resend flows on login/account/booking widget and rate limiting. - Admins get a private, rotatable iCalendar (ICS) subscription feed of their confirmed bookings and public events, timezone-correct for Europe/Berlin including DST, never exposing meeting passwords. - Adds a full SEO layer: per-page canonical/OG/Twitter metadata with CMS-editable overrides and content-derived fallbacks, a dynamic sitemap.xml and robots.txt driven by real published content, JSON-LD (Organization/LocalBusiness, WebSite, WebPage, BreadcrumbList, Service, Event, BlogPosting) that never fabricates data, and a CMS-managed redirect table for changed slugs. - Global ANOUMA-naming audit: the brand name is never used to label personal account/calendar areas anywhere in the app, CMS, or emails. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Minimal in-memory fixed-window rate limiter for a single Node process
|
||||
* (this app always runs as one process — see server.ts). Good enough to
|
||||
* blunt abuse of the email-verification resend endpoint without adding an
|
||||
* external store; resets on deploy/restart, which is an acceptable
|
||||
* trade-off for this use case.
|
||||
*/
|
||||
const buckets = new Map<string, { count: number; resetAt: number }>();
|
||||
|
||||
// Opportunistic cleanup so long-running processes don't accumulate an
|
||||
// unbounded number of stale keys (one per distinct IP/email ever seen).
|
||||
const MAX_TRACKED_KEYS = 5000;
|
||||
|
||||
function sweepExpired(now: number) {
|
||||
for (const [key, bucket] of buckets) {
|
||||
if (bucket.resetAt < now) buckets.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
export function checkRateLimit(key: string, opts: { max: number; windowMs: number }): boolean {
|
||||
const now = Date.now();
|
||||
if (buckets.size > MAX_TRACKED_KEYS) sweepExpired(now);
|
||||
|
||||
const bucket = buckets.get(key);
|
||||
if (!bucket || bucket.resetAt < now) {
|
||||
buckets.set(key, { count: 1, resetAt: now + opts.windowMs });
|
||||
return true;
|
||||
}
|
||||
if (bucket.count >= opts.max) return false;
|
||||
bucket.count += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function getClientIp(request: Request): string {
|
||||
const forwarded = request.headers.get("x-forwarded-for");
|
||||
if (forwarded) return forwarded.split(",")[0]!.trim();
|
||||
return "unknown";
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
|
||||
/** How long a freshly issued email-verification link stays valid. */
|
||||
export const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/** 256 bits of randomness, hex-encoded — not guessable, never derived from user data. */
|
||||
export function generateVerificationToken(): string {
|
||||
return randomBytes(32).toString("hex");
|
||||
}
|
||||
|
||||
/**
|
||||
* Only this hash is ever persisted (see collections/Customers.ts) — the
|
||||
* plaintext token exists only in the URL sent by email and briefly in
|
||||
* memory while that email is being sent.
|
||||
*/
|
||||
export function hashVerificationToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
export function verificationExpiryISO(): string {
|
||||
return new Date(Date.now() + EMAIL_VERIFICATION_TTL_MS).toISOString();
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { getCMS } from "@/lib/payload/getPayload";
|
||||
import { hashVerificationToken } from "@/lib/auth/verification";
|
||||
|
||||
const TOKEN_SHAPE = /^[0-9a-f]{64}$/i;
|
||||
|
||||
/**
|
||||
* Verifies a token from a /auth/verify-email/[token] link: looks it up by
|
||||
* hash (the plaintext is never stored), checks it hasn't expired, then
|
||||
* marks the account verified and immediately clears the hash + expiry so
|
||||
* the same link can never be used a second time.
|
||||
*/
|
||||
export async function verifyEmailToken(token: string): Promise<boolean> {
|
||||
if (!TOKEN_SHAPE.test(token)) return false;
|
||||
|
||||
const payload = await getCMS();
|
||||
const hash = hashVerificationToken(token);
|
||||
|
||||
const { docs } = await payload.find({
|
||||
collection: "customers",
|
||||
where: { emailVerificationTokenHash: { equals: hash } },
|
||||
limit: 1,
|
||||
});
|
||||
const customer = docs[0];
|
||||
if (!customer || !customer.emailVerificationExpires) return false;
|
||||
if (new Date(customer.emailVerificationExpires).getTime() < Date.now()) return false;
|
||||
|
||||
await payload.update({
|
||||
collection: "customers",
|
||||
id: customer.id,
|
||||
data: {
|
||||
emailVerified: true,
|
||||
emailVerificationTokenHash: null,
|
||||
emailVerificationExpires: null,
|
||||
},
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { Payload } from "payload";
|
||||
import { EVENT_CATEGORIES } from "@/collections/Events";
|
||||
import type { ICSEvent } from "./ics";
|
||||
import type { BookingRequest, Customer, Event, Offer } from "@/payload-types";
|
||||
|
||||
// A rolling window rather than "everything ever": calendar apps refetch a
|
||||
// subscribed feed periodically on their own, so this just needs to cover a
|
||||
// sensible range each time, not paginate an entire history.
|
||||
const WINDOW_PAST_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
const WINDOW_FUTURE_MS = 400 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Builds the calendar entries for Anna's personal ICS feed: confirmed
|
||||
* bookings (never pending ones) plus standalone public events — onsite and
|
||||
* online alike. Deliberately never includes the meeting password anywhere
|
||||
* in the output, only a link to the protected join page.
|
||||
*
|
||||
* Local API is used with the default overrideAccess: true because this is
|
||||
* only ever reached after the caller already verified the feed's secret
|
||||
* token (see app/(frontend)/calendar/[tokenFile]/route.ts) — equivalent
|
||||
* trust to the existing admin calendar view.
|
||||
*/
|
||||
export async function getAdminFeedICSEvents(payload: Payload): Promise<ICSEvent[]> {
|
||||
const from = new Date(Date.now() - WINDOW_PAST_MS);
|
||||
const to = new Date(Date.now() + WINDOW_FUTURE_MS);
|
||||
const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL || "http://localhost:3000";
|
||||
const domainHost = new URL(serverUrl).host;
|
||||
|
||||
const [{ docs: bookings }, { docs: events }, settings] = await Promise.all([
|
||||
payload.find({
|
||||
collection: "booking-requests",
|
||||
where: {
|
||||
and: [
|
||||
{ status: { equals: "confirmed" } },
|
||||
{ date: { greater_than_equal: from.toISOString() } },
|
||||
{ date: { less_than_equal: to.toISOString() } },
|
||||
],
|
||||
},
|
||||
depth: 2,
|
||||
limit: 1000,
|
||||
}),
|
||||
payload.find({
|
||||
collection: "events",
|
||||
where: {
|
||||
and: [
|
||||
{ date: { greater_than_equal: from.toISOString() } },
|
||||
{ date: { less_than_equal: to.toISOString() } },
|
||||
{ isPrivateBooking: { not_equals: true } },
|
||||
],
|
||||
},
|
||||
depth: 0,
|
||||
limit: 1000,
|
||||
}),
|
||||
payload.findGlobal({ slug: "booking-settings" }),
|
||||
]);
|
||||
|
||||
const addressParts = [settings.locationName, settings.street, [settings.postalCode, settings.city].filter(Boolean).join(" ")].filter(Boolean);
|
||||
const fullAddress = addressParts.join(", ");
|
||||
|
||||
const bookingEvents: ICSEvent[] = (bookings as BookingRequest[]).map((b) => {
|
||||
const offer = typeof b.offer === "object" ? (b.offer as Offer) : null;
|
||||
const customer = typeof b.user === "object" ? (b.user as Customer) : null;
|
||||
const isOnline = b.appointmentType === "online";
|
||||
|
||||
const description = [
|
||||
customer?.name ? `Mit: ${customer.name}` : null,
|
||||
isOnline ? "Online-Termin" : "Vor-Ort-Termin",
|
||||
b.userMessage ? `Nachricht: ${b.userMessage}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
let url: string | undefined;
|
||||
if (isOnline && b.linkedEvent && typeof b.linkedEvent === "object") {
|
||||
url = `${serverUrl}/termine/${(b.linkedEvent as Event).slug}/beitreten`;
|
||||
} else if (!isOnline && fullAddress) {
|
||||
url = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(fullAddress)}`;
|
||||
}
|
||||
|
||||
return {
|
||||
uid: `booking-${b.id}@${domainHost}`,
|
||||
start: new Date(b.startTime),
|
||||
end: new Date(b.endTime),
|
||||
summary: offer?.title ?? "Termin",
|
||||
description: description || undefined,
|
||||
// Vor Ort: vollständige Adresse. Online: literal "Online" — never the
|
||||
// meeting password, which is intentionally not part of this feed.
|
||||
location: isOnline ? "Online" : fullAddress || undefined,
|
||||
url,
|
||||
};
|
||||
});
|
||||
|
||||
const eventEvents: ICSEvent[] = (events as Event[]).map((e) => {
|
||||
const isOnline = Boolean(e.isOnline);
|
||||
const start = new Date(e.startTime || e.date);
|
||||
const end = new Date(e.endTime || e.startTime || e.date);
|
||||
return {
|
||||
uid: `event-${e.id}@${domainHost}`,
|
||||
start,
|
||||
end,
|
||||
summary: e.title,
|
||||
description: EVENT_CATEGORIES.find((c) => c.value === e.category)?.label,
|
||||
location: isOnline ? "Online" : e.location || fullAddress || undefined,
|
||||
url: e.slug ? `${serverUrl}/termine/${e.slug}` : undefined,
|
||||
};
|
||||
});
|
||||
|
||||
return [...bookingEvents, ...eventEvents];
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
|
||||
/**
|
||||
* Long-lived, random, rotatable secret for a personal calendar-subscription
|
||||
* URL (/calendar/<token>.ics) — treated like an API key, not a
|
||||
* short-lived link: only its hash is stored, so a database leak alone
|
||||
* can't be used to subscribe to anyone's calendar, and rotating it
|
||||
* (overwriting the stored hash) immediately invalidates the old URL.
|
||||
*/
|
||||
export function generateCalendarFeedToken(): string {
|
||||
return randomBytes(32).toString("hex");
|
||||
}
|
||||
|
||||
export function hashCalendarFeedToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
export function calendarFeedUrl(token: string): string {
|
||||
const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL || "http://localhost:3000";
|
||||
return `${serverUrl}/calendar/${token}.ics`;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { BERLIN_VTIMEZONE_LINES, toBerlinICSDateTime, toUTCICSStamp } from "./timezone";
|
||||
|
||||
export type ICSEvent = {
|
||||
uid: string;
|
||||
start: Date;
|
||||
end: Date;
|
||||
summary: string;
|
||||
description?: string;
|
||||
location?: string;
|
||||
url?: string;
|
||||
};
|
||||
|
||||
function escapeICSText(value: string): string {
|
||||
return value
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(/;/g, "\\;")
|
||||
.replace(/,/g, "\\,")
|
||||
.replace(/\n/g, "\\n");
|
||||
}
|
||||
|
||||
/** RFC 5545 line folding: lines must not exceed 75 octets; continuations start with a single space. */
|
||||
function foldLine(line: string): string {
|
||||
const encoder = new TextEncoder();
|
||||
if (encoder.encode(line).length <= 75) return line;
|
||||
|
||||
const chunks: string[] = [];
|
||||
let current = "";
|
||||
for (const char of line) {
|
||||
const candidate = current + char;
|
||||
if (encoder.encode(candidate).length > 75) {
|
||||
chunks.push(current);
|
||||
current = char;
|
||||
} else {
|
||||
current = candidate;
|
||||
}
|
||||
}
|
||||
if (current) chunks.push(current);
|
||||
return chunks.join("\r\n ");
|
||||
}
|
||||
|
||||
/** Builds a complete RFC 5545 VCALENDAR document, Europe/Berlin timezone-aware throughout. */
|
||||
export function buildICSCalendar(args: { calendarName: string; events: ICSEvent[] }): string {
|
||||
const lines: string[] = [
|
||||
"BEGIN:VCALENDAR",
|
||||
"VERSION:2.0",
|
||||
"PRODID:-//ANOUMA//Calendar Feed//DE",
|
||||
"CALSCALE:GREGORIAN",
|
||||
"METHOD:PUBLISH",
|
||||
`X-WR-CALNAME:${escapeICSText(args.calendarName)}`,
|
||||
"X-WR-TIMEZONE:Europe/Berlin",
|
||||
...BERLIN_VTIMEZONE_LINES,
|
||||
];
|
||||
|
||||
const stamp = toUTCICSStamp(new Date());
|
||||
for (const ev of args.events) {
|
||||
lines.push(
|
||||
"BEGIN:VEVENT",
|
||||
`UID:${ev.uid}`,
|
||||
`DTSTAMP:${stamp}`,
|
||||
`DTSTART;TZID=Europe/Berlin:${toBerlinICSDateTime(ev.start)}`,
|
||||
`DTEND;TZID=Europe/Berlin:${toBerlinICSDateTime(ev.end)}`,
|
||||
`SUMMARY:${escapeICSText(ev.summary)}`,
|
||||
);
|
||||
if (ev.description) lines.push(`DESCRIPTION:${escapeICSText(ev.description)}`);
|
||||
if (ev.location) lines.push(`LOCATION:${escapeICSText(ev.location)}`);
|
||||
if (ev.url) lines.push(`URL:${ev.url}`);
|
||||
lines.push("STATUS:CONFIRMED", "END:VEVENT");
|
||||
}
|
||||
|
||||
lines.push("END:VCALENDAR");
|
||||
return lines.map(foldLine).join("\r\n") + "\r\n";
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
const BERLIN_TZ = "Europe/Berlin";
|
||||
|
||||
/**
|
||||
* Converts a JS Date (a UTC instant) into its Europe/Berlin wall-clock
|
||||
* representation for iCalendar's local `TZID` date-time form
|
||||
* (`DTSTART;TZID=Europe/Berlin:YYYYMMDDTHHMMSS`). Uses the ICU timezone
|
||||
* database via Intl rather than manual UTC+1/+2 arithmetic, so daylight
|
||||
* saving transitions are always handled correctly — no naive UTC offset
|
||||
* math that would drift by an hour half the year.
|
||||
*/
|
||||
export function toBerlinICSDateTime(date: Date): string {
|
||||
const parts = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: BERLIN_TZ,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
hourCycle: "h23",
|
||||
}).formatToParts(date);
|
||||
|
||||
const get = (type: string) => parts.find((p) => p.type === type)?.value ?? "00";
|
||||
return `${get("year")}${get("month")}${get("day")}T${get("hour")}${get("minute")}${get("second")}`;
|
||||
}
|
||||
|
||||
/** UTC timestamp form (`YYYYMMDDTHHMMSSZ`) — used only for DTSTAMP, which marks generation time, not a local event time. */
|
||||
export function toUTCICSStamp(date: Date): string {
|
||||
return date.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z";
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard IANA Europe/Berlin VTIMEZONE block (the same one commonly
|
||||
* embedded by calendar exporters): CEST from the last Sunday in March,
|
||||
* CET from the last Sunday in October — the actual EU DST rule, not an
|
||||
* approximation.
|
||||
*/
|
||||
export const BERLIN_VTIMEZONE_LINES = [
|
||||
"BEGIN:VTIMEZONE",
|
||||
"TZID:Europe/Berlin",
|
||||
"X-LIC-LOCATION:Europe/Berlin",
|
||||
"BEGIN:DAYLIGHT",
|
||||
"TZOFFSETFROM:+0100",
|
||||
"TZOFFSETTO:+0200",
|
||||
"TZNAME:CEST",
|
||||
"DTSTART:19700329T020000",
|
||||
"RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU",
|
||||
"END:DAYLIGHT",
|
||||
"BEGIN:STANDARD",
|
||||
"TZOFFSETFROM:+0200",
|
||||
"TZOFFSETTO:+0100",
|
||||
"TZNAME:CET",
|
||||
"DTSTART:19701025T030000",
|
||||
"RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU",
|
||||
"END:STANDARD",
|
||||
"END:VTIMEZONE",
|
||||
];
|
||||
@@ -0,0 +1,14 @@
|
||||
import { paragraph, renderButton, renderEmailShell } from "./layout";
|
||||
|
||||
export function verificationEmail(args: { name: string; verifyUrl: string; expiresHours: number }): { subject: string; html: string } {
|
||||
const html = renderEmailShell({
|
||||
bodyHtml: [
|
||||
paragraph(`Hallo ${args.name},`),
|
||||
paragraph("dein Konto wurde erstellt.", { italic: true }),
|
||||
paragraph("Bitte bestätige deine E-Mail-Adresse, um dein Konto zu aktivieren."),
|
||||
renderButton("E-Mail-Adresse bestätigen", args.verifyUrl),
|
||||
paragraph(`Dieser Link ist ${args.expiresHours} Stunden gültig. Falls du kein Konto erstellt hast, kannst du diese E-Mail ignorieren.`, { small: true }),
|
||||
].join("\n"),
|
||||
});
|
||||
return { subject: "Bitte bestätige deine E-Mail-Adresse", html };
|
||||
}
|
||||
@@ -98,7 +98,7 @@ export function bookingRejectedEmail(args: BaseArgs): { subject: string; html: s
|
||||
{ label: "Datum", value: args.dateLabel },
|
||||
{ label: "Uhrzeit", value: args.timeLabel },
|
||||
]),
|
||||
paragraph("Melde dich gerne für einen neuen Termin — schau einfach wieder in deinem ANOUMA-Konto vorbei.", { small: true }),
|
||||
paragraph("Melde dich gerne für einen neuen Termin — schau einfach wieder in deinem Konto vorbei.", { small: true }),
|
||||
].join("\n"),
|
||||
});
|
||||
return { subject: "Deine Terminanfrage bei ANOUMA", html };
|
||||
|
||||
+11
-1
@@ -1,6 +1,6 @@
|
||||
import { cache } from "react";
|
||||
import { getCMS } from "@/lib/payload/getPayload";
|
||||
import type { About, AktuellesIntro, AngeboteIntro, Booking, Contact, Home } from "@/payload-types";
|
||||
import type { About, AktuellesIntro, AngeboteIntro, Booking, BookingSetting, Contact, Home, SeoSetting } from "@/payload-types";
|
||||
|
||||
export const getHomeGlobal = cache(async (): Promise<Home> => {
|
||||
const payload = await getCMS();
|
||||
@@ -31,3 +31,13 @@ export const getBookingGlobal = cache(async (): Promise<Booking> => {
|
||||
const payload = await getCMS();
|
||||
return payload.findGlobal({ slug: "booking" });
|
||||
});
|
||||
|
||||
export const getBookingSettingsGlobal = cache(async (): Promise<BookingSetting> => {
|
||||
const payload = await getCMS();
|
||||
return payload.findGlobal({ slug: "booking-settings" });
|
||||
});
|
||||
|
||||
export const getSEOSettingsGlobal = cache(async (): Promise<SeoSetting> => {
|
||||
const payload = await getCMS();
|
||||
return payload.findGlobal({ slug: "seo-settings" });
|
||||
});
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { getSEOSettingsGlobal } from "@/lib/payload/globals";
|
||||
import { siteConfig } from "@/lib/site";
|
||||
|
||||
function stripTrailingSlash(url: string): string {
|
||||
return url.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* The canonical base URL for the whole site. Prefers the CMS override
|
||||
* (SEO-Einstellungen → Website-URL) when it's a valid absolute URL, then
|
||||
* NEXT_PUBLIC_SERVER_URL (the single source of truth used everywhere else
|
||||
* in this app — emails, meeting links, Payload's own serverURL), then the
|
||||
* hardcoded siteConfig fallback. Never throws — SEO metadata must never
|
||||
* break a page render.
|
||||
*/
|
||||
export async function getSiteUrl(): Promise<string> {
|
||||
try {
|
||||
const settings = await getSEOSettingsGlobal();
|
||||
if (settings.siteUrl && /^https?:\/\/.+/.test(settings.siteUrl)) {
|
||||
return stripTrailingSlash(settings.siteUrl);
|
||||
}
|
||||
} catch {
|
||||
// CMS/DB unreachable — fall through to the env-based default.
|
||||
}
|
||||
return stripTrailingSlash(process.env.NEXT_PUBLIC_SERVER_URL || siteConfig.domain);
|
||||
}
|
||||
|
||||
/** Whether the site should be indexable at all (global kill switch in the CMS). */
|
||||
export async function isSiteIndexable(): Promise<boolean> {
|
||||
try {
|
||||
const settings = await getSEOSettingsGlobal();
|
||||
return settings.robotsIndexable !== false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Formats a JS Date as an ISO 8601 string carrying its actual Europe/Berlin
|
||||
* UTC offset (e.g. "2026-06-15T09:00:00+02:00" in summer,
|
||||
* "...+01:00" in winter) — what schema.org's Event startDate/endDate
|
||||
* expect. Uses Intl's timezone database rather than hardcoded +1/+2 math,
|
||||
* so it's correct across the DST transition automatically.
|
||||
*/
|
||||
export function toBerlinOffsetISOString(date: Date): string {
|
||||
const parts = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
hourCycle: "h23",
|
||||
timeZoneName: "shortOffset",
|
||||
}).formatToParts(date);
|
||||
|
||||
const get = (type: string) => parts.find((p) => p.type === type)?.value ?? "00";
|
||||
const tzName = parts.find((p) => p.type === "timeZoneName")?.value ?? "GMT+0";
|
||||
const match = /GMT([+-])(\d+)(?::(\d+))?/.exec(tzName);
|
||||
const sign = match?.[1] ?? "+";
|
||||
const offsetHours = (match?.[2] ?? "0").padStart(2, "0");
|
||||
const offsetMinutes = (match?.[3] ?? "0").padStart(2, "0");
|
||||
|
||||
return `${get("year")}-${get("month")}-${get("day")}T${get("hour")}:${get("minute")}:${get("second")}${sign}${offsetHours}:${offsetMinutes}`;
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import { siteConfig } from "@/lib/site";
|
||||
import { toBerlinOffsetISOString } from "./dates";
|
||||
import type { BookingSetting, Contact, Event, Offer, Post, SeoSetting } from "@/payload-types";
|
||||
|
||||
// Server-only builders — every function here returns `null` instead of
|
||||
// guessing when the real data needed for a valid/honest result isn't
|
||||
// present. Nothing here ever invents a review, price, address or phone
|
||||
// number (see section 27/35 of the SEO brief).
|
||||
|
||||
/** JSON.stringify with `<` escaped so this can never be broken out of by any (currently non-existent) embedded "</script>" sequence. */
|
||||
function toSafeJsonLdString(data: unknown): string {
|
||||
return JSON.stringify(data).replace(/</g, "\\u003c");
|
||||
}
|
||||
|
||||
type JsonLdValue = Record<string, unknown>;
|
||||
|
||||
export function organizationName(settings: SeoSetting | null | undefined): string {
|
||||
return settings?.businessName?.trim() || siteConfig.name;
|
||||
}
|
||||
|
||||
function hasFullAddress(booking: BookingSetting | null | undefined): booking is BookingSetting & { street: string; city: string; postalCode: string } {
|
||||
return Boolean(booking?.street?.trim() && booking?.city?.trim() && booking?.postalCode?.trim());
|
||||
}
|
||||
|
||||
function postalAddress(booking: BookingSetting) {
|
||||
return {
|
||||
"@type": "PostalAddress",
|
||||
streetAddress: booking.street!.trim(),
|
||||
postalCode: booking.postalCode!.trim(),
|
||||
addressLocality: booking.city!.trim(),
|
||||
...(booking.region?.trim() ? { addressRegion: booking.region.trim() } : {}),
|
||||
...(booking.country?.trim() ? { addressCountry: booking.country.trim() } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Organization (always safe — just a name and a URL) upgraded to
|
||||
* ProfessionalService/LocalBusiness once a real, complete street address
|
||||
* has actually been entered in the CMS. Phone/opening hours/geo are added
|
||||
* only when present; nothing is fabricated to "complete" the schema.
|
||||
*/
|
||||
export function organizationOrLocalBusinessJsonLd(args: {
|
||||
settings: SeoSetting | null | undefined;
|
||||
booking: BookingSetting | null | undefined;
|
||||
contact: Contact | null | undefined;
|
||||
siteUrl: string;
|
||||
}): JsonLdValue {
|
||||
const name = organizationName(args.settings);
|
||||
const base: JsonLdValue = {
|
||||
"@context": "https://schema.org",
|
||||
name,
|
||||
url: args.siteUrl,
|
||||
};
|
||||
if (args.settings?.businessDescription?.trim()) base.description = args.settings.businessDescription.trim();
|
||||
if (args.contact?.email) base.email = args.contact.email;
|
||||
|
||||
if (!hasFullAddress(args.booking)) {
|
||||
return { ...base, "@type": "Organization" };
|
||||
}
|
||||
|
||||
const result: JsonLdValue = {
|
||||
...base,
|
||||
"@type": "ProfessionalService",
|
||||
address: postalAddress(args.booking),
|
||||
};
|
||||
|
||||
if (args.contact?.phone?.trim()) result.telephone = args.contact.phone.trim();
|
||||
if (typeof args.settings?.latitude === "number" && typeof args.settings?.longitude === "number") {
|
||||
result.geo = { "@type": "GeoCoordinates", latitude: args.settings.latitude, longitude: args.settings.longitude };
|
||||
}
|
||||
if (args.settings?.openingHours?.length) {
|
||||
result.openingHoursSpecification = args.settings.openingHours.map((entry) => ({
|
||||
"@type": "OpeningHoursSpecification",
|
||||
dayOfWeek: entry.days.map((day) => `https://schema.org/${day}`),
|
||||
opens: entry.opens,
|
||||
closes: entry.closes,
|
||||
}));
|
||||
}
|
||||
if (args.settings?.socialLinks?.length) {
|
||||
result.sameAs = args.settings.socialLinks.map((link) => link.url).filter(Boolean);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function websiteJsonLd(siteUrl: string): JsonLdValue {
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "WebSite",
|
||||
name: siteConfig.name,
|
||||
url: siteUrl,
|
||||
};
|
||||
}
|
||||
|
||||
export function webPageJsonLd(args: { name: string; description: string; url: string }): JsonLdValue {
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "WebPage",
|
||||
name: args.name,
|
||||
description: args.description,
|
||||
url: args.url,
|
||||
};
|
||||
}
|
||||
|
||||
export function breadcrumbJsonLd(items: { name: string; url?: string }[]): JsonLdValue | null {
|
||||
if (items.length === 0) return null;
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "BreadcrumbList",
|
||||
// The last item's "item" URL is deliberately omitted when absent —
|
||||
// that's the current page, and per Google's guidelines a BreadcrumbList
|
||||
// entry doesn't need a URL for the page the visitor is already on.
|
||||
itemListElement: items.map((item, index) => ({
|
||||
"@type": "ListItem",
|
||||
position: index + 1,
|
||||
name: item.name,
|
||||
...(item.url ? { item: item.url } : {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function serviceJsonLd(args: {
|
||||
offer: Offer;
|
||||
description: string;
|
||||
imageUrl?: string;
|
||||
siteUrl: string;
|
||||
providerName: string;
|
||||
areaServed?: string;
|
||||
}): JsonLdValue {
|
||||
const result: JsonLdValue = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Service",
|
||||
name: args.offer.title,
|
||||
description: args.description,
|
||||
url: `${args.siteUrl}/angebote/${args.offer.slug}`,
|
||||
provider: { "@type": "Organization", name: args.providerName, url: args.siteUrl },
|
||||
};
|
||||
if (args.imageUrl) result.image = args.imageUrl;
|
||||
if (args.areaServed) result.areaServed = args.areaServed;
|
||||
// Deliberately no "offers"/price — the CMS "price" field is free text
|
||||
// (e.g. "auf Anfrage") and can't be turned into a valid structured price
|
||||
// without risking incorrect data.
|
||||
return result;
|
||||
}
|
||||
|
||||
export function eventJsonLd(args: {
|
||||
event: Event;
|
||||
description: string;
|
||||
imageUrl?: string;
|
||||
joinUrl?: string;
|
||||
siteUrl: string;
|
||||
providerName: string;
|
||||
booking: BookingSetting | null | undefined;
|
||||
}): JsonLdValue | null {
|
||||
const { event } = args;
|
||||
// Private single-session bookings must never surface as a public Event
|
||||
// (see section 18) — defense in depth alongside the page-level checks
|
||||
// that already keep them out of public listings entirely.
|
||||
if (event.isPrivateBooking) return null;
|
||||
if (!event.date) return null;
|
||||
|
||||
const start = new Date(event.startTime || event.date);
|
||||
const isOnline = Boolean(event.isOnline);
|
||||
|
||||
const result: JsonLdValue = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Event",
|
||||
name: event.title,
|
||||
description: args.description,
|
||||
startDate: toBerlinOffsetISOString(start),
|
||||
eventStatus: "https://schema.org/EventScheduled",
|
||||
eventAttendanceMode: isOnline ? "https://schema.org/OnlineEventAttendanceMode" : "https://schema.org/OfflineEventAttendanceMode",
|
||||
url: `${args.siteUrl}/termine/${event.slug}`,
|
||||
organizer: { "@type": "Organization", name: args.providerName, url: args.siteUrl },
|
||||
};
|
||||
|
||||
if (event.endTime) result.endDate = toBerlinOffsetISOString(new Date(event.endTime));
|
||||
if (args.imageUrl) result.image = args.imageUrl;
|
||||
|
||||
if (isOnline) {
|
||||
result.location = { "@type": "VirtualLocation", url: args.joinUrl ?? result.url };
|
||||
} else if (hasFullAddress(args.booking)) {
|
||||
result.location = {
|
||||
"@type": "Place",
|
||||
name: event.location || args.booking.locationName || args.providerName,
|
||||
address: postalAddress(args.booking),
|
||||
};
|
||||
} else if (event.location) {
|
||||
// No structured address on file, but the event itself names a place —
|
||||
// still valid schema.org (address is optional on Place).
|
||||
result.location = { "@type": "Place", name: event.location };
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function articleJsonLd(args: {
|
||||
post: Post;
|
||||
description: string;
|
||||
imageUrl?: string;
|
||||
siteUrl: string;
|
||||
providerName: string;
|
||||
}): JsonLdValue {
|
||||
const url = `${args.siteUrl}/aktuelles/${args.post.slug}`;
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "BlogPosting",
|
||||
headline: args.post.title,
|
||||
description: args.description,
|
||||
url,
|
||||
mainEntityOfPage: url,
|
||||
datePublished: new Date(args.post.publishDate ?? args.post.createdAt).toISOString(),
|
||||
dateModified: new Date(args.post.updatedAt).toISOString(),
|
||||
author: { "@type": "Person", name: args.post.author?.trim() || args.providerName },
|
||||
publisher: { "@type": "Organization", name: args.providerName, url: args.siteUrl },
|
||||
...(args.imageUrl ? { image: args.imageUrl } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Renders one or more JSON-LD objects as server-side <script> tags. Filters out any null entries so callers can pass conditional builders directly. */
|
||||
export function JsonLd({ data }: { data: JsonLdValue | JsonLdValue[] | null | (JsonLdValue | null)[] }) {
|
||||
const items = (Array.isArray(data) ? data : [data]).filter((item): item is JsonLdValue => Boolean(item));
|
||||
if (items.length === 0) return null;
|
||||
return (
|
||||
<>
|
||||
{items.map((item, index) => (
|
||||
<script key={index} type="application/ld+json" dangerouslySetInnerHTML={{ __html: toSafeJsonLdString(item) }} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Metadata } from "next";
|
||||
import { siteConfig } from "@/lib/site";
|
||||
import { getSiteUrl, isSiteIndexable } from "./config";
|
||||
|
||||
/**
|
||||
* Single shared Metadata builder used by every public page's
|
||||
* generateMetadata — guarantees every page gets its own canonical, robots,
|
||||
* Open Graph and Twitter/X card data instead of copy-pasted boilerplate
|
||||
* (and the accidental duplicate-description bugs that come with that).
|
||||
*
|
||||
* `path` is the page's path relative to the site root (e.g.
|
||||
* "/angebote/doula-begleitung", or "" for the homepage).
|
||||
*/
|
||||
export async function buildMetadata(args: {
|
||||
title: string;
|
||||
description: string;
|
||||
path: string;
|
||||
ogImageUrl?: string;
|
||||
keywords?: string;
|
||||
noindex?: boolean;
|
||||
type?: "website" | "article";
|
||||
}): Promise<Metadata> {
|
||||
const [siteUrl, sitewideIndexable] = await Promise.all([getSiteUrl(), isSiteIndexable()]);
|
||||
const canonical = `${siteUrl}${args.path}`;
|
||||
const indexable = !args.noindex && sitewideIndexable;
|
||||
const images = args.ogImageUrl ? [{ url: args.ogImageUrl }] : undefined;
|
||||
|
||||
return {
|
||||
title: args.title,
|
||||
description: args.description,
|
||||
keywords: args.keywords,
|
||||
alternates: { canonical },
|
||||
robots: indexable
|
||||
? { index: true, follow: true }
|
||||
: { index: false, follow: false },
|
||||
openGraph: {
|
||||
title: args.title,
|
||||
description: args.description,
|
||||
url: canonical,
|
||||
siteName: siteConfig.name,
|
||||
type: args.type ?? "website",
|
||||
images,
|
||||
locale: siteConfig.locale,
|
||||
},
|
||||
twitter: {
|
||||
card: images ? "summary_large_image" : "summary",
|
||||
title: args.title,
|
||||
description: args.description,
|
||||
images: images?.map((image) => image.url),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { cache } from "react";
|
||||
import { getCMS } from "@/lib/payload/getPayload";
|
||||
|
||||
/**
|
||||
* Looks up a CMS-configured redirect for a changed slug (see
|
||||
* collections/Redirects.ts). Only called from the three dynamic [slug]
|
||||
* detail pages right before they'd otherwise 404 — not a catch-all
|
||||
* middleware, so this never adds a database lookup to the other ~30 routes
|
||||
* that never need it.
|
||||
*/
|
||||
export const resolveRedirect = cache(async (fromPath: string): Promise<{ to: string; permanent: boolean } | null> => {
|
||||
const payload = await getCMS();
|
||||
const { docs } = await payload.find({
|
||||
collection: "redirects",
|
||||
where: { and: [{ fromPath: { equals: fromPath } }, { enabled: { equals: true } }] },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: false,
|
||||
});
|
||||
const redirect = docs[0];
|
||||
if (!redirect) return null;
|
||||
return { to: redirect.toPath, permanent: redirect.type !== "temporary" };
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { Media } from "@/payload-types";
|
||||
import { mediaUrl } from "@/lib/payload/media";
|
||||
|
||||
type MediaRef = Media | number | null | undefined;
|
||||
|
||||
type SeoGroup =
|
||||
| {
|
||||
title?: string | null;
|
||||
description?: string | null;
|
||||
keywords?: string | null;
|
||||
ogImage?: MediaRef;
|
||||
}
|
||||
| null
|
||||
| undefined;
|
||||
|
||||
export type ResolvedSeo = {
|
||||
title: string;
|
||||
description: string;
|
||||
keywords?: string;
|
||||
ogImageUrl?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Priority chain used everywhere on the site (see section 32 of the SEO
|
||||
* brief): manual CMS field → content-derived fallback → nothing invented.
|
||||
* `fallbackDescription` may be a thunk so callers only pay for building an
|
||||
* excerpt (walking richText) when the manual field is actually empty.
|
||||
*/
|
||||
export function resolveSeo(args: {
|
||||
seo?: SeoGroup;
|
||||
fallbackTitle: string;
|
||||
fallbackDescription: string | (() => string);
|
||||
fallbackImage?: MediaRef;
|
||||
defaultOgImage?: MediaRef;
|
||||
}): ResolvedSeo {
|
||||
const title = args.seo?.title?.trim() || args.fallbackTitle;
|
||||
const description =
|
||||
args.seo?.description?.trim() ||
|
||||
(typeof args.fallbackDescription === "function" ? args.fallbackDescription() : args.fallbackDescription);
|
||||
|
||||
const ogImageUrl =
|
||||
mediaUrl(args.seo?.ogImage, "hero") ?? mediaUrl(args.fallbackImage, "hero") ?? mediaUrl(args.defaultOgImage, "hero");
|
||||
|
||||
return {
|
||||
title,
|
||||
description,
|
||||
keywords: args.seo?.keywords?.trim() || undefined,
|
||||
ogImageUrl,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
type LexicalNode = { text?: string; children?: LexicalNode[] };
|
||||
|
||||
function collectText(node: LexicalNode, out: string[]): void {
|
||||
if (typeof node.text === "string" && node.text) out.push(node.text);
|
||||
if (Array.isArray(node.children)) {
|
||||
for (const child of node.children) collectText(child, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** Walks a Lexical richText field's JSON (any node shape) and extracts plain text, regardless of formatting/links/lists used. */
|
||||
export function plainTextFromRichText(data: unknown): string {
|
||||
if (!data || typeof data !== "object") return "";
|
||||
const root = (data as { root?: LexicalNode }).root;
|
||||
if (!root) return "";
|
||||
const parts: string[] = [];
|
||||
collectText(root, parts);
|
||||
return parts.join(" ").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
/** Truncates at a word boundary rather than mid-word, for a natural-reading meta description fallback. */
|
||||
export function excerpt(text: string, maxLength = 160): string {
|
||||
const clean = text.replace(/\s+/g, " ").trim();
|
||||
if (clean.length <= maxLength) return clean;
|
||||
const truncated = clean.slice(0, maxLength);
|
||||
const lastSpace = truncated.lastIndexOf(" ");
|
||||
const safe = lastSpace > maxLength * 0.6 ? truncated.slice(0, lastSpace) : truncated;
|
||||
return `${safe.trim()}…`;
|
||||
}
|
||||
|
||||
export function excerptFromRichText(data: unknown, maxLength = 160): string {
|
||||
return excerpt(plainTextFromRichText(data), maxLength);
|
||||
}
|
||||
Reference in New Issue
Block a user