Dev.to Security 🔐 Cybersecurity 👁 0 📖 7 min read

Our unsubscribe link is a 64 character HMAC, and the GET that mail scanners follow is built to do nothing

PubTrivia sends product update emails to venues who opted in. Those emails need an unsubscribe link that works for a person who is not signed in, who may be reading in a mail client that will never show them a browser, a

PubTrivia sends product update emails to venues who opted in. Those emails need an unsubscribe link that works for a person who is not signed in, who may be reading in a mail client that will never show them a browser, and whose message has already been opened and refetched by two or three security scanners before they see it.

That is four constraints, and they decide the whole design. Here is what we ended up with, and the live endpoints you can poke at while you read.

The token

The authorisation is an HMAC of the user id, and nothing else:

function sign(userId: string, key: string): string {
  return createHmac('sha256', key).update(`unsubscribe:${userId}`).digest('hex')
}

64 hex characters. The link carries the user id in the clear and the signature beside it:

https://pub-trivia.app/unsubscribe?uid=<userId>&token=<64 hex chars>

Verification refuses on shape before it touches crypto, then compares in constant time:

export function verifyUnsubscribeToken(userId: string, token: string): boolean {
  const key = secret()
  if (!key || !userId || !/^[0-9a-f]{64}$/i.test(token)) return false
  const expected = Buffer.from(sign(userId, key), 'hex')
  const given = Buffer.from(token, 'hex')
  return expected.length === given.length && timingSafeEqual(expected, given)
}

Three details in five lines, and each one is load bearing. The regex refuses garbage before any crypto runs. The length comparison is there because timingSafeEqual throws on buffers of different sizes, and Buffer.from('zz', 'hex') does not throw, it quietly hands back an empty buffer. And timingSafeEqual rather than === because a comparison that returns early is a comparison that tells you how much of your guess was right.

The result is that garbage and a plausible forgery get the same answer:

$ curl -s -X POST "https://pub-trivia.app/api/email/unsubscribe?uid=abc&token=$(python3 -c 'print("a"*64)')"
{"error":"Invalid unsubscribe link"}   # 400

$ curl -s -X POST "https://pub-trivia.app/api/email/unsubscribe?uid=abc&token=zz"
{"error":"Invalid unsubscribe link"}   # 400

There is no fallback secret

function secret(): string | null {
  return process.env.EMAIL_UNSUBSCRIBE_SECRET?.trim() || null
}

No ?? 'dev-secret', no derived default. A guessable key here would let anybody unsubscribe anybody, and the failure mode of a missing key is much easier to live with than the failure mode of a default one. So the broadcast action checks first and refuses to send at all:

if (!unsubscribeConfigured()) {
  return { ok: false, error: 'EMAIL_UNSUBSCRIBE_SECRET is not set, so the emails would have no working unsubscribe link. Set it and redeploy.' }
}

An email with a dead unsubscribe link is worse than an email that never went out. The error names the variable, because the person who will read it is me, at the moment I am trying to send something.

Two links per recipient, and only one of them is a page

Every broadcast carries both. The footer link goes to a page. The List-Unsubscribe header goes to an API route:

headers: {
  'List-Unsubscribe': `<${oneClickUnsubscribeUrl(r.id)}>`,
  'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
}

That pair is RFC 8058. It is what makes Gmail and Outlook draw their own Unsubscribe button next to the sender name, and the reason to want it is not politeness. The alternative button, the one people press when they cannot find yours, is Report spam, and that one costs you deliverability for every other recipient.

Two signed URLs, two paths, one boolean at the end of both:

What the recipient does Where it goes Method What acts
Presses the mail client's Unsubscribe /api/email/unsubscribe POST the route handler
Clicks the link in the footer /unsubscribe GET nothing, it renders a button
Presses that button /unsubscribe POST (server action) the action, after re-verifying
Turns the toggle off in settings /dashboard/settings POST (server action) the action, using the session

The GET that deliberately does nothing

