Emailing New Posts From a Hugo Deploy With Amazon SES built the sending side of the new-post email. When it first worked, the subscriber list had one contact on it, and that contact was my own test address. Nobody else could join. Ghost used to handle this with a “Sign up” link in its secondary navigation, and I dropped that link along with members when the blog moved to Hugo.

A Hugo site is a folder of files, so there’s nowhere for a form to post. And an address typed into a box doesn’t prove who owns it, so I wanted a confirmation step before anything else gets sent: double opt-in.

I don’t think Ghost was double opt-in, but a lot of it ran where I couldn’t see it. Now that I’m hosting and running things myself, I wanted to be sure.

The subscribe page is live, and the code quoted below is the sanitized copy in Hugo/new-post-email in my companion repo, the same folder the first post draws on, so you’ll see example.com and “Example Blog” where my own names would be.

A signup, start to finish

You type an address into the form and press Subscribe. The form posts to /api/subscribe, which adds the address to the SES contact list as a pending contact and sends one confirmation email from news@techbyjeff.net. You land on a “Check your inbox” page.

The email has a link to /subscribe/confirm/. That page shows a single button. Pressing it posts to /api/confirm, which opts the contact in to the new-posts topic and records when. You land on a “You’re Subscribed” page, and the next post I publish goes to you.

Until you press that button, the confirmation is the only email the address gets.

Functions beside a static site

Azure Static Web Apps can host a small API next to the static files. You put an Azure Functions project in a folder, tell the deploy where it is, and SWA serves it under /api/. Mine is api/, on Node 22. The deploy step gained one line, and the site’s config names the runtime:

1
2
3
# The signup Functions. The site is built above; the action builds only the
# API, installing api/package.json's dependencies from its lock file.
api_location: "api"
1
"platform": { "apiRuntime": "node:22" }

The whole entry point, api/src/functions/signup.js, is this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const { subscribe, confirm } = makeHandlers({
  ses,
  seal,
  open,
  takeSlot: makeThrottle(20),
  verifyHuman: makeVerifier(process.env.TURNSTILE_SECRET),
  site: 'https://www.example.com',
});

app.http('subscribe', { methods: ['POST'], authLevel: 'anonymous', handler: subscribe });
app.http('confirm', { methods: ['POST'], authLevel: 'anonymous', handler: confirm });

Both Functions are POST only, and anonymous means no function key is needed to call them, as you’d expect for a public form. The handlers come from makeHandlers, which takes everything it depends on as arguments: the SES calls, the token functions, a throttle, the Turnstile verifier. That shape is for the tests further down.

SWA calls these managed Functions, and Microsoft’s comparison with a Functions app you bring yourself lists what they give up. HTTP triggers are the only kind, which is fine for a pair of POST handlers. There’s also no managed identity, so the Functions have no Azure identity to federate into AWS the way the sending job uses GitHub’s. This side holds a stored key.

The key lives in the SWA app settings, along with a TOKEN_SECRET and the region, and it belongs to an IAM user, swa-signup, that can do very little. It can send only as news@techbyjeff.net through the blog-posts configuration set, and it can get, create and update contacts on the one list. It can’t list contacts and it can’t delete them. Whoever stole it could send as news@ and look up one address at a time. They couldn’t dump my subscriber list.

api also joined the reserved slug list in Test-Post.ps1. Post URLs sit at the site root here, so a post named api.md would collide with the Functions.

Pending as a missing preference

The first post covered the list’s one topic and its OPT_OUT default: a contact with no preference recorded isn’t mailed. I used that gap as the pending state. A signup creates the contact and says nothing about the topic, in api/src/lib/ses.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// UpdateContact clears AttributesData when it is left out (seen on the live list,
// 27 November 2026), so every write here sends the full attribute set. Leaving out
// TopicPreferences keeps them, which is what lets a pending write leave an existing
// subscription alone.
export const savePending = (email, attributes, exists) => {
  const input = { ContactListName: LIST, EmailAddress: email, AttributesData: JSON.stringify(attributes) };
  return client.send(exists ? new UpdateContactCommand(input) : new CreateContactCommand(input));
};

