forked from fahrPool/fahrPool
56 lines
2.1 KiB
TypeScript
56 lines
2.1 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { timingSafeEqual } from "node:crypto";
|
|
import { createAdminClient } from "@/lib/supabase/admin";
|
|
import { getWhatsAppConfig } from "@/lib/notifications/config";
|
|
import { verarbeiteOutbox, type Handler } from "@/lib/notifications/dispatch";
|
|
import { protokollMailHandler, whatsappHandler } from "@/lib/notifications/handler";
|
|
|
|
export const runtime = "nodejs";
|
|
export const dynamic = "force-dynamic";
|
|
|
|
// Verhindert Log-Flut, wenn ein fehlkonfigurierter Cron diese Route minuetlich
|
|
// trifft: der 500-Fall wird nur einmal pro Prozess geloggt.
|
|
let secretFehltGemeldet = false;
|
|
|
|
function sichererVergleich(a: string, b: string): boolean {
|
|
const bufA = Buffer.from(a);
|
|
const bufB = Buffer.from(b);
|
|
if (bufA.length !== bufB.length) return false;
|
|
return timingSafeEqual(bufA, bufB);
|
|
}
|
|
|
|
export async function POST(request: Request): Promise<Response> {
|
|
const secret = process.env.NOTIFICATION_DISPATCH_SECRET;
|
|
if (!secret) {
|
|
if (!secretFehltGemeldet) {
|
|
console.error("[notifications] NOTIFICATION_DISPATCH_SECRET nicht gesetzt");
|
|
secretFehltGemeldet = true;
|
|
}
|
|
return NextResponse.json({ fehler: "Fehlkonfiguration" }, { status: 500 });
|
|
}
|
|
|
|
const auth = request.headers.get("authorization") ?? "";
|
|
const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
|
|
if (!token || !sichererVergleich(token, secret)) {
|
|
return NextResponse.json({ fehler: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const handler: Record<string, Handler> = {};
|
|
const waCfg = getWhatsAppConfig();
|
|
|
|
try {
|
|
const admin = createAdminClient();
|
|
// Protokoll-Mails werden immer geclaimt: ob ein SMTP existiert, steht erst
|
|
// pro Zeile fest (Firmen-SMTP oder globaler Fallback).
|
|
handler.protokoll_abgeschlossen = protokollMailHandler(admin);
|
|
if (waCfg) {
|
|
handler.auftrag_erstellt = whatsappHandler(admin, waCfg);
|
|
}
|
|
const ergebnis = await verarbeiteOutbox(admin, handler);
|
|
return NextResponse.json(ergebnis);
|
|
} catch (e) {
|
|
console.error("[notifications] Dispatch fehlgeschlagen:", e);
|
|
return NextResponse.json({ fehler: "Dispatch fehlgeschlagen" }, { status: 500 });
|
|
}
|
|
}
|