saturn
- 187 commits
- 2 branches
- 0 tags
- updated
- CI 2/2
email.js
7.6 KB · 188 lines
1// email worker: cloudflare email routing hands it everything sent to2// reply@replies.danieldaum.net. a good comment is saved (live, or held if it3// has a link) and daniel gets an email to approve or delete it.4// fixable mistakes bounce; anything that looks like abuse is dropped silently,5// since a bounce would go to a forged address.6// the sender's address is only used for the author check, never stored78import PostalMime from "postal-mime";9import { EmailMessage } from "cloudflare:email";10import { SITE, REPLY_TO, hmac, isLikeable } from "./lib.js";1112const AUTHOR = "daniel@danieldaum.net";13const NOTIFY_FROM = "notify@replies.danieldaum.net";1415// "re: https://danieldaum.net/now/sep-2026/", plus "#comment-<id>" for a reply16const SUBJECT_RE = /^\s*(?:re:\s*)*https:\/\/danieldaum\.net(\/[a-z0-9\/-]*)(?:#comment-([0-9a-f-]{36}))?\s*$/i;1718const MAX_PER_HOUR = 20;19const MAX_BODY = 2000;20const MAX_LINKS = 2;21const MAX_NAME = 40;2223export default {24 async email(message, env) {25 const auth = (message.headers.get("Authentication-Results") || "").toLowerCase();26 if (!auth.includes("dkim=pass") || !(auth.includes("spf=pass") || auth.includes("dmarc=pass"))) {27 console.log("drop: failed authentication");28 return;29 }3031 // site-wide, so nothing per sender is kept32 const since = new Date(Date.now() - 60 * 60 * 1000).toISOString();33 const recent = await env.DB.prepare("SELECT COUNT(*) AS n FROM Comments WHERE created_at > ?").bind(since).first();34 if (recent.n >= MAX_PER_HOUR) {35 console.log("drop: hourly cap");36 return;37 }3839 const email = await PostalMime.parse(message.raw);4041 // /now/ itself moves to the next edition, so comments go on the edition42 const match = (email.subject || "").match(SUBJECT_RE);43 const page = match ? match[1].toLowerCase() : "";44 if (!isLikeable(page) || page === "/now/" || !(await pageExists(env, page))) {45 message.setReject("Please use the reply link on the post, so the subject is the post's address");46 return;47 }4849 // one level of nesting; unknown ids become top-level50 const parent = match[2] ? await topLevelParent(env, match[2].toLowerCase(), page) : null;5152 const { name, body } = cleanBody(email);53 const isAuthor = (email.from?.address || "").trim().toLowerCase() === AUTHOR && fromMyDomain(email);54 if (!name && !isAuthor) {55 message.setReject(`Please start your comment with a line like "name: sam". That name is shown with your comment`);56 return;57 }58 if (body.length < 2 || body.length > MAX_BODY) {59 message.setReject(`Comments must be between 2 and ${MAX_BODY} characters`);60 return;61 }62 const links = (body.match(/https?:\/\//g) || []).length;63 if (links > MAX_LINKS) {64 message.setReject(`Comments can have at most ${MAX_LINKS} links`);65 return;66 }6768 // links are what spam is for, so those wait for approval69 const approved = isAuthor || links === 0;70 const id = crypto.randomUUID();71 const shownName = isAuthor ? "daniel" : name;72 await env.DB.prepare("INSERT INTO Comments (id, page, parent, name, body, is_author, approved, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")73 .bind(id, page, parent, shownName, body, isAuthor ? 1 : 0, approved ? 1 : 0, new Date().toISOString())74 .run();7576 // every comment, mine too, so each one has a delete link77 try {78 const sig = await hmac(env.SOCIAL_SECRET, "moderate:" + id);79 const link = `${env.SITE_ORIGIN || SITE}/api/moderate?id=${id}&sig=${sig}`;80 await env.NOTIFY.send(new EmailMessage(NOTIFY_FROM, AUTHOR, notification({ page, id, name: shownName, body, approved, link })));81 } catch (err) {82 console.log("notify failed: " + (err?.message || err));83 }84 },85};8687// ===== checks =====8889// only cloudflare's own result counts: it strips forged headers carrying its id90function fromMyDomain(email) {91 return email.headers.some(92 (h) => h.key === "authentication-results" && /^\s*mx\.cloudflare\.net;/i.test(h.value) && /\bdmarc=pass\b[^;]*\bheader\.from=danieldaum\.net\b/i.test(h.value)93 );94}9596// SITE_ORIGIN (.dev.vars) points at wrangler pages dev when testing locally97async function pageExists(env, page) {98 try {99 const res = await fetch((env.SITE_ORIGIN || SITE) + page, { method: "HEAD" });100 return res.status === 200;101 } catch {102 return false;103 }104}105106async function topLevelParent(env, id, page) {107 const row = await env.DB.prepare("SELECT page, parent FROM Comments WHERE id = ? AND approved = 1").bind(id).first();108 if (!row || row.page !== page) return null;109 return row.parent || id;110}111112// ===== text =====113114// plain text without quoted mail or signatures. an optional "name: ..."115// first line sets the display name. escaped later, when rendered116function cleanBody(email) {117 const text = (email.text?.trim() ? email.text : htmlToText(email.html || "")).replace(/\r\n?/g, "\n");118 const lines = text.split("\n");119120 let name = "";121 const kept = [];122 for (let i = 0; i < lines.length; i++) {123 const line = lines[i].trimEnd();124 const t = line.trim();125126 // gmail can wrap "On <date> <name> wrote:" over two lines127 if (128 /^On\s.*wrote:$/.test(t) ||129 (/^On\s/.test(t) && /wrote:$/.test((lines[i + 1] || "").trim())) ||130 /^-{2,}\s*(original|forwarded) message/i.test(t) ||131 /^From:\s/.test(t) ||132 /^_{5,}$/.test(t) ||133 t === "--" ||134 /reply above this line/i.test(t) ||135 /^sent from my /i.test(t)136 ) {137 break;138 }139 if (t.startsWith(">")) continue;140141 const nameLine = t.match(/^name:\s*(.*)$/i);142 if (nameLine && !name && !kept.some((k) => k.trim())) {143 name = nameLine[1];144 continue;145 }146 kept.push(line);147 }148149 name = name.replace(/[\x00-\x1f\x7f]/g, "").replace(/\s+/g, " ").trim().slice(0, MAX_NAME);150 const body = kept.join("\n").replace(/\n{3,}/g, "\n\n").trim();151 return { name, body };152}153154function htmlToText(html) {155 return html156 .replace(/<(script|style)[\s\S]*?<\/\1>/gi, "")157 .replace(/<br\s*\/?>/gi, "\n")158 .replace(/<\/(p|div|li|blockquote|h[1-6]|tr)>/gi, "\n")159 .replace(/<[^>]+>/g, "")160 .replace(/ /g, " ")161 .replace(/</g, "<")162 .replace(/>/g, ">")163 .replace(/"/g, '"')164 .replace(/'/g, "'")165 .replace(/&/g, "&");166}167168// ===== notification =====169170// replying to it posts an answer under the comment. the marker line keeps the171// quoted notification out of that answer172function notification({ page, id, name, body, approved, link }) {173 const headers = [174 `From: ${NOTIFY_FROM}`,175 `To: ${AUTHOR}`,176 `Reply-To: ${REPLY_TO}`,177 `Subject: re: ${SITE}${page}#comment-${id}`,178 `Date: ${new Date().toUTCString().replace(/GMT$/, "+0000")}`,179 `Message-ID: <${crypto.randomUUID()}@replies.danieldaum.net>`,180 `MIME-Version: 1.0`,181 `Content-Type: text/plain; charset=utf-8`,182 `Content-Transfer-Encoding: 8bit`,183 ];184 const status = approved ? "It is live." : "It has a link, so it is waiting for approval.";185 const action = approved ? "Delete" : "Approve or delete";186 const text = [`## reply above this line to answer on the site ##`, ``, `${name} commented on ${page}:`, ``, body, ``, status, `${action}: ${link}`, ``].join("\n");187 return headers.join("\r\n") + "\r\n\r\n" + text.replace(/\n/g, "\r\n");188}