export const optIn = (email, attributes) =>
  client.send(new UpdateContactCommand({
    ContactListName: LIST,
    EmailAddress: email,
    UnsubscribeAll: false,
    TopicPreferences: [{ TopicName: TOPIC, SubscriptionStatus: 'OPT_IN' }],
    AttributesData: JSON.stringify(attributes),
  }));

savePending writes attributes only. optIn is the one call that sets a topic preference, and only /api/confirm makes it. The comment at the top is from a surprise on the live list: an update that left AttributesData out wiped it.

Unsubscribing through the SES link records an opt-out on the contact, and that is a preference. Subscribed, unsubscribed and unconfirmed each look different on the contact, and I didn’t have to add a status field to tell them apart.

The form gives one answer

The handlers are in api/src/lib/handlers.js. Every signup that passes the basic checks ends at the same page:

1
2
3
// Every outcome of a signup gets the same answer, so the form never reveals whether
// an address is already on the list.
const done = () => redirect('/subscribe/check-your-inbox/');

New, pending, already subscribed, or asked an hour ago: every address gets “Check your inbox”. The text on that page is worded to stay true in each case:

1
2
3
If that address isn't subscribed yet, a confirmation email from news@example.com is on
its way. Open the link in it and press the button, and you're in. The link works for 48
hours.

If the form said “you’re already subscribed”, anyone could type in an address and learn whether it’s on my list.

A sealed token after the

The confirmation email is short and plain text:

The plain-text confirmation email in a mail client, with a confirm link whose token after the hash is redacted and a note that it works for 48 hours
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
export const confirmationEmail = (link) => ({
  subject: 'Confirm your Example Blog subscription',
  text: [
    'Someone, hopefully you, asked for an email whenever a new post goes up on',
    'Example Blog. To confirm, open this link and press the button:',
    '',
    link,
    '',
    "The link works for 48 hours. If this wasn't you, ignore this email and",
    'nothing more will be sent.',
  ].join('\n'),
});

It goes out without SES’s list management, so it carries no unsubscribe link. It’s a one-off answer to a request, and the address isn’t subscribed to anything yet.

The link in it has to carry proof that it came from my confirmation email and which address it’s for. The usual way is a signed token: the address in the clear, plus a signature. I didn’t want the address readable in a URL at all, so the token is encrypted, in api/src/lib/tokens.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
export const seal = (claim, secret = process.env.TOKEN_SECRET) => {
  const iv = randomBytes(12);
  const cipher = createCipheriv('aes-256-gcm', keyFrom(secret), iv);
  const body = Buffer.concat([cipher.update(JSON.stringify(claim)), cipher.final()]);
  return Buffer.concat([iv, body, cipher.getAuthTag()]).toString('base64url');
};

// Returns the claim, or null for anything that is not a token this secret sealed.
export const open = (token, secret = process.env.TOKEN_SECRET) => {
  try {
    const raw = Buffer.from(String(token ?? ''), 'base64url');
    if (raw.length < 12 + 16 + 1) return null;
    const decipher = createDecipheriv('aes-256-gcm', keyFrom(secret), raw.subarray(0, 12));
    decipher.setAuthTag(raw.subarray(-16));
    const text = Buffer.concat([decipher.update(raw.subarray(12, -16)), decipher.final()]).toString();
    return JSON.parse(text);
  } catch {
    return null;
  }
};

The cipher is AES-256-GCM with a random 12-byte IV, and the key is a SHA-256 of TOKEN_SECRET. GCM authenticates as well as encrypts. A token that was edited or sealed with a different secret fails at decipher.final(), lands in the catch, and comes back as null. The handler treats null the same as an expired link.

The claim inside holds the address, the time it was issued and a one-time code. The link is built like this:

1
2
3
4
// The token goes after '#', which browsers never send to a server or to the
// analytics on the page, so it stays out of every log.
const link = `${site}/subscribe/confirm/#t=${seal({ e: email, i: now(), n: nonce })}`;
await ses.sendConfirmation(email, confirmationEmail(link));

