MBO-Tech-IT-Webseite/lib/form-guard.ts

66 lines
2.1 KiB
TypeScript

// Missbrauchsschutz für öffentliche Formulare (Kontakt etc.).
// In-Memory: gilt pro Prozess und wird bei einem Neustart zurückgesetzt.
const hits = new Map<string, number[]>();
setInterval(() => {
const now = Date.now();
for (const [key, list] of hits.entries()) {
if (list.every((t) => now - t > 24 * 60 * 60 * 1000)) hits.delete(key);
}
}, 10 * 60 * 1000).unref?.();
/** Gleitendes Fenster: true = erlaubt (Treffer wird gezählt), false = Limit erreicht. */
export function slidingWindowAllow(key: string, max: number, windowMs: number): boolean {
const now = Date.now();
const list = (hits.get(key) ?? []).filter((t) => now - t < windowMs);
if (list.length >= max) {
hits.set(key, list);
return false;
}
list.push(now);
hits.set(key, list);
return true;
}
/**
* Client-IP hinter Traefik: der letzte X-Forwarded-For-Eintrag stammt vom
* Reverse Proxy und ist nicht durch den Client fälschbar (der erste schon).
*/
export function getClientIp(request: Request): string {
const xff = request.headers.get("x-forwarded-for");
if (xff) {
const parts = xff.split(",").map((p) => p.trim()).filter(Boolean);
if (parts.length) return parts[parts.length - 1];
}
return request.headers.get("x-real-ip") ?? "unknown";
}
const EMAIL_RE = /^[^\s@<>"',;:]+@[^\s@<>"',;:]+\.[a-zA-Z]{2,}$/;
export function isValidEmail(email: string): boolean {
return email.length <= 254 && EMAIL_RE.test(email);
}
export const LIMITS = {
name: 100,
email: 254,
telefon: 40,
betreff: 200,
nachricht: 5000,
} as const;
const URL_PATTERN = "(https?:\\/\\/|www\\.)";
/** Offensichtlicher Spam: Links in Name/Betreff, mehr als 2 Links in der Nachricht. */
export function looksLikeSpam(fields: { name: string; betreff: string; nachricht?: string }): boolean {
const single = new RegExp(URL_PATTERN, "i");
if (single.test(fields.name) || single.test(fields.betreff)) return true;
const links = (fields.nachricht ?? "").match(new RegExp(URL_PATTERN, "gi"))?.length ?? 0;
return links > 2;
}
export function hasLineBreak(...values: (string | undefined)[]): boolean {
return values.some((v) => v !== undefined && /[\r\n]/.test(v));
}