saturn
- 187 commits
- 2 branches
- 0 tags
- updated
- CI 2/2
lib.js
5.0 KB · 122 lines
1// shared by the pages functions and the email worker23export const SITE = "https://danieldaum.net";4export const REPLY_TO = "reply@replies.danieldaum.net";56// /about/, /now/, /now/<slug>/, /blog/<slug>/ (/projects/ is showcase, see functions/projects/)7export function isLikeable(path) {8 return /^\/(about|now)\/$|^\/(blog|now)\/[a-z0-9-]+\/$/.test(path);9}1011// ===== hmac =====1213export async function hmac(secret, message) {14 if (!secret) throw new Error("SOCIAL_SECRET is not set");15 const enc = new TextEncoder();16 const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);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// constant time22export async function hmacMatches(secret, message, sig) {23 const expected = await hmac(secret, message);24 if (typeof sig !== "string" || sig.length !== expected.length) return false;25 let diff = 0;26 for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);27 return diff === 0;28}2930// one like per visitor per page per day: ip + browser + date, hashed.31// no cookies, nothing reversible, stops matching at utc midnight32export function voterId(secret, request) {33 const ip = request.headers.get("CF-Connecting-IP") || "";34 const ua = request.headers.get("User-Agent") || "";35 return hmac(secret, `${ip}|${ua}|${new Date().toISOString().slice(0, 10)}`);36}3738// ===== html =====3940export function escapeHtml(str) {41 return String(str).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);42}4344// blank lines split paragraphs, single newlines become <br>45export function bodyHtml(body) {46 return body47 .split(/\n{2,}/)48 .map((para) => `<p>${escapeHtml(para).replace(/\n/g, "<br />")}</p>`)49 .join("");50}5152// what goes inside [data-social]. key has passed isLikeable(), so it is safe as-is53export function renderSocial(key, likes, rows) {54 const replies = new Map();55 for (const row of rows) {56 if (row.parent) replies.set(row.parent, [...(replies.get(row.parent) || []), row]);57 }58 const top = rows.filter((row) => !row.parent);59 const title = rows.length === 0 ? "no comments yet" : rows.length === 1 ? "1 comment" : `${rows.length} comments`;6061 const thread = (list) => `<ol class="comment-thread">${list.map((row) => `<li>${comment(row)}</li>`).join("")}</ol>`;62 const comment = (row) => {63 const id = `comment-${row.id}`;64 const kids = replies.get(row.id);65 return `<article class="comment" id="${id}">66 <p class="meta">67 <span class="comment-name">${escapeHtml(row.name)}</span>${row.is_author ? `<span class="comment-author">author</span>` : ""}68 <a class="comment-time" href="#${id}"><time datetime="${escapeHtml(row.created_at)}">${when(row.created_at)}</time></a>69 </p>70 <div class="comment-body">${bodyHtml(row.body)}</div>71 <a class="comment-link" href="${mailto(key + "#" + id)}">reply →</a>72 ${kids ? thread(kids) : ""}73</article>`;74 };7576 return `<div class="social-head">77 <h2 class="social-title">${title}</h2>78 ${likeForm(key, likes)}79</div>80${top.length ? thread(top) : ""}81<div class="social-foot">82 <a class="comment-link" href="${mailto(key)}">comment by email →</a>83 <p class="meta">Start with a "name:" line for your display name. Your email is never shown or stored</p>84</div>`;85}8687function likeForm(key, { count, liked }) {88 const noun = count === 1 ? "like" : "likes";89 const label = liked ? `you liked this post, ${count} ${noun}` : `like this post, ${count} ${noun}`;90 const state = liked ? ` disabled aria-pressed="true"` : "";91 return `<form class="like-form" id="likes" method="POST" action="/api/like">92 <input type="hidden" name="path" value="${key}" />93 <button type="submit" class="like-button" aria-label="${label}"${state}>${HEART} ${count}</button>94 </form>`;95}9697// feather icons, mit98const HEART = `<svg class="like-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" /></svg>`;99100// the email worker reads the subject to know where a comment goes101function mailto(target) {102 const subject = encodeURIComponent(`re: ${SITE}${target}`);103 return `mailto:${REPLY_TO}?subject=${subject}&body=${encodeURIComponent("name: ")}`;104}105106// "4 Sep 2026 · 09:12", oakland time107function when(iso) {108 const p = Object.fromEntries(109 new Intl.DateTimeFormat("en-GB", {110 timeZone: "America/Los_Angeles",111 day: "numeric",112 month: "short",113 year: "numeric",114 hour: "2-digit",115 minute: "2-digit",116 hourCycle: "h23",117 })118 .formatToParts(new Date(iso))119 .map((part) => [part.type, part.value])120 );121 return `${p.day} ${p.month} ${p.year} · ${p.hour}:${p.minute}`;122}