From e38e081373ea5851adbeb7c09064d21198901a5e Mon Sep 17 00:00:00 2001 From: Jonny Date: Thu, 3 Sep 2026 17:25:48 +0200 Subject: [PATCH 1/9] feat: notification_outbox Tabelle, Enqueue-Trigger und Batch-Claim-Funktion --- .../20260903100000_notification_outbox.sql | 94 ++++++++++++++++ .../tests/notification_outbox_rls_test.sql | 102 ++++++++++++++++++ 2 files changed, 196 insertions(+) create mode 100644 supabase/migrations/20260903100000_notification_outbox.sql create mode 100644 supabase/tests/notification_outbox_rls_test.sql diff --git a/supabase/migrations/20260903100000_notification_outbox.sql b/supabase/migrations/20260903100000_notification_outbox.sql new file mode 100644 index 0000000..3c0f0c7 --- /dev/null +++ b/supabase/migrations/20260903100000_notification_outbox.sql @@ -0,0 +1,94 @@ +-- Transaktionale Outbox fuer ausgehende Benachrichtigungen. Vorerst nur das +-- Ereignis 'auftrag_erstellt' (WhatsApp an eine feste Sammel-Nummer), aber +-- event_type/payload sind generisch fuer spaetere Ereignisse. Geschrieben wird +-- ausschliesslich vom SECURITY DEFINER-Enqueue-Trigger und vom +-- Service-Role-Client der Dispatch-Route; RLS gibt nur admin Leserechte. +create table public.notification_outbox ( + id uuid primary key default gen_random_uuid(), + event_type text not null, + auftrag_id uuid references public.auftraege(id) on delete set null, + payload jsonb not null, + status text not null default 'pending' + check (status in ('pending', 'sending', 'sent', 'failed', 'dead')), + versuche int not null default 0, + max_versuche int not null default 5, + naechster_versuch_ab timestamptz not null default now(), + letzter_fehler text, + wa_message_id text, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +create index notification_outbox_faellig_idx + on public.notification_outbox (status, naechster_versuch_ab); + +alter table public.notification_outbox enable row level security; + +-- Nur Einsicht fuer admin (Studio / spaeteres Admin-View). Kein +-- INSERT/UPDATE/DELETE fuer authenticated: der Enqueue-Trigger laeuft als +-- SECURITY DEFINER, die Dispatch-Route ueber den Service-Role-Key -- beide +-- umgehen RLS. +create policy "Admin liest notification_outbox" + on public.notification_outbox for select + using (public.user_role() = 'admin'); + +-- Enqueue: bei jedem INSERT in auftraege genau eine pending-Zeile. Laeuft als +-- AFTER INSERT, auftragsnummer ist zu diesem Zeitpunkt vom BEFORE-Trigger +-- auftragsnummer_generieren bereits gefuellt. +create function public.auftrag_notification_enqueue() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + insert into public.notification_outbox (event_type, auftrag_id, payload) + select + 'auftrag_erstellt', + new.id, + jsonb_build_object( + 'auftragsnummer', new.auftragsnummer, + 'abholort_adresse', abhol.adresse, + 'zielort_adresse', ziel.adresse, + 'kennzeichen', fz.kennzeichen) + from public.orte abhol + join public.orte ziel on ziel.id = new.zielort_id + join public.fahrzeuge fz on fz.id = new.fahrzeug_id + where abhol.id = new.abholort_id; + return new; +end; +$$; + +create trigger auftrag_notification_enqueue_trg + after insert on public.auftraege + for each row execute function public.auftrag_notification_enqueue(); + +-- Atomare Batch-Uebernahme fuer den Dispatcher: selektiert faellige Zeilen +-- (pending/failed und Zeitpunkt erreicht, oder in 'sending' haengengeblieben +-- seit >15 min) und setzt sie in einem Rutsch auf 'sending'. FOR UPDATE SKIP +-- LOCKED verhindert Doppel-Uebernahme bei ueberlappenden Laeufen. +create function public.claim_notification_batch(p_limit int) +returns setof public.notification_outbox +language sql +security definer +set search_path = public +as $$ + update public.notification_outbox o + set status = 'sending', updated_at = now() + where o.id in ( + select id from public.notification_outbox + where (status in ('pending', 'failed') and naechster_versuch_ab <= now()) + or (status = 'sending' and updated_at < now() - interval '15 minutes') + order by created_at + limit p_limit + for update skip locked + ) + returning o.*; +$$; + +revoke all on function public.claim_notification_batch(int) from public; +revoke all on function public.claim_notification_batch(int) from anon; +revoke all on function public.claim_notification_batch(int) from authenticated; + +-- Nur die Dispatch-Route (Service-Role-Client) darf den Batch uebernehmen. +grant execute on function public.claim_notification_batch(int) to service_role; diff --git a/supabase/tests/notification_outbox_rls_test.sql b/supabase/tests/notification_outbox_rls_test.sql new file mode 100644 index 0000000..c42ba73 --- /dev/null +++ b/supabase/tests/notification_outbox_rls_test.sql @@ -0,0 +1,102 @@ +begin; +select plan(8); + +insert into auth.users (id, email) values + ('c1111111-1111-1111-1111-111111111111', 'admin-outbox@auftraege.test.local'), + ('c2222222-2222-2222-2222-222222222222', 'disponent-outbox@auftraege.test.local'); + +update public.profiles set role = 'admin' where id = 'c1111111-1111-1111-1111-111111111111'; +update public.profiles set role = 'disponent' where id = 'c2222222-2222-2222-2222-222222222222'; + +insert into public.orte (id, adresse, ansprechpartner) values + ('c3111111-1111-1111-1111-111111111111', 'Startstr. 1, Teststadt', 'Frau A'), + ('c3222222-2222-2222-2222-222222222222', 'Zielstr. 2, Teststadt', 'Herr B'); + +insert into public.fahrzeuge (id, kennzeichen) values + ('c3333333-0000-0000-0000-000000000001', 'S-WA 42'); + +set local role authenticated; +set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}'; + +-- 1) Disponent legt einen Auftrag an -> Enqueue-Trigger erzeugt genau eine Zeile. +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status) +values ( + 'c4000000-0000-0000-0000-00000000000a', + 'c3111111-1111-1111-1111-111111111111', + 'c3222222-2222-2222-2222-222222222222', + 'c3333333-0000-0000-0000-000000000001', + 'c2222222-2222-2222-2222-222222222222', + 'offen' +); + +reset role; +reset request.jwt.claims; + +select is( + (select count(*)::int from public.notification_outbox + where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'), + 1, + 'Enqueue-Trigger legt genau eine notification_outbox-Zeile pro neuem Auftrag an' +); + +select is( + (select status from public.notification_outbox + where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'), + 'pending', + 'Neue Outbox-Zeile hat status = pending' +); + +select is( + (select event_type from public.notification_outbox + where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'), + 'auftrag_erstellt', + 'Neue Outbox-Zeile hat event_type = auftrag_erstellt' +); + +select is( + (select payload->>'kennzeichen' from public.notification_outbox + where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'), + 'S-WA 42', + 'payload.kennzeichen kommt aus dem verknuepften Fahrzeug' +); + +select is( + (select payload->>'abholort_adresse' from public.notification_outbox + where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'), + 'Startstr. 1, Teststadt', + 'payload.abholort_adresse kommt aus dem Abholort (nicht dem Zielort)' +); + +-- 2) SELECT-RLS: Disponent sieht die Outbox nicht. +set local role authenticated; +set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}'; +select is_empty( + $$ select id from public.notification_outbox $$, + 'Disponent sieht keine notification_outbox-Zeilen (keine SELECT-Policy fuer disponent)' +); + +-- 3) SELECT-RLS: Admin sieht die Outbox. +reset request.jwt.claims; +set local request.jwt.claims to '{"sub": "c1111111-1111-1111-1111-111111111111", "role": "authenticated"}'; +select isnt_empty( + $$ select id from public.notification_outbox $$, + 'Admin sieht notification_outbox-Zeilen' +); + +-- 4) EXECUTE-Recht: authenticated darf die Batch-Claim-Funktion nicht aufrufen +-- (revoke von authenticated, grant nur an service_role). +set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}'; +-- 2-arg throws_ok(sql, sqlstate): die 3-arg-Form (sql, sqlstate, description) +-- kollidiert mit pgTAPs throws_ok(sql, errcode, errmsg)-Signatur und wuerde die +-- Beschreibung als erwartete Fehlermeldung interpretieren. Getestet wird +-- unveraendert: authenticated laeuft in SQLSTATE 42501 (insufficient_privilege). +select throws_ok( + $$ select public.claim_notification_batch(5) $$, + '42501' +); + +reset role; +reset request.jwt.claims; + +select * from finish(); +rollback; From 71ea72c9fc1542f39574273f0f91a7b8b55a9f9a Mon Sep 17 00:00:00 2001 From: Jonny Date: Thu, 3 Sep 2026 17:30:56 +0200 Subject: [PATCH 2/9] feat: getWhatsAppConfig -- WhatsApp-Konfiguration aus env --- web/lib/notifications/config.test.ts | 58 ++++++++++++++++++++++++++++ web/lib/notifications/config.ts | 32 +++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 web/lib/notifications/config.test.ts create mode 100644 web/lib/notifications/config.ts diff --git a/web/lib/notifications/config.test.ts b/web/lib/notifications/config.test.ts new file mode 100644 index 0000000..d729a9e --- /dev/null +++ b/web/lib/notifications/config.test.ts @@ -0,0 +1,58 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { getWhatsAppConfig } from "./config"; + +const PFLICHT = { + WHATSAPP_ACCESS_TOKEN: "tok", + WHATSAPP_PHONE_NUMBER_ID: "123", + WHATSAPP_RECIPIENT: "4915100000000", + WHATSAPP_TEMPLATE_NAME: "neuer_auftrag", + WHATSAPP_TEMPLATE_LANG: "de", +}; + +let alt: Record; + +beforeEach(() => { + alt = {}; + for (const k of [...Object.keys(PFLICHT), "WHATSAPP_GRAPH_VERSION"]) { + alt[k] = process.env[k]; + delete process.env[k]; + } +}); + +afterEach(() => { + for (const [k, v] of Object.entries(alt)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } +}); + +describe("getWhatsAppConfig", () => { + it("liefert die Config, wenn alle Pflichtvariablen gesetzt sind", () => { + Object.assign(process.env, PFLICHT); + expect(getWhatsAppConfig()).toEqual({ + accessToken: "tok", + phoneNumberId: "123", + recipient: "4915100000000", + templateName: "neuer_auftrag", + templateLang: "de", + graphVersion: "v21.0", + }); + }); + + it("uebernimmt WHATSAPP_GRAPH_VERSION, wenn gesetzt", () => { + Object.assign(process.env, PFLICHT, { WHATSAPP_GRAPH_VERSION: "v22.0" }); + expect(getWhatsAppConfig()?.graphVersion).toBe("v22.0"); + }); + + it.each(Object.keys(PFLICHT))("liefert null, wenn %s fehlt", (fehlt) => { + const teil = { ...PFLICHT } as Record; + delete teil[fehlt]; + Object.assign(process.env, teil); + expect(getWhatsAppConfig()).toBeNull(); + }); + + it("liefert null, wenn eine Pflichtvariable leer ist", () => { + Object.assign(process.env, PFLICHT, { WHATSAPP_ACCESS_TOKEN: "" }); + expect(getWhatsAppConfig()).toBeNull(); + }); +}); diff --git a/web/lib/notifications/config.ts b/web/lib/notifications/config.ts new file mode 100644 index 0000000..f142a08 --- /dev/null +++ b/web/lib/notifications/config.ts @@ -0,0 +1,32 @@ +export type WhatsAppConfig = { + accessToken: string; + phoneNumberId: string; + recipient: string; + templateName: string; + templateLang: string; + graphVersion: string; +}; + +// Liest die WhatsApp-Cloud-API-Konfiguration aus den Umgebungsvariablen. +// Gibt null zurueck, sobald eine Pflichtvariable fehlt oder leer ist -- der +// Dispatcher behandelt null als "Feature aus" und verarbeitet keine Zeilen. +export function getWhatsAppConfig(): WhatsAppConfig | null { + const accessToken = process.env.WHATSAPP_ACCESS_TOKEN; + const phoneNumberId = process.env.WHATSAPP_PHONE_NUMBER_ID; + const recipient = process.env.WHATSAPP_RECIPIENT; + const templateName = process.env.WHATSAPP_TEMPLATE_NAME; + const templateLang = process.env.WHATSAPP_TEMPLATE_LANG; + + if (!accessToken || !phoneNumberId || !recipient || !templateName || !templateLang) { + return null; + } + + return { + accessToken, + phoneNumberId, + recipient, + templateName, + templateLang, + graphVersion: process.env.WHATSAPP_GRAPH_VERSION || "v21.0", + }; +} From 4ed9a3bede4838d6eb63e0d38d68f47cce1c3905 Mon Sep 17 00:00:00 2001 From: Jonny Date: Thu, 3 Sep 2026 17:33:43 +0200 Subject: [PATCH 3/9] feat: buildTemplateComponents und sendWhatsAppTemplate (Meta Cloud API) --- web/lib/notifications/whatsapp.test.ts | 80 ++++++++++++++++++++++++++ web/lib/notifications/whatsapp.ts | 78 +++++++++++++++++++++++++ 2 files changed, 158 insertions(+) create mode 100644 web/lib/notifications/whatsapp.test.ts create mode 100644 web/lib/notifications/whatsapp.ts diff --git a/web/lib/notifications/whatsapp.test.ts b/web/lib/notifications/whatsapp.test.ts new file mode 100644 index 0000000..00dff5e --- /dev/null +++ b/web/lib/notifications/whatsapp.test.ts @@ -0,0 +1,80 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { WhatsAppConfig } from "./config"; +import { buildTemplateComponents, sendWhatsAppTemplate } from "./whatsapp"; + +const CFG: WhatsAppConfig = { + accessToken: "tok", + phoneNumberId: "PN1", + recipient: "4915100000000", + templateName: "neuer_auftrag", + templateLang: "de", + graphVersion: "v21.0", +}; + +const PAYLOAD = { + auftragsnummer: "26-09-03-0001", + abholort_adresse: "Startstr. 1, Teststadt", + zielort_adresse: "Zielstr. 2, Teststadt", + kennzeichen: "S-WA 42", +}; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("buildTemplateComponents", () => { + it("baut genau einen body-Component mit vier text-Parametern in fester Reihenfolge", () => { + expect(buildTemplateComponents(PAYLOAD)).toEqual([ + { + type: "body", + parameters: [ + { type: "text", text: "26-09-03-0001" }, + { type: "text", text: "Startstr. 1, Teststadt" }, + { type: "text", text: "Zielstr. 2, Teststadt" }, + { type: "text", text: "S-WA 42" }, + ], + }, + ]); + }); +}); + +describe("sendWhatsAppTemplate", () => { + it("POSTet an die Meta-Graph-URL und gibt bei 2xx die message id zurueck", async () => { + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response(JSON.stringify({ messages: [{ id: "wamid.ABC" }] }), { status: 200 }) + ); + + const res = await sendWhatsAppTemplate(CFG, PAYLOAD); + + expect(res).toEqual({ ok: true, messageId: "wamid.ABC" }); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe("https://graph.facebook.com/v21.0/PN1/messages"); + expect(init?.method).toBe("POST"); + expect((init?.headers as Record).Authorization).toBe("Bearer tok"); + const body = JSON.parse(init?.body as string); + expect(body).toMatchObject({ + messaging_product: "whatsapp", + to: "4915100000000", + type: "template", + template: { name: "neuer_auftrag", language: { code: "de" } }, + }); + expect(body.template.components[0].parameters).toHaveLength(4); + }); + + it("gibt bei nicht-2xx ok:false mit Status und Body zurueck", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response(JSON.stringify({ error: { message: "Template not found" } }), { status: 404 }) + ); + const res = await sendWhatsAppTemplate(CFG, PAYLOAD); + expect(res.ok).toBe(false); + expect(res).toMatchObject({ ok: false }); + if (!res.ok) expect(res.fehler).toContain("404"); + if (!res.ok) expect(res.fehler).toContain("Template not found"); + }); + + it("gibt bei einer fetch-Exception ok:false zurueck", async () => { + vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("ECONNRESET")); + const res = await sendWhatsAppTemplate(CFG, PAYLOAD); + expect(res).toEqual({ ok: false, fehler: "ECONNRESET" }); + }); +}); diff --git a/web/lib/notifications/whatsapp.ts b/web/lib/notifications/whatsapp.ts new file mode 100644 index 0000000..e3e3d33 --- /dev/null +++ b/web/lib/notifications/whatsapp.ts @@ -0,0 +1,78 @@ +import type { WhatsAppConfig } from "./config"; + +export type AuftragErstelltPayload = { + auftragsnummer: string; + abholort_adresse: string; + zielort_adresse: string; + kennzeichen: string; +}; + +export type TemplateParameter = { type: "text"; text: string }; +export type TemplateComponent = { type: "body"; parameters: TemplateParameter[] }; + +export type SendErgebnis = { ok: true; messageId: string } | { ok: false; fehler: string }; + +// Body-Parameter in fester Reihenfolge -- muss zu {{1}}..{{4}} im genehmigten +// Meta-Template "neuer_auftrag" passen: Auftragsnummer, Abholort, Zielort, +// Kennzeichen. +export function buildTemplateComponents(payload: AuftragErstelltPayload): TemplateComponent[] { + return [ + { + type: "body", + parameters: [ + { type: "text", text: payload.auftragsnummer }, + { type: "text", text: payload.abholort_adresse }, + { type: "text", text: payload.zielort_adresse }, + { type: "text", text: payload.kennzeichen }, + ], + }, + ]; +} + +const TIMEOUT_MS = 10_000; + +export async function sendWhatsAppTemplate( + cfg: WhatsAppConfig, + payload: AuftragErstelltPayload +): Promise { + const url = `https://graph.facebook.com/${cfg.graphVersion}/${cfg.phoneNumberId}/messages`; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), TIMEOUT_MS); + + try { + const response = await fetch(url, { + method: "POST", + headers: { + Authorization: `Bearer ${cfg.accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + messaging_product: "whatsapp", + to: cfg.recipient, + type: "template", + template: { + name: cfg.templateName, + language: { code: cfg.templateLang }, + components: buildTemplateComponents(payload), + }, + }), + signal: controller.signal, + }); + + const text = await response.text(); + if (!response.ok) { + return { ok: false, fehler: `${response.status} ${text}`.slice(0, 500) }; + } + + const daten = JSON.parse(text) as { messages?: { id?: string }[] }; + const messageId = daten.messages?.[0]?.id; + if (!messageId) { + return { ok: false, fehler: `2xx ohne message id: ${text}`.slice(0, 500) }; + } + return { ok: true, messageId }; + } catch (fehler) { + return { ok: false, fehler: fehler instanceof Error ? fehler.message : String(fehler) }; + } finally { + clearTimeout(timer); + } +} From 018ad1fbfe5a6a8ed6bc8ed8427960c65c87afc1 Mon Sep 17 00:00:00 2001 From: Jonny Date: Thu, 3 Sep 2026 17:39:21 +0200 Subject: [PATCH 4/9] feat: verarbeiteOutbox -- Outbox-Batch mit Retry/Backoff verarbeiten Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01Dimk8Jo64b4wULp2yAzSNh --- web/lib/notifications/dispatch.test.ts | 116 +++++++++++++++++++++++++ web/lib/notifications/dispatch.ts | 91 +++++++++++++++++++ 2 files changed, 207 insertions(+) create mode 100644 web/lib/notifications/dispatch.test.ts create mode 100644 web/lib/notifications/dispatch.ts diff --git a/web/lib/notifications/dispatch.test.ts b/web/lib/notifications/dispatch.test.ts new file mode 100644 index 0000000..8cc95c1 --- /dev/null +++ b/web/lib/notifications/dispatch.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it, vi } from "vitest"; +import type { WhatsAppConfig } from "./config"; +import type { SendErgebnis } from "./whatsapp"; +import { verarbeiteOutbox, type OutboxRow } from "./dispatch"; + +const CFG: WhatsAppConfig = { + accessToken: "tok", + phoneNumberId: "PN1", + recipient: "4915100000000", + templateName: "neuer_auftrag", + templateLang: "de", + graphVersion: "v21.0", +}; + +function row(over: Partial = {}): OutboxRow { + return { + id: over.id ?? "r1", + event_type: "auftrag_erstellt", + payload: { + auftragsnummer: "26-09-03-0001", + abholort_adresse: "A", + zielort_adresse: "B", + kennzeichen: "S-WA 42", + }, + versuche: over.versuche ?? 0, + max_versuche: over.max_versuche ?? 5, + ...over, + }; +} + +// Minimaler Fake des supabase-js-Clients: rpc() liefert die geclaimten Zeilen, +// from(...).update(...).eq(...) protokolliert die Updates. +function fakeAdmin(claimed: OutboxRow[]) { + const updates: { id: string; felder: Record }[] = []; + const client = { + rpc: vi.fn(async () => ({ data: claimed, error: null })), + from: vi.fn(() => ({ + update: (felder: Record) => ({ + eq: async (_spalte: string, id: string) => { + updates.push({ id, felder }); + return { data: null, error: null }; + }, + }), + })), + }; + return { client, updates }; +} + +describe("verarbeiteOutbox", () => { + it("markiert eine erfolgreich gesendete Zeile als sent mit wa_message_id", async () => { + const { client, updates } = fakeAdmin([row({ id: "r1" })]); + const sender = vi.fn(async (): Promise => ({ ok: true, messageId: "wamid.1" })); + + const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender }); + + expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 1, fehlgeschlagen: 0, tot: 0 }); + expect(updates).toHaveLength(1); + expect(updates[0]).toMatchObject({ + id: "r1", + felder: { status: "sent", wa_message_id: "wamid.1", letzter_fehler: null }, + }); + }); + + it("setzt bei Fehler status=failed, versuche+1 und einen Backoff in der Zukunft", async () => { + const jetzt = new Date("2026-09-03T12:00:00.000Z"); + const { client, updates } = fakeAdmin([row({ id: "r1", versuche: 0, max_versuche: 5 })]); + const sender = vi.fn(async (): Promise => ({ ok: false, fehler: "404 Template not found" })); + + const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender, jetzt: () => jetzt }); + + expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 0, fehlgeschlagen: 1, tot: 0 }); + expect(updates[0].felder).toMatchObject({ status: "failed", versuche: 1 }); + // 2^1 = 2 Minuten + expect(updates[0].felder.naechster_versuch_ab).toBe("2026-09-03T12:02:00.000Z"); + expect(updates[0].felder.letzter_fehler).toContain("404"); + }); + + it("deckelt den Backoff bei 60 Minuten", async () => { + const jetzt = new Date("2026-09-03T12:00:00.000Z"); + const { client, updates } = fakeAdmin([row({ id: "r1", versuche: 9, max_versuche: 20 })]); + const sender = vi.fn(async (): Promise => ({ ok: false, fehler: "500" })); + + await verarbeiteOutbox(client as never, CFG, { sender, jetzt: () => jetzt }); + + expect(updates[0].felder.naechster_versuch_ab).toBe("2026-09-03T13:00:00.000Z"); + }); + + it("setzt status=dead, sobald versuche max_versuche erreicht", async () => { + const { client, updates } = fakeAdmin([row({ id: "r1", versuche: 4, max_versuche: 5 })]); + const sender = vi.fn(async (): Promise => ({ ok: false, fehler: "500" })); + + const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender }); + + expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 0, fehlgeschlagen: 0, tot: 1 }); + expect(updates[0].felder).toMatchObject({ status: "dead", versuche: 5 }); + }); + + it("macht nichts und ruft den sender nicht, wenn keine Zeilen faellig sind", async () => { + const { client, updates } = fakeAdmin([]); + const sender = vi.fn(async (): Promise => ({ ok: true, messageId: "x" })); + + const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender }); + + expect(ergebnis).toEqual({ verarbeitet: 0, gesendet: 0, fehlgeschlagen: 0, tot: 0 }); + expect(sender).not.toHaveBeenCalled(); + expect(updates).toHaveLength(0); + }); + + it("uebergibt p_limit 20 an die claim-Funktion", async () => { + const { client } = fakeAdmin([]); + await verarbeiteOutbox(client as never, CFG, { + sender: vi.fn(async (): Promise => ({ ok: true, messageId: "x" })), + }); + expect(client.rpc).toHaveBeenCalledWith("claim_notification_batch", { p_limit: 20 }); + }); +}); diff --git a/web/lib/notifications/dispatch.ts b/web/lib/notifications/dispatch.ts new file mode 100644 index 0000000..5e236ba --- /dev/null +++ b/web/lib/notifications/dispatch.ts @@ -0,0 +1,91 @@ +import type { SupabaseClient } from "@supabase/supabase-js"; +import type { WhatsAppConfig } from "./config"; +import { sendWhatsAppTemplate, type AuftragErstelltPayload } from "./whatsapp"; + +export type OutboxRow = { + id: string; + event_type: string; + payload: AuftragErstelltPayload; + versuche: number; + max_versuche: number; +}; + +export type VerarbeitungsErgebnis = { + verarbeitet: number; + gesendet: number; + fehlgeschlagen: number; + tot: number; +}; + +export type DispatchDeps = { + sender?: typeof sendWhatsAppTemplate; + jetzt?: () => Date; +}; + +const BATCH_LIMIT = 20; +const BACKOFF_MAX_MIN = 60; + +// Uebernimmt einen Batch faelliger Outbox-Zeilen (atomar via +// claim_notification_batch) und sendet sie einzeln. Erfolg -> sent; Fehler -> +// failed mit exponentiellem Backoff, bzw. dead sobald max_versuche erreicht. +export async function verarbeiteOutbox( + admin: SupabaseClient, + cfg: WhatsAppConfig, + deps: DispatchDeps = {} +): Promise { + const sender = deps.sender ?? sendWhatsAppTemplate; + const jetzt = deps.jetzt ?? (() => new Date()); + + const { data, error } = await admin.rpc("claim_notification_batch", { p_limit: BATCH_LIMIT }); + if (error) { + throw new Error(`claim_notification_batch fehlgeschlagen: ${error.message}`); + } + const rows = (data ?? []) as OutboxRow[]; + + const ergebnis: VerarbeitungsErgebnis = { + verarbeitet: 0, + gesendet: 0, + fehlgeschlagen: 0, + tot: 0, + }; + + for (const row of rows) { + ergebnis.verarbeitet += 1; + const res = await sender(cfg, row.payload); + + if (res.ok) { + await admin + .from("notification_outbox") + .update({ + status: "sent", + wa_message_id: res.messageId, + letzter_fehler: null, + updated_at: jetzt().toISOString(), + }) + .eq("id", row.id); + ergebnis.gesendet += 1; + continue; + } + + const neueVersuche = row.versuche + 1; + const tot = neueVersuche >= row.max_versuche; + const backoffMin = Math.min(2 ** neueVersuche, BACKOFF_MAX_MIN); + const naechster = new Date(jetzt().getTime() + backoffMin * 60_000); + + await admin + .from("notification_outbox") + .update({ + status: tot ? "dead" : "failed", + versuche: neueVersuche, + naechster_versuch_ab: naechster.toISOString(), + letzter_fehler: res.fehler.slice(0, 500), + updated_at: jetzt().toISOString(), + }) + .eq("id", row.id); + + if (tot) ergebnis.tot += 1; + else ergebnis.fehlgeschlagen += 1; + } + + return ergebnis; +} From 0d5b3ef10b0d38d8e608536febfd56ff21ea26e5 Mon Sep 17 00:00:00 2001 From: Jonny Date: Thu, 3 Sep 2026 17:43:17 +0200 Subject: [PATCH 5/9] feat: POST /api/notifications/dispatch -- Outbox-Dispatch-Route mit Shared-Secret --- .../api/notifications/dispatch/route.test.ts | 77 +++++++++++++++++++ web/app/api/notifications/dispatch/route.ts | 38 +++++++++ 2 files changed, 115 insertions(+) create mode 100644 web/app/api/notifications/dispatch/route.test.ts create mode 100644 web/app/api/notifications/dispatch/route.ts diff --git a/web/app/api/notifications/dispatch/route.test.ts b/web/app/api/notifications/dispatch/route.test.ts new file mode 100644 index 0000000..072556d --- /dev/null +++ b/web/app/api/notifications/dispatch/route.test.ts @@ -0,0 +1,77 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@/lib/supabase/admin", () => ({ createAdminClient: vi.fn(() => ({})) })); +vi.mock("@/lib/notifications/config", () => ({ getWhatsAppConfig: vi.fn() })); +vi.mock("@/lib/notifications/dispatch", () => ({ verarbeiteOutbox: vi.fn() })); + +import { getWhatsAppConfig } from "@/lib/notifications/config"; +import { verarbeiteOutbox } from "@/lib/notifications/dispatch"; +import { POST } from "./route"; + +const CFG = { + accessToken: "tok", + phoneNumberId: "PN1", + recipient: "4915100000000", + templateName: "neuer_auftrag", + templateLang: "de", + graphVersion: "v21.0", +}; + +function req(headers: Record = {}) { + return new Request("http://localhost/api/notifications/dispatch", { method: "POST", headers }); +} + +let altSecret: string | undefined; + +beforeEach(() => { + altSecret = process.env.NOTIFICATION_DISPATCH_SECRET; + process.env.NOTIFICATION_DISPATCH_SECRET = "geheim"; + vi.mocked(getWhatsAppConfig).mockReset(); + vi.mocked(verarbeiteOutbox).mockReset(); +}); + +afterEach(() => { + if (altSecret === undefined) delete process.env.NOTIFICATION_DISPATCH_SECRET; + else process.env.NOTIFICATION_DISPATCH_SECRET = altSecret; +}); + +describe("POST /api/notifications/dispatch", () => { + it("antwortet 401 ohne Bearer-Token", async () => { + const res = await POST(req()); + expect(res.status).toBe(401); + expect(verarbeiteOutbox).not.toHaveBeenCalled(); + }); + + it("antwortet 401 bei falschem Token", async () => { + const res = await POST(req({ Authorization: "Bearer falsch" })); + expect(res.status).toBe(401); + }); + + it("antwortet 500, wenn NOTIFICATION_DISPATCH_SECRET nicht gesetzt ist", async () => { + delete process.env.NOTIFICATION_DISPATCH_SECRET; + const res = await POST(req({ Authorization: "Bearer geheim" })); + expect(res.status).toBe(500); + }); + + it("antwortet 200 uebersprungen, wenn keine WhatsApp-Config vorhanden ist", async () => { + vi.mocked(getWhatsAppConfig).mockReturnValue(null); + const res = await POST(req({ Authorization: "Bearer geheim" })); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ verarbeitet: 0, uebersprungen: true }); + expect(verarbeiteOutbox).not.toHaveBeenCalled(); + }); + + it("ruft verarbeiteOutbox und gibt dessen Ergebnis als 200 zurueck", async () => { + vi.mocked(getWhatsAppConfig).mockReturnValue(CFG); + vi.mocked(verarbeiteOutbox).mockResolvedValue({ + verarbeitet: 2, + gesendet: 1, + fehlgeschlagen: 1, + tot: 0, + }); + const res = await POST(req({ Authorization: "Bearer geheim" })); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ verarbeitet: 2, gesendet: 1, fehlgeschlagen: 1, tot: 0 }); + expect(verarbeiteOutbox).toHaveBeenCalledOnce(); + }); +}); diff --git a/web/app/api/notifications/dispatch/route.ts b/web/app/api/notifications/dispatch/route.ts new file mode 100644 index 0000000..2fbef58 --- /dev/null +++ b/web/app/api/notifications/dispatch/route.ts @@ -0,0 +1,38 @@ +import { NextResponse } from "next/server"; +import { timingSafeEqual } from "crypto"; +import { createAdminClient } from "@/lib/supabase/admin"; +import { getWhatsAppConfig } from "@/lib/notifications/config"; +import { verarbeiteOutbox } from "@/lib/notifications/dispatch"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +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 { + const secret = process.env.NOTIFICATION_DISPATCH_SECRET; + if (!secret) { + console.error("[notifications] NOTIFICATION_DISPATCH_SECRET nicht gesetzt"); + return new NextResponse("Fehlkonfiguration", { status: 500 }); + } + + const auth = request.headers.get("authorization") ?? ""; + const token = auth.startsWith("Bearer ") ? auth.slice(7) : ""; + if (!token || !sichererVergleich(token, secret)) { + return new NextResponse("Unauthorized", { status: 401 }); + } + + const cfg = getWhatsAppConfig(); + if (!cfg) { + console.warn("[notifications] WhatsApp nicht konfiguriert – Outbox wird nicht verarbeitet"); + return NextResponse.json({ verarbeitet: 0, uebersprungen: true }); + } + + const ergebnis = await verarbeiteOutbox(createAdminClient(), cfg); + return NextResponse.json(ergebnis); +} From a233cbb1b0e8f7b1c859714e4908d11a95c62832 Mon Sep 17 00:00:00 2001 From: Jonny Date: Fri, 4 Sep 2026 00:03:33 +0200 Subject: [PATCH 6/9] feat: pg_cron-Job stoesst minuetlich die Dispatch-Route an --- ...60903101000_notification_dispatch_cron.sql | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 supabase/migrations/20260903101000_notification_dispatch_cron.sql diff --git a/supabase/migrations/20260903101000_notification_dispatch_cron.sql b/supabase/migrations/20260903101000_notification_dispatch_cron.sql new file mode 100644 index 0000000..82d80cb --- /dev/null +++ b/supabase/migrations/20260903101000_notification_dispatch_cron.sql @@ -0,0 +1,22 @@ +-- Minuetlicher Anstoss der Dispatch-Route. URL und Secret stehen bewusst +-- NICHT hier (umgebungsabhaengig, kein Secret in Git), sondern in den +-- DB-Settings app.notification_dispatch_url / app.notification_dispatch_secret, +-- die pro Stack out-of-band gesetzt werden. Ist die URL leer/ungesetzt (z.B. +-- lokaler CLI-Dev-Stack), verhindert die where-Bedingung jeden http_post -- +-- der Job existiert dann, tut aber nichts. +create extension if not exists pg_cron; +create extension if not exists pg_net; + +select cron.schedule( + 'notification-dispatch', + '* * * * *', + $$ + select net.http_post( + url := current_setting('app.notification_dispatch_url', true), + headers := jsonb_build_object( + 'Content-Type', 'application/json', + 'Authorization', 'Bearer ' || current_setting('app.notification_dispatch_secret', true)), + body := '{}'::jsonb) + where coalesce(current_setting('app.notification_dispatch_url', true), '') <> '' + $$ +); From 26f7a70b546c5819988239babf8c30abf8dcbe76 Mon Sep 17 00:00:00 2001 From: Jonny Date: Fri, 4 Sep 2026 00:08:05 +0200 Subject: [PATCH 7/9] chore: env-Doku und docker-compose fuer WhatsApp-Benachrichtigung, rebuild-master-stack-Hinweis --- .claude/skills/rebuild-master-stack/SKILL.md | 14 ++++++++++++++ docker-compose.yaml | 10 ++++++++++ web/.env.local.example | 18 ++++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/.claude/skills/rebuild-master-stack/SKILL.md b/.claude/skills/rebuild-master-stack/SKILL.md index 2319d95..8c4abe0 100644 --- a/.claude/skills/rebuild-master-stack/SKILL.md +++ b/.claude/skills/rebuild-master-stack/SKILL.md @@ -48,4 +48,18 @@ The user granted standing permission (2026-08-19) to run this proactively after docker exec -i aushilfsfahrer-db-1 psql -U postgres -d postgres -c "insert into supabase_migrations.schema_migrations (version) values ('') on conflict (version) do nothing;" ``` + Enthielten die neuen Migrationen einen `pg_cron`-Job, der die App aufruft + (z.B. `notification-dispatch`), zusätzlich die beiden DB-Settings setzen, die + die Migration bewusst nicht enthält: + + ```bash + docker exec -i aushilfsfahrer-db-1 psql -U postgres -d postgres -c \ + "alter database postgres set app.notification_dispatch_url = 'http://web:3000/api/notifications/dispatch';" + docker exec -i aushilfsfahrer-db-1 psql -U postgres -d postgres -c \ + "alter database postgres set app.notification_dispatch_secret = '';" + ``` + + Danach greifen neue Verbindungen die Settings auf; der Cron-Job ruft ab der + nächsten Minute `POST /api/notifications/dispatch` auf. + Report the admin login URL/credentials back to the user once verified (`admin@aushilfsfahrer.local` / `Admin123!`, or the current password — see the `supabase-local-dev` skill if it's been reset). diff --git a/docker-compose.yaml b/docker-compose.yaml index 16997d0..81c9e85 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -181,3 +181,13 @@ services: # denselben Wert, den kong/auth/rest bereits als SERVICE_KEY bekommen # (siehe SERVICE_ROLE_KEY in der Root-.env). SUPABASE_SERVICE_ROLE_KEY: ${SERVICE_ROLE_KEY} + # WhatsApp-Benachrichtigung -- Werte aus der Root-.env. Fehlt eine der + # fuenf WHATSAPP_*-Pflichtvariablen, ueberspringt der Dispatcher sauber. + WHATSAPP_ACCESS_TOKEN: ${WHATSAPP_ACCESS_TOKEN} + WHATSAPP_PHONE_NUMBER_ID: ${WHATSAPP_PHONE_NUMBER_ID} + WHATSAPP_RECIPIENT: ${WHATSAPP_RECIPIENT} + WHATSAPP_TEMPLATE_NAME: ${WHATSAPP_TEMPLATE_NAME} + WHATSAPP_TEMPLATE_LANG: ${WHATSAPP_TEMPLATE_LANG} + WHATSAPP_GRAPH_VERSION: ${WHATSAPP_GRAPH_VERSION} + # Muss mit dem DB-Setting app.notification_dispatch_secret uebereinstimmen. + NOTIFICATION_DISPATCH_SECRET: ${NOTIFICATION_DISPATCH_SECRET} diff --git a/web/.env.local.example b/web/.env.local.example index cb45971..189c477 100644 --- a/web/.env.local.example +++ b/web/.env.local.example @@ -10,3 +10,21 @@ SUPABASE_INTERNAL_URL=http://localhost:8000 # `npx supabase status` (Repo-Root) auslesen ("service_role key"). Fuer den # Docker-Compose-Master-Stack ist es SERVICE_ROLE_KEY aus der Root-.env. SUPABASE_SERVICE_ROLE_KEY= + +# --- WhatsApp-Benachrichtigung (Meta WhatsApp Cloud API) --- +# Fehlt eine der folgenden fuenf Pflichtvariablen, ist das Feature "aus": +# die Dispatch-Route antwortet dann 200 { uebersprungen: true } und verschickt +# nichts. Werte stammen aus dem Meta Business Manager (WhatsApp > API-Setup). +WHATSAPP_ACCESS_TOKEN= +WHATSAPP_PHONE_NUMBER_ID= +# Feste Empfaenger-Sammelnummer, E.164 ohne fuehrendes "+" (z.B. 4915112345678). +WHATSAPP_RECIPIENT= +# Name + Sprache des genehmigten Message-Templates. +WHATSAPP_TEMPLATE_NAME=neuer_auftrag +WHATSAPP_TEMPLATE_LANG=de +# Optional, Default v21.0. +WHATSAPP_GRAPH_VERSION= +# Shared Secret fuer den Aufruf des pg_cron-Jobs an POST +# /api/notifications/dispatch. MUSS mit dem DB-Setting +# app.notification_dispatch_secret uebereinstimmen (siehe unten). +NOTIFICATION_DISPATCH_SECRET= From 7409b557293ebcb563679f9986d3338f6ea47df1 Mon Sep 17 00:00:00 2001 From: Jonny Date: Fri, 4 Sep 2026 00:13:58 +0200 Subject: [PATCH 8/9] fix: /api/notifications/dispatch vom Middleware-Session-Gate ausnehmen Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01Dimk8Jo64b4wULp2yAzSNh --- web/middleware.test.ts | 49 ++++++++++++++++++++++++++++++++++++++++++ web/middleware.ts | 8 ++++++- 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 web/middleware.test.ts diff --git a/web/middleware.test.ts b/web/middleware.test.ts new file mode 100644 index 0000000..94426e3 --- /dev/null +++ b/web/middleware.test.ts @@ -0,0 +1,49 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { NextResponse, NextRequest } from "next/server"; + +// updateSession telefoniert normalerweise ueber das Netz zu Supabase +// (supabase.auth.getUser()). Fuer einen schnellen, deterministischen Test +// stubben wir es und pruefen nur, ob die Middleware es aufruft oder umgeht. +vi.mock("@/lib/supabase/middleware", () => ({ + updateSession: vi.fn(), +})); + +import { updateSession } from "@/lib/supabase/middleware"; +import { middleware } from "@/middleware"; + +beforeEach(() => { + vi.mocked(updateSession).mockReset(); + vi.mocked(updateSession).mockImplementation(async (request) => { + const url = request.nextUrl.clone(); + url.pathname = "/login"; + return NextResponse.redirect(url); + }); +}); + +describe("middleware", () => { + it("laesst POST /api/notifications/dispatch ohne Session-Cookie ohne Redirect passieren", async () => { + const request = new NextRequest("http://localhost/api/notifications/dispatch", { + method: "POST", + }); + + const res = await middleware(request); + + // Session-Gate (updateSession) darf fuer diese Route gar nicht laufen + expect(updateSession).not.toHaveBeenCalled(); + // Kein 3xx-Redirect nach /login + expect(res.status).toBe(200); + const location = res.headers.get("location"); + expect(location === null || !location.endsWith("/login")).toBe(true); + }); + + it("leitet GET /dashboard ohne Session-Cookie weiterhin auf /login um", async () => { + const request = new NextRequest("http://localhost/dashboard", { method: "GET" }); + + const res = await middleware(request); + + expect(updateSession).toHaveBeenCalledTimes(1); + expect(res.status).toBeGreaterThanOrEqual(300); + expect(res.status).toBeLessThan(400); + expect(res.headers.get("location")).toMatch(/\/login$/); + }); +}); diff --git a/web/middleware.ts b/web/middleware.ts index 4fb87fb..a14caab 100644 --- a/web/middleware.ts +++ b/web/middleware.ts @@ -1,7 +1,13 @@ -import { type NextRequest } from "next/server"; +import { NextResponse, type NextRequest } from "next/server"; import { updateSession } from "@/lib/supabase/middleware"; export async function middleware(request: NextRequest) { + // Interne Endpunkte mit eigener Authentifizierung (Shared Secret) umgehen + // das Supabase-Session-Gating -- der pg_cron-Aufruf an diese Route traegt + // kein Session-Cookie. + if (request.nextUrl.pathname === "/api/notifications/dispatch") { + return NextResponse.next(); + } return await updateSession(request); } From 4957a5c7bfb480e895eadbc5490b76c75301dd2b Mon Sep 17 00:00:00 2001 From: Jonny Date: Fri, 4 Sep 2026 00:35:50 +0200 Subject: [PATCH 9/9] fix: Abschluss-Review -- Outbox-Update-Fehler nicht schlucken, event_type-Guard, Route-Hardening, Cron-Secret-Guard, pgTAP fuer claim/Write-Denial Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01Dimk8Jo64b4wULp2yAzSNh --- .env.example | 13 +++ ...60903101000_notification_dispatch_cron.sql | 4 +- .../tests/notification_outbox_rls_test.sql | 59 +++++++++++- .../api/notifications/dispatch/route.test.ts | 34 +++++-- web/app/api/notifications/dispatch/route.ts | 24 +++-- web/lib/notifications/dispatch.test.ts | 39 +++++++- web/lib/notifications/dispatch.ts | 91 +++++++++++++++---- 7 files changed, 225 insertions(+), 39 deletions(-) diff --git a/.env.example b/.env.example index 496de8c..7a5fff8 100644 --- a/.env.example +++ b/.env.example @@ -26,3 +26,16 @@ STUDIO_PORT=8082 # Muss von aussen erreichbar sein (Browser!), nicht der interne Docker-Hostname: NEXT_PUBLIC_SUPABASE_URL=http://localhost:8000 NEXT_PUBLIC_SUPABASE_ANON_KEY= + +# --- WhatsApp-Benachrichtigung (Meta WhatsApp Cloud API) --- +# Fehlt eine der fuenf Pflichtvariablen, ist das Feature "aus": die +# Dispatch-Route antwortet dann 200 { uebersprungen: true } und sendet nichts. +WHATSAPP_ACCESS_TOKEN= +WHATSAPP_PHONE_NUMBER_ID= +WHATSAPP_RECIPIENT= +WHATSAPP_TEMPLATE_NAME=neuer_auftrag +WHATSAPP_TEMPLATE_LANG=de +WHATSAPP_GRAPH_VERSION= +# MUSS mit dem DB-Setting app.notification_dispatch_secret uebereinstimmen +# (siehe .claude/skills/rebuild-master-stack/SKILL.md). +NOTIFICATION_DISPATCH_SECRET= diff --git a/supabase/migrations/20260903101000_notification_dispatch_cron.sql b/supabase/migrations/20260903101000_notification_dispatch_cron.sql index 82d80cb..f5b8a13 100644 --- a/supabase/migrations/20260903101000_notification_dispatch_cron.sql +++ b/supabase/migrations/20260903101000_notification_dispatch_cron.sql @@ -3,7 +3,8 @@ -- DB-Settings app.notification_dispatch_url / app.notification_dispatch_secret, -- die pro Stack out-of-band gesetzt werden. Ist die URL leer/ungesetzt (z.B. -- lokaler CLI-Dev-Stack), verhindert die where-Bedingung jeden http_post -- --- der Job existiert dann, tut aber nichts. +-- der Job existiert dann, tut aber nichts. Gleiches gilt, solange +-- app.notification_dispatch_url ODER app.notification_dispatch_secret leer ist. create extension if not exists pg_cron; create extension if not exists pg_net; @@ -18,5 +19,6 @@ select cron.schedule( 'Authorization', 'Bearer ' || current_setting('app.notification_dispatch_secret', true)), body := '{}'::jsonb) where coalesce(current_setting('app.notification_dispatch_url', true), '') <> '' + and coalesce(current_setting('app.notification_dispatch_secret', true), '') <> '' $$ ); diff --git a/supabase/tests/notification_outbox_rls_test.sql b/supabase/tests/notification_outbox_rls_test.sql index c42ba73..464736c 100644 --- a/supabase/tests/notification_outbox_rls_test.sql +++ b/supabase/tests/notification_outbox_rls_test.sql @@ -1,5 +1,5 @@ begin; -select plan(8); +select plan(11); insert into auth.users (id, email) values ('c1111111-1111-1111-1111-111111111111', 'admin-outbox@auftraege.test.local'), @@ -98,5 +98,62 @@ select throws_ok( reset role; reset request.jwt.claims; +-- 5) claim_notification_batch waehlt genau die faelligen Zeilen aus. +-- Zuerst die vom Enqueue-Trigger oben angelegte Zeile entfernen, damit die +-- erwartete Ergebnismenge exakt ist (als postgres, RLS-umgehend). +delete from public.notification_outbox + where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'; + +insert into public.notification_outbox + (id, event_type, status, payload, naechster_versuch_ab, updated_at) +values + -- faellig: pending, Zeitpunkt erreicht + ('c5000000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb, + now() - interval '1 minute', now()), + -- nicht faellig: failed, Backoff noch in der Zukunft + ('c5000000-0000-0000-0000-000000000002', 'auftrag_erstellt', 'failed', '{}'::jsonb, + now() + interval '1 hour', now()), + -- nicht reclaimt: sending, erst vor 2 Minuten uebernommen + ('c5000000-0000-0000-0000-000000000003', 'auftrag_erstellt', 'sending', '{}'::jsonb, + now(), now() - interval '2 minutes'), + -- reclaimt: sending, seit 20 Minuten haengengeblieben + ('c5000000-0000-0000-0000-000000000004', 'auftrag_erstellt', 'sending', '{}'::jsonb, + now(), now() - interval '20 minutes'); + +select results_eq( + $$ select id::text from public.claim_notification_batch(10) order by id $$, + $$ values ('c5000000-0000-0000-0000-000000000001'::text), + ('c5000000-0000-0000-0000-000000000004') $$, + 'claim_notification_batch liefert genau die faellige pending- und die abgestandene sending-Zeile' +); + +-- 6) Write-RLS: authenticated (disponent) darf nicht in die Outbox schreiben. +set local role authenticated; +set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}'; + +-- 2-arg throws_ok(sql, sqlstate): siehe Kommentar bei Assertion 4 -- die 3-arg-Form +-- wuerde die Beschreibung als erwartete Fehlermeldung interpretieren. Geprueft wird +-- nur, dass der INSERT in SQLSTATE 42501 (RLS: keine INSERT-Policy) laeuft. +select throws_ok( + $$ insert into public.notification_outbox (event_type, payload) values ('x', '{}'::jsonb) $$, + '42501' +); + +-- RLS ohne UPDATE-Policy wirft nicht, sondern trifft schlicht 0 Zeilen: das +-- UPDATE laeuft durch, aendert aber keine Zeile. Danach (als postgres) pruefen, +-- dass wirklich keine der vier Zeilen auf 'sent' gekippt ist. (Ein +-- data-modifying UPDATE laesst sich nicht in einen Sub-SELECT/CTE-Ausdruck +-- packen, daher als eigenes Statement + separate Assertion.) +update public.notification_outbox set status = 'sent' where true; + +reset role; +reset request.jwt.claims; + +select is( + (select count(*)::int from public.notification_outbox where status = 'sent'), + 0, + 'authenticated-UPDATE auf notification_outbox aendert keine Zeile (keine Write-Policy)' +); + select * from finish(); rollback; diff --git a/web/app/api/notifications/dispatch/route.test.ts b/web/app/api/notifications/dispatch/route.test.ts index 072556d..1a66948 100644 --- a/web/app/api/notifications/dispatch/route.test.ts +++ b/web/app/api/notifications/dispatch/route.test.ts @@ -22,35 +22,53 @@ function req(headers: Record = {}) { } let altSecret: string | undefined; +let fehlerSpy: ReturnType; +let warnSpy: ReturnType; beforeEach(() => { altSecret = process.env.NOTIFICATION_DISPATCH_SECRET; process.env.NOTIFICATION_DISPATCH_SECRET = "geheim"; vi.mocked(getWhatsAppConfig).mockReset(); vi.mocked(verarbeiteOutbox).mockReset(); + fehlerSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); }); afterEach(() => { if (altSecret === undefined) delete process.env.NOTIFICATION_DISPATCH_SECRET; else process.env.NOTIFICATION_DISPATCH_SECRET = altSecret; + fehlerSpy.mockRestore(); + warnSpy.mockRestore(); }); describe("POST /api/notifications/dispatch", () => { - it("antwortet 401 ohne Bearer-Token", async () => { + // Muss zuerst laufen: route.ts drosselt den Missing-Secret-Log ueber ein + // modul-lokales Flag, das nach dem ersten Treffer gesetzt bleibt. + it("antwortet 500 (JSON), wenn NOTIFICATION_DISPATCH_SECRET nicht gesetzt ist, und loggt nur einmal", async () => { + delete process.env.NOTIFICATION_DISPATCH_SECRET; + + const res1 = await POST(req({ Authorization: "Bearer geheim" })); + expect(res1.status).toBe(500); + expect(await res1.json()).toEqual({ fehler: "Fehlkonfiguration" }); + + const res2 = await POST(req({ Authorization: "Bearer geheim" })); + expect(res2.status).toBe(500); + + // Log-Drossel: trotz zweier Aufrufe nur ein console.error. + expect(fehlerSpy).toHaveBeenCalledTimes(1); + }); + + it("antwortet 401 (JSON) ohne Bearer-Token", async () => { const res = await POST(req()); expect(res.status).toBe(401); + expect(await res.json()).toEqual({ fehler: "Unauthorized" }); expect(verarbeiteOutbox).not.toHaveBeenCalled(); }); - it("antwortet 401 bei falschem Token", async () => { + it("antwortet 401 (JSON) bei falschem Token", async () => { const res = await POST(req({ Authorization: "Bearer falsch" })); expect(res.status).toBe(401); - }); - - it("antwortet 500, wenn NOTIFICATION_DISPATCH_SECRET nicht gesetzt ist", async () => { - delete process.env.NOTIFICATION_DISPATCH_SECRET; - const res = await POST(req({ Authorization: "Bearer geheim" })); - expect(res.status).toBe(500); + expect(await res.json()).toEqual({ fehler: "Unauthorized" }); }); it("antwortet 200 uebersprungen, wenn keine WhatsApp-Config vorhanden ist", async () => { diff --git a/web/app/api/notifications/dispatch/route.ts b/web/app/api/notifications/dispatch/route.ts index 2fbef58..9a57891 100644 --- a/web/app/api/notifications/dispatch/route.ts +++ b/web/app/api/notifications/dispatch/route.ts @@ -1,5 +1,5 @@ import { NextResponse } from "next/server"; -import { timingSafeEqual } from "crypto"; +import { timingSafeEqual } from "node:crypto"; import { createAdminClient } from "@/lib/supabase/admin"; import { getWhatsAppConfig } from "@/lib/notifications/config"; import { verarbeiteOutbox } from "@/lib/notifications/dispatch"; @@ -7,6 +7,10 @@ import { verarbeiteOutbox } from "@/lib/notifications/dispatch"; 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); @@ -17,14 +21,17 @@ function sichererVergleich(a: string, b: string): boolean { export async function POST(request: Request): Promise { const secret = process.env.NOTIFICATION_DISPATCH_SECRET; if (!secret) { - console.error("[notifications] NOTIFICATION_DISPATCH_SECRET nicht gesetzt"); - return new NextResponse("Fehlkonfiguration", { status: 500 }); + 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 new NextResponse("Unauthorized", { status: 401 }); + return NextResponse.json({ fehler: "Unauthorized" }, { status: 401 }); } const cfg = getWhatsAppConfig(); @@ -33,6 +40,11 @@ export async function POST(request: Request): Promise { return NextResponse.json({ verarbeitet: 0, uebersprungen: true }); } - const ergebnis = await verarbeiteOutbox(createAdminClient(), cfg); - return NextResponse.json(ergebnis); + try { + const ergebnis = await verarbeiteOutbox(createAdminClient(), cfg); + return NextResponse.json(ergebnis); + } catch (e) { + console.error("[notifications] Dispatch fehlgeschlagen:", e); + return NextResponse.json({ fehler: "Dispatch fehlgeschlagen" }, { status: 500 }); + } } diff --git a/web/lib/notifications/dispatch.test.ts b/web/lib/notifications/dispatch.test.ts index 8cc95c1..3c45a0f 100644 --- a/web/lib/notifications/dispatch.test.ts +++ b/web/lib/notifications/dispatch.test.ts @@ -29,16 +29,18 @@ function row(over: Partial = {}): OutboxRow { } // Minimaler Fake des supabase-js-Clients: rpc() liefert die geclaimten Zeilen, -// from(...).update(...).eq(...) protokolliert die Updates. -function fakeAdmin(claimed: OutboxRow[]) { +// from(...).update(...).eq(...) protokolliert die Updates. Ueber eqFehler laesst +// sich pro Update-Aufruf (Index) ein Fehlerobjekt einschleusen. +function fakeAdmin(claimed: OutboxRow[], eqFehler: Array<{ message: string } | null> = []) { const updates: { id: string; felder: Record }[] = []; const client = { rpc: vi.fn(async () => ({ data: claimed, error: null })), from: vi.fn(() => ({ update: (felder: Record) => ({ eq: async (_spalte: string, id: string) => { + const fehler = eqFehler[updates.length] ?? null; updates.push({ id, felder }); - return { data: null, error: null }; + return { data: null, error: fehler }; }, }), })), @@ -113,4 +115,35 @@ describe("verarbeiteOutbox", () => { }); expect(client.rpc).toHaveBeenCalledWith("claim_notification_batch", { p_limit: 20 }); }); + + it("macht nach erfolgreicher Sendung einen Poison-Write auf dead, wenn das sent-Update fehlschlaegt", async () => { + const fehlerSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + // Erster Update-Aufruf (sent) schlaegt fehl, zweiter (dead) geht durch. + const { client, updates } = fakeAdmin([row({ id: "r1" })], [{ message: "boom" }, null]); + const sender = vi.fn(async (): Promise => ({ ok: true, messageId: "wamid.1" })); + + const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender }); + + expect(ergebnis.gesendet).toBe(1); + expect(updates).toHaveLength(2); + expect(updates[0].felder).toMatchObject({ status: "sent", wa_message_id: "wamid.1" }); + expect(updates[1].felder.status).toBe("dead"); + expect(String(updates[1].felder.letzter_fehler)).toContain("manuell pruefen"); + fehlerSpy.mockRestore(); + }); + + it("setzt eine Zeile mit unbekanntem event_type auf dead, ohne den sender zu rufen", async () => { + const fehlerSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + const { client, updates } = fakeAdmin([row({ id: "r1", event_type: "irgendwas_anderes" })]); + const sender = vi.fn(async (): Promise => ({ ok: true, messageId: "x" })); + + const ergebnis = await verarbeiteOutbox(client as never, CFG, { sender }); + + expect(sender).not.toHaveBeenCalled(); + expect(ergebnis).toEqual({ verarbeitet: 1, gesendet: 0, fehlgeschlagen: 0, tot: 1 }); + expect(updates).toHaveLength(1); + expect(updates[0].felder).toMatchObject({ status: "dead" }); + expect(String(updates[0].felder.letzter_fehler)).toContain("irgendwas_anderes"); + fehlerSpy.mockRestore(); + }); }); diff --git a/web/lib/notifications/dispatch.ts b/web/lib/notifications/dispatch.ts index 5e236ba..bd41226 100644 --- a/web/lib/notifications/dispatch.ts +++ b/web/lib/notifications/dispatch.ts @@ -50,19 +50,66 @@ export async function verarbeiteOutbox( }; for (const row of rows) { + const nun = jetzt(); + + // Jeder Status-Schreibvorgang wird geprueft: schlaegt er fehl, bleibt die + // Zeile sonst in 'sending' haengen und wird nach 15 min erneut geclaimt -> + // die Nachricht ginge wiederholt raus. Deshalb laut loggen und dem Aufrufer + // ueber den Rueckgabewert signalisieren. + async function schreibe(felder: Record): Promise { + const { error: updateFehler } = await admin + .from("notification_outbox") + .update(felder) + .eq("id", row.id); + if (updateFehler) { + console.error( + "[notifications] Outbox-Status-Update fehlgeschlagen fuer", + row.id, + "-", + updateFehler.message + ); + return false; + } + return true; + } + ergebnis.verarbeitet += 1; + + if (row.event_type !== "auftrag_erstellt") { + console.error( + "[notifications] unbekannter event_type, Zeile wird auf dead gesetzt:", + row.id, + row.event_type + ); + await schreibe({ + status: "dead", + letzter_fehler: `unbekannter event_type: ${row.event_type}`, + updated_at: nun.toISOString(), + }); + ergebnis.tot += 1; + continue; + } + const res = await sender(cfg, row.payload); if (res.ok) { - await admin - .from("notification_outbox") - .update({ - status: "sent", - wa_message_id: res.messageId, - letzter_fehler: null, - updated_at: jetzt().toISOString(), - }) - .eq("id", row.id); + const ok = await schreibe({ + status: "sent", + wa_message_id: res.messageId, + letzter_fehler: null, + updated_at: nun.toISOString(), + }); + if (!ok) { + // Nachricht ging raus, aber der Status-Schreibvorgang scheiterte. Ein + // einmaliger Poison-Write auf 'dead' verhindert, dass die 15-min-Reclaim + // die Nachricht im haeufigen transienten Fall erneut verschickt. + await schreibe({ + status: "dead", + letzter_fehler: + "Sendung an Meta ok, aber Status-Update fehlgeschlagen - manuell pruefen", + updated_at: nun.toISOString(), + }); + } ergebnis.gesendet += 1; continue; } @@ -70,18 +117,22 @@ export async function verarbeiteOutbox( const neueVersuche = row.versuche + 1; const tot = neueVersuche >= row.max_versuche; const backoffMin = Math.min(2 ** neueVersuche, BACKOFF_MAX_MIN); - const naechster = new Date(jetzt().getTime() + backoffMin * 60_000); + const naechster = new Date(nun.getTime() + backoffMin * 60_000); - await admin - .from("notification_outbox") - .update({ - status: tot ? "dead" : "failed", - versuche: neueVersuche, - naechster_versuch_ab: naechster.toISOString(), - letzter_fehler: res.fehler.slice(0, 500), - updated_at: jetzt().toISOString(), - }) - .eq("id", row.id); + const ok = await schreibe({ + status: tot ? "dead" : "failed", + versuche: neueVersuche, + naechster_versuch_ab: naechster.toISOString(), + letzter_fehler: res.fehler.slice(0, 500), + updated_at: nun.toISOString(), + }); + + if (!ok) { + // Status-Schreibvorgang gescheitert -> der laute Log oben ist das + // Operator-Signal; die Zeile zaehlt als fehlgeschlagen (nicht tot). + ergebnis.fehlgeschlagen += 1; + continue; + } if (tot) ergebnis.tot += 1; else ergebnis.fehlgeschlagen += 1;