Build scanner-safe double opt-in
By Flavio
Tagged: Cloudflare
Build a double opt-in flow that uses one-time hashed tokens and requires a POST, so email scanners cannot confirm subscriptions by opening links.
Opening a double opt-in link shouldn’t confirm an email address on its own.
I know that sounds backwards at first, since clicking a link in your inbox is how confirmation usually works. The problem is that plenty of email providers and security tools open links before the recipient ever does, checking the destination for malware and phishing. If your GET request flips a subscriber from pending to confirmed, those scanners will confirm the address for someone who never clicked.
The fix is to split confirmation into two steps:
GET /confirm?token=...shows a confirmation pagePOST /confirmperforms the confirmation
Because the first request is read-only, GET-only scanners can’t confirm the address, while the visible POST form adds an intentional step from the user. An automated client could still submit the form, so the one-time token itself is still what authorizes the confirmation.
Generate a one-time token
Start with 32 random bytes:
function createToken() {
const bytes = new Uint8Array(32)
crypto.getRandomValues(bytes)
return btoa(String.fromCharCode(...bytes))
.replaceAll('+', '-')
.replaceAll('/', '_')
.replaceAll('=', '')
}
That gives you a 43-character base64url token. Send the original token in the email, and don’t store it in the database.
Store an HMAC of it instead:
async function hashToken(secret, token) {
const encoder = new TextEncoder()
const key = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
)
const signature = await crypto.subtle.sign(
'HMAC',
key,
encoder.encode(`confirm:${token}`)
)
return [...new Uint8Array(signature)]
.map(byte => byte.toString(16).padStart(2, '0'))
.join('')
}
If your database ever leaks, nobody can turn those stored values into working confirmation links. Adding the confirm: prefix also keeps this token separate from anything else you sign with the same secret.
Make the GET request read-only
When someone opens the confirmation link, the page should only show a form:
<form method="post" action="/confirm">
<input type="hidden" name="token" value="THE_TOKEN" />
<button type="submit">Confirm my place</button>
</form>
Don’t update the database inside the GET handler. Return the page with headers that keep the token from leaking:
return new Response(html, {
headers: {
'content-type': 'text/html; charset=utf-8',
'cache-control': 'no-store',
'referrer-policy': 'no-referrer',
'x-robots-tag': 'noindex, nofollow',
'content-security-policy':
"default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'"
}
})
Don’t load analytics, images, fonts, or any other third-party resources on this page, and configure your access logs to strip the token query parameter too.
With that in place, all of these can load the page without confirming the subscriber:
- email security scanners
- link previews
- chat apps that fetch shared URLs
- browser prefetching
Confirm with one atomic query
When the form is submitted, hash the token and update only a matching pending subscriber:
UPDATE subscribers
SET
status = 'confirmed',
confirmed_at = unixepoch(),
confirmation_token_hash = NULL,
confirmation_expires_at = NULL
WHERE status = 'pending'
AND confirmation_token_hash = ?
AND confirmation_expires_at >= ?
RETURNING id;
The query only matches an existing, unexpired token for a subscriber who’s still pending. It’s also single-use, because a successful update removes the hash so the same token can’t confirm anything a second time.
Store confirmation_expires_at as integer Unix seconds and bind the current Unix time to the final placeholder. That matches unixepoch() in confirmed_at and keeps your confirmation and cleanup comparisons consistent.
Keep the token in the POST body
You need the token in the email link’s query string so the GET handler can build the page, but the form action doesn’t need it:
<form method="post" action="/confirm">
<input type="hidden" name="token" value="THE_TOKEN" />
</form>
On the server, read the token only from the form body:
const token = form.get('token')
if (!validToken(token)) {
return new Response('Invalid confirmation request', {
status: 400
})
}
Putting the token in the POST URL exposes it to another request log without adding any protection.
Do we need CSRF protection?
Not here, because the token itself authorizes this one action.
There’s no logged-in user and no session cookie sitting in the browser. A different site can’t guess a 256-bit token and confirm an arbitrary address.
An Origin check doesn’t add much here, and it can reject legitimate requests coming through a custom domain or proxy. An authenticated admin form still needs normal CSRF protection because it relies on a user session.
Expire pending requests
Give confirmation links a short lifetime, with 24 hours as a reasonable default. Then delete expired pending rows with a cleanup query:
DELETE FROM subscribers
WHERE status = 'pending'
AND confirmation_expires_at < ?;
Run that query from a scheduled job so expired signups don’t pile up. I used this same setup in Build a waiting list with double opt-in on your own Cloudflare account.
Want me to talk about your product? You can sponsor this site.
Related posts about cloudflare: