Manual
Almnck.
Price: 50ⓐ

Newsletter Subscription Implementation Plan

For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

Goal: Add a self-hosted mailing list (Listmonk) to the Almanack stack, with a subscribe margin box, a no-JS /subscribe/ page, Caddy rate limiting, and operational scripts.

Architecture: Listmonk + Postgres containers added to the existing docker-compose. Caddy (custom-built with rate-limit plugin) proxies only public subscription endpoints on list.almnck.com; admin UI binds to Tailscale only. A margin box with interactive JS provides inline subscribe; a static /subscribe/ page is the no-JS fallback. Operational scripts (a-list-*) SSH to production and run Listmonk CLI/API commands.

Tech Stack: Listmonk, Postgres 16, Caddy + caddy-ratelimit plugin, Podman/Docker Compose, Django/django-distill, Playwright (browser tests), PurelyMail SMTP.

Design doc: doc/process/plans/2026-02-18-newsletter-subscribe-design.md


Task 1: Custom Caddy Dockerfile

Build a Caddy image that includes the mholt/caddy-ratelimit plugin.

Files: - Create: assets/system/Dockerfile.caddy

Step 1: Create the Dockerfile

# assets/system/Dockerfile.caddy
FROM docker.io/library/caddy:builder AS builder
RUN xcaddy build --with github.com/mholt/caddy-ratelimit

FROM docker.io/library/caddy:latest
COPY --from=builder /usr/bin/caddy /usr/bin/caddy

Step 2: Commit

git add assets/system/Dockerfile.caddy
git commit -m "infra: custom Caddy image with rate-limit plugin"

Task 2: Docker Compose — Listmonk + Postgres

Add Listmonk and its Postgres database to the existing compose file. Update the Caddy service to build from the custom Dockerfile.

Files: - Modify: assets/system/docker-compose.yml

Step 1: Update docker-compose.yml

The final file should be:

name: almanack

services:
  caddy:
    build:
      context: .
      dockerfile: Dockerfile.caddy
    image: almanack-caddy:latest
    ports:
      - 80:80
      - 443:443
    environment:
      - CADDY_INGRESS_NETWORKS=almanack_caddy
      - CADDY_DOCKER_NO_REPLICAS=true
      - ACME_AGREE=true
      - EMAIL=a+acme@almnck.com
    networks:
      - caddy
    volumes:
      - /run/user/1000/podman.sock:/var/run/docker.sock
      - /home/danny/caddy/:/data:Z

  almnck:
    expose:
      - "80"
    image: docker.io/library/caddy:latest
    volumes:
      - /var/local/www/www.almnck.com/:/usr/share/caddy:ro,Z
      - /var/local/www/www.almnck.com/Caddyfile:/etc/caddy/Caddyfile:ro,Z
    networks:
        - caddy
    labels:
        caddy_0: www.almnck.com
        caddy_0.redir: https://almnck.com{uri} permanent
        caddy_1: almnck.com
        caddy_1.reverse_proxy: "{{upstreams 80}}"

  membership-api:
    build:
      context: /var/local/src/almnck
      dockerfile: api/Dockerfile
    expose:
      - "8000"
    env_file:
      - /var/local/api/.env
    environment:
      - DATABASE_URL=sqlite:////app/data/members.db
    volumes:
      - /var/local/api/:/app/data:Z
    networks:
      - caddy
    labels:
      caddy: api.almnck.com
      caddy.reverse_proxy: "{{upstreams 8000}}"
    restart: unless-stopped

  listmonk-db:
    image: docker.io/library/postgres:16-alpine
    environment:
      - POSTGRES_USER=listmonk
      - POSTGRES_PASSWORD_FILE=/run/secrets/listmonk_db_pass
      - POSTGRES_DB=listmonk
    volumes:
      - /var/local/listmonk/pgdata:/var/lib/postgresql/data:Z
    networks:
      - listmonk-internal
    secrets:
      - listmonk_db_pass
    restart: unless-stopped

  listmonk:
    image: docker.io/listmonk/listmonk:latest
    command: >
      sh -c "./listmonk --install --idempotent --yes --config '' && ./listmonk --config ''"
    depends_on:
      - listmonk-db
    env_file:
      - /var/local/listmonk/.env
    ports:
      - "${TAILSCALE_IP:?}:9000:9000"
    expose:
      - "9000"
    networks:
      - caddy
      - listmonk-internal
    labels:
      caddy: list.almnck.com
      caddy.@subscription: path /api/public/subscription
      caddy.rate_limit: "@subscription { zone subscription_zone { key {remote_host} events 5 window 1m } }"
      caddy.@public_0: path /api/public/*
      caddy.@public_1: path /subscription/*
      caddy.reverse_proxy: "@public {{upstreams 9000}}"
      caddy.respond: "404"
    restart: unless-stopped

secrets:
  listmonk_db_pass:
    file: /var/local/listmonk/secrets/db_password

networks:
  caddy:
    driver: bridge
  listmonk-internal:
    driver: bridge

Key details: - TAILSCALE_IP is the production host’s Tailscale IP — get it with ssh "$PROD_HOST" 'tailscale ip -4' - The command runs --install --idempotent on every start so Postgres tables are created on first boot without a manual step - Caddy labels restrict list.almnck.com to only /api/public/* and /subscription/* paths; everything else gets 404 - Rate limit: 5 requests per minute per IP on the subscription endpoint

Step 2: Create the Listmonk env file template

Create a reference .env template for documentation (the real file lives on the server at /var/local/listmonk/.env):

# assets/system/listmonk.env.example
LISTMONK_app__address=0.0.0.0:9000
LISTMONK_app__admin_username=admin
LISTMONK_app__admin_password=CHANGEME
LISTMONK_db__host=listmonk-db
LISTMONK_db__port=5432
LISTMONK_db__user=listmonk
LISTMONK_db__password=CHANGEME
LISTMONK_db__database=listmonk
LISTMONK_db__ssl_mode=disable

Step 3: Commit

git add assets/system/docker-compose.yml assets/system/listmonk.env.example
git commit -m "infra: add Listmonk + Postgres to docker-compose"

Task 3: Operational Scripts

Shell scripts for managing the mailing list from the local dev machine. All SSH to production.

Files: - Create: bin/a-list-count - Create: bin/a-list-export - Create: bin/a-list-backup

Step 1: a-list-count — Show subscriber count

#!/bin/zsh
# a-list-count - Show number of confirmed subscribers
# Usage: a-list-count

set -euo pipefail

PROD_SERVER="${PROD_SERVER:-sj}"

# Query Listmonk API on Tailscale address
count=$(ssh "$PROD_SERVER" \
  'curl -s -u "$LISTMONK_ADMIN_USER:$LISTMONK_ADMIN_PASS" \
    "http://localhost:9000/api/subscribers?page=1&per_page=1" \
    | python3 -c "import sys,json; print(json.load(sys.stdin)[\"data\"][\"total\"])"' \
  2>/dev/null)

echo "${count:-0} subscribers"

Note: This uses the Listmonk private API on localhost inside the server. The admin credentials should be available as env vars or sourced from a file. The implementation should read from /var/local/listmonk/.env on the server. Adjust as needed:

#!/bin/zsh
# a-list-count - Show number of confirmed subscribers
# Usage: a-list-count

set -euo pipefail

PROD_SERVER="${PROD_SERVER:-sj}"

count=$(ssh "$PROD_SERVER" '
  eval $(grep LISTMONK_app__admin /var/local/listmonk/.env | sed "s/^/export /")
  curl -s -u "${LISTMONK_app__admin_username}:${LISTMONK_app__admin_password}" \
    "http://localhost:9000/api/subscribers?page=1&per_page=1&subscription_status=confirmed" \
    | python3 -c "import sys,json; print(json.load(sys.stdin)[\"data\"][\"total\"])"
' 2>/dev/null)

echo "${count:-0} confirmed subscribers"

Step 2: a-list-export — Dump names and emails to stdout

#!/bin/zsh
# a-list-export - Export subscriber names and emails to stdout
# Usage: a-list-export
# Output: tab-separated name\temail, one per line

set -euo pipefail

PROD_SERVER="${PROD_SERVER:-sj}"

ssh "$PROD_SERVER" '
  eval $(grep LISTMONK_app__admin /var/local/listmonk/.env | sed "s/^/export /")
  page=1
  per_page=100
  while true; do
    result=$(curl -s -u "${LISTMONK_app__admin_username}:${LISTMONK_app__admin_password}" \
      "http://localhost:9000/api/subscribers?page=${page}&per_page=${per_page}&subscription_status=confirmed")
    echo "$result" | python3 -c "
import sys, json
data = json.load(sys.stdin)[\"data\"]
for s in data[\"results\"]:
    print(s[\"name\"] + \"\t\" + s[\"email\"])
if data[\"page\"] * data[\"per_page\"] >= data[\"total\"]:
    sys.exit(1)
" || break
    page=$((page + 1))
  done
'

Step 3: a-list-backup — Back up Listmonk Postgres database

#!/bin/zsh
# a-list-backup - Download Listmonk Postgres dump
# Usage: a-list-backup
# Output: db-backups/listmonk-YYYY-MM-DDTHH.sql.gz

set -euo pipefail

PROD_SERVER="${PROD_SERVER:-sj}"
ALMANACK_ROOT="${ALMANACK_ROOT:?ALMANACK_ROOT not set}"

mkdir -p "$ALMANACK_ROOT/db-backups"

timestamp=$(date -Ihours)
outfile="$ALMANACK_ROOT/db-backups/listmonk-${timestamp}.sql.gz"

echo "Backing up Listmonk database from ${PROD_SERVER}..."

ssh "$PROD_SERVER" '
  podman exec almanack-listmonk-db-1 \
    pg_dump -U listmonk -d listmonk \
    | gzip
' > "$outfile"

echo "Backup saved to ${outfile}"
ls -lh "$outfile"

Step 4: Make scripts executable and commit

chmod +x bin/a-list-count bin/a-list-export bin/a-list-backup
git add bin/a-list-count bin/a-list-export bin/a-list-backup
git commit -m "ops: add a-list-count, a-list-export, a-list-backup scripts"

Task 4: Makefile Targets

Add convenience targets for list operations.

Files: - Modify: Makefile

Step 1: Add targets

Add to the help text, in a new “Mailing List” section before the Production section:

    @echo ""
    @echo "$(YELLOW)Mailing List:$(RESET)"
    @echo "  list-count          Show subscriber count"
    @echo "  list-export         Export subscriber names and emails"
    @echo "  list-backup         Download Listmonk database backup"

Add the targets themselves (after the prod section or in a new section):

# ============================================================
# MAILING LIST
# ============================================================

.PHONY: list-count
list-count:
    @$(ALMANACK_ROOT)/bin/a-list-count

.PHONY: list-export
list-export:
    @$(ALMANACK_ROOT)/bin/a-list-export

.PHONY: list-backup
list-backup:
    @$(ALMANACK_ROOT)/bin/a-list-backup

Step 2: Commit

git add Makefile
git commit -m "make: add list-count, list-export, list-backup targets"

Task 5: Subscribe Page — Editorial Content + View

Create the no-JS /subscribe/ page.

Files: - Create: editorial/pages/subscribe/page.md - Modify: src/almnck/units/views.py — add ?thanks=1 handling in page_detail - Modify: src/almnck/templates/units/article.html — add noscript subscribe link - Modify: src/almnck/templates/base.html — (if needed, noscript in base)

Step 1: Create the editorial page

---
title: Subscribe
slug: subscribe
almanac-day: ""
---

<section class="subscribe-page" id="subscribe-section">

## Get the Almanack by Post

News of new articles, delivered by electrical mail. We send
infrequently, and never share your address.

<form class="subscribe-form" id="subscribe-form"
      action="https://list.almnck.com/api/public/subscription"
      method="POST">
  <input type="hidden" name="list_uuids" value="CHANGEME-LIST-UUID">
  <p>
    <label for="sub-name">Name <small>(optional)</small></label><br>
    <input id="sub-name" name="name" type="text"
           autocomplete="name" class="subscribe-input">
  </p>
  <p>
    <label for="sub-email">Email</label><br>
    <input id="sub-email" name="email" type="email" required
           placeholder="you@example.com" autocomplete="email"
           class="subscribe-input">
  </p>
  <input name="hp" tabindex="-1" autocomplete="off"
         aria-hidden="true"
         style="position:absolute;left:-9999px">
  <p>
    <button type="submit" class="subscribe-button">Subscribe</button>
  </p>
</form>

</section>

Note: The CHANGEME-LIST-UUID must be replaced with the real list UUID after Listmonk is set up. This is a manual step during deployment (see setup checklist in the design doc).

Step 2: Add ?thanks=1 handling to page_detail view

In src/almnck/units/views.py, modify page_detail to detect the query parameter and pass it to the template context:

Find:

    return render(
        request,
        "units/article.html",
        {
            "unit": unit,
            "content": content,
            "display_date": display_date,
            "almanac_day": unit.frontmatter.get("almanac-day", ""),
            "margin_boxes": margin_boxes,
            "nav_current": output_path,
        },
    )

Replace with:

    context = {
        "unit": unit,
        "content": content,
        "display_date": display_date,
        "almanac_day": unit.frontmatter.get("almanac-day", ""),
        "margin_boxes": margin_boxes,
        "nav_current": output_path,
    }

    # Subscribe page: handle post-submission redirect
    if request.GET.get("thanks") == "1" and unit.slug == "subscribe":
        context["subscribe_thanks"] = True

    return render(request, "units/article.html", context)

Step 3: Add noscript subscribe link to article template

In src/almnck/templates/units/article.html, after the closing </article> tag but before the closing </div> of margins-layout, add:

    <noscript>
      <div class="noscript-subscribe">
        <a href="/subscribe/">Get the Almanack by post →</a>
      </div>
    </noscript>

Step 4: Add subscribe confirmation JS

When the /subscribe/ page loads with ?thanks=1, client-side JS should swap the form for a thank-you message. Add a small inline script or a block in the page content itself. Since this is a static page rendered via markdown, the simplest approach is a <script> tag in the markdown:

Append to editorial/pages/subscribe/page.md:

<div id="subscribe-thanks" style="display:none">
  <p><strong>Check your post</strong></p>
  <p>We've sent a confirmation. Click the link in the email
  to complete your subscription.</p>
</div>

<script>
  if (new URLSearchParams(window.location.search).get('thanks') === '1') {
    var form = document.getElementById('subscribe-form');
    var thanks = document.getElementById('subscribe-thanks');
    if (form) form.style.display = 'none';
    if (thanks) thanks.style.display = 'block';
  }
</script>

For the static build: Since django-distill generates a single /subscribe/index.html, the ?thanks=1 parameter is only relevant at runtime in the browser. The script above handles it client-side. The subscribe_thanks context variable in the view is only useful during dev server use — for the static site, the JS handles it.

Step 5: Commit

git add editorial/pages/subscribe/page.md
git add src/almnck/units/views.py
git add src/almnck/templates/units/article.html
git commit -m "feat: add /subscribe/ page with no-JS form and thanks handling"

Task 6: Subscribe Form CSS

Style the form for both the /subscribe/ page and the margin box.

Files: - Modify: assets/css/almanack.css

Step 1: Add subscribe form styles

Append to assets/css/almanack.css:

/* ================================================================
   Subscribe form (margin box + /subscribe/ page)
   ================================================================ */

.subscribe-form {
    font-family: var(--font-body);
    font-size: 0.85rem;
}

.subscribe-form label {
    display: block;
    margin-bottom: 0.25em;
    font-family: var(--font-display);
    font-size: 0.9em;
}

.subscribe-form label small {
    font-family: var(--font-body);
    color: var(--color-muted);
}

.subscribe-input,
.subscribe-form input[type="text"],
.subscribe-form input[type="email"] {
    display: block;
    width: 100%;
    padding: 0.4em 0.5em;
    border: 1px solid var(--color-text);
    background: var(--color-bg);
    color: var(--color-text);
    font-family: var(--font-body);
    font-size: 0.9em;
    box-sizing: border-box;
}

.subscribe-form input:focus {
    outline: 2px solid var(--color-text);
    outline-offset: 1px;
}

.subscribe-button,
.subscribe-form button[type="submit"] {
    display: inline-block;
    padding: 0.4em 1.2em;
    border: 1px solid var(--color-text);
    background: var(--color-text);
    color: var(--color-bg);
    font-family: var(--font-display);
    font-size: 0.9em;
    cursor: pointer;
    transition: opacity 0.2s;
}

.subscribe-form button:hover {
    opacity: 0.85;
}

.subscribe-form button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

/* Margin box variant: tighter spacing */
.margin-box .subscribe-form p {
    margin: 0.5em 0;
}

.margin-box .subscribe-form input {
    font-size: 0.85em;
}

/* Noscript fallback link */
.noscript-subscribe {
    text-align: center;
    margin: 2em 0;
    padding: 1em;
    border-top: 1px solid var(--color-text);
    border-bottom: 1px solid var(--color-text);
    font-family: var(--font-display);
}

Step 2: Commit

git add assets/css/almanack.css
git commit -m "style: subscribe form and noscript fallback"

Task 7: Subscribe Margin Box — Editorial Content

Create the margin box markdown and interactive JS module.

Files: - Create: editorial/margin-boxes/subscribe/margin-box.md - Create: editorial/margin-boxes/subscribe/assets/subscribe.js - Create: assets/margin-boxes/subscribe/subscribe.js (dev symlink)

Step 1: Create the margin box markdown

---
type: editorial
placement: right-bottom
priority: normal
pages: [articles]
weight: 70
active: true
interactive: subscribe
---

**Get the Almanack by Post**

News of new articles, delivered by electrical mail.

[Subscribe →](/subscribe/)

Step 2: Create the interactive JS module

// subscribe.js — Interactive subscribe form for margin box
//
// Replaces static content with an inline email form.
// Pre-fills name from the identity system.
// Posts directly to Listmonk's public subscription API.

// List UUID — set after Listmonk setup
const LIST_UUID = 'CHANGEME-LIST-UUID';
const LISTMONK_URL = 'https://list.almnck.com/api/public/subscription';

export const meta = {
  name: 'subscribe',
  description: 'Inline newsletter subscription form',
  version: '1.0.0'
};

function escapeHtml(str) {
  const div = document.createElement('div');
  div.textContent = str;
  return div.innerHTML;
}

export function setup(container) {
  // Get whimsical name from identity system (may not be loaded yet)
  const identity = window.AlmanackIdentity;
  const prefillName = identity?.getName?.() || '';
  const escapedName = escapeHtml(prefillName);

  container.innerHTML = `
    <p><strong>Get the Almanack by Post</strong></p>
    <p style="font-size:0.85em">News of new articles, delivered by electrical mail.</p>
    <form class="subscribe-form" novalidate>
      <p>
        <label for="subscribe-name">Name</label>
        <input id="subscribe-name" name="name" type="text"
               value="${escapedName}" autocomplete="name"
               class="subscribe-input">
      </p>
      <p>
        <label for="subscribe-email">Email</label>
        <input id="subscribe-email" name="email" type="email"
               required placeholder="you@example.com"
               autocomplete="email" class="subscribe-input">
      </p>
      <input name="hp" tabindex="-1" autocomplete="off"
             aria-hidden="true"
             style="position:absolute;left:-9999px">
      <p>
        <button type="submit" class="subscribe-button">Subscribe</button>
      </p>
    </form>
  `;

  const form = container.querySelector('.subscribe-form');
  const nameInput = container.querySelector('[name="name"]');
  const originalName = prefillName;

  form.addEventListener('submit', async (e) => {
    e.preventDefault();

    // Honeypot check — if filled, silently discard
    if (form.querySelector('[name="hp"]').value) return;

    const email = form.querySelector('[name="email"]').value.trim();
    const name = nameInput.value.trim();

    if (!email) {
      form.querySelector('[name="email"]').focus();
      return;
    }

    // Disable button
    const btn = form.querySelector('button');
    btn.disabled = true;
    btn.textContent = 'Sending\u2026';

    try {
      const resp = await fetch(LISTMONK_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: email,
          name: name,
          list_uuids: [LIST_UUID]
        })
      });

      if (resp.ok) {
        // Track name preference if changed
        if (name && name !== originalName) {
          try {
            localStorage.setItem('almanack:preferred-name', name);
          } catch { /* localStorage unavailable */ }
        }

        container.innerHTML = `
          <p><strong>Check your post</strong></p>
          <p style="font-size:0.85em">We\u2019ve sent a confirmation to
          <em>${escapeHtml(email)}</em>.
          Click the link to complete your subscription.</p>
        `;
      } else if (resp.status === 429) {
        btn.textContent = 'Too many attempts';
        setTimeout(() => {
          btn.disabled = false;
          btn.textContent = 'Subscribe';
        }, 30000);
      } else {
        throw new Error(`${resp.status}`);
      }
    } catch {
      btn.textContent = 'Something went wrong';
      setTimeout(() => {
        btn.disabled = false;
        btn.textContent = 'Subscribe';
      }, 5000);
    }
  });
}
mkdir -p assets/margin-boxes/subscribe
ln -sf ../../../editorial/margin-boxes/subscribe/assets/subscribe.js \
       assets/margin-boxes/subscribe/subscribe.js

Step 4: Commit

git add editorial/margin-boxes/subscribe/
git add assets/margin-boxes/subscribe/
git commit -m "feat: subscribe margin box with interactive JS form"

Task 8: Load Subscribe Module in Base Template

The interactive margin box JS needs to be loaded. Unlike article figures (which use a manifest/runtime loader), margin box interactivity follows the identity-dropdown pattern: a standalone script loaded in the base template that finds its target element and enhances it.

Files: - Create: assets/js/subscribe-box.js — Loader that finds the margin box and calls the module - Modify: src/almnck/templates/base.html — Add script tag

Step 1: Create the loader script

The margin box module is an ES module with setup(), but the base template loads scripts as classic <script defer>. Create a thin loader:

// subscribe-box.js — Loader for subscribe margin box interactive module
//
// Waits for sidenotes to be ready, finds the subscribe margin box,
// and initialises the inline form.
(function() {
  'use strict';

  function init() {
    // Find the subscribe margin box (injected or static)
    const box = document.querySelector('[data-slug="subscribe"][data-interactive="subscribe"]')
               || document.querySelector('[data-interactive="subscribe"]');
    if (!box) return;

    // Dynamic import of the ES module
    // Resolve path relative to static assets
    const scriptTag = document.querySelector('script[src*="subscribe-box"]');
    const base = scriptTag ? scriptTag.src.replace(/subscribe-box\.js.*$/, '') : '/static/js/';
    import(base + 'subscribe.js')
      .then(mod => {
        if (typeof mod.setup === 'function') {
          mod.setup(box);
        }
      })
      .catch(err => console.error('Subscribe module failed:', err));
  }

  // Wait for sidenotes to position the box before enhancing it
  if (window.Sidenotes?.whenReady) {
    window.Sidenotes.whenReady().then(init);
  } else {
    // Fallback: try after DOMContentLoaded
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', init);
    } else {
      init();
    }
  }
})();

Step 2: Copy the ES module to assets/js/

The subscribe.js module needs to be available at /static/js/subscribe.js. Copy it:

cp editorial/margin-boxes/subscribe/assets/subscribe.js assets/js/subscribe.js

Important: This means there are two copies — the editorial source and the assets copy. The editorial one is the source of truth; the assets copy must be updated when the editorial one changes. Add a note in the file header:

// subscribe.js — Interactive subscribe form for margin box
// Source: editorial/margin-boxes/subscribe/assets/subscribe.js
// This copy in assets/js/ is loaded by subscribe-box.js at runtime.

Step 3: Add script tag to base template

In src/almnck/templates/base.html, after the identity-dropdown script:

    <script src="{% cdnstatic 'js/subscribe-box.js' %}" defer></script>

Step 4: Commit

git add assets/js/subscribe-box.js assets/js/subscribe.js
git add src/almnck/templates/base.html
git commit -m "feat: load subscribe margin box interactive module"

Task 9: Unit Tests — Margin Box Sync

Test that the subscribe margin box syncs correctly.

Files: - Modify: src/tests/test_sync_margin_boxes.py

Step 1: Write the test

Add a new test to the existing TestSyncMarginBoxes class:

    def test_sync_interactive_margin_box(self, tmp_path, monkeypatch):
        """Sync an interactive margin box preserves interactive field."""
        from almnck.units.models import MarginBox

        mb_dir = tmp_path / "margin-boxes" / "subscribe"
        mb_dir.mkdir(parents=True)
        (mb_dir / "margin-box.md").write_text("""---
type: editorial
placement: right-bottom
priority: normal
pages: [articles]
weight: 70
active: true
interactive: subscribe
---

**Get the Almanack by Post**

[Subscribe →](/subscribe/)
""")
        monkeypatch.setattr(settings, "EDITORIAL_DIR", str(tmp_path))
        call_command("sync_with_repo")

        box = MarginBox.objects.get(slug="subscribe")
        assert box.box_type == "editorial"
        assert box.interactive == "subscribe"
        assert box.placement == "right-bottom"
        assert box.weight == 70
        assert "articles" in box.pages
        assert "Subscribe" in box.content

Step 2: Run test to verify it passes

cd src && python -m pytest tests/test_sync_margin_boxes.py::TestSyncMarginBoxes::test_sync_interactive_margin_box -v

Expected: PASS (the sync infrastructure already handles interactive — this just confirms it works for our new box).

Step 3: Commit

git add src/tests/test_sync_margin_boxes.py
git commit -m "test: sync of interactive subscribe margin box"

Task 10: Unit Tests — Subscribe Page

Test that the /subscribe/ page renders correctly.

Files: - Create: src/tests/test_subscribe_page.py

Step 1: Write the tests

"""Tests for the /subscribe/ page."""

import pytest
from django.conf import settings
from django.core.management import call_command
from django.test import RequestFactory

from almnck.units.models import Unit
from almnck.units.views import page_detail


@pytest.mark.django_db
class TestSubscribePage:
    """Test the subscribe page renders and handles thanks param."""

    @pytest.fixture(autouse=True)
    def setup_subscribe_page(self, tmp_path, monkeypatch):
        """Create and sync the subscribe page."""
        pages_dir = tmp_path / "pages" / "subscribe"
        pages_dir.mkdir(parents=True)
        (pages_dir / "page.md").write_text("""---
title: Subscribe
slug: subscribe
almanac-day: ""
---

<form class="subscribe-form" id="subscribe-form"
      action="https://list.almnck.com/api/public/subscription"
      method="POST">
  <input type="hidden" name="list_uuids" value="test-uuid">
  <label for="sub-email">Email</label>
  <input id="sub-email" name="email" type="email" required>
  <button type="submit">Subscribe</button>
</form>

<div id="subscribe-thanks" style="display:none">
  <p>Check your post</p>
</div>
""")
        monkeypatch.setattr(settings, "EDITORIAL_DIR", str(tmp_path))
        call_command("sync_with_repo")

    def test_subscribe_page_renders(self):
        """The /subscribe/ page renders with a form."""
        factory = RequestFactory()
        request = factory.get("/subscribe/")
        response = page_detail(request, "subscribe/")
        assert response.status_code == 200
        content = response.content.decode()
        assert "subscribe-form" in content
        assert 'action="https://list.almnck.com/api/public/subscription"' in content

    def test_subscribe_thanks_context(self):
        """The ?thanks=1 param sets subscribe_thanks in context."""
        factory = RequestFactory()
        request = factory.get("/subscribe/", {"thanks": "1"})
        response = page_detail(request, "subscribe/")
        assert response.status_code == 200
        # The context variable is set — we verify by checking the
        # response rendered (the JS handles the actual swap, but
        # the view should still render successfully)
        content = response.content.decode()
        assert "subscribe-form" in content

Step 2: Run tests

cd src && python -m pytest tests/test_subscribe_page.py -v

Expected: PASS.

Step 3: Commit

git add src/tests/test_subscribe_page.py
git commit -m "test: subscribe page rendering and thanks param"

Task 11: Browser Tests — Subscribe Margin Box

End-to-end tests using Playwright to verify the margin box appears and the form works.

Files: - Create: src/tests/test_subscribe_box.py

Step 1: Write the browser tests

"""Browser tests for the subscribe margin box.

Tests verify:
- The subscribe margin box appears on article pages
- The form pre-fills the name from identity
- Honeypot field is hidden but present
- Form submission (mocked) shows confirmation
- No-JS fallback link is present in noscript
"""

import pytest

pytestmark = pytest.mark.browser

ARTICLE_URL = "/5921/2/13/kropotkins-funeral/"


class TestSubscribeMarginBox:
    """Test the subscribe margin box renders and functions."""

    def test_subscribe_box_appears(self, browser, dev_server_url):
        """Subscribe margin box is present on article pages."""
        page = browser.new_page()
        page.goto(dev_server_url + ARTICLE_URL)
        page.wait_for_function("window.Sidenotes?.whenReady")
        page.evaluate("() => window.Sidenotes.whenReady()")

        # Find the subscribe box
        box = page.query_selector('[data-slug="subscribe"]')
        assert box is not None, "Subscribe margin box not found"
        page.close()

    def test_subscribe_form_has_fields(self, browser, dev_server_url):
        """Subscribe form has email, name, and honeypot fields."""
        page = browser.new_page()
        page.goto(dev_server_url + ARTICLE_URL)
        page.wait_for_function("window.Sidenotes?.whenReady")
        page.evaluate("() => window.Sidenotes.whenReady()")

        # Wait for the interactive module to enhance the box
        page.wait_for_selector('[data-slug="subscribe"] .subscribe-form',
                               timeout=5000)

        box = page.query_selector('[data-slug="subscribe"]')
        assert box.query_selector('input[name="email"]') is not None
        assert box.query_selector('input[name="name"]') is not None
        assert box.query_selector('input[name="hp"]') is not None
        assert box.query_selector('button[type="submit"]') is not None
        page.close()

    def test_subscribe_form_prefills_name(self, browser, dev_server_url):
        """Subscribe form pre-fills name from identity system."""
        page = browser.new_page()
        page.goto(dev_server_url + ARTICLE_URL)
        page.wait_for_function("window.Sidenotes?.whenReady")
        page.evaluate("() => window.Sidenotes.whenReady()")
        page.wait_for_selector('[data-slug="subscribe"] .subscribe-form',
                               timeout=5000)

        name_val = page.eval_on_selector(
            '[data-slug="subscribe"] input[name="name"]',
            'el => el.value'
        )
        # Identity system generates a name — it shouldn't be empty
        # (unless identity failed to init, in which case it's '')
        # We just check it's a string
        assert isinstance(name_val, str)
        page.close()

    def test_honeypot_is_offscreen(self, browser, dev_server_url):
        """Honeypot field is positioned off-screen."""
        page = browser.new_page()
        page.goto(dev_server_url + ARTICLE_URL)
        page.wait_for_function("window.Sidenotes?.whenReady")
        page.evaluate("() => window.Sidenotes.whenReady()")
        page.wait_for_selector('[data-slug="subscribe"] .subscribe-form',
                               timeout=5000)

        hp_box = page.eval_on_selector(
            '[data-slug="subscribe"] input[name="hp"]',
            'el => { const r = el.getBoundingClientRect(); return { left: r.left, top: r.top }; }'
        )
        assert hp_box['left'] < 0, "Honeypot should be off-screen"
        page.close()


class TestSubscribeNoscript:
    """Test no-JS fallback."""

    def test_noscript_link_in_source(self, browser, dev_server_url):
        """Article HTML source contains noscript subscribe link."""
        page = browser.new_page(java_script_enabled=False)
        page.goto(dev_server_url + ARTICLE_URL)
        content = page.content()
        assert '/subscribe/' in content
        assert 'Get the Almanack by post' in content
        page.close()

Step 2: Run tests (requires dev server)

make sync
make serve &  # start dev server in background
cd src && python -m pytest tests/test_subscribe_box.py -v -m browser

Expected: All PASS (after Tasks 5-8 are complete and make sync has imported the content).

Step 3: Commit

git add src/tests/test_subscribe_box.py
git commit -m "test: browser tests for subscribe margin box and noscript fallback"

Task 12: Subscribe Page Browser Test

End-to-end test for the /subscribe/ static page.

Files: - Modify: src/tests/test_subscribe_page.py — Add browser test class

Step 1: Add browser tests

Append to src/tests/test_subscribe_page.py:

@pytest.mark.browser
class TestSubscribePageBrowser:
    """Browser tests for the /subscribe/ page."""

    def test_subscribe_page_has_form(self, browser, dev_server_url):
        """The /subscribe/ page has a working form."""
        page = browser.new_page()
        page.goto(dev_server_url + "/subscribe/")
        page.wait_for_selector('.subscribe-form')

        assert page.query_selector('input[name="email"]') is not None
        assert page.query_selector('button[type="submit"]') is not None
        page.close()

    def test_subscribe_thanks_shows_message(self, browser, dev_server_url):
        """The ?thanks=1 param shows confirmation message."""
        page = browser.new_page()
        page.goto(dev_server_url + "/subscribe/?thanks=1")

        # The JS should hide the form and show the thanks message
        page.wait_for_function(
            "document.getElementById('subscribe-thanks')?.style.display === 'block'",
            timeout=3000
        )

        thanks = page.query_selector('#subscribe-thanks')
        assert thanks is not None
        assert thanks.is_visible()

        form = page.query_selector('#subscribe-form')
        assert not form.is_visible()
        page.close()

Step 2: Run tests

cd src && python -m pytest tests/test_subscribe_page.py -v

Expected: Unit tests PASS immediately. Browser tests PASS with dev server running.

Step 3: Commit

git add src/tests/test_subscribe_page.py
git commit -m "test: browser tests for /subscribe/ page"

Task 13: Documentation

Update project docs with mailing list information.

Files: - Create: doc/ops/listmonk.md - Modify: CLAUDE.md — Add mailing list section to common commands

Step 1: Create ops doc

# Listmonk — Mailing List Operations

## Overview

Almanack uses [Listmonk](https://listmonk.app/) (self-hosted) for its
mailing list, with [PurelyMail](https://purelymail.com/) for outbound
SMTP delivery.

## Access

- **Admin UI:** `http://<tailscale-host>:9000` (Tailscale only)
- **Public API:** https://list.almnck.com/api/public/subscription
- **Data:** `/var/local/listmonk/` on production host

## Commands

```sh
make list-count        # Show confirmed subscriber count
make list-export       # Export names and emails to stdout
make list-backup       # Download Postgres dump to db-backups/

Configuration

SMTP (PurelyMail)

Configured in Listmonk admin → Settings → SMTP:

Field Value
Host smtp.purelymail.com
Port 587
Auth LOGIN
TLS STARTTLS
From list@almnck.com

Secrets

  • DB password: /var/local/listmonk/secrets/db_password
  • Listmonk env: /var/local/listmonk/.env
  • SMTP credentials: configured in Listmonk admin UI

Backup & Restore

Backup

make list-backup
# → db-backups/listmonk-YYYY-MM-DDTHH.sql.gz

Restore

# Stop Listmonk
ssh sj 'cd ~ && podman-compose stop listmonk'

# Restore
gunzip -c db-backups/listmonk-XXXX.sql.gz | \
  ssh sj 'podman exec -i almanack-listmonk-db-1 psql -U listmonk -d listmonk'

# Restart
ssh sj 'cd ~ && podman-compose start listmonk'

Margin Box

The subscribe margin box is at editorial/margin-boxes/subscribe/. It has an interactive JS module that replaces the static content with an inline form, pre-filled with the reader’s identity name.

The list UUID must be set in two places: - editorial/margin-boxes/subscribe/assets/subscribe.js - editorial/pages/subscribe/page.md

Abuse Prevention

Layer Mechanism
Caddy 5 req/min/IP rate limit on subscription endpoint
Form Hidden honeypot field
JS 30s button debounce after submit
Listmonk Double opt-in email
Admin Tailscale-only access

### Step 2: Update CLAUDE.md

Add to the "Common Commands" section, after the Editorial subsection:

```markdown
### Mailing List
```sh
make list-count          # Show confirmed subscriber count
make list-export         # Export subscriber names and emails
make list-backup         # Download Listmonk database backup

### Step 3: Commit

```bash
git add doc/ops/listmonk.md CLAUDE.md
git commit -m "docs: Listmonk operations guide and CLAUDE.md update"

Task 14: Sync, Build, and Verify

Smoke test the full pipeline locally.

Step 1: Sync and build

make sync
make build

Verify no errors.

Step 2: Check the subscribe page was built

test -f web/subscribe/index.html && echo "ok - subscribe page built" || echo "not ok - subscribe page missing"

Step 3: Check the margin box fragment was built

test -f web/margin-boxes/subscribe.html && echo "ok - margin box fragment built" || echo "not ok - margin box fragment missing"

Step 4: Run the test suite

make test

Expected: All pass.

Step 5: Run browser tests

make test-browser

Expected: All pass (including new subscribe tests).

Step 6: Commit any fixes if needed


Deployment Checklist (Post-Implementation)

These steps happen on the production server, not in this plan:

  1. SSH to sj, create /var/local/listmonk/ directory tree
  2. Generate Postgres password: openssl rand -base64 32 > /var/local/listmonk/secrets/db_password
  3. Create /var/local/listmonk/.env from assets/system/listmonk.env.example
  4. Verify Tailscale IP: tailscale ip -4
  5. Add DNS: list.almnck.com → production host IP
  6. Pull code, rebuild: podman-compose up -d --build
  7. Access admin at http://<tailscale-host>:9000
  8. Configure SMTP (PurelyMail credentials)
  9. Create mailing list, copy UUID
  10. Replace CHANGEME-LIST-UUID in subscribe.js and page.md
  11. Configure Listmonk redirect URL: /subscribe/?thanks=1
  12. make sync && make build && make prod-push
  13. Test: submit a subscription, verify opt-in email arrives