71 lines
2.3 KiB
TypeScript
71 lines
2.3 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;
|
|
}
|
|
|
|
/** Nur IP-Zeichen zulassen, damit Header-Inhalte keine Logzeilen fälschen können. */
|
|
function cleanIp(raw: string): string {
|
|
return raw.replace(/[^0-9a-fA-F:.]/g, "").slice(0, 45) || "unknown";
|
|
}
|
|
|
|
/**
|
|
* 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 cleanIp(parts[parts.length - 1]);
|
|
}
|
|
return cleanIp(request.headers.get("x-real-ip") ?? "");
|
|
}
|
|
|
|
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));
|
|
}
|