The token goes after #. Your browser doesn’t send the fragment with the request, so the token stays out of Azure’s request logs. The confirm page, content/subscribe-confirm.md, reads it, copies it into a hidden form field and clears it from the address bar:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// The token rides after '#', so it never reaches a server log or the analytics on
// this page. It's copied into the form, then dropped from the address bar.
var tbjT = new URLSearchParams(location.hash.slice(1)).get('t');
var tbjShow = function (id) {
  document.getElementById('tbj-confirm-intro').hidden = true;
  document.getElementById('tbj-confirm-form').hidden = true;
  document.getElementById(id).hidden = false;
};
if (new URLSearchParams(location.search).has('error')) {
  tbjShow('tbj-confirm-error');
} else if (tbjT) {
  document.getElementById('tbj-confirm-t').value = tbjT;
  history.replaceState(null, '', location.pathname);
} else {
  tbjShow('tbj-confirm-missing');
}

A link lasts 48 hours. After that the handler sends you to a page that says the link expired and points back to the form.

Confirming takes a button press

I could have made the link itself do the confirming. Open it, you’re in. Plenty of signup flows work that way, and mail security scanners break them: a scanner that opens every link in a message before delivering it would confirm people who never clicked anything. Both Functions accept POST only, and a scanner fetching the link gets a page with a button on it.

The Confirm Your Subscription page with one line of text and a Confirm my subscription button

My first commit of the handlers stopped there, and a review before the merge found a hole in it. A link worked as often as you pressed it for 48 hours. Confirming also clears UnsubscribeAll, as it has to if someone who unsubscribed is ever going to sign up again. Put those together: you subscribe, confirm, and the next day unsubscribe. The confirmation email is still in your inbox. Press that link again and you’re back on the list.

This was the confirm call at the time:

1
await ses.optIn(claim.e, { ...attributes, confirmedAt: attributes.confirmedAt ?? new Date(now()).toISOString() });

Each signup now stores a one-time code on the contact and seals the same code into its link:

1
2
3
4
5
// Each signup gets a one-time code, stored on the contact and sealed into the link.
// Confirming spends it, and a newer signup replaces it, so a link works once and
// only while it is the newest. The contact is saved before the email goes out,
// because confirm needs it to exist.
const nonce = randomUUID();

Confirming compares the two and then removes the code from the contact:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
if (attributes.confirmNonce !== claim.n) {
  // This link was already used, or a newer signup replaced it. A second press of a
  // link that just worked lands on the confirmed page; otherwise the link is dead.
  // Either way nothing changes, so a used link can never undo an unsubscribe.
  return redirect(isOptedIn(contact) ? '/subscribe/confirmed/' : '/subscribe/expired/');
}

const { confirmNonce, ...rest } = attributes; // spend the code
await ses.optIn(claim.e, fitAttributes({ ...rest, confirmedAt: new Date(now()).toISOString() }));
return redirect('/subscribe/confirmed/');

A link works once, and only while it’s the newest one issued for that address, since a later signup replaces the code. Pressing a used link has no effect. If it’s the link that just worked, you still land on the confirmed page.

Keeping scripts off the form

A public form that sends email is a way to make my domain mail strangers. Somebody could feed it a list of addresses, and SES would send each one a confirmation from news@techbyjeff.net. The form itself, in content/subscribe.md, carries a honeypot and a timer:

1
2
3
4
5
6
7
8
<form class="tbj-subscribe" method="post" action="/api/subscribe">
  <label for="tbj-sub-email">Your email address</label>
  <input id="tbj-sub-email" name="email" type="email" required autocomplete="email" maxlength="254" placeholder="you@example.com">
  <div class="tbj-hp" aria-hidden="true">
    <label for="tbj-sub-website">Leave this empty</label>
    <input id="tbj-sub-website" name="website" type="text" tabindex="-1" autocomplete="off">
  </div>
  <input type="hidden" name="elapsed" id="tbj-sub-elapsed">
1
.tbj-hp { position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden; }

(The Turnstile widget and the Subscribe button come after these.) The website field is the honeypot. It’s positioned off the screen, hidden from screen readers and out of the tab order, and a person who somehow finds it is told to leave it empty. It’s off screen and not display: none because some bots skip a field that isn’t rendered at all. elapsed is how long the page was open, filled in by the page’s script when you submit. The Function reads both before it looks at anything else:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const email = String(form.get('email') ?? '').trim().toLowerCase();
const elapsed = Number(form.get('elapsed'));

// The honeypot is a field people never see. 'elapsed' is how long the page was open
// before the form was sent, measured in the browser with performance.now(), so the
// visitor's clock and the server's never get compared: a fast or slow device clock
// cannot make a real signup look like a bot. A filled honeypot, no script, or a form
// sent within three seconds is a bot, and gets the normal answer with no email.
if (form.get('website') || !Number.isFinite(elapsed) || elapsed < MIN_ELAPSED_MS) return done();
if (email.length > 254 || !EMAIL.test(email)) return redirect('/subscribe/?invalid=1');

Anything under three seconds is treated as a bot. A request that fails either check gets the normal “Check your inbox” answer and no email.

One confirmation a day

Past those checks, each address gets one confirmation a day, and there’s a ceiling across all addresses:

1
2
3
4
5
6
7
const contact = await ses.getContact(email);
if (isOptedIn(contact)) return done();

const attributes = parseAttributes(contact);
const lastSent = Date.parse(attributes.confirmSentAt ?? '');
if (Number.isFinite(lastSent) && now() - lastSent < DAY_MS) return done(); // one a day per address
if (!takeSlot()) { context.warn('Confirmation cap reached for this hour; not sending.'); return done(); }

The daily limit is the timestamp confirmSentAt on the contact. My first commit wrote it too early:

1
2
3
4
5
await ses.savePending(email, {
  ...attributes,
  source: attributes.source ?? 'form',
  confirmSentAt: new Date(now()).toISOString(),
}, Boolean(contact));

That save ran before the link was sealed and the email sent. If the send failed, the address had already used up its one confirmation for the day. You’d retry, get told to check your inbox, and no email would come. The timestamp is now written only after SES accepts the email:

1
2
3
4
5
6
7
8
// Only now does the one-a-day limit start: a send that failed must not block a retry.
// If this write fails, the email has still gone out; the worst case is a second
// confirmation on a retry today, so it is logged rather than shown as an error.
try {
  await ses.savePending(email, recorded, true);
} catch (err) {
  context.warn(`confirmation sent but its time was not recorded: ${describe(err, email)}`);
}

If that last write fails, the email has still gone out. The worst case is a second confirmation on a retry the same day, so the failure is logged and you see the normal page. The “Check your inbox” page mentions the daily limit, because otherwise a second attempt that produces no email looks broken.

The ceiling across all addresses is a counter in memory, api/src/lib/throttle.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
export const makeThrottle = (cap, now = () => Date.now()) => {
  let hour = -1;
  let used = 0;
  return () => {
    const h = Math.floor(now() / 3_600_000);
    if (h !== hour) { hour = h; used = 0; }
    used += 1;
    return used <= cap;
  };
};

Twenty confirmations per clock hour. The count is per instance and resets when an instance starts, so it slows a burst and guarantees little. The per-address limit is the real guard, and that one lives on the contact in SES.

Turnstile for what a script can fake

The honeypot and elapsed share a weakness: the sender supplies both values. A script that leaves one field empty and sets the other to 5000 passes, and the form could still be made to send confirmation mail to any address.

Cloudflare Turnstile is a different kind of check. A widget on the page runs Cloudflare’s challenge in your browser and puts a token in a hidden form field. The server sends that token to Cloudflare with a secret, and Cloudflare says whether it’s good. Cloudflare’s docs give a token five minutes and one use.

The Get New Posts by Email page with an empty address field, a Cloudflare Turnstile widget showing Success and a Subscribe button

