projects

saturn

My website

feat: add reply by email

daniel daum committed parent 7889e35 commit 505c6c2Signed, not verified

SignedGitea couldn't verify the signature.

Showing 5 changed files with 251 additions and 0 deletions.

workers/comments/.gitignoreadded +1 −0
@@ -0,0 +1 @@1node_modules/
workers/comments/package-lock.jsonadded +19 −0
@@ -0,0 +1,19 @@1{2    "name": "saturn-comments",3    "lockfileVersion": 3,4    "requires": true,5    "packages": {6        "": {7            "name": "saturn-comments",8            "dependencies": {9                "postal-mime": "2.4.3"10            }11        },12        "node_modules/postal-mime": {13            "version": "2.4.3",14            "resolved": "https://registry.npmjs.org/postal-mime/-/postal-mime-2.4.3.tgz",15            "integrity": "sha512-KT8P+/We7LH48EhjmLRLEiQx+HI6zZ5TTeuzhuZkMbcJnp9mdmxm/FgiRIzmhZm8mxmk8mtisIAelq1wNwumxg==",16            "license": "MIT-0"17        }18    }19}
workers/comments/package.jsonadded +8 −0
@@ -0,0 +1,8 @@1{2    "name": "saturn-comments",3    "private": true,4    "type": "module",5    "dependencies": {6        "postal-mime": "2.4.3"7    }8}
workers/comments/src/index.jsadded +209 −0
@@ -0,0 +1,209 @@1// email worker for comments. cloudflare email routing hands it everything2// sent to reply@replies.danieldaum.net. each message goes through the checks3// below in order; a good one is saved (live, or held if it has a link) and4// daniel gets an email with a link to approve or delete it.5//6// a fixable mistake (bad subject, empty body) bounces so the sender knows.7// anything that looks like abuse is dropped silently, since a bounce would8// go to whoever's address was forged.9//10// the sender's address is used for the author check and then forgotten:11// it is never stored, hashed or logged.1213import PostalMime from "postal-mime";14import { EmailMessage } from "cloudflare:email";15import { hmacHex } from "../../../functions/_lib/hmac.js";16import { isLikeable } from "../../../functions/_lib/likes.js";1718const SITE_URL = "https://danieldaum.net";19const AUTHOR = "daniel@danieldaum.net";20const NOTIFY_FROM = "notify@replies.danieldaum.net";2122// "re: https://danieldaum.net/now/sep-2026/" with an optional23// "#comment-<id>" when replying to a comment. mail apps may add more "re:"s24const SUBJECT_RE = /^\s*(?:re:\s*)*https:\/\/danieldaum\.net(\/[a-z0-9\/-]*)(?:#comment-([0-9a-f-]{36}))?\s*$/i;2526const MAX_PER_HOUR = 20;27const MAX_BODY = 2000;28const MAX_LINKS = 2;29const MAX_NAME = 40;3031export default {32    async email(message, env) {33        // 1. the mail really comes from the domain it claims34        const auth = (message.headers.get("Authentication-Results") || "").toLowerCase();35        if (!auth.includes("dkim=pass") || !(auth.includes("spf=pass") || auth.includes("dmarc=pass"))) {36            console.log("drop: failed authentication");37            return;38        }3940        // 2. site-wide cap, counted from rows only, nothing per sender41        const since = new Date(Date.now() - 60 * 60 * 1000).toISOString();42        const recent = await env.DB.prepare("SELECT COUNT(*) AS n FROM Comments WHERE created_at > ?").bind(since).first();43        if (recent.n >= MAX_PER_HOUR) {44            console.log("drop: hourly cap reached");45            return;46        }4748        const email = await PostalMime.parse(message.raw);4950        // 3. subject names a real post. /now/ itself is excluded because it51        //    moves to a new edition; comments belong to the edition52        const match = (email.subject || "").match(SUBJECT_RE);53        const page = match ? match[1].toLowerCase() : "";54        if (!isLikeable(page) || page === "/now/" || !(await pageExists(env, page))) {55            message.setReject("Please use the reply link on the post, so the subject is the post's address");56            return;57        }5859        // 4. a reply to a comment hangs under that comment's top-level60        //    comment (one level of nesting). unknown ids become top-level61        const parent = match[2] ? await topLevelParent(env, match[2].toLowerCase(), page) : null;6263        // 5. the text itself, without quoted mail or signatures. everyone64        //    but daniel (proven by dmarc) picks their own name65        const { name, body } = cleanBody(email);66        const from = (email.from?.address || "").trim().toLowerCase();67        const isAuthor = from === AUTHOR && auth.includes("dmarc=pass");68        if (!name && !isAuthor) {69            message.setReject(`Please start your comment with a line like "name: sam". That name is shown with your comment`);70            return;71        }72        if (body.length < 2 || body.length > MAX_BODY) {73            message.setReject(`Comments must be between 2 and ${MAX_BODY} characters`);74            return;75        }76        const links = (body.match(/https?:\/\//g) || []).length;77        if (links > MAX_LINKS) {78            message.setReject(`Comments can have at most ${MAX_LINKS} links`);79            return;80        }8182        // 6. plain comments go live at once. links are what spam is for, so83        //    a comment with one waits for approval. daniel's are always live84        const approved = isAuthor || links === 0;8586        const id = crypto.randomUUID();87        const shownName = isAuthor ? "daniel" : name;88        await env.DB89            .prepare(90                "INSERT INTO Comments (id, page, parent, name, body, is_author, approved, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"91            )92            .bind(id, page, parent, shownName, body, isAuthor ? 1 : 0, approved ? 1 : 0, new Date().toISOString())93            .run();9495        // 7. tell daniel about every comment, his own included, so each one96        //    has a delete link. the comment is already saved, so a failure97        //    here only logs98        try {99            const sig = await hmacHex(env.SOCIAL_SECRET, "moderate:" + id);100            const raw = notification({ page, id, name: shownName, body, approved, link: `${env.SITE_ORIGIN || SITE_URL}/api/moderate?id=${id}&sig=${sig}` });101            await env.NOTIFY.send(new EmailMessage(NOTIFY_FROM, AUTHOR, raw));102        } catch (err) {103            console.log("notify failed: " + (err?.message || err));104        }105    },106};107108// ===== checks =====109110// SITE_ORIGIN is for local testing only (.dev.vars): it points the page111// check and the moderation link at wrangler pages dev instead of the live site112async function pageExists(env, page) {113    try {114        const res = await fetch((env.SITE_ORIGIN || SITE_URL) + page, { method: "HEAD" });115        return res.status === 200;116    } catch {117        return false;118    }119}120121async function topLevelParent(env, id, page) {122    const row = await env.DB.prepare("SELECT page, parent FROM Comments WHERE id = ? AND approved = 1").bind(id).first();123    if (!row || row.page !== page) {124        return null;125    }126    return row.parent || id;127}128129// ===== text =====130131// plain text with quoted history and signatures cut off. a "name: ..."132// first line sets the display name (empty if missing).133// stored as plain text, escaped when the page is rendered134function cleanBody(email) {135    const text = (email.text?.trim() ? email.text : htmlToText(email.html || "")).replace(/\r\n?/g, "\n");136    const lines = text.split("\n");137138    let name = "";139    const kept = [];140    for (let i = 0; i < lines.length; i++) {141        const line = lines[i].trimEnd();142        const t = line.trim();143144        // where the previous message or a signature starts. gmail can wrap145        // "On <date> <name> wrote:" over two lines146        if (147            /^On\s.*wrote:$/.test(t) ||148            (/^On\s/.test(t) && /wrote:$/.test((lines[i + 1] || "").trim())) ||149            /^-{2,}\s*(original|forwarded) message/i.test(t) ||150            /^From:\s/.test(t) ||151            /^_{5,}$/.test(t) ||152            t === "--" ||153            /reply above this line/i.test(t) ||154            /^sent from my /i.test(t)155        ) {156            break;157        }158        if (t.startsWith(">")) {159            continue;160        }161        const nameLine = t.match(/^name:\s*(.*)$/i);162        if (nameLine && !name && !kept.some((k) => k.trim())) {163            name = nameLine[1];164            continue;165        }166        kept.push(line);167    }168169    name = name.replace(/[\x00-\x1f\x7f]/g, "").replace(/\s+/g, " ").trim().slice(0, MAX_NAME);170    const body = kept.join("\n").replace(/\n{3,}/g, "\n\n").trim();171    return { name, body };172}173174function htmlToText(html) {175    return html176        .replace(/<(script|style)[\s\S]*?<\/\1>/gi, "")177        .replace(/<br\s*\/?>/gi, "\n")178        .replace(/<\/(p|div|li|blockquote|h[1-6]|tr)>/gi, "\n")179        .replace(/<[^>]+>/g, "")180        .replace(/&nbsp;/g, " ")181        .replace(/&lt;/g, "<")182        .replace(/&gt;/g, ">")183        .replace(/&quot;/g, "\"")184        .replace(/&#39;/g, "'")185        .replace(/&amp;/g, "&");186}187188// ===== notification =====189190// a minimal plain-text email, built by hand. its reply-to and subject make191// hitting reply post an answer under the comment. the marker line keeps the192// quoted notification (and its moderation link) out of that answer193function notification({ page, id, name, body, approved, link }) {194    const headers = [195        `From: ${NOTIFY_FROM}`,196        `To: ${AUTHOR}`,197        `Reply-To: reply@replies.danieldaum.net`,198        `Subject: re: ${SITE_URL}${page}#comment-${id}`,199        `Date: ${new Date().toUTCString().replace(/GMT$/, "+0000")}`,200        `Message-ID: <${crypto.randomUUID()}@replies.danieldaum.net>`,201        `MIME-Version: 1.0`,202        `Content-Type: text/plain; charset=utf-8`,203        `Content-Transfer-Encoding: 8bit`,204    ];205    const status = approved ? "It is live." : "It has a link, so it is waiting for approval.";206    const action = approved ? "Delete" : "Approve or delete";207    const text = [`## reply above this line to answer on the site ##`, ``, `${name} commented on ${page}:`, ``, body, ``, status, `${action}: ${link}`, ``].join("\n");208    return headers.join("\r\n") + "\r\n\r\n" + text.replace(/\n/g, "\r\n");209}
workers/comments/wrangler.tomladded +14 −0
@@ -0,0 +1,14 @@1# keeps the old worker's name so its email routing rule still points here2name = "saturn-replies-inbound"3main = "src/index.js"4compatibility_date = "2026-09-01"5workers_dev = false67[[d1_databases]]8binding = "DB"9database_name = "saturn-social"10database_id = "2cc8bddd-d422-4d1e-8480-c1c75c8d02b0"1112[[send_email]]13name = "NOTIFY"14destination_address = "daniel@danieldaum.net"