saturn
- 187 commits
- 2 branches
- 0 tags
- updated
- CI 2/2
feat: add reply by email
SignedGitea couldn't verify the signature.
Showing 13 changed files with 380 additions and 48 deletions.
.gitea/workflows/deploy.yaml
+1 −1
@@ -31,7 +31,7 @@ jobs:3131 run: |3232 mkdir dist3333 git ls-files -z \34 | grep -zv -e '^internal/' -e '^\.gitea/' -e '^\.gitignore$' \34 | grep -zv -e '^internal/' -e '^workers/' -e '^\.gitea/' -e '^\.gitignore$' \3535 | xargs -0 cp --parents -t dist36363737 - name: Deploy to Cloudflare Pages
about/index.html
+3 −3
@@ -125,9 +125,9 @@125125126126 </section>127127128 <footer class="post-likes" id="likes" data-likes>129 <p class="meta">likes unavailable</p>130 </footer>128 <section class="post-social" id="comments" data-social aria-label="likes and comments">129 <p class="meta">likes and comments unavailable</p>130 </section>131131 </article>132132133133 <nav class="pager" aria-label="post navigation">
functions/_lib/comments.jsadded
+82 −0
@@ -0,0 +1,82 @@1// shared by _middleware.js and api/moderate.js23// everything from d1 or a request goes through this before it is written4// into a page5export function escapeHtml(str) {6 return String(str)7 .replace(/&/g, "&")8 .replace(/</g, "<")9 .replace(/>/g, ">")10 .replace(/"/g, """);11}1213// a stored comment as paragraphs: blank lines split paragraphs, single14// newlines become <br>15export function bodyHtml(body) {16 return body17 .split(/\n{2,}/)18 .map((para) => `<p>${escapeHtml(para).replace(/\n/g, "<br />")}</p>`)19 .join("");20}2122// approved comments for one page, oldest first, as a one-level thread plus23// the heading count and the "comment by email" footer. key passed24// isLikeable(), so it is safe to write into the page as-is25export function renderComments(key, rows) {26 const replies = new Map();27 for (const row of rows) {28 if (row.parent) {29 replies.set(row.parent, [...(replies.get(row.parent) || []), row]);30 }31 }32 const top = rows.filter((row) => !row.parent);33 const thread = (list) => `<ol class="comment-thread">${list.map((row) => `<li>${comment(row, replies.get(row.id))}</li>`).join("")}</ol>`;3435 const title = rows.length === 0 ? "no comments yet" : rows.length === 1 ? "1 comment" : `${rows.length} comments`;36 return {37 title,38 thread: top.length ? thread(top) : "",39 foot: `<div class="social-foot">40 <a class="comment-link" href="${mailto(key)}">comment by email →</a>41 <p class="meta">start with a "name:" line; that name is shown. comments with links wait for approval. your address is never shown or stored</p>42</div>`,43 };4445 function comment(row, children) {46 const id = `comment-${row.id}`;47 return `<article class="comment" id="${id}">48 <p class="meta">49 <span class="comment-name">${escapeHtml(row.name)}</span>${row.is_author ? `<span class="comment-author">author</span>` : ""}50 <a class="comment-time" href="#${id}"><time datetime="${escapeHtml(row.created_at)}">${when(row.created_at)}</time></a>51 </p>52 <div class="comment-body">${bodyHtml(row.body)}</div>53 <a class="comment-link" href="${mailto(key + "#" + id)}">reply →</a>54 ${children ? thread(children) : ""}55</article>`;56 }57}5859// the subject is what the email worker reads to know where a comment goes;60// the body starts with an empty name line as a hint61function mailto(target) {62 const subject = encodeURIComponent(`re: https://danieldaum.net${target}`);63 return `mailto:reply@replies.danieldaum.net?subject=${subject}&body=${encodeURIComponent("name: ")}`;64}6566// "4 Sep 2026 · 09:12", oakland time67function when(iso) {68 const parts = Object.fromEntries(69 new Intl.DateTimeFormat("en-GB", {70 timeZone: "America/Los_Angeles",71 day: "numeric",72 month: "short",73 year: "numeric",74 hour: "2-digit",75 minute: "2-digit",76 hourCycle: "h23",77 })78 .formatToParts(new Date(iso))79 .map((p) => [p.type, p.value])80 );81 return `${parts.day} ${parts.month} ${parts.year} · ${parts.hour}:${parts.minute}`;82}
functions/_lib/hmac.jsadded
+33 −0
@@ -0,0 +1,33 @@1// keyed sha-256 hash as hex. shared by likes, comment moderation and the2// email worker (workers/comments imports this file), so signatures made on3// one side always match on the other45export async function hmacHex(secret, message) {6 if (!secret) {7 throw new Error("SOCIAL_SECRET is not set");8 }9 const enc = new TextEncoder();10 const key = await crypto.subtle.importKey(11 "raw",12 enc.encode(secret),13 { name: "HMAC", hash: "SHA-256" },14 false,15 ["sign"]16 );17 const sig = await crypto.subtle.sign("HMAC", key, enc.encode(message));18 return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");19}2021// checks a signature from a link. compares every character so the time taken22// doesn't reveal how much of a guess was right23export async function hmacMatches(secret, message, sig) {24 const expected = await hmacHex(secret, message);25 if (typeof sig !== "string" || sig.length !== expected.length) {26 return false;27 }28 let diff = 0;29 for (let i = 0; i < sig.length; i++) {30 diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);31 }32 return diff === 0;33}
functions/_lib/likes.js
+3 −14
@@ -1,5 +1,7 @@11// shared by _middleware.js and api/like.js223import { hmacHex } from "./hmac.js";435// pages that can carry likes: /about/, /now/, /now/<slug>/, /blog/<slug>/.46// never /blog/ itself57export function isLikeable(pathname) {@@ -10,21 +12,8 @@ export function isLikeable(pathname) {1012// a keyed hash of ip + browser + today's date. it can't be reversed, and it1113// stops matching at utc midnight.1214export async function voterId(secret, request) {13 if (!secret) {14 throw new Error("SOCIAL_SECRET is not set");15 }1615 const ip = request.headers.get("CF-Connecting-IP") || "";1716 const ua = request.headers.get("User-Agent") || "";1817 const day = new Date().toISOString().slice(0, 10);1920 const enc = new TextEncoder();21 const key = await crypto.subtle.importKey(22 "raw",23 enc.encode(secret),24 { name: "HMAC", hash: "SHA-256" },25 false,26 ["sign"]27 );28 const sig = await crypto.subtle.sign("HMAC", key, enc.encode(`${ip}|${ua}|${day}`));29 return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");18 return hmacHex(secret, `${ip}|${ua}|${day}`);3019}
functions/_middleware.js
+18 −10
@@ -1,9 +1,10 @@11// runs in front of /about/, /now/*, /blog/* and /api/* (see _routes.json).2// on likeable pages it reads the like count from d1 and writes the like3// button into the page's [data-likes] placeholder. if anything fails, the2// on likeable pages it reads likes and approved comments from d1 and writes3// them into the page's [data-social] placeholder. if anything fails, the44// page is served untouched with its fallback text.5566import { isLikeable, voterId } from "./_lib/likes.js";7import { renderComments } from "./_lib/comments.js";7889export async function onRequest(context) {910 const { request, env } = context;@@ -31,24 +32,31 @@ export async function onRequest(context) {3132 }32333334 const page = new HTMLRewriter()34 .on("[data-likes]", {35 .on("[data-social]", {3536 async element(el) {36 // the placeholder can name another page's count, e.g. /now/37 // shares /now/sep-2026/'s. empty means this page.38 const key = el.getAttribute("data-likes") || pathname;37 // the placeholder can name another page, e.g. /now/ shows38 // /now/sep-2026/'s likes and comments. empty means this page.39 const key = el.getAttribute("data-social") || pathname;3940 if (!isLikeable(key)) {4041 return;4142 }4243 try {43 const [count, liked] = await env.DB.batch([44 const [count, liked, comments] = await env.DB.batch([4445 env.DB.prepare("SELECT count FROM Likes WHERE page = ?").bind(key),4546 env.DB.prepare("SELECT 1 FROM LikeVoters WHERE page = ? AND voter = ?").bind(key, voter),47 env.DB48 .prepare("SELECT id, parent, name, body, is_author, created_at FROM Comments WHERE page = ? AND approved = 1 ORDER BY created_at")49 .bind(key),4650 ]);4751 const likes = {4852 count: Number(count.results[0]?.count ?? 0),4953 liked: liked.results.length > 0,5054 };51 el.setInnerContent(renderLikes(key, likes), { html: true });55 const { title, thread, foot } = renderComments(key, comments.results);56 el.setInnerContent(57 `<div class="social-head"><h2 class="social-title">${title}</h2>${renderLikes(key, likes)}</div>${thread}${foot}`,58 { html: true }59 );5260 } catch {5361 // leave the fallback text5462 }@@ -56,7 +64,7 @@ export async function onRequest(context) {5664 })5765 .transform(response);586659 // the count is per visitor and changes on submit, so the back button67 // the like state is per visitor and changes on submit, so the back button6068 // must not show a cached copy6169 const out = new Response(page.body, page);6270 out.headers.set("Cache-Control", "private, no-cache");@@ -70,7 +78,7 @@ function renderLikes(key, { count, liked }) {7078 const noun = count === 1 ? "like" : "likes";7179 const label = liked ? `you liked this post, ${count} ${noun}` : `like this post, ${count} ${noun}`;7280 const state = liked ? ` disabled aria-pressed="true"` : "";73 return `<form class="like-form" method="POST" action="/api/like">81 return `<form class="like-form" id="likes" method="POST" action="/api/like">7482 <input type="hidden" name="path" value="${key}" />7583 <button type="submit" class="like-button" aria-label="${label}"${state}>${HEART} ${count}</button>7684</form>`;
functions/api/moderate.jsadded
+101 −0
@@ -0,0 +1,101 @@1// /api/moderate: the link in a new-comment email lands here.2// GET only shows the comment with approve / delete buttons, because mail apps3// and link scanners open links on their own. the buttons POST. both need the4// signature from the email, so nobody else can use this page.56import { hmacMatches } from "../_lib/hmac.js";7import { bodyHtml, escapeHtml } from "../_lib/comments.js";89const ID_RE = /^[0-9a-f-]{36}$/;1011export async function onRequestGet({ request, env }) {12 const params = new URL(request.url).searchParams;13 const id = params.get("id");14 const sig = params.get("sig");15 if (!(await authorized(env, id, sig))) {16 return forbidden();17 }1819 const comment = await env.DB.prepare("SELECT page, name, body, approved FROM Comments WHERE id = ?").bind(id).first();20 if (!comment) {21 return page(`<p>This comment has already been deleted.</p>`);22 }2324 const hidden = `<input type="hidden" name="id" value="${id}" /><input type="hidden" name="sig" value="${escapeHtml(sig)}" />`;25 return page(`26 <p class="meta">${escapeHtml(comment.name)} on <a href="${comment.page}">${comment.page}</a>, ${comment.approved ? "approved" : "waiting for approval"}</p>27 <blockquote>${bodyHtml(comment.body)}</blockquote>28 <div class="moderate-actions">29 ${comment.approved ? "" : `<form method="POST">${hidden}<button class="like-button" name="action" value="approve">approve</button></form>`}30 <form method="POST">${hidden}<button class="like-button" name="action" value="delete">delete</button></form>31 </div>`);32}3334export async function onRequestPost({ request, env }) {35 let form;36 try {37 form = await request.formData();38 } catch {39 return forbidden();40 }41 const id = form.get("id");42 if (!(await authorized(env, id, form.get("sig")))) {43 return forbidden();44 }4546 const comment = await env.DB.prepare("SELECT page FROM Comments WHERE id = ?").bind(id).first();47 if (!comment) {48 return page(`<p>This comment has already been deleted.</p>`);49 }5051 if (form.get("action") === "approve") {52 await env.DB.prepare("UPDATE Comments SET approved = 1 WHERE id = ?").bind(id).run();53 return new Response(null, { status: 303, headers: { Location: `${comment.page}#comment-${id}` } });54 }5556 // gone for good, along with any replies to it57 await env.DB.prepare("DELETE FROM Comments WHERE id = ? OR parent = ?").bind(id, id).run();58 return page(`<p>Deleted. <a href="${comment.page}">Back to the post</a></p>`);59}6061async function authorized(env, id, sig) {62 return typeof id === "string" && ID_RE.test(id) && (await hmacMatches(env.SOCIAL_SECRET, "moderate:" + id, sig));63}6465function forbidden() {66 return new Response("forbidden", { status: 403, headers: { "Content-Type": "text/plain; charset=utf-8" } });67}6869// page paths in d1 passed isLikeable() on the way in, so they are safe to70// write into the page as-is71function page(content) {72 const html = `<!DOCTYPE html>73<html lang="en">7475<head>76 <meta charset="UTF-8" />77 <meta name="viewport" content="width=device-width, initial-scale=1.0" />78 <meta name="robots" content="noindex" />79 <meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self'; font-src 'self';" />80 <meta name="referrer" content="no-referrer" />81 <link rel="stylesheet" href="/global.css" />82 <link rel="icon" type="image/png" sizes="32x32" href="/assets/favicon/favicon-32x32.png" />83 <title>daniel daum - moderate</title>84</head>8586<body>87 <main id="main">88 <header class="page-header">89 <h1><span aria-hidden="true">/</span>moderate</h1>90 </header>91 <section>${content}92 </section>93 </main>94</body>9596</html>97`;98 return new Response(html, {99 headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" },100 });101}
global.css
+112 −8
@@ -654,21 +654,121 @@ article:has(> .page-header--post) {654654}655655656656/*============================*/657/* components - likes */657/* components - likes + comments */658658/*============================*/659659660/* filled in by functions/_middleware.js. right-aligned under a dashed661 rule; the comments heading will sit on its left */662.post-likes {663 display: flex;664 justify-content: flex-end;660/* filled in by functions/_middleware.js: comment count and like button in661 one row under a dashed rule, then the thread, then the email footer */662.post-social {665663 margin-top: 3rem;666664 padding-top: 1.25rem;667665 border-top: 1px dashed var(--borders);668666}669667670.post-likes .meta {668.post-social > .meta {669 margin: 0;670}671672.social-head {673 display: flex;674 justify-content: space-between;675 align-items: center;676 gap: 1rem;677 margin-bottom: 0.5rem;678}679680.social-title {681 margin: 0;682 font-size: 0.78rem;683 font-weight: 600;684 letter-spacing: 0.12em;685 color: var(--accent);686}687688.comment-thread {689 list-style: none;690 margin: 0;691 padding: 0;692}693694.comment-thread li {695 margin: 0;696}697698/* replies: one level, indented on a rule */699.comment-thread .comment-thread {700 margin-top: 0.25rem;701 padding-left: 1rem;702 border-left: 1px solid var(--borders);703}704705.comment {706 padding: 1rem 0;707}708709.comment-thread > li + li > .comment {710 border-top: 1px solid var(--borders);711}712713.comment .meta {714 display: flex;715 flex-wrap: wrap;716 gap: 0.25rem 0.75rem;717 margin: 0 0 0.5rem;718 font-size: 0.78rem;719 letter-spacing: 0.04em;720}721722.comment-name {723 color: var(--text-headings);724 font-weight: 600;725}726727.comment-author {728 padding: 0 0.35rem;729 border: 1px solid var(--borders);730 font-size: 0.7rem;731 letter-spacing: 0.08em;732 color: var(--accent);733}734735.comment-time {736 color: var(--text-secondary);737}738739.comment-time:hover {740 color: var(--accent);741}742743.comment-body p {744 margin: 0 0 0.5rem;745}746747.comment-link {748 font-size: 0.75rem;749 letter-spacing: 0.08em;750}751752.social-foot {753 display: flex;754 flex-wrap: wrap;755 justify-content: space-between;756 align-items: baseline;757 gap: 0.5rem 1rem;758 margin-top: 0.75rem;759 padding-top: 1rem;760 border-top: 1px solid var(--borders);761}762763.social-foot .meta {671764 margin: 0;765 font-size: 0.75rem;766}767768/* /api/moderate's buttons */769.moderate-actions {770 display: flex;771 gap: 0.75rem;672772}673773674774.like-form {@@ -1884,7 +1984,11 @@ footer nav a,18841984.entry-heading h1,18851985.pager-title,18861986.photo-caption-date,1887.tracker-caption-line {1987.tracker-caption-line,1988.social-title,1989.comment-author,1990.comment-time,1991.comment-link {18881992 text-transform: uppercase;18891993}18901994
internal/template.html
+3 −3
@@ -72,9 +72,9 @@7272 </p>7373 </section>747475 <footer class="post-likes" id="likes" data-likes>76 <p class="meta">likes unavailable</p>77 </footer>75 <section class="post-social" id="comments" data-social aria-label="likes and comments">76 <p class="meta">likes and comments unavailable</p>77 </section>7878 </article>79798080 <nav class="pager" aria-label="post navigation">
now/index.html
+3 −3
@@ -159,9 +159,9 @@159159 </p>160160 </section>161161162 <footer class="post-likes" id="likes" data-likes="/now/sep-2026/">163 <p class="meta">likes unavailable</p>164 </footer>162 <section class="post-social" id="comments" data-social="/now/sep-2026/" aria-label="likes and comments">163 <p class="meta">likes and comments unavailable</p>164 </section>165165 </article>166166167167 <nav class="pager" aria-label="post navigation">
now/jan-2026/index.html
+3 −3
@@ -197,9 +197,9 @@197197 </ul>198198 </section>199199200 <footer class="post-likes" id="likes" data-likes>201 <p class="meta">likes unavailable</p>202 </footer>200 <section class="post-social" id="comments" data-social aria-label="likes and comments">201 <p class="meta">likes and comments unavailable</p>202 </section>203203 </article>204204205205 <nav class="pager" aria-label="post navigation">
now/sep-2026/index.html
+3 −3
@@ -159,9 +159,9 @@159159 </p>160160 </section>161161162 <footer class="post-likes" id="likes" data-likes>163 <p class="meta">likes unavailable</p>164 </footer>162 <section class="post-social" id="comments" data-social aria-label="likes and comments">163 <p class="meta">likes and comments unavailable</p>164 </section>165165 </article>166166167167 <nav class="pager" aria-label="post navigation">
schema.sql
+15 −0
@@ -11,3 +11,18 @@ CREATE TABLE IF NOT EXISTS LikeVoters (1111 created_at TEXT NOT NULL,1212 PRIMARY KEY (page, voter)1313);1415-- comments: arrive by email. ones with links are hidden until approved.16-- nothing about the sender is kept, not even a hash of their address17CREATE TABLE IF NOT EXISTS Comments (18 id TEXT PRIMARY KEY,19 page TEXT NOT NULL,20 parent TEXT,21 name TEXT NOT NULL,22 body TEXT NOT NULL,23 is_author INTEGER NOT NULL DEFAULT 0,24 approved INTEGER NOT NULL DEFAULT 0,25 created_at TEXT NOT NULL26);2728CREATE INDEX IF NOT EXISTS idx_comments_page ON Comments (page, approved, created_at);