The check is api/src/lib/turnstile.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
export const makeVerifier = (secret, { fetchImpl = fetch, timeoutMs = 5000 } = {}) => {
  if (!secret) return null;
  return async (token) => {
    if (!token || token.length > 2048) return false;
    const res = await fetchImpl(VERIFY_URL, {
      method: 'POST',
      body: new URLSearchParams({ secret, response: token }),
      signal: AbortSignal.timeout(timeoutMs),
    });
    if (!res.ok) throw new Error(`siteverify answered HTTP ${res.status}`);
    const body = await res.json();
    return body?.success === true;
  };
};

The handler has to tell a person from a refused token, and both from a Cloudflare that couldn’t be asked. true is a person. false is a token Cloudflare refused. A thrown error means the question went unanswered.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// The two checks above are values the sender supplies. This one is not: see
// turnstile.js. It runs before anything touches SES, and unlike the checks above
// it says so when it fails, because a real reader can fail it (a widget that had
// not finished, a token older than five minutes) and needs to know to try again.
if (verifyHuman) {
  let human;
  try { human = await verifyHuman(String(form.get('cf-turnstile-response') ?? '')); } catch (err) {
    context.error(`the Turnstile check could not be made: ${describe(err, email)}`);
    return redirect('/subscribe/?error=1');
  }
  if (!human) return redirect('/subscribe/?verify=1');
}

A refused token sends you back to the form with a note that the check hadn’t finished. This is the one bot check that tells you it failed, because a real reader can fail it by submitting before the widget is done or by leaving the tab open past five minutes. If Cloudflare is unreachable, the signup fails closed with the generic error.

describe is the log formatter, and it exists because of your address. SES sometimes quotes an address back in its error text, so anything headed for the Functions’ log has the address cut out first:

1
2
3
4
5
6
7
// One line for the log. SES sometimes quotes the address back in its error text, and a
// reader's address does not belong in the logs, so it is cut out.
export const describe = (err, email) => {
  const text = `${err?.name ?? 'Error'}: ${err?.message ?? err}`;
  if (!email) return text;
  return text.replace(new RegExp(email.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), '<address>');
};

The page tries to save you the round trip. If the widget is on the page and hasn’t produced a token yet, the submit handler stops the form and shows the same note:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
document.querySelector('.tbj-subscribe').addEventListener('submit', function (e) {
  document.getElementById('tbj-sub-elapsed').value = Math.round(performance.now());
  // With the Turnstile widget on the page, the form has nothing to prove it with
  // until the widget has filled in its field. Say so here and keep the address in
  // the box; sending it now would only come back with the same message. Only once
  // Cloudflare's script has loaded, though: if it was blocked or never arrived, no
  // token is coming, so let the form go and the server answer for itself.
  if (this.querySelector('.cf-turnstile') && typeof window.turnstile !== 'undefined') {
    var tbjToken = this.querySelector('[name="cf-turnstile-response"]');
    if (!tbjToken || !tbjToken.value) {
      e.preventDefault();
      document.getElementById('tbj-sub-verify').hidden = false;
    }
  }
});

The typeof window.turnstile test wasn’t in my first version, and a review caught what that meant. The widget’s <div> is written into the page by Hugo whenever the site key is set. If Cloudflare’s script is blocked, by a content blocker or a mistake in the CSP, the <div> is there and no token arrives. The form would have stopped every submit with “hadn’t finished” for as long as you kept trying, and since nothing reached the server, there’d have been no log of it either. The fix is one condition:

