projects

saturn

My website

feat: remove junk

daniel daum committed parent 845c32f commit a0c2ddcSigned, not verified

SignedGitea couldn't verify the signature.

Showing 24 changed files with 2 additions and 2216 deletions.

.gitea/workflows/deploy-replies-worker.yamldeleted +0 −26
@@ -1,26 +0,0 @@1# .gitea/workflows/deploy-replies-worker.yaml2name: Deploy replies worker3on:4    push:5        branches:6            - main7        paths:8            - "workers/replies-inbound/**"9    workflow_dispatch:10jobs:11    deploy:12        runs-on: ubuntu-latest13        steps:14            - name: Checkout15              uses: actions/checkout@v416            - name: Install dependencies17              run: npm ci18              working-directory: workers/replies-inbound19            - name: Deploy to Cloudflare Workers20              uses: cloudflare/wrangler-action@v321              with:22                  apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}23                  accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}24                  workingDirectory: workers/replies-inbound25                  wranglerVersion: "4.129.0"26                  command: deploy
.gitea/workflows/mirror.yamldeleted +0 −59
@@ -1,59 +0,0 @@1name: mirror2on:3    push:4        branches: [main]5    workflow_dispatch:67env:8    TANGLED_SSH_PORT: "2222"9    TANGLED_REMOTE: "ssh://git@knot.danieldaum.net:2222/danieldaum.net/saturn"1011jobs:12    mirror:13        runs-on: ubuntu-latest14        steps:15            - name: Checkout16              uses: actions/checkout@v417              with:18                  fetch-depth: 01920            - name: Push to GitHub21              run: |22                  git remote add github https://x-access-token:${{ secrets.GH_MIRROR_TOKEN }}@github.com/daniel-daum/saturn.git23                  git push github main --force24                  git push github --tags --force2526            - name: Set up SSH for Tangled27              env:28                  TANGLED_SSH_KEY: ${{ secrets.TANGLED_SSH_KEY }}29                  # Public half of the deploy key registered on Tangled as "gitea-ci-mirror".30                  EXPECTED_PUBKEY: ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDNl8WEwlLHsqWi15NNoZCqkDG2/GjiGgthdIYVm8kNM31              run: |32                  mkdir -p ~/.ssh && chmod 700 ~/.ssh33                  if [ -z "$TANGLED_SSH_KEY" ]; then34                      echo "::error::secret TANGLED_SSH_KEY is empty or not visible to this workflow"35                      exit 136                  fi37                  # Strip CRs (pasted from Windows/clipboard) and guarantee a trailing newline.38                  printf '%s\n' "$TANGLED_SSH_KEY" | tr -d '\r' > ~/.ssh/tangled_ci39                  chmod 600 ~/.ssh/tangled_ci40                  echo "key file: $(wc -l < ~/.ssh/tangled_ci) lines, first line: $(head -n1 ~/.ssh/tangled_ci)"41                  # Derive the public key; this fails loudly if the private key is malformed.42                  if ! actual=$(ssh-keygen -y -f ~/.ssh/tangled_ci); then43                      echo "::error::TANGLED_SSH_KEY is not a valid private key (check it is the PRIVATE key, all lines intact)"44                      exit 145                  fi46                  echo "derived pubkey: $actual"47                  if [ "$(echo "$actual" | cut -d' ' -f1,2)" != "$EXPECTED_PUBKEY" ]; then48                      echo "::error::TANGLED_SSH_KEY does not match the gitea-ci-mirror key registered on Tangled"49                      exit 150                  fi51                  ssh-keyscan -t ed25519 -p "$TANGLED_SSH_PORT" knot.danieldaum.net >> ~/.ssh/known_hosts5253            - name: Push to Tangled54              env:55                  GIT_SSH_COMMAND: ssh -i ~/.ssh/tangled_ci -o IdentitiesOnly=yes -o UserKnownHostsFile=~/.ssh/known_hosts56              run: |57                  git remote add tangled "$TANGLED_REMOTE"58                  git push tangled main --force59                  git push tangled --tags --force
.well-known/atproto-diddeleted +0 −1
@@ -1 +0,0 @@1did:plc:be2e4qfe6docqcysyxxwvsor
AGENTS.mddeleted +0 −81
@@ -1,81 +0,0 @@1# AGENTS.md23Review guidance for this repo. Personal site, served by Cloudflare Pages.45## What this is67Hand-written static HTML, one file per page, no build step and no bundler.8Vite is dev-server only; deploying is `git push` to `main`. Pages are plain9files, so there is no template layer and shared markup (the `<head>`, the10header, the footer) is genuinely duplicated across pages on purpose.1112Dynamic behaviour lives at the edge in `functions/`, not in the browser.1314## Invariants — flag any change that breaks one1516**No client-side JavaScript.** There is not one `<script>` tag on the site and17no inline handlers. Likes and replies work as plain form POSTs handled by edge18middleware. A change that adds JS to a page breaks the core constraint.1920**Edge code fails open.** `functions/_middleware.js` must serve the page's21static fallback markup on any error from D1 or the PDS, never a 500 and never a22broken page. Any new `catch` that rethrows, or new code that can throw before23`context.next()` resolves, is a bug.2425**Escape everything from outside.** Reply bodies, Bluesky post text and any26other remote or user-supplied string must go through `escapeHtml` before it27reaches HTML.2829**`_routes.json` stays in step** with `ALLOWED_PATHS` in30`functions/_middleware.js` and `isBlogPost()` in `functions/_lib/social.js`.31Adding a dynamic path in one place and not the others silently disables it.3233**Feed IDs are permanent.** A published `<id>` never changes and a published34post directory is never renamed or moved — it re-notifies every subscriber and35404s saved links. `/now/` is a living URL and must never be a feed entry; each36edition is archived to a dated directory first. See `FEED.md`.3738**Secrets stay out of the repo.** `.dev.vars` is gitignored; bindings and39secrets are configured in Cloudflare, not committed.4041## Conventions4243- **Colours come from the custom properties** in the `html {}` block of44  `global.css` (`--accent`, `--text-body`, `--text-secondary`, `--borders`, the45  rating scale). Flag hardcoded hex in new CSS. Adding a token means adding it46  to the `prefers-contrast: high` block too.47- **Fonts are self-hosted only** (`assets/fonts/`, woff2, preloaded). No font48  CDNs.49- **The CSP is a per-page `<meta>` tag.** Any new external origin has to be50  added to the CSP on every page that loads from it, or it will be blocked in51  production but not in dev.52- **The `og:`/`twitter:` block is duplicated in every page's head** and53  maintained by hand. If a PR changes it in one page it should change it in all54  of them; only title, description and `og:url` differ per page.55- **URLs**: directory pages are canonical with a trailing slash56  (`/garden/books/`), root-level pages without an extension (`/about`). Pages57  308-redirects the other forms.58- **Accessibility is part of review**: semantic elements, `aria-label` on nav59  landmarks, `aria-hidden` on decorative glyphs, visible `:focus-visible`60  styles, and the `prefers-reduced-motion` / `prefers-contrast` blocks kept61  working.62- **Comments explain why, not what.** Match the existing lowercase, prose style.6364## Out of scope — do not raise these6566- Suggesting a framework, static-site generator, template engine, bundler or67  build step. The absence of one is the design.68- Flagging duplicated `<head>`, header or footer markup as a DRY problem. With69  no build step, duplication is the only option.70- Suggesting client-side JS, analytics, trackers or third-party embeds.71- Suggesting a test suite or CI test job for static HTML and CSS.72- Adding npm dependencies to the site itself. `workers/` may have them.73- Style nits already settled by the existing file: lowercase page titles and74  comments, uppercase display text in markup.7576## Priorities7778Rank findings: broken invariants above > correctness in `functions/` >79accessibility and CSP regressions > everything else. Prefer few specific80comments over broad ones. If a change is a deliberate deviation the author81explained in a comment, leave it alone.
FEED.mddeleted +0 −255
@@ -1,255 +0,0 @@1# Publishing to the feed23`/feed.xml` is hand-maintained. There is no build step and nothing generates it.4When you publish a post you edit two files: the post itself, and `feed.xml`.56Canonical base URL: `https://danieldaum.net` (apex, no `www`).78---910## The two rules that cannot be broken1112**1. An `<id>` never changes once published.**13Feed readers use `<id>` to decide whether they have already shown an entry. If you14change it, every subscriber sees the post again as if it were brand new. If you15change it back, some readers will show it a third time. There is no way to undo16this from your end.1718**2. A published post file is never renamed or moved.**19The `<id>` is the post's URL. Renaming `blog/foo/` to `blog/bar/` breaks rule 120and 404s every link anyone has saved. If you must change a slug, keep the old21directory in place serving a redirect, and leave the feed entry alone.2223Corollary: get the slug right *before* the first deploy. Afterwards it is frozen.2425---2627## Publishing a new post, in order2829### 1. Create the post file3031Copy the template:3233```bash34cp new-post-template.html blog/YOUR-SLUG/index.html35```3637Replace every placeholder:3839| Placeholder | Replace with |40|---|---|41| `POST TITLE` | the title, in caps (appears twice: `nav-back` and `<h1>`) |42| `daniel daum - POST TITLE` | the `<title>` tag |43| `SLUG` | the directory name — must match exactly |44| `ONE SENTENCE SUMMARY - ...` | the `<meta name="description">` |45| `000 WORDS` | actual word count |46| `1 JANUARY 2026` | the publish date |47| `#TAG1` | your tags |4849Write the summary once, in `<meta name="description">`, and reuse that exact50sentence in the feed. Do not write two different summaries for the same post.5152### 2. Work out the canonical URL5354This is the part that is easy to get wrong.5556- A **file** at the repo root is served without a trailing slash:57  `about.html` → `https://danieldaum.net/about`58- A **directory** with an `index.html` is served **with** a trailing slash.59  Cloudflare Pages issues a `308` from the slashless form:60  `blog/my-post/index.html` → `https://danieldaum.net/blog/my-post/`6162Use the form Cloudflare actually settles on — the one with the trailing slash for63directories. Verify before you commit:6465```bash66curl -sSI https://danieldaum.net/blog/YOUR-SLUG | grep -iE '^(HTTP|location)'67```6869A `200` means the URL is canonical. A `308` means use the `location:` value instead.7071### 3. Add the entry to `feed.xml`7273Insert it **directly below the `<!-- NEWEST FIRST -->` comment**, above the74existing top entry. Newest first, always.7576```xml77  <entry>78    <title>Your Title In Sentence Case</title>79    <link rel="alternate" type="text/html" href="https://danieldaum.net/blog/YOUR-SLUG/" />80    <id>https://danieldaum.net/blog/YOUR-SLUG/</id>81    <published>2026-10-04T09:00:00-07:00</published>82    <updated>2026-10-04T09:00:00-07:00</updated>83    <category term="TAG" />84    <summary type="text">The same sentence you put in meta description.</summary>85  </entry>86```8788`<id>` and the `<link href>` must be byte-identical to each other.8990### 4. Update the feed-level `<updated>`9192Near the top of `feed.xml`, above the first `<entry>`:9394```xml95  <updated>2026-10-04T09:00:00-07:00</updated>96```9798Set it to the **exact same value** as your new entry's `<updated>`. This is the99field pollers key off. If you forget this step, the post is in the file but100nothing notices it exists.101102### 5. Validate before deploying103104```bash105python3 -c "import xml.etree.ElementTree as ET; ET.parse('feed.xml'); print('ok')"106```107108After deploying, run the live file through <https://validator.w3.org/feed/>.109A malformed feed fails silently — readers just stop updating, with no error110anywhere you would see it.111112---113114## Timestamps115116RFC 3339, always, with an explicit offset. A bare date is invalid and will be117rejected.118119```1202026-10-04T09:00:00-07:00    valid1212026-01-21T09:00:00-08:00    valid1222026-10-04                   INVALID - no time, no offset1232026-10-04T09:00:00          INVALID - no offset124```125126Watch the offset when you cross daylight saving:127128- **PDT is `-07:00`** — roughly March through early November129- **PST is `-08:00`** — roughly November through March130131The existing January entry uses `-08:00` and the two later ones use `-07:00`.132That is correct, not an inconsistency.133134Publish times are approximated at `09:00` local, since posts only carry a date.135Keep using `09:00` so ordering stays stable.136137---138139## Editing a post after publishing140141Small typo fix: change nothing in the feed. Not worth resurfacing the post.142143Substantive rewrite worth re-notifying subscribers about:1441451. Change **only** that entry's `<updated>` to the new time.1462. Leave `<published>` alone — it records first publication.1473. Leave `<id>` alone. Always.1484. Update the feed-level `<updated>` to match, **only if** this is now the newest149   `<updated>` in the file.150151Do not reorder entries on edit. Order follows `<published>`, not `<updated>`.152153---154155## The `/now` page has its own rule156157`/now` is a living URL — it gets overwritten with each new edition, so it can158never be a feed entry. A reader that fetched "Wake Me Up When September Ends"159from `/now` would later find different content at the same URL.160161So each edition gets archived to a dated, permanent directory, and **the feed162points at the archive, never at `/now`**:163164- `/now/jan-2026/` — January 2026 edition165- `/now/sep-2026/` — September 2026 edition166- `/now/` — always a copy of the newest edition167168When you write the next now page:1691701. Copy the *current* `now/index.html` to `now/MONTH-YEAR/index.html` — this171   freezes the outgoing edition at a permanent URL.1722. In that new archive copy, change the blockquote to point readers at `/now` for173   the current edition.1743. Fix the `page-nav` pagers. The pager is not now-page specific: it walks the175   writing table on `/blog` from the oldest entry (bottom) to the newest (top),176   and every page in that table carries one. So the archive you just created177   gets `next` pointing at the new edition's archive URL, the new178   `now/index.html` (and its archive twin) gets `prev` pointing at the archive179   you just created and a disabled `next`, and any page between them in the180   table (an `/about` rewrite, a blog post) links to its neighbours.1814. Now overwrite `now/index.html` with the new edition.1825. Add a feed entry pointing at the **archive** URL, e.g.183   `https://danieldaum.net/now/oct-2026/`.1846. Repoint the two listing links at the new archive, so they keep pointing at the185   edition they name rather than drifting to whatever `/now` holds later:186   - `index.html` — the `recent-writing-list` entry187   - `blog/index.html` — the `content-table` row188189   ```bash190   grep -rn '/now/sep-2026/' index.html blog/index.html191   ```192193Never add a feed entry whose `<id>` is `https://danieldaum.net/now/`. Same rule194for the listing links in step 6 — they name a specific edition, so they must195point at that edition's permanent URL, never at `/now`.196197---198199## Adding the autodiscovery tag to new pages200201Every HTML page carries this in `<head>`, immediately after the webmanifest link:202203```html204<link rel="alternate" type="application/atom+xml" title="daniel daum" href="https://danieldaum.net/feed.xml" />205```206207`new-post-template.html` already has it. If you hand-write a page from scratch,208add it. To find pages missing it:209210```bash211grep -rL 'application/atom+xml' --include='*.html' .212```213214The `FEED` link in the footer is separate — that one is for humans. New pages215need both.216217---218219## Content type220221`_headers` sets the MIME type Cloudflare serves `feed.xml` with:222223```224/feed.xml225  Content-Type: application/atom+xml; charset=utf-8226```227228Without this it goes out as `application/xml` or `text/xml`, which mostly works229but is not what some pollers expect. Do not remove it.230231---232233## robots.txt234235`robots.txt` denies the default `User-agent: *` group everything except the feed:236237```238User-agent: *239Allow: /feed.xml240Disallow: /241Crawl-delay: 10242```243244`Allow: /feed.xml` wins over `Disallow: /` because Google and Bing resolve245conflicts by longest matching path, and `/feed.xml` is longer than `/`. So246pollers that respect robots.txt — annot.at, and anything else you point at the247feed later — can fetch it, while the rest of the site stays closed to them.248249The named AI-bot groups (`GPTBot`, `CCBot`, `Claude-Web`, and the rest) still get250a bare `Disallow: /`. A user-agent-specific group replaces the `*` group entirely251rather than merging with it, so those crawlers are blocked from `/feed.xml` too.252That is intentional — do not add an `Allow` line to any of them.253254If you ever move the feed, update the `Allow` path to match or pollers go dark255with no error anywhere you would see it.
MICRO.mddeleted +0 −125
@@ -1,125 +0,0 @@1# Micro posts23Micro posts on this site are Bluesky posts, pulled from my own PDS and injected4into the static HTML at the Cloudflare edge. Nothing about them lives in this5repo except the placeholders and the middleware that fills them.67## Where posts come from89I post from the Bluesky iOS app. Each post is an `app.bsky.feed.post` record in10my repo on my PDS:1112- DID: `did:plc:be2e4qfe6docqcysyxxwvsor`13- PDS: `https://atproto.danieldaum.net`14- Handle: `danieldaum.net`1516`functions/_middleware.js` calls `com.atproto.repo.listRecords` on the PDS,17drops replies, sorts by `createdAt` descending, and renders the result into18the page. Replies are never shown.1920## The 300 grapheme limit2122Bluesky caps a post at 300 graphemes. That is a hard constraint on how I write23here: a micro post is at most 300 characters, full stop. Anything longer is a24longform post and belongs under `/blog` or `/now` with an entry in `feed.xml`25(see `FEED.md`).2627## The `data-micro` modes2829The middleware looks for any element carrying a `data-micro` attribute and30replaces its inner HTML. The attribute value picks what gets rendered:3132| Mode | Renders | Used on |33|---|---|---|34| `latest-activity` | one row's worth of content for an `<li class="activity-item">`: icon, `NEW MICRO POST &mdash; <text>` link (or `3 NEW MICRO POSTS` when several landed on the same Pacific day), and a `1 SEP` style date. The text is capped at 140 characters server-side; the row never wraps and css fades whatever does not fit | `/` (activity feed) |35| `latest-featured` | one `<article class="micro-post micro-featured">` for the newest post, timestamp linking to its anchor on `/blog/micro/`, media included | `/` (recent post card), `/blog` |36| `all` | every post as `<article class="micro-post">`, newest first, each with an `id` anchor, media included | `/blog/micro/` |3738Anchor ids are the record key (the last path segment of the `at://` URI, a39TID). The old `YYYY-MM-DD-N` convention is gone.4041Whatever is inside the `data-micro` element in the HTML is the fallback. It is42what visitors see when the PDS is down, returns an error, or has no posts. The43middleware never touches a page in that case, so the fallback must be real,44presentable markup, not an empty div.4546## Adding a new injection point4748Three steps, all required:49501. Add an element with `data-micro="<mode>"` and fallback content to the page.512. Add every path form the page can be requested at to `ALLOWED_PATHS` in52   `functions/_middleware.js` (for a directory page that means `/foo`,53   `/foo/`, and `/foo/index.html`).543. Make sure `_routes.json` at the repo root routes the path through55   Functions. Anything not listed in its `include` array is served straight56   from the static asset store and never reaches the middleware.5758The allowlist is checked before anything is fetched, so a page that is not on59it is served exactly as written and never causes a PDS request. Forgetting step602 means the placeholder stays as the fallback text forever.6162Blog post pages are not on the allowlist and never will be; their `data-likes`63and `data-replies` injection is a separate path, documented in `SOCIAL.md`.6465If the new page needs images, add `https://atproto.danieldaum.net` to66`img-src` in that page's CSP meta tag. Only the three pages listed above have67that today. Video is same-origin (see below) and is covered by the68`media-src 'self'` every page already carries.6970## Media7172A post can carry a set of images (`app.bsky.embed.images`) or one video73(`app.bsky.embed.video`); the middleware renders both below the text, in74`latest-featured` and `all`. A quote-with-media post75(`app.bsky.embed.recordWithMedia`) keeps its media and drops the quote.7677Images are `<img>` tags pointing straight at the PDS's78`com.atproto.sync.getBlob`, which is why the PDS origin is in `img-src`.7980Video is different. The PDS answers every blob request with the whole file81and no `Accept-Ranges`, and Safari (so every browser on iOS) will not play a82video it cannot seek into. So the `<video>` src is `/media/<cid>`, served by83`functions/media/[cid].js`: it fetches the blob from the PDS once, stores it84in the Cloudflare cache (immutable, blobs are content-addressed), and lets the85Cache API answer every request after that, `Range` included. On the first,86cold request the function slices the range itself. Only image and video87content types are passed through; the cid has to look like a base32 CIDv1 or88nothing is fetched.8990`/media/*` is in `_routes.json` so it reaches the function. No CSP change is91needed for it: it is same-origin.9293The player is not autoplayed or muted, it is `controls` and94`preload="metadata"`, and it sits above the card's stretched permalink in the95stacking order so the controls take the tap instead of the card.9697## Local dev9899- `mise run dev` runs Vite. Vite does not run Pages Functions, so every100  `data-micro` element shows its fallback ("NO POSTS YET").101- `mise run preview` runs `wrangler pages dev .`, which does run the102  middleware and shows real posts from the PDS. Its default port is 8788.103  Wrangler writes its state to `.wrangler/`, which is gitignored.104105No `package.json`, no dependencies. `npx` fetches wrangler on demand.106107## Caching108109The PDS fetch is made with a 60 second edge cache (`cf.cacheTtl`), so each110Cloudflare PoP asks the PDS at most once a minute regardless of traffic. A new111post can take up to a minute to appear on the site. Deleting a post on Bluesky112takes the same minute to disappear.113114## Not implemented115116Deliberately left out of this pass. Everything below renders as plain text or117is ignored:118119- rich text facets: links, mentions and hashtags are not linkified120- quote posts: the quoted record is dropped, only my text shows (a121  quote-with-media keeps the media, see above)122- external link cards123- video posters: the record has no thumbnail, so the player shows the first124  frame once metadata loads125- threading: replies are filtered out entirely, and thread structure is ignored
SOCIAL.mddeleted +0 −292
@@ -1,292 +0,0 @@1# Likes and replies23Blog posts carry two social features, both rendered with zero client-side4JavaScript: a like button and reply-by-email comments. Everything lives at the5Cloudflare edge; the static HTML only carries placeholders and fallback text.6Micro posts (`/blog/micro/`) get neither. See `MICRO.md` for that side.78## Scope910A "blog post page" is any path matching `^/blog/[a-z0-9-]+/$` that is not11`/blog/micro/`. That predicate is `isBlogPost()` in `functions/_lib/social.js`12and is the single gate used by the middleware and the like endpoint. Nothing13else on the site (home, `/blog`, `/now/*`, `/about`) is touched.1415## Moving parts1617| Piece | Where | Role |18|---|---|---|19| D1 database `saturn-social` | bound as `DB` to the Pages project and the worker | all state |20| `functions/_middleware.js` | Pages Function | renders like count, liked-state and the reply thread into the page |21| `functions/api/like.js` | Pages Function, `POST /api/like` | records a like, 303s back to the post |22| `functions/api/moderate.js` | Pages Function, `GET`/`POST /api/moderate` | signed delete link from the notification email |23| `functions/_lib/social.js` | shared module | `isBlogPost`, `hmacHex`, `safeEqual`, `voterId` |24| `workers/replies-inbound/` | separate email Worker | receives mail on `reply@replies.danieldaum.net`, validates, inserts, notifies |25| `schema.sql` | repo root | the tables below |2627## Tables2829`Likes`: one row per page.3031| column | meaning |32|---|---|33| `page` | the post path, `/blog/<slug>/` (primary key) |34| `count` | total likes ever recorded |3536`LikeVoters`: who has liked what today. Rows are disposable.3738| column | meaning |39|---|---|40| `page` | post path |41| `voter` | daily-rotating HMAC of the visitor (see below); `(page, voter)` is the primary key |42| `created_at` | ISO timestamp, used only so stale rows can be purged |4344`Replies`: every comment ever received, including deleted ones.4546| column | meaning |47|---|---|48| `guid` | random UUID, primary key; also the HTML anchor `#reply-<guid>` |49| `url` | post path the reply belongs to |50| `parent` | guid of the reply being answered, or NULL for top-level |51| `name` | display name, stored raw and escaped at render |52| `message` | plain text body after quote stripping, stored raw and escaped at render |53| `sender` | HMAC of the sender's lowercased address; used only for rate limiting. The address itself is never stored anywhere |54| `approved` | always 1 today. Exists so switching to a moderation queue later is a query change, not a migration |55| `created_at` | ISO timestamp |56| `deleted_at` | NULL while live; set by `/api/moderate`. Rows are never physically deleted |5758Indexes: `(url, deleted_at, created_at)` for the thread query and59`(sender, created_at)` for the rate limit.6061## Likes6263The like button is a plain form:6465```html66<form class="like-form" method="POST" action="/api/like">67    <input type="hidden" name="path" value="/blog/SLUG/" />68    <button type="submit" class="like-button" aria-label="like this post, 0 likes">&#9825; <span class="like-count">0</span></button>69</form>70```7172`POST /api/like`, in order:73741. `path` must satisfy `isBlogPost()`, else 400.752. The page must exist: `env.ASSETS.fetch(origin + path)` must be 200, else76   404. No counter rows for pages that do not exist.773. Compute the voter key.784. One D1 batch: `INSERT OR IGNORE` into `LikeVoters`, plus a purge of79   `LikeVoters` rows older than two days. If the insert changed a row80   (`meta.changes === 1`), upsert `Likes.count + 1`. A repeat like is a silent81   no-op, never an error.825. `303 See Other` to `path + "#likes"`. The endpoint never renders a body.8384There is no `onRequestGet`. A GET to `/api/like` falls through Pages Functions85to static assets and gets the site's 404. (Pages does not synthesise a 405 for86an unhandled method; the important property is that GET never mutates.)8788### The voter key8990```91voter = HMAC-SHA-256(SOCIAL_SECRET, ip + "|" + user_agent + "|" + YYYY-MM-DD in UTC)92```9394`ip` is `CF-Connecting-IP`. The key changes at UTC midnight, so95`PRIMARY KEY (page, voter)` naturally scopes to one like per person per page96per day. Nothing that identifies the person is stored: without the secret the97hash is opaque, and even with it there is nothing to reverse. `LikeVoters` rows98are purged after two days on every call to `/api/like`.99100The middleware computes the same key for the current request to decide whether101to render the button as already-liked (filled heart, `disabled`,102`aria-pressed="true"`, and an `aria-label` that says "you liked this post"103rather than "like this post"). The label always carries the count, since the104visible label is only a heart and a number. Both sides call `voterId()` in `_lib/social.js` so they105cannot drift.106107## Replies108109The reply affordance is a `mailto:` link with a prefilled subject:110111```112mailto:reply@replies.danieldaum.net?subject=re:%20https://danieldaum.net/blog/SLUG/113```114115Replying to a specific comment appends its guid as a URL fragment,116`%23<guid>`. The worker parses it back out to thread the reply. Threads render117from `parent IS NULL` downward, nested at most 6 deep (anything deeper is118flattened into the list at depth 6, not dropped), with a visited set guarding119against cycles. A reply whose parent was deleted is re-parented to the top120level at render time.121122### The email worker, gate by gate123124`workers/replies-inbound/src/index.js`, `email(message, env, ctx)`. Each step125short-circuits on failure. "Reject" means `message.setReject(reason)`, which126bounces with the reason; "drop" means `console.log` and return, no bounce.1271281. **Authentication.** `Authentication-Results` must contain `dkim=pass` and129   at least one of `spf=pass` / `dmarc=pass`. Else drop (a bounce here would be130   backscatter).1312. **Parse** with `postal-mime`.1323. **Subject** must match133   `re: https://danieldaum.net/blog/<slug>/` with an optional `#<guid>`,134   case-insensitive, and the path must not be `/blog/micro/`. Else reject.135   This is the one user-fixable failure, so the bounce is useful.1364. **Page exists.** `HEAD https://danieldaum.net<path>` must be 200. Else137   reject.1385. **Parent.** If a guid was given it must be a live reply on the same post.139   Otherwise the reply is stored as top-level; never rejected for this.1406. **Body.** `text` part, or `html` with tags stripped. Every line starting141   with `>` is dropped, and everything from the first `On ... wrote:`,142   `-- Original Message` or `From: ` line onward is cut. Three or more blank143   lines collapse to two. Result must be 2 to 2000 characters, else reject.144   More than 2 URLs, reject.1457. **Sender** = `HMAC(SOCIAL_SECRET, lowercased address)`. The address is146   never stored and never logged.1478. **Rate limits.** In the last hour: at most 5 replies per sender, at most148   30 site-wide. Else drop.1499. **Name.** `From` display name trimmed, else the local part of the address.150   Control characters stripped, capped at 40 characters, stored raw.15110. **Insert** with a random UUID, ISO `created_at`, `approved = 1`.152    Nothing is held for moderation.15311. **Notify** me with a hand-built RFC 5322 plain-text message via the154    `NOTIFY` send_email binding, containing the name, the first 500155    characters, a link to the reply's anchor on the post, and a signed delete156    link. A notification failure is logged and does not undo the insert.157158### Delete links and `/api/moderate`159160The delete link is161162```163https://danieldaum.net/api/moderate?id=<guid>&sig=<HMAC(SOCIAL_SECRET, "delete:" + guid)>164```165166`GET /api/moderate` verifies the signature (constant-time compare; 403 with a167plain-text body on any mismatch or malformed id), looks the reply up, and168renders a confirm page: name, first 200 characters, the post path, and a form169that POSTs the same `id` and `sig` with one DELETE button. **GET never170mutates.** Mail clients and link scanners prefetch URLs in email; if GET171deleted, a security scanner could remove every comment before I ever saw the172notification.173174`POST /api/moderate` verifies the same signature, sets175`deleted_at = datetime('now')`, and renders a one-line confirmation with a link176back to the post. Because `deleted_at` is checked in every read query, the177reply disappears from the page immediately.178179`hmacHex` exists in two places, `functions/_lib/social.js` and180`workers/replies-inbound/src/lib.js`, and must stay identical. Both files say181so at the top.182183## Adding the placeholders to a new post184185`new-post-template.html` already carries them. Directly after the closing186`</section>` of `.post-body` and before `</main>`:187188```html189        <section class="post-social" aria-label="likes and replies">190            <div id="likes" data-likes>191                <p class="meta">LIKES UNAVAILABLE</p>192            </div>193            <div id="replies" data-replies>194                <p class="meta">REPLIES UNAVAILABLE</p>195            </div>196        </section>197```198199The middleware replaces the inner content of each `data-*` element. Whatever200is written inside them is the fallback: it is what visitors see if D1 throws,201the secret is missing, or anything else goes wrong. The middleware never202touches the page in that case (same rule as the PDS fallback in `MICRO.md`).203There is no allowlist to update: any path matching `isBlogPost()` is handled.204`_routes.json` already sends all of `/blog/*` and `/api/*` through Functions.205206Transformed blog post responses carry `Cache-Control: private, no-cache` so207the back button after a like does not show a stale count.208209## Secrets210211One secret, `SOCIAL_SECRET`, set in two places with the same value.212Generate it once with `openssl rand -hex 32`.213214| where | command |215|---|---|216| Pages project | `npx wrangler pages secret put SOCIAL_SECRET --project-name saturn` (repo root) |217| Email worker | `npx wrangler secret put SOCIAL_SECRET` (from `workers/replies-inbound/`) |218219If the values differ, the worker's delete links will never verify on the Pages220side. Rotating the secret invalidates every outstanding delete link and resets221today's liked-state for everyone (the counts are unaffected).222223Local dev reads `.dev.vars` (gitignored) in the repo root and in224`workers/replies-inbound/`. Any throwaway value works, as long as both files225agree.226227## Local dev228229Pages side:230231- `mise run db-local` applies `schema.sql` to the local D1 (idempotent).232- `mise run preview` runs `wrangler pages dev .` on port 8788 with the `DB`233  binding, `ASSETS`, and `.dev.vars`. Likes, the thread, and `/api/*` all work.234- `mise run dev` (Vite) runs no Functions, so every placeholder shows its235  fallback text.236237Worker side:238239- `mise run replies-dev` runs `wrangler dev` in `workers/replies-inbound/` on240  port 8787 with `--persist-to ../../.wrangler/state`. That flag is the point:241  Pages dev and worker dev each default to their own `.wrangler/state`, which242  means two separate local D1 databases. Pointing the worker at the root's243  state directory makes a reply posted to the worker show up on the page244  served by `mise run preview`. Both configs must carry the same245  `database_id`; local D1 files are keyed on it.246- The worker's `.dev.vars` also sets `PAGE_CHECK_ORIGIN=http://localhost:8788`247  so the "page exists" gate checks the local preview instead of the live site.248  This variable is a dev-only override; it is not set in production and249  everything else (subject parsing, links, notification) always uses250  `https://danieldaum.net`.251- Feed the worker a message by POSTing raw RFC 822 to252  `http://localhost:8787/cdn-cgi/handler/email?from=<addr>&to=reply@replies.danieldaum.net`253  with `Content-Type: message/rfc822`. Local wrangler insists on a254  `Message-ID` header before the worker runs at all. The response body says255  whether the worker processed, rejected (with the reason), or errored.256  Silent drops look like "processed" from the outside; check the row count.257- Locally, `send_email` does not send. Each notification is written as an258  `.eml` under `workers/replies-inbound/.wrangler/tmp/email/`, which is where259  to find the delete link for testing `/api/moderate`.260- Worker dev serves an email handler only; a browser GET to port 8787 logs a261  "does not export a fetch()" error. That is expected.262263Only the worker directory has a `package.json` (`postal-mime`). The repo root264has none and must not get one.265266## Deploy267268`.gitea/workflows/deploy.yaml` deploys the Pages project (unchanged).269`.gitea/workflows/deploy-replies-worker.yaml` deploys the worker on pushes270that touch `workers/replies-inbound/**`, or by hand. It runs `npm ci` in that271directory and `wrangler deploy` from it. Email Routing for272`replies.danieldaum.net` and the custom address `reply@` that targets the273worker are configured in the dashboard, not in code.274275`wrangler pages deploy` uploads the repo root as static assets. Its built-in276ignore list is `functions`, `.wrangler`, `_worker.js`, `_redirects`,277`_headers`, `_routes.json`, `**/node_modules`, `**/.git`, `**/.DS_Store`, so278`workers/replies-inbound/src/*.js`, its `package.json` and `wrangler.toml` are279served as public files, the same way `MICRO.md` and `schema.sql` are. They280contain no secrets.281282## Not implemented283284Deliberately left out of this pass:285286- per-reply likes287- a moderation queue (`approved` exists so this is a query change later)288- editing a reply289- an email confirmation to the commenter290- likes on micro posts291- deleting a reply from anywhere but the emailed delete link292- rendering links in reply bodies; URLs are plain text
_headersdeleted +0 −8
@@ -1,8 +0,0 @@1/.well-known/atproto-did2  Content-Type: text/plain34/feed.xml5  Content-Type: application/atom+xml; charset=utf-867/assets/fonts/*8  Cache-Control: public, max-age=31536000, immutable
_routes.jsondeleted +0 −6
@@ -1,6 +0,0 @@1{2    "version": 1,3    "description": "Only these paths run through functions/. Everything else (pages, css, fonts, images) is served straight from the static asset store, which is faster and edge-cacheable. Keep in step with ALLOWED_PATHS in functions/_middleware.js and isBlogPost() in functions/_lib/social.js. /media/* is the blob proxy in functions/media/, see MICRO.md.",4    "include": ["/", "/index.html", "/blog", "/blog/*", "/api/*", "/media/*"],5    "exclude": []6}
blog/index.html +2 −2
@@ -63,7 +63,7 @@636364646565        <!-- MICRO - newest post only, acts as the doorway to the full feed -->66        <section aria-label="micro posts">66        <!--<section aria-label="micro posts">6767            <div class="section-head">6868                <h2 class="section-label">posts</h2>6969                <a class="section-more" href="/blog/micro">all posts &rarr;</a>@@ -72,7 +72,7 @@7272            <div data-micro="latest-featured">7373                <p class="meta">NO POSTS YET</p>7474            </div>75        </section>75        </section>-->76767777        <!-- LONGFORM -->7878        <section aria-label="longform writing">
functions/_lib/social.jsdeleted +0 −86
@@ -1,86 +0,0 @@1// Shared helpers for likes and reply-by-email comments on blog posts.2// Used by functions/_middleware.js, functions/api/like.js and3// functions/api/moderate.js. See SOCIAL.md for the full write-up.4//5// hmacHex MUST stay in sync with workers/replies-inbound/src/lib.js. The6// email worker signs delete links and sender hashes with its copy; the7// Pages side verifies and matches them with this one. Same secret, same8// algorithm, same output, or moderation links stop working.910const BLOG_POST_RE = /^\/blog\/[a-z0-9-]+\/$/;1112// Every string that came from the PDS, D1 or a request goes through this13// before it is written into a page.14export function escapeHtml(str) {15    return String(str)16        .replace(/&/g, "&amp;")17        .replace(/</g, "&lt;")18        .replace(/>/g, "&gt;")19        .replace(/"/g, "&quot;");20}2122// Blog post pages are the only pages that carry likes and replies. The micro23// feed lives at /blog/micro/ and is excluded on purpose.24export function isBlogPost(pathname) {25    return BLOG_POST_RE.test(pathname) && pathname !== "/blog/micro/";26}2728// ---------------------------------------------------------------------------29// hmac3031export async function hmacHex(secret, message) {32    if (typeof secret !== "string" || secret.length === 0) {33        throw new Error("SOCIAL_SECRET is not set");34    }35    const enc = new TextEncoder();36    const key = await crypto.subtle.importKey(37        "raw",38        enc.encode(secret),39        { name: "HMAC", hash: "SHA-256" },40        false,41        ["sign"]42    );43    const sig = await crypto.subtle.sign("HMAC", key, enc.encode(message));44    return toHex(new Uint8Array(sig));45}4647function toHex(bytes) {48    let out = "";49    for (const b of bytes) {50        out += b.toString(16).padStart(2, "0");51    }52    return out;53}5455// Constant-time string comparison for signatures. Length differences short56// circuit, which leaks nothing useful because every valid signature has the57// same length.58export function safeEqual(a, b) {59    if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) {60        return false;61    }62    let diff = 0;63    for (let i = 0; i < a.length; i++) {64        diff |= a.charCodeAt(i) ^ b.charCodeAt(i);65    }66    return diff === 0;67}6869// ---------------------------------------------------------------------------70// voter identity7172// "YYYY-MM-DD" in UTC. The voter hash rotates when this changes.73export function utcDate(now = new Date()) {74    return now.toISOString().slice(0, 10);75}7677// One like per person per page per day, without a cookie and without storing78// anything that identifies the person: the voter key is an HMAC of the79// connection details plus today's date, so it cannot be reversed and it stops80// matching tomorrow. Both the like endpoint and the middleware call this so81// "already liked" is computed exactly the same way on both sides.82export async function voterId(secret, request) {83    const ip = request.headers.get("CF-Connecting-IP") || "";84    const ua = request.headers.get("User-Agent") || "";85    return hmacHex(secret, ip + "|" + ua + "|" + utcDate());86}
functions/_middleware.jsdeleted +0 −507
@@ -1,507 +0,0 @@1// Cloudflare Pages Functions middleware: injects Bluesky posts from my PDS2// into the static pages at the edge. See MICRO.md for the full write-up.3//4// Blog post pages get a different treatment: like counts and the reply thread5// are read from D1 and rendered into their data-likes / data-replies6// placeholders. See SOCIAL.md. The two paths never overlap: a blog post never7// triggers a PDS request, and a micro page never touches D1.89import { escapeHtml, isBlogPost, voterId } from "./_lib/social.js";1011const PDS_HOST = "https://atproto.danieldaum.net";12const REPO_DID = "did:plc:be2e4qfe6docqcysyxxwvsor";13const HANDLE = "danieldaum.net";14const LIMIT = 50;15const CACHE_TTL = 60;16const TZ = "America/Los_Angeles";1718// Only these paths ever trigger a PDS request. Every other page on the site is19// passed through untouched. Adding a new injection point means adding a20// data-micro element to the page AND adding its path(s) here.21const ALLOWED_PATHS = new Set([22    "/",23    "/index.html",24    "/blog",25    "/blog/",26    "/blog/index.html",27    "/blog/micro",28    "/blog/micro/",29    "/blog/micro/index.html",30]);3132// The activity row never wraps: css fades the text out at the right edge, so33// this only caps what is sent, it is not the visible cut.34const ACTIVITY_SNIPPET_LENGTH = 140;3536// Blog post likes and replies. Blog post pages match isBlogPost() rather than37// ALLOWED_PATHS, so a new post needs no change here: only the placeholder38// markup in the page (see SOCIAL.md).39const SITE_URL = "https://danieldaum.net";40const REPLY_ADDRESS = "reply@replies.danieldaum.net";41const MAX_THREAD_DEPTH = 6;4243export async function onRequest(context) {44    const { pathname } = new URL(context.request.url);45    if (!ALLOWED_PATHS.has(pathname) && !isBlogPost(pathname)) {46        return context.next();47    }4849    // Kick the PDS request off before waiting on the asset so the two round50    // trips overlap instead of queueing.51    const pending = isBlogPost(pathname) ? null : fetchPosts();5253    let response = await context.next();54    const contentType = response.headers.get("content-type") || "";55    if (!contentType.includes("text/html")) {56        return response;57    }5859    let posts = null;60    let social = null;61    if (isBlogPost(pathname)) {62        social = await loadSocial(context, pathname);63        if (!social) {64            // D1 unreachable, errored, or the secret is missing: leave the65            // static fallback markup ("LIKES UNAVAILABLE") exactly as written.66            return response;67        }68        // The like count and liked-state are per visitor and change the moment69        // the form is submitted, so the browser must not serve this page from70        // its cache on back navigation.71        response = new Response(response.body, response);72        response.headers.set("Cache-Control", "private, no-cache");73    } else {74        posts = await pending;75        if (!posts) {76            // PDS unreachable, errored, or has no posts: leave the static fallback77            // markup ("NO POSTS YET") exactly as written in the HTML.78            return response;79        }80    }8182    return new HTMLRewriter()83        .on("[data-micro]", {84            element(el) {85                if (!posts) {86                    return;87                }88                const mode = el.getAttribute("data-micro");89                const html = render(mode, posts);90                if (html !== null) {91                    el.setInnerContent(html, { html: true });92                }93            },94        })95        .on("[data-likes]", {96            element(el) {97                if (social) {98                    el.setInnerContent(renderLikes(social), { html: true });99                }100            },101        })102        .on("[data-replies]", {103            element(el) {104                if (social) {105                    el.setInnerContent(renderReplies(social), { html: true });106                }107            },108        })109        .transform(response);110}111112// ---------------------------------------------------------------------------113// data114115async function fetchPosts() {116    const url = new URL("/xrpc/com.atproto.repo.listRecords", PDS_HOST);117    url.searchParams.set("repo", REPO_DID);118    url.searchParams.set("collection", "app.bsky.feed.post");119    url.searchParams.set("limit", String(LIMIT));120121    let data;122    try {123        const res = await fetch(url.toString(), {124            cf: { cacheTtl: CACHE_TTL, cacheEverything: true },125        });126        if (!res.ok) {127            return null;128        }129        data = await res.json();130    } catch {131        return null;132    }133134    const records = Array.isArray(data?.records) ? data.records : [];135    const posts = records136        .filter((r) => r?.value && typeof r.value.text === "string" && !r.value.reply)137        .map((r) => ({138            rkey: rkeyFromUri(r.uri),139            text: r.value.text,140            createdAt: r.value.createdAt || "",141            ...mediaFrom(r.value.embed),142        }))143        .filter((p) => p.rkey)144        .sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));145146    return posts.length > 0 ? posts : null;147}148149// Like count, whether this visitor already liked today, and the live reply150// rows for one blog post. Returns null on any failure so the page is served151// with its fallback markup: D1 must never break a page.152async function loadSocial(context, pathname) {153    const { env, request } = context;154    try {155        const voter = await voterId(env.SOCIAL_SECRET, request);156        const [likes, liked, replies] = await env.DB.batch([157            env.DB.prepare("SELECT count FROM Likes WHERE page = ?").bind(pathname),158            env.DB.prepare("SELECT 1 FROM LikeVoters WHERE page = ? AND voter = ?").bind(pathname, voter),159            env.DB160                .prepare(161                    "SELECT guid, parent, name, message, created_at FROM Replies WHERE url = ? AND approved = 1 AND deleted_at IS NULL ORDER BY created_at ASC"162                )163                .bind(pathname),164        ]);165        return {166            path: pathname,167            count: Number(likes.results[0]?.count ?? 0),168            liked: liked.results.length > 0,169            replies: replies.results,170        };171    } catch {172        return null;173    }174}175176function rkeyFromUri(uri) {177    if (typeof uri !== "string") return "";178    const idx = uri.lastIndexOf("/");179    return idx === -1 ? "" : uri.slice(idx + 1);180}181182// Media attached to a post: a set of images or one video, the two things the183// Bluesky app can attach. A quote-with-media post carries the same embed one184// level down under `media`, so it is unwrapped here and the quoted record is185// dropped. Anything else (link cards, bare quotes) yields no media.186function mediaFrom(embed) {187    const media = embed?.$type === "app.bsky.embed.recordWithMedia" ? embed.media : embed;188    return { images: imagesFrom(media), video: videoFrom(media) };189}190191function imagesFrom(embed) {192    if (!embed || embed.$type !== "app.bsky.embed.images" || !Array.isArray(embed.images)) {193        return [];194    }195    return embed.images196        .map((img) => ({ cid: img?.image?.ref?.$link, alt: img?.alt || "" }))197        .filter((img) => typeof img.cid === "string" && img.cid.length > 0);198}199200// The aspect ratio is optional on the record; when present it is written201// out as width/height attributes so the box is reserved before the video's202// metadata has loaded and the page does not jump.203function videoFrom(embed) {204    if (!embed || embed.$type !== "app.bsky.embed.video") {205        return null;206    }207    const cid = embed.video?.ref?.$link;208    if (typeof cid !== "string" || cid.length === 0) {209        return null;210    }211    const ratio = embed.aspectRatio;212    const width = Number.isInteger(ratio?.width) && ratio.width > 0 ? ratio.width : 0;213    const height = Number.isInteger(ratio?.height) && ratio.height > 0 ? ratio.height : 0;214    return { cid, alt: typeof embed.alt === "string" ? embed.alt : "", width, height };215}216217// ---------------------------------------------------------------------------218// rendering219220function render(mode, posts) {221    switch (mode) {222        case "all":223            return posts.map((p) => renderArticle(p, { featured: false })).join("\n");224        case "latest-featured":225            return renderArticle(posts[0], { featured: true });226        case "latest-activity":227            return renderActivityItem(posts);228        default:229            return null;230    }231}232233function renderArticle(post, { featured }) {234    const cls = featured ? "micro-post micro-featured" : "micro-post";235    const id = featured ? "" : ` id="${escapeHtml(post.rkey)}"`;236    const href = featured ? `/blog/micro/#${escapeHtml(post.rkey)}` : `#${escapeHtml(post.rkey)}`;237238    const images = post.images239        .map(240            (img) =>241                `<img class="micro-img" src="${blobUrl(img.cid)}" alt="${escapeHtml(img.alt)}" loading="lazy" />`242        )243        .join("\n    ");244    const video = post.video ? renderVideo(post.video) : "";245246    return [247        `<article${id} class="${cls}">`,248        `    <p class="meta">`,249        `        <span class="micro-at">@${escapeHtml(HANDLE)}</span>`,250        `        <a class="micro-time" href="${href}"><time datetime="${escapeHtml(post.createdAt)}">${formatTimestamp(post.createdAt)}</time></a>`,251        `    </p>`,252        `    <p class="micro-body">${formatBody(post.text)}</p>`,253        images ? `    ${images}` : null,254        video ? `    ${video}` : null,255        `</article>`,256    ]257        .filter((line) => line !== null)258        .join("\n");259}260261// One row for the newest post. When several posts landed on the same262// (Pacific) day the label counts them; the text is always the newest one.263function renderActivityItem(posts) {264    const post = posts[0];265    const day = dayKey(post.createdAt);266    const sameDay = posts.filter((p) => dayKey(p.createdAt) === day).length;267    const label = sameDay > 1 ? `${sameDay} NEW MICRO POSTS` : "NEW MICRO POST";268    const href = `/blog/micro/#${escapeHtml(post.rkey)}`;269    return [270        `<span class="activity-icon" aria-hidden="true">&#9670;</span>`,271        `<a class="activity-link" href="${href}">${label} &mdash; ${snippet(post.text)}</a>`,272        `<span class="activity-date">${formatActivityDate(post.createdAt)}</span>`,273    ].join("\n");274}275276// Not autoplayed and not muted: it is a post attachment, the visitor presses277// play. `playsinline` keeps iOS from taking over the screen on tap. The link278// inside is what a browser without <video> support gets.279//280// There is no poster: the record carries no thumbnail. Safari will not paint281// a frame of a poster-less video on preload="metadata", it leaves the box282// blank, so the src carries a media fragment just past zero, which makes it283// seek and paint the first frame. Chrome and Firefox paint it either way.284function renderVideo(video) {285    const src = mediaUrl(video.cid);286    const size = video.width && video.height ? ` width="${video.width}" height="${video.height}"` : "";287    const label = video.alt ? ` aria-label="${escapeHtml(video.alt)}"` : "";288    return `<video class="micro-video" src="${src}#t=0.001"${size}${label} controls playsinline preload="metadata"><a href="${src}">VIDEO</a></video>`;289}290291function blobUrl(cid) {292    const url = new URL("/xrpc/com.atproto.sync.getBlob", PDS_HOST);293    url.searchParams.set("did", REPO_DID);294    url.searchParams.set("cid", cid);295    return escapeHtml(url.toString());296}297298// Video is served through /media/<cid> (functions/media/[cid].js) rather than299// straight from the PDS: the PDS ignores Range requests, and Safari will not300// play a video it cannot seek. Images keep going to the PDS directly.301function mediaUrl(cid) {302    return escapeHtml(`/media/${encodeURIComponent(cid)}`);303}304305// ---------------------------------------------------------------------------306// rendering: likes and replies307308function renderLikes({ path, count, liked }) {309    const heart = liked ? "&#9829;" : "&#9825;";310    const state = liked ? ` disabled aria-pressed="true"` : "";311    // the visible label is a heart and a number, so spell it out for312    // screen readers, count included313    const likes = count === 1 ? "1 like" : `${count} likes`;314    const label = liked ? `you liked this post, ${likes}` : `like this post, ${likes}`;315    return [316        `<form class="like-form" method="POST" action="/api/like">`,317        `    <input type="hidden" name="path" value="${escapeHtml(path)}" />`,318        `    <button type="submit" class="like-button" aria-label="${label}"${state}>${heart} <span class="like-count">${count}</span></button>`,319        `</form>`,320    ].join("\n");321}322323function renderReplies({ path, replies }) {324    const n = replies.length;325    const label = n === 0 ? "NO REPLIES YET" : n === 1 ? "1 REPLY" : `${n} REPLIES`;326    const head = [327        `<div class="reply-head">`,328        `    <p class="meta">${label}</p>`,329        `    <a class="reply-link" href="${replyHref(path, null)}">REPLY BY EMAIL &rarr;</a>`,330        `</div>`,331    ];332    if (n === 0) {333        return head.join("\n");334    }335    const byParent = groupByParent(replies);336    return head.concat(renderThread(byParent, null, path, 0, new Set(), "")).join("\n");337}338339// Children keyed by parent guid. A reply whose parent is gone (deleted, or340// never existed) is re-parented to the top level rather than dropped.341function groupByParent(replies) {342    const live = new Set(replies.map((r) => r.guid));343    const byParent = new Map();344    for (const r of replies) {345        const key = r.parent && live.has(r.parent) ? r.parent : null;346        if (!byParent.has(key)) {347            byParent.set(key, []);348        }349        byParent.get(key).push(r);350    }351    return byParent;352}353354// One <ol class="reply-thread"> for the children of `parent`. Nesting stops at355// MAX_THREAD_DEPTH: anything deeper is flattened into the list at that depth356// so it still renders. `visited` guards against cycles in the parent column.357function renderThread(byParent, parent, path, depth, visited, indent) {358    const flatten = depth >= MAX_THREAD_DEPTH;359    const items = (flatten ? descendants(byParent, parent, visited) : byParent.get(parent) || []).filter(360        (r) => !visited.has(r.guid)361    );362    if (items.length === 0) {363        return [];364    }365    const lines = [`${indent}<ol class="reply-thread">`];366    for (const r of items) {367        visited.add(r.guid);368        const id = `reply-${escapeHtml(r.guid)}`;369        const children = flatten ? [] : renderThread(byParent, r.guid, path, depth + 1, visited, `${indent}        `);370        lines.push(371            `${indent}    <li>`,372            `${indent}        <article id="${id}" class="reply">`,373            `${indent}            <p class="meta">`,374            `${indent}                <span class="reply-name">${escapeHtml(r.name)}</span>`,375            `${indent}                <a class="reply-time" href="#${id}"><time datetime="${escapeHtml(r.created_at)}">${formatTimestamp(r.created_at)}</time></a>`,376            `${indent}            </p>`,377            `${indent}            <p class="reply-body">${formatBody(r.message)}</p>`,378            `${indent}            <a class="reply-link" href="${replyHref(path, r.guid)}">REPLY &rarr;</a>`,379            ...children,380            `${indent}        </article>`,381            `${indent}    </li>`382        );383    }384    lines.push(`${indent}</ol>`);385    return lines;386}387388// Every reply below `parent`, depth first, in thread order.389function descendants(byParent, parent, visited) {390    const out = [];391    const stack = [...(byParent.get(parent) || [])].reverse();392    const seen = new Set(visited);393    while (stack.length > 0) {394        const r = stack.pop();395        if (seen.has(r.guid)) {396            continue;397        }398        seen.add(r.guid);399        out.push(r);400        const kids = byParent.get(r.guid) || [];401        for (let i = kids.length - 1; i >= 0; i--) {402            stack.push(kids[i]);403        }404    }405    return out;406}407408// mailto: link with the post URL as the subject. Replying to a specific reply409// carries its guid as a URL fragment in the subject; the inbound email worker410// parses it back out to thread the comment.411function replyHref(path, parentGuid) {412    // path is /blog/<slug>/ and the guid is a UUID, so neither needs encoding;413    // only the space and the "#" do.414    let href = `mailto:${REPLY_ADDRESS}?subject=re:%20${SITE_URL}${path}`;415    if (parentGuid) {416        href += `%23${parentGuid}`;417    }418    return escapeHtml(href);419}420421// ---------------------------------------------------------------------------422// text helpers423424// Post text is plain text with real newlines; keep them.425function formatBody(text) {426    return escapeHtml(text).replace(/\r?\n/g, "<br />\n");427}428429// One-line excerpt for the homepage activity row: whitespace collapsed,430// truncated on a word boundary, uppercased to match the neighbouring rows.431function snippet(text) {432    const flat = text.replace(/\s+/g, " ").trim();433    if (flat.length <= ACTIVITY_SNIPPET_LENGTH) {434        return escapeHtml(flat.toUpperCase());435    }436    let cut = flat.slice(0, ACTIVITY_SNIPPET_LENGTH);437    const lastSpace = cut.lastIndexOf(" ");438    if (lastSpace > ACTIVITY_SNIPPET_LENGTH / 2) {439        cut = cut.slice(0, lastSpace);440    }441    return escapeHtml(cut.toUpperCase()) + "&hellip;";442}443444// "1 SEPTEMBER 2026 &middot; 18:42 PDT"445function formatTimestamp(iso) {446    const date = new Date(iso);447    if (Number.isNaN(date.getTime())) {448        return escapeHtml(iso);449    }450    const parts = partsOf(451        new Intl.DateTimeFormat("en-US", {452            timeZone: TZ,453            day: "numeric",454            month: "long",455            year: "numeric",456            hour: "2-digit",457            minute: "2-digit",458            hourCycle: "h23",459            timeZoneName: "short",460        }),461        date462    );463    return `${parts.day} ${parts.month.toUpperCase()} ${parts.year} &middot; ${parts.hour}:${parts.minute} ${parts.timeZoneName}`;464}465466// "1 SEP"467function formatActivityDate(iso) {468    const date = new Date(iso);469    if (Number.isNaN(date.getTime())) {470        return "";471    }472    const parts = partsOf(473        new Intl.DateTimeFormat("en-US", { timeZone: TZ, day: "numeric", month: "short" }),474        date475    );476    return `${parts.day} ${parts.month.toUpperCase()}`;477}478479// "2026-09-03" in the site's time zone, for grouping posts by day.480function dayKey(iso) {481    const date = new Date(iso);482    if (Number.isNaN(date.getTime())) {483        return "";484    }485    const parts = partsOf(486        new Intl.DateTimeFormat("en-US", { timeZone: TZ, year: "numeric", month: "2-digit", day: "2-digit" }),487        date488    );489    return `${parts.year}-${parts.month}-${parts.day}`;490}491492function partsOf(formatter, date) {493    const out = {};494    for (const { type, value } of formatter.formatToParts(date)) {495        out[type] = value;496    }497    return out;498}499500// ---------------------------------------------------------------------------501// Deliberately NOT implemented in this pass:502//503// - rich text facets: links, mentions and hashtags render as plain text504// - quote posts (app.bsky.embed.record): the quoted record is ignored, only505//   the text shows. quote-with-media keeps its images or video, drops the quote506// - external link cards (app.bsky.embed.external)507// - threading: replies are filtered out entirely, thread structure is ignored
functions/api/like.jsdeleted +0 −71
@@ -1,71 +0,0 @@1// POST /api/like: records one like for a blog post and redirects back to it.2// Plain HTML form target, no JavaScript. See SOCIAL.md.3//4// There is deliberately no onRequestGet: a GET to this path falls through to5// the platform's 405 so link prefetchers and crawlers can never add a like.67import { isBlogPost, voterId } from "../_lib/social.js";89// LikeVoters rows only need to live for the day they were created; keep two10// days so a purge never races the UTC rollover.11const VOTER_TTL_MS = 2 * 24 * 60 * 60 * 1000;1213export async function onRequestPost(context) {14    const { request, env } = context;1516    let form;17    try {18        form = await request.formData();19    } catch {20        return plain("bad request", 400);21    }2223    const path = form.get("path");24    if (typeof path !== "string" || !isBlogPost(path)) {25        return plain("bad request", 400);26    }2728    // Refuse to create counter rows for pages that do not exist.29    const { origin } = new URL(request.url);30    const page = await env.ASSETS.fetch(new Request(origin + path));31    if (page.status !== 200) {32        return plain("not found", 404);33    }3435    const now = new Date();36    const voter = await voterId(env.SOCIAL_SECRET, request);37    const cutoff = new Date(now.getTime() - VOTER_TTL_MS).toISOString();3839    // ---------------------------------------------------------------------------40    // record4142    const [inserted] = await env.DB.batch([43        env.DB44            .prepare("INSERT OR IGNORE INTO LikeVoters (page, voter, created_at) VALUES (?, ?, ?)")45            .bind(path, voter, now.toISOString()),46        // opportunistic purge of stale voter rows on every call47        env.DB.prepare("DELETE FROM LikeVoters WHERE created_at < ?").bind(cutoff),48    ]);4950    // A repeat like from the same voter is a silent no-op, never an error.51    if (inserted.meta.changes === 1) {52        await env.DB53            .prepare(54                "INSERT INTO Likes (page, count) VALUES (?, 1) ON CONFLICT(page) DO UPDATE SET count = count + 1"55            )56            .bind(path)57            .run();58    }5960    return new Response(null, {61        status: 303,62        headers: { Location: path + "#likes" },63    });64}6566function plain(body, status) {67    return new Response(body, {68        status,69        headers: { "Content-Type": "text/plain; charset=utf-8" },70    });71}
functions/api/moderate.jsdeleted +0 −164
@@ -1,164 +0,0 @@1// /api/moderate: the delete link from a reply notification email lands here.2// See SOCIAL.md.3//4// GET renders a confirm page and never mutates anything, because mail clients5// and link scanners prefetch URLs. Only the POST from the confirm page's form6// performs the delete. Both require a valid signature over the reply guid.78import { escapeHtml, hmacHex, safeEqual } from "../_lib/social.js";910const GUID_RE = /^[0-9a-f-]{36}$/;11const PREVIEW_LENGTH = 200;1213export async function onRequestGet(context) {14    const { searchParams } = new URL(context.request.url);15    const id = searchParams.get("id");16    const sig = searchParams.get("sig");17    if (!(await authorized(context.env, id, sig))) {18        return forbidden();19    }2021    const reply = await lookup(context.env, id);22    if (!reply || reply.deleted_at !== null) {23        return page("MODERATE", [24            `<p>No such reply, or it has already been deleted.</p>`,25            reply ? `<p><a href="${escapeHtml(reply.url)}">BACK TO THE POST &rarr;</a></p>` : null,26        ]);27    }2829    return page("MODERATE", [30        `<p class="meta">DELETE THIS REPLY?</p>`,31        `<article class="reply">`,32        `    <p class="meta">`,33        `        <span class="reply-name">${escapeHtml(reply.name)}</span>`,34        `        <a class="reply-time" href="${escapeHtml(reply.url)}#reply-${escapeHtml(reply.guid)}">${escapeHtml(reply.url)}</a>`,35        `    </p>`,36        `    <p class="reply-body">${escapeHtml(preview(reply.message))}</p>`,37        `</article>`,38        `<form class="moderate-form" method="POST" action="/api/moderate">`,39        `    <input type="hidden" name="id" value="${escapeHtml(id)}" />`,40        `    <input type="hidden" name="sig" value="${escapeHtml(sig)}" />`,41        `    <button type="submit" class="moderate-button">DELETE</button>`,42        `</form>`,43    ]);44}4546export async function onRequestPost(context) {47    let form;48    try {49        form = await context.request.formData();50    } catch {51        return forbidden();52    }53    const id = form.get("id");54    const sig = form.get("sig");55    if (!(await authorized(context.env, id, sig))) {56        return forbidden();57    }5859    const reply = await lookup(context.env, id);60    if (!reply) {61        return page("MODERATE", [`<p>No such reply.</p>`]);62    }6364    await context.env.DB65        .prepare("UPDATE Replies SET deleted_at = datetime('now') WHERE guid = ? AND deleted_at IS NULL")66        .bind(id)67        .run();6869    return page("MODERATE", [70        `<p>Reply deleted. <a href="${escapeHtml(reply.url)}">BACK TO THE POST &rarr;</a></p>`,71    ]);72}7374// ---------------------------------------------------------------------------75// auth and data7677async function authorized(env, id, sig) {78    if (typeof id !== "string" || !GUID_RE.test(id) || typeof sig !== "string") {79        return false;80    }81    const expected = await hmacHex(env.SOCIAL_SECRET, "delete:" + id);82    return safeEqual(sig, expected);83}8485async function lookup(env, id) {86    const row = await env.DB87        .prepare("SELECT guid, url, name, message, deleted_at FROM Replies WHERE guid = ?")88        .bind(id)89        .first();90    return row || null;91}9293function forbidden() {94    return new Response("forbidden", {95        status: 403,96        headers: { "Content-Type": "text/plain; charset=utf-8" },97    });98}99100// ---------------------------------------------------------------------------101// rendering102103function preview(message) {104    const flat = String(message).replace(/\s+/g, " ").trim();105    return flat.length > PREVIEW_LENGTH ? flat.slice(0, PREVIEW_LENGTH) + "…" : flat;106}107108// Same head, header and CSP as every static page on the site.109function page(title, lines) {110    const body = lines.filter((line) => line !== null).join("\n            ");111    const html = `<!DOCTYPE html>112<html lang="en">113114<head>115    <meta charset="UTF-8" />116    <meta name="viewport" content="width=device-width, initial-scale=1.0" />117    <meta name="robots" content="noindex" />118    <meta http-equiv="Content-Security-Policy"119        content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' https://assets.danieldaum.net; media-src 'self' https://assets.danieldaum.net;" />120    <meta name="referrer" content="strict-origin-when-cross-origin" />121    <link rel="preload" href="/assets/fonts/ioskeleymono/IoskeleyMono-Regular.woff2" as="font" type="font/woff2" crossorigin />122    <link rel="preload" href="/assets/fonts/ioskeleymono/IoskeleyMono-Bold.woff2" as="font" type="font/woff2" crossorigin />123    <link rel="preload" href="/assets/fonts/ioskeleymono/IoskeleyMono-SemiBold.woff2" as="font" type="font/woff2" crossorigin />124    <link rel="stylesheet" href="/global.css" />125    <link rel="icon" type="image/png" sizes="32x32" href="/assets/favicon/favicon-32x32.png" />126    <link rel="icon" type="image/png" sizes="16x16" href="/assets/favicon/favicon-16x16.png" />127    <link rel="apple-touch-icon" sizes="180x180" href="/assets/favicon/apple-touch-icon.png" />128    <link rel="manifest" href="/assets/favicon/site.webmanifest" />129    <title>daniel daum - ${escapeHtml(title.toLowerCase())}</title>130</head>131132<body>133    <header class="site-header">134        <a class="site-name" href="/">DANIEL DAUM</a>135        <nav aria-label="main navigation">136            <a href="/">HOME</a>137            <a href="/about">ABOUT</a>138            <a href="/now">NOW</a>139            <a href="/blog">BLOG</a>140            <a href="/projects">PROJECTS</a>141            <a href="/garden">GARDEN</a>142        </nav>143    </header>144145    <main id="main">146        <section class="hero">147            <h1>/${escapeHtml(title)}</h1>148        </section>149        <section class="post-social">150            ${body}151        </section>152    </main>153</body>154155</html>156`;157    return new Response(html, {158        status: 200,159        headers: {160            "Content-Type": "text/html; charset=utf-8",161            "Cache-Control": "private, no-store",162        },163    });164}
functions/media/[cid].jsdeleted +0 −160
@@ -1,160 +0,0 @@1// GET /media/<cid>: one blob from my PDS, served same-origin with Range2// support. See MICRO.md.3//4// The PDS answers every request for a blob with the whole file and no5// Accept-Ranges, and Safari (so every browser on iOS) refuses to play a6// video it cannot seek into. Cloudflare's Cache API does honour Range on a7// cached object, so the blob is stored there once and every later request,8// ranged or not, is served from the edge. Blobs are content-addressed, which9// is why the cache entry can be immutable.10//11// This route serves blobs only; a page that fails to reach it just shows an12// empty player. It is not on the middleware's fail-open path.1314const PDS_HOST = "https://atproto.danieldaum.net";15const REPO_DID = "did:plc:be2e4qfe6docqcysyxxwvsor";1617// CIDv1 in base32, the only form the PDS hands out. Anything else is refused18// before a request is made upstream.19const CID_RE = /^b[a-z2-7]{20,}$/;2021// Only media is proxied. The PDS sets the type from the record, so it is22// trusted here, but a blob of any other type is not something a page embeds.23const MEDIA_TYPE_RE = /^(image|video)\//;2425export async function onRequestGet(context) {26    const { request, params } = context;27    const cid = params.cid;28    if (typeof cid !== "string" || !CID_RE.test(cid)) {29        return plain("not found", 404);30    }3132    const cache = caches.default;33    // The key is the canonical URL without the query string, so /media/<cid>34    // and /media/<cid>?x share an entry. Range is carried on the lookup35    // request, which is what makes the Cache API return a 206.36    const keyUrl = new URL(request.url);37    keyUrl.search = "";38    const lookup = new Request(keyUrl.toString(), { headers: rangeOnly(request) });3940    let response = await cache.match(lookup);41    if (response) {42        return response;43    }4445    let upstream;46    try {47        upstream = await fetch(blobUrl(cid));48    } catch {49        return plain("bad gateway", 502);50    }51    if (!upstream.ok) {52        return plain("not found", upstream.status === 404 ? 404 : 502);53    }54    const type = upstream.headers.get("content-type") || "";55    if (!MEDIA_TYPE_RE.test(type)) {56        return plain("not found", 404);57    }5859    // Everything goes through memory once so the cached copy and the response60    // are built from the same bytes. Only the first request for a blob at a61    // given PoP pays for this.62    let body;63    try {64        body = await upstream.arrayBuffer();65    } catch {66        return plain("bad gateway", 502);67    }68    const headers = mediaHeaders(type, body.byteLength);69    context.waitUntil(cache.put(lookup.url, new Response(body.slice(0), { status: 200, headers })));7071    return ranged(request, body, headers);72}7374// The range parsing here only runs on a cache miss; the Cache API does the75// same job on every hit. One range, bytes only. Anything the parser does not76// understand gets the whole file, which is what the spec asks for.77function ranged(request, body, headers) {78    const length = body.byteLength;79    const range = parseRange(request.headers.get("range"), length);80    if (range === null) {81        return new Response(body, { status: 200, headers });82    }83    if (range === false) {84        const h = new Headers(headers);85        h.set("content-range", `bytes */${length}`);86        h.delete("content-length");87        return new Response(null, { status: 416, headers: h });88    }89    const [start, end] = range;90    const h = new Headers(headers);91    h.set("content-range", `bytes ${start}-${end}/${length}`);92    h.set("content-length", String(end - start + 1));93    return new Response(body.slice(start, end + 1), { status: 206, headers: h });94}9596// null: no usable range, serve everything. false: unsatisfiable, 416.97// [start, end]: inclusive byte range within the file.98function parseRange(header, length) {99    if (!header || length === 0) {100        return null;101    }102    const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());103    if (!m || (m[1] === "" && m[2] === "")) {104        return null;105    }106    let start;107    let end;108    if (m[1] === "") {109        // suffix range: the last N bytes110        const suffix = Number(m[2]);111        if (suffix === 0) {112            return false;113        }114        start = Math.max(0, length - suffix);115        end = length - 1;116    } else {117        start = Number(m[1]);118        end = m[2] === "" ? length - 1 : Math.min(Number(m[2]), length - 1);119    }120    if (start >= length || start > end) {121        return false;122    }123    return [start, end];124}125126function mediaHeaders(type, length) {127    return {128        "content-type": type,129        "content-length": String(length),130        "accept-ranges": "bytes",131        // content-addressed: the bytes behind a cid never change132        "cache-control": "public, max-age=31536000, immutable",133        "x-content-type-options": "nosniff",134        // a blob must never be able to run anything, whatever it claims to be135        "content-security-policy": "default-src 'none'; sandbox",136    };137}138139function rangeOnly(request) {140    const headers = new Headers();141    const range = request.headers.get("range");142    if (range) {143        headers.set("range", range);144    }145    return headers;146}147148function blobUrl(cid) {149    const url = new URL("/xrpc/com.atproto.sync.getBlob", PDS_HOST);150    url.searchParams.set("did", REPO_DID);151    url.searchParams.set("cid", cid);152    return url.toString();153}154155function plain(text, status) {156    return new Response(text, {157        status,158        headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },159    });160}
schema.sqldeleted +0 −26
@@ -1,26 +0,0 @@1CREATE TABLE IF NOT EXISTS Likes (2    page TEXT PRIMARY KEY,3    count INTEGER NOT NULL DEFAULT 04);56CREATE TABLE IF NOT EXISTS LikeVoters (7    page TEXT NOT NULL,8    voter TEXT NOT NULL,9    created_at TEXT NOT NULL,10    PRIMARY KEY (page, voter)11);1213CREATE TABLE IF NOT EXISTS Replies (14    guid TEXT PRIMARY KEY,15    url TEXT NOT NULL,16    parent TEXT,17    name TEXT NOT NULL,18    message TEXT NOT NULL,19    sender TEXT NOT NULL,20    approved INTEGER NOT NULL DEFAULT 1,21    created_at TEXT NOT NULL,22    deleted_at TEXT23);2425CREATE INDEX IF NOT EXISTS idx_replies_url ON Replies (url, deleted_at, created_at);26CREATE INDEX IF NOT EXISTS idx_replies_sender ON Replies (sender, created_at);
vite.config.jsdeleted +0 −23
@@ -1,23 +0,0 @@1const { existsSync } = require('node:fs')2const { resolve } = require('node:path')34module.exports = {5  appType: 'mpa',6  plugins: [7    {8      name: 'directory-index',9      configureServer(server) {10        server.middlewares.use((req, res, next) => {11          const url = (req.url ?? '/').split('?')[0]12          if (!url.endsWith('/') && !url.includes('.')) {13            const indexPath = resolve(__dirname, url.slice(1), 'index.html')14            if (existsSync(indexPath)) {15              req.url = url + '/index.html'16            }17          }18          next()19        })20      }21    }22  ]23}
workers/replies-inbound/.gitignoredeleted +0 −3
@@ -1,3 +0,0 @@1node_modules/2.wrangler/3.dev.vars
workers/replies-inbound/package-lock.jsondeleted +0 −21
@@ -1,21 +0,0 @@1{2    "name": "saturn-replies-inbound",3    "version": "1.0.0",4    "lockfileVersion": 3,5    "requires": true,6    "packages": {7        "": {8            "name": "saturn-replies-inbound",9            "version": "1.0.0",10            "dependencies": {11                "postal-mime": "^2.4.3"12            }13        },14        "node_modules/postal-mime": {15            "version": "2.7.6",16            "resolved": "https://registry.npmjs.org/postal-mime/-/postal-mime-2.7.6.tgz",17            "integrity": "sha512-UUlyE2KlxmvwMGq060onF/VWU3zD6dVW31FwokQ5v26jWd35fbs2MoTFzh+jXnPwAyV2MULMKXcBInGOl5TO6Q==",18            "license": "MIT-0"19        }20    }21}
workers/replies-inbound/package.jsondeleted +0 −10
@@ -1,10 +0,0 @@1{2    "name": "saturn-replies-inbound",3    "version": "1.0.0",4    "private": true,5    "type": "module",6    "description": "Email worker for reply-by-email comments on danieldaum.net. See ../../SOCIAL.md.",7    "dependencies": {8        "postal-mime": "^2.4.3"9    }10}
workers/replies-inbound/src/index.jsdeleted +0 −239
@@ -1,239 +0,0 @@1// Email Worker for reply-by-email comments on blog posts. Cloudflare Email2// Routing delivers everything sent to reply@replies.danieldaum.net here.3// Each message passes a fixed sequence of gates, in the order below, and is4// inserted into D1 as a public comment. See ../../SOCIAL.md.5//6// Failure modes, deliberately different:7// - setReject: the sender did something fixable (wrong subject, empty body),8//   so a bounce is useful to them.9// - silent drop (console.log + return): authentication or rate limit10//   failures, where a bounce would only be backscatter.1112import PostalMime from "postal-mime";13import { EmailMessage } from "cloudflare:email";14import { hmacHex } from "./lib.js";1516const SITE_URL = "https://danieldaum.net";17const NOTIFY_FROM = "notify@replies.danieldaum.net";18const NOTIFY_TO = "daniel@danieldaum.net";1920const SUBJECT_RE = /^\s*re:\s*https:\/\/danieldaum\.net(\/blog\/[a-z0-9-]+\/)(?:#([0-9a-f-]{36}))?\s*$/i;21const URL_RE = /https?:\/\/\S+/g;22const CONTROL_RE = /[\x00-\x1f\x7f]/g;2324const MIN_BODY = 2;25const MAX_BODY = 2000;26const MAX_URLS = 2;27const MAX_NAME = 40;28const NOTIFY_PREVIEW = 500;2930const PER_SENDER_PER_HOUR = 5;31const GLOBAL_PER_HOUR = 30;3233export default {34    async email(message, env, ctx) {35        // 1. authentication: only mail that passed DKIM and at least one of36        //    SPF / DMARC at Cloudflare's edge gets any further.37        const auth = (message.headers.get("Authentication-Results") || "").toLowerCase();38        if (!auth.includes("dkim=pass") || !(auth.includes("spf=pass") || auth.includes("dmarc=pass"))) {39            console.log("drop: authentication failed");40            return;41        }4243        // 2. parse44        const email = await PostalMime.parse(message.raw);4546        // 3. subject carries the post URL and, optionally, the parent guid47        const match = (email.subject || "").match(SUBJECT_RE);48        if (!match || match[1] === "/blog/micro/") {49            message.setReject("Subject must be the reply link from the post page");50            return;51        }52        const path = match[1];53        const requestedParent = match[2] ? match[2].toLowerCase() : null;5455        // 4. the post must exist56        if (!(await pageExists(env, path))) {57            message.setReject("That post does not exist");58            return;59        }6061        // 5. parent: must be a live reply on the same post, else top-level62        const parent = requestedParent ? await liveParent(env, requestedParent, path) : null;6364        // 6. body65        const body = cleanBody(email);66        if (body.length < MIN_BODY || body.length > MAX_BODY) {67            message.setReject(`Reply must be between ${MIN_BODY} and ${MAX_BODY} characters after quoted text is removed`);68            return;69        }70        if ((body.match(URL_RE) || []).length > MAX_URLS) {71            message.setReject(`Reply may contain at most ${MAX_URLS} links`);72            return;73        }7475        // 7. sender: a keyed hash of the address, used only for rate limiting.76        //    The address itself is never stored and never logged.77        const address = (email.from?.address || "").trim().toLowerCase();78        if (!address) {79            console.log("drop: no from address");80            return;81        }82        const sender = await hmacHex(env.SOCIAL_SECRET, address);8384        // 8. rate limits85        if (!(await underRateLimits(env, sender))) {86            console.log("drop: rate limited");87            return;88        }8990        // 9. display name91        const name = displayName(email.from?.name, address);9293        // 10. insert94        const guid = crypto.randomUUID();95        const createdAt = new Date().toISOString();96        await env.DB97            .prepare(98                "INSERT INTO Replies (guid, url, parent, name, message, sender, approved, created_at) VALUES (?, ?, ?, ?, ?, ?, 1, ?)"99            )100            .bind(guid, path, parent, name, body, sender, createdAt)101            .run();102103        // 11. notify, with a signed delete link. A failure here must not undo104        //     the insert, so it only logs.105        try {106            const deleteSig = await hmacHex(env.SOCIAL_SECRET, "delete:" + guid);107            const raw = notification({ path, guid, name, body, deleteSig });108            await env.NOTIFY.send(new EmailMessage(NOTIFY_FROM, NOTIFY_TO, raw));109        } catch (err) {110            console.log("notify failed: " + (err && err.message ? err.message : String(err)));111        }112    },113};114115// ---------------------------------------------------------------------------116// gates117118// PAGE_CHECK_ORIGIN is a local-dev override only (set in .dev.vars) so the119// check can point at `wrangler pages dev` instead of the live site. It is120// never set in production; links and subjects always use SITE_URL.121async function pageExists(env, path) {122    try {123        const origin = env.PAGE_CHECK_ORIGIN || SITE_URL;124        const res = await fetch(origin + path, { method: "HEAD" });125        return res.status === 200;126    } catch {127        return false;128    }129}130131async function liveParent(env, guid, path) {132    const row = await env.DB133        .prepare("SELECT url FROM Replies WHERE guid = ? AND deleted_at IS NULL")134        .bind(guid)135        .first();136    return row && row.url === path ? guid : null;137}138139async function underRateLimits(env, sender) {140    const [mine, all] = await env.DB.batch([141        env.DB142            .prepare("SELECT COUNT(*) AS n FROM Replies WHERE sender = ? AND created_at > datetime('now', '-1 hour')")143            .bind(sender),144        env.DB.prepare("SELECT COUNT(*) AS n FROM Replies WHERE created_at > datetime('now', '-1 hour')"),145    ]);146    const perSender = Number(mine.results[0]?.n ?? 0);147    const global = Number(all.results[0]?.n ?? 0);148    return perSender < PER_SENDER_PER_HOUR && global < GLOBAL_PER_HOUR;149}150151// ---------------------------------------------------------------------------152// text153154// Plain text body with quoted history removed. Stored raw; escaping happens155// when the middleware renders it.156function cleanBody(email) {157    let text = typeof email.text === "string" && email.text.trim() ? email.text : htmlToText(email.html || "");158    text = text.replace(/\r\n?/g, "\n");159160    const kept = [];161    for (const line of text.split("\n")) {162        // everything from the first quote header onward is the previous message163        if (/^On .+ wrote:$/.test(line.trim()) || /^-{2,}\s*Original Message/i.test(line) || /^From: /.test(line)) {164            break;165        }166        if (line.startsWith(">")) {167            continue;168        }169        kept.push(line.replace(/\s+$/, ""));170    }171172    return kept173        .join("\n")174        .replace(/\n{3,}/g, "\n\n")175        .trim();176}177178function htmlToText(html) {179    return html180        .replace(/<(script|style)[\s\S]*?<\/\1>/gi, "")181        .replace(/<br\s*\/?>/gi, "\n")182        .replace(/<\/(p|div|li|blockquote|h[1-6]|tr)>/gi, "\n")183        .replace(/<[^>]+>/g, "")184        .replace(/&nbsp;/g, " ")185        .replace(/&lt;/g, "<")186        .replace(/&gt;/g, ">")187        .replace(/&quot;/g, "\"")188        .replace(/&#39;/g, "'")189        .replace(/&amp;/g, "&");190}191192function displayName(fromName, address) {193    let name = typeof fromName === "string" ? fromName.trim() : "";194    if (!name) {195        name = address.split("@")[0];196    }197    name = name.replace(CONTROL_RE, "").trim();198    if (name.length > MAX_NAME) {199        name = name.slice(0, MAX_NAME);200    }201    return name || "anonymous";202}203204// ---------------------------------------------------------------------------205// notification206207// A minimal RFC 5322 message, built by hand. Plain text only.208function notification({ path, guid, name, body, deleteSig }) {209    const postUrl = `${SITE_URL}${path}#reply-${guid}`;210    const deleteUrl = `${SITE_URL}/api/moderate?id=${guid}&sig=${deleteSig}`;211    const preview = body.length > NOTIFY_PREVIEW ? body.slice(0, NOTIFY_PREVIEW) + "..." : body;212213    const headers = [214        `From: ${NOTIFY_FROM}`,215        `To: ${NOTIFY_TO}`,216        `Subject: New reply on ${path}`,217        `Date: ${rfc5322Date(new Date())}`,218        `Message-ID: <${crypto.randomUUID()}@replies.danieldaum.net>`,219        `MIME-Version: 1.0`,220        `Content-Type: text/plain; charset=utf-8`,221        `Content-Transfer-Encoding: 8bit`,222    ];223    const lines = [224        `${name} replied on ${path}:`,225        ``,226        preview,227        ``,228        `View: ${postUrl}`,229        ``,230        `Delete: ${deleteUrl}`,231        ``,232    ];233    return headers.join("\r\n") + "\r\n\r\n" + lines.join("\n").replace(/\r?\n/g, "\r\n");234}235236// "Thu, 03 Sep 2026 18:42:00 +0000"237function rfc5322Date(date) {238    return date.toUTCString().replace(/GMT$/, "+0000");239}
workers/replies-inbound/src/lib.jsdeleted +0 −30
@@ -1,30 +0,0 @@1// Shared crypto helper for the replies worker.2//3// hmacHex MUST stay in sync with functions/_lib/social.js at the repo root.4// This worker signs delete links and sender hashes with it; the Pages side5// verifies and matches them with its copy. Same secret, same algorithm, same6// output, or moderation links stop working.78export async function hmacHex(secret, message) {9    if (typeof secret !== "string" || secret.length === 0) {10        throw new Error("SOCIAL_SECRET is not set");11    }12    const enc = new TextEncoder();13    const key = await crypto.subtle.importKey(14        "raw",15        enc.encode(secret),16        { name: "HMAC", hash: "SHA-256" },17        false,18        ["sign"]19    );20    const sig = await crypto.subtle.sign("HMAC", key, enc.encode(message));21    return toHex(new Uint8Array(sig));22}2324function toHex(bytes) {25    let out = "";26    for (const b of bytes) {27        out += b.toString(16).padStart(2, "0");28    }29    return out;30}
workers/replies-inbound/wrangler.tomldeleted +0 −13
@@ -1,13 +0,0 @@1name = "saturn-replies-inbound"2main = "src/index.js"3compatibility_date = "2026-09-01"4workers_dev = false56[[d1_databases]]7binding = "DB"8database_name = "saturn-social"9database_id = "2cc8bddd-d422-4d1e-8480-c1c75c8d02b0"1011[[send_email]]12name = "NOTIFY"13destination_address = "daniel@danieldaum.net"
wrangler.tomldeleted +0 −8
@@ -1,8 +0,0 @@1name = "saturn"2pages_build_output_dir = "."3compatibility_date = "2026-09-01"45[[d1_databases]]6binding = "DB"7database_name = "saturn-social"8database_id = "2cc8bddd-d422-4d1e-8480-c1c75c8d02b0"