MBO-Tech-IT-Webseite/app/api/contact/route.ts

124 lines
4.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { NextResponse } from "next/server";
import { sendeKontaktEmail, sendeAnfrageBestaetigung } from "@/lib/mailer";
import { createServiceClient } from "@/lib/supabase";
import {
LIMITS,
getClientIp,
hasLineBreak,
isValidEmail,
looksLikeSpam,
slidingWindowAllow,
} from "@/lib/form-guard";
const HOUR = 60 * 60 * 1000;
const MIN_FILL_TIME_MS = 3000;
// Erkannte Bots bekommen eine 4xx-Antwort, damit das Fail2Ban-Plugin in Traefik sie zählt
// und sperrt. Ein stilles 200 wäre dort unsichtbar (und würde echte Nutzer täuschen).
// Feste Zeilenform für Fail2Ban: "[Contact] BLOCKED ip=<IP> reason=<Grund>"
type BlockReason = "honeypot" | "too_fast" | "rate_ip" | "rate_global" | "spam" | "rate_email";
const blocked = (ip: string, reason: BlockReason) =>
console.warn(`[Contact] BLOCKED ip=${ip} reason=${reason}`);
const tooMany = () =>
NextResponse.json(
{ ok: false, error: "Zu viele Anfragen. Bitte versuchen Sie es später erneut oder rufen Sie uns an." },
{ status: 429, headers: { "Retry-After": "3600" } }
);
const rejected = (error: string) => NextResponse.json({ ok: false, error }, { status: 403 });
export async function POST(request: Request) {
let body: Record<string, string>;
try {
body = await request.json();
} catch {
return NextResponse.json({ ok: false, error: "Ungültige Anfrage" }, { status: 400 });
}
const ip = getClientIp(request);
// 1. Honeypot und Mindest-Ausfüllzeit
if (body.website) {
blocked(ip, "honeypot");
return rejected("Anfrage abgelehnt.");
}
const startedAt = Number(body._t);
if (!Number.isFinite(startedAt) || Date.now() - startedAt < MIN_FILL_TIME_MS) {
blocked(ip, "too_fast");
return NextResponse.json(
{ ok: false, error: "Bitte einen Moment warten und das Formular erneut absenden." },
{ status: 429, headers: { "Retry-After": "5" } }
);
}
// 2. Rate-Limits (IP, global)
if (!slidingWindowAllow(`contact:ip:${ip}`, 3, HOUR)) {
blocked(ip, "rate_ip");
return tooMany();
}
if (!slidingWindowAllow("contact:global", 30, HOUR)) {
blocked(ip, "rate_global");
return tooMany();
}
// 3. Validierung
const { name, email, betreff, nachricht, telefon } = body;
if (
[name, email, betreff].some((v) => typeof v !== "string" || !v.trim()) ||
[nachricht, telefon].some((v) => v !== undefined && typeof v !== "string")
) {
return NextResponse.json({ ok: false, error: "Pflichtfelder fehlen" }, { status: 400 });
}
if (
name.length > LIMITS.name ||
email.length > LIMITS.email ||
betreff.length > LIMITS.betreff ||
(nachricht?.length ?? 0) > LIMITS.nachricht ||
(telefon?.length ?? 0) > LIMITS.telefon
) {
return NextResponse.json({ ok: false, error: "Eingabe zu lang" }, { status: 400 });
}
if (!isValidEmail(email.trim()) || hasLineBreak(name, email, betreff, telefon)) {
return NextResponse.json({ ok: false, error: "Ungültige E-Mail-Adresse" }, { status: 400 });
}
// 4. Spam still verwerfen; pro Adresse höchstens 2 Anfragen/Stunde (schützt Dritte vor Bestätigungsmails)
if (looksLikeSpam({ name, betreff, nachricht })) {
blocked(ip, "spam");
return rejected("Bitte lassen Sie Links in Name und Betreff weg und verwenden Sie höchstens zwei Links in der Nachricht.");
}
if (!slidingWindowAllow(`contact:email:${email.trim().toLowerCase()}`, 2, HOUR)) {
blocked(ip, "rate_email");
return tooMany();
}
const result = await sendeKontaktEmail({ name, email, betreff, nachricht, telefon });
try {
const db = createServiceClient();
await db.from("anfragen").insert({ name, email, betreff, nachricht: nachricht || null, status: "offen" });
} catch (err) {
console.error("[Contact] Supabase insert error:", err);
}
sendeAnfrageBestaetigung({ name, email, betreff }).catch((err) =>
console.error("[Contact] Bestätigungsmail fehlgeschlagen:", err)
);
if (!result.sent && !result.queued) {
console.error(
`[Contact] UNZUSTELLBAR – Anfrage konnte weder gesendet noch in Queue gespeichert werden:\n` +
` Zeit: ${new Date().toISOString()}\n` +
` Name: ${name}\n` +
` E-Mail: ${email}\n` +
` Telefon: ${telefon ?? "(nicht angegeben)"}\n` +
` Betreff: ${betreff}\n` +
` Nachricht: ${nachricht ?? "(keine)"}`
);
return NextResponse.json({ ok: false, error: "Mail konnte nicht gesendet werden" }, { status: 500 });
}
return NextResponse.json({ ok: true, queued: result.queued });
}