1
2
-    if (this.querySelector('.cf-turnstile')) {
+    if (this.querySelector('.cf-turnstile') && typeof window.turnstile !== 'undefined') {

Now the form only waits for a token when Cloudflare’s script has loaded. If it hasn’t, the form goes through and the server answers for itself.

The site key is public and lives in hugo.toml. A shortcode, layouts/_shortcodes/turnstile.html, writes the widget into the page only when the key is set:

1
2
3
4
{{- with site.Params.turnstile -}}{{- with .siteKey -}}
<div class="cf-turnstile" data-sitekey="{{ . }}" data-theme="auto"></div>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
{{- end -}}{{- end -}}

The secret is an SWA app setting, and with no secret makeVerifier returns null and the handler skips the check. Mind the order you set them in. A secret with no widget on the page refuses every signup, since no form can produce a token. The key has to deploy first, or in the same deploy as the code that reads the secret. Removing the secret is the rollback.

The Content Security Policy needed https://challenges.cloudflare.com in both script-src and frame-src (staticwebapp.config.example.json has a cut-down policy with both). Azure serves that header, so hugo server can’t tell you whether you got it right. The only real test is the deployed page with the console open.

The downside to turning Turnstile on was that some of my automation could no longer test signups, but it was a small price to pay.

Tests against a fake SES

makeHandlers takes its dependencies as arguments so the tests can hand it an in-memory SES, a clock they control and a Turnstile verifier that says whatever the test needs. The test runner is Node’s built-in one, node --test, with no test framework installed. There are 25 tests in api/test/handlers.test.js, and their names read like the rules. A few of them:

1
2
3
4
5
a used confirm link cannot sign someone back up after they unsubscribe
pressing the confirm button twice still lands on the confirmed page
a newer signup retires the older confirm link
a confirmation that fails to send does not use up the daily limit
when Cloudflare cannot be asked, the signup fails closed with the error page

The deploy runs them before the Hugo build, so a failing test blocks the site from deploying:

1
2
3
4
5
6
- name: Test the signup API
  working-directory: api
  run: |
    npm ci
    npm test
    rm -rf node_modules

node_modules is removed afterward because the SWA deploy step installs the API’s dependencies itself, and I wanted it to start from the same tree it always had.

The page went live with nothing pointing at it, so I could test it on the real site first with plus-addresses. Then I added the links.

The footer of every page has one. PaperMod renders a footer.text parameter through markdownify, so it took a config value and no template override (hugo.example.toml has it with the other hugo.toml blocks):

1
2
[params.footer]
  text = '[Get new posts by email](/subscribe/)'

The end of every post has a line above the Ko-fi button: “Get new posts by email, one message when the next one goes up.” It’s gated on the page being a post, separately from the kofi flag, so a post that opts out of the tip button still shows it. The About page got one sentence. That puts a signup entry point back on every page, where Ghost had one, without adding to the main menu.

Pruning unconfirmed signups

/api/subscribe saves an address before its owner has agreed to anything. It has to, since the confirm step needs a contact to find. Most pending contacts confirm or get retried. Some are typos, changes of mind or bots that got through, and after the 48-hour link expires those are addresses I’m holding with nobody’s consent.

A weekly scheduled workflow removes them a week after the last attempt. The script, scripts/Remove-PendingContact.ps1, is conservative about what counts:

1
2
3
4
5
6
7
8
9
function Test-Pending($Contact, [datetime] $Cutoff) {
    if (-not $Contact) { return $false }
    if (& $get $Contact 'UnsubscribeAll') { return $false }
    foreach ($preference in @(& $get $Contact 'TopicPreferences')) {
        if ($preference -and (& $get $preference 'TopicName') -eq $Topic) { return $false }
    }
    $changed = ConvertTo-Utc (& $get $Contact 'LastUpdatedTimestamp')
    return ($null -ne $changed -and $changed -lt $Cutoff)
}

A contact with any preference for the topic is skipped, which covers subscribers and people who unsubscribed. After that first cut the script fetches each candidate again and checks its attributes: no confirmedAt, no record of posts sent, and a source of form. Anything it can’t read, it keeps.

The send role can’t delete contacts, so the prune runs as a second role that can. It’s off until a repo variable turns it on, and a run by hand defaults to a dry run. My first dry run reported would delete 0, kept 3 of 3 contacts, failed 0. The variable is on now, and that second role is gh-blog-prune.

If you signed up on that page, your address went through all of this: the honeypot and the timer, Turnstile, one confirmation email and a button you pressed yourself. If you never pressed it, the prune lets you go a week later.