This is the part worth copying. The API route exports a GET, and the GET does not unsubscribe:

export function GET(req: NextRequest): NextResponse {
  const url = req.nextUrl.clone()
  url.pathname = '/unsubscribe'
  return NextResponse.redirect(url)
}
$ curl -s -o /dev/null -w '%{http_code} -> %{redirect_url}\n' \
    "https://pub-trivia.app/api/email/unsubscribe?uid=abc&token=x"
307 -> https://pub-trivia.app/unsubscribe?uid=abc&token=x

Mail security gateways, link scanners and preview generators fetch every URL in a message, usually with a GET, usually before the recipient has seen the subject line. A GET that unsubscribes is a GET that quietly drops people who never clicked anything, and you will not find out, because the symptom is a mailing list that slowly stops having anyone on it.

So the page is the same shape: it asks. Visiting /unsubscribe with a signed link renders a heading, a sentence about what you will still receive, and one button. The act is a server action, and the action verifies the token again rather than trusting the page it was rendered on, because every export of a "use server" file is a public POST endpoint whether you think of it that way or not.

With no parameters at all, the page says so: open pub-trivia.app/unsubscribe and you get "This link is incomplete" and a link to settings. No form, nothing to submit, and a noindex, nofollow on it:

$ curl -s https://pub-trivia.app/unsubscribe | grep -o '<meta name="robots"[^>]*>'
<meta name="robots" content="noindex, nofollow"/>

It is also one of the eight prefixes in our robots.txt disallow list, which you can read at pub-trivia.app/robots.txt. The meta tag is the one that matters, since robots.txt stops crawling rather than indexing, but a crawler that never asks cannot follow an unsubscribe link either.

The site URL is hardcoded on purpose

// Always the real site, never NEXT_PUBLIC_WEBSITE_URL: a broadcast sent from a
// laptop whose env points at localhost must still carry working links.
const SITE_URL = 'https://pub-trivia.app'

Every other link in the product is built from an environment derived base URL, which is correct for a product that runs on previews and on localhost. An email is the one artifact that leaves the building. A preview deployment can send a real email to a real person, and http://localhost:3000/unsubscribe?uid=... in their inbox is not a link, it is a dead end with my development environment's name on it.

What this token cannot do

Being honest about the limits, because the design is a trade and not a win:

It never expires. There is no timestamp in the signed message, so a link in a two year old email still works. That is deliberate: an expired unsubscribe link is the single most annoying thing an email can contain, and people unsubscribe from old mail more often than from new mail.

It is not single use. Pressing it twice sets the same boolean to false twice.

It names the user id in the query string, which is in the recipient's inbox, their mail provider's logs and any scanner in between. The thing it buys with that exposure is bounded precisely: the only statement the token authorises is email_updates = false for that one row. It cannot read anything, it cannot sign anyone in, and it is useless on any other endpoint.

And it is per account rather than per address, so changing the email address on an account does not invalidate the links already sent to the old one. For a product update list, I am fine with all four. For anything that moved money I would not be.

One more detail that is easy to miss: the opted-in set is re-queried on every batch of a broadcast rather than snapshotted at the start, so somebody who presses Unsubscribe while a send is running is already gone by the next batch:

.where(and(eq(usersTable.email_updates, true), cursor ? gt(usersTable.id, cursor) : undefined))

Check the refusals yourself

All three of these are live, and none of them need an account:

curl -i "https://pub-trivia.app/unsubscribe"                                   # 200, noindex, "This link is incomplete"
curl -i -X POST "https://pub-trivia.app/api/email/unsubscribe?uid=x&token=x"   # 400, refused on shape
curl -i "https://pub-trivia.app/api/email/unsubscribe?uid=x&token=x"           # 307 to the confirm page

The one thing you cannot test from outside is the happy path, which is the point of an HMAC. If you want to see the page that a real link opens, there is a free tier with no card at pub-trivia.app, the email updates box is in settings once you are in, and what we do with the address is written out in plain words at pub-trivia.app/legal/privacy.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.