Skip to content

Commit 0136e7c

Browse files
Mihai - Alexandru ChindrișMihai - Alexandru Chindriș
authored andcommitted
Fix dev webhook handler
1 parent 1fff1ed commit 0136e7c

1 file changed

Lines changed: 60 additions & 1 deletion

File tree

apps/webhook-receiver/src/server.ts

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,66 @@ app.post("/webhook/mymx/dev", async (req, res) => {
426426
const event = req.body && typeof req.body === "string" ? JSON.parse(req.body) : req.body;
427427
if (!event?.id || !event?.email) return res.status(400).json({ error: "invalid_event" });
428428
req.body = JSON.stringify(event);
429-
return app.handle(req, res);
429+
const rawBody = req.body;
430+
const headers = Object.fromEntries(
431+
Object.entries(req.headers).map(([k, v]) => [k, Array.isArray(v) ? v.join(",") : v])
432+
);
433+
434+
const parsedEvent = JSON.parse(rawBody);
435+
if (seen.has(parsedEvent.id)) {
436+
return res.status(200).set(MYMX_CONFIRMED_HEADER, "true").end();
437+
}
438+
439+
remember(parsedEvent.id);
440+
441+
const rules = loadRules();
442+
const from = parsedEvent.email.headers.from;
443+
const subject = parsedEvent.email.headers.subject;
444+
const bodyText = parsedEvent.email.parsed?.body_text || null;
445+
446+
const blocked = isBlockedSender(from, rules);
447+
const { score, reasons, flags } = scoreEmail(subject, bodyText, from, rules);
448+
449+
let notified = false;
450+
if (!blocked) {
451+
const isVip = isVipSender(from, rules);
452+
const hasFlags = flags.length > 0;
453+
const shouldNotify = (score >= notifyThreshold && !hasFlags) || (isVip && !hasFlags);
454+
455+
if (shouldNotify) {
456+
const summary = [
457+
`📬 ${subject || "(no subject)"}`,
458+
`From: ${from || "unknown"}`,
459+
`Score: ${score}`,
460+
reasons.length ? `Why: ${reasons.join(" | ")}` : "",
461+
]
462+
.filter(Boolean)
463+
.join("\n");
464+
465+
notified = await sendNotification(summary);
466+
console.log(`Notification sent: ${notified}`);
467+
}
468+
}
469+
470+
const record = {
471+
id: parsedEvent.id,
472+
received_at: parsedEvent.email.received_at,
473+
from,
474+
subject,
475+
to: parsedEvent.email.headers.to,
476+
body_text: bodyText,
477+
spam_score: parsedEvent.email.analysis?.spamassassin?.score ?? null,
478+
score,
479+
reasons,
480+
flags,
481+
blocked,
482+
notified,
483+
raw_event: parsedEvent,
484+
};
485+
486+
appendEvent(JSON.stringify(record));
487+
console.log(`Event stored: ${parsedEvent.id}`);
488+
return res.status(200).set(MYMX_CONFIRMED_HEADER, "true").end();
430489
} catch (err) {
431490
console.error(err);
432491
return res.status(400).json({ error: "invalid_json" });

0 commit comments

Comments
 (0)