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

95 lines
3.5 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;
// Bots bekommen eine Erfolgsmeldung, damit sie nicht gezielt umgehen können.
const fakeOk = () => NextResponse.json({ ok: true, queued: false });
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 });
}
// 1. Honeypot und Mindest-Ausfüllzeit
const startedAt = Number(body._t);
if (body.website || !Number.isFinite(startedAt) || Date.now() - startedAt < MIN_FILL_TIME_MS) {
return fakeOk();
}
// 2. Rate-Limits (IP, global)
const ip = getClientIp(request);
if (!slidingWindowAllow(`contact:ip:${ip}`, 3, HOUR) || !slidingWindowAllow("contact:global", 30, HOUR)) {
return 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" } }
);
}
// 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 })) return fakeOk();
if (!slidingWindowAllow(`contact:email:${email.trim().toLowerCase()}`, 2, HOUR)) return fakeOk();
